texts: Encode two integers into colour values and compare them in a HLSL shader

texts:
I am writing a 2D point and click adventure game in Monogame, and I'd like to be able to create an image mask for every room which defines which parts of the background a character can walk behind, and at which Y value a character needs to be at for the background to be drawn above the character.

I haven't done any shader work before but after doing some reading I thought the following solution should work:

Create a mask for the room with different walk behind areas painted in a colour that defines the baseline Y value (Walk Behind Mask)
Render all objects to a RenderTarget2D (Base Texture)
Render all objects to a different RenderTarget2D, but changing every pixel of each object to a colour that defines its Y value (Position Mask)
Pass these two textures plus the image mask into the shader, and for each pixel compare the colour of the image mask to the colour of the Position Mask to the Walk Behind Mask - if the Position Mask pixel is larger (thus lower on the screen and closer to the camera) than the Walk Behind Mask, draw the pixel from the Base Texture, otherwise draw a transparent pixel (allowing the background to show through).

I've got it mostly working, but I'm having trouble packing and unpacking the Y values into colours and retrieving them correctly in the shader. Here are some code examples of how I'm doing it so far:

(When drawing to the Position Mask RenderTarget2D)

Color posColor = new Color(((int)Position.Y >> 16) & 255, ((int)Position.Y >> 8) & 255, (int)Position.Y & 255);

So as far as I can tell, this should be taking the first 3 bytes of the position integer and encoding them into a 4 byte colour (ignoring the alpha as the 4th byte). This seems to work fine, as when my character is at Y = 600, the resulting Color from this is: {[Color: R=0, G=2, B=88, A=255, PackedValue=4283957760]}.

I then have an area in my Walk Behind Mask that I only want the character to be displayed behind if his Y value is lower than 655, so I've painted it with R=0, G=2, B=143, A=255.

Now, I think I have the shader OK as well, here's what I have:

sampler BaseTexture : register(s0);
sampler MaskTexture : register(s1);
sampler PositionTexture : register(s2);

float4 mask( float2 coords : TEXCOORD0 ) : COLOR0
{
    float4 color = tex2D(BaseTexture, coords);
    float4 maskColor = tex2D(MaskTexture, coords);
    float4 positionColor = tex2D(PositionTexture, coords);
    float maskCompare = (maskColor.r * pow(2,24)) + (maskColor.g * pow(2,16)) + (maskColor.b * pow(2,8));
    float positionCompare = (positionColor.r * pow(2,24)) + (positionColor.g * pow(2,16)) + (positionColor.b * pow(2,8));
    return positionCompare < maskCompare ? float4(0,0,0,0) : color;
}

technique Technique1
{
    pass NoEffect
    {
        PixelShader = compile ps_3_0 mask();
    }

}

This isn't working, however - currently all characters are displayed behind the walk behind area, regardless of their Y value.

I tried printing out some debug info by grabbing the pixel from both the Position Mask and the Walk Under Mask under the current mouse position, and it seems like maybe the colours aren't being rendered to the Position Mask correctly? When calculating the colour in that code above I'm getting  R=0, G=2, B=88, A=255, but when I mouseover my character I get R=0, G=0, B=30, A=255.

Any ideas what I'm doing wrong? It seems like maybe I'm losing some information when rendering to the RenderTarget2D, but I'm now knowledgeable enough to figure out what's happening.

Also, I should probably ask, is this an efficient way to do this? Will there be a performance impact?

Edit: Whoops, turns out there was a bug that I'd introduced myself, I was drawing out the Position Mask with the position Color, left over from some early testing I was doing. So this solution is working perfectly, though I'm still interested in whether this is an efficient solution performance wise.


texts: LibGDX how to remove PointLight that is attached a destroyed Body

texts:
I have this code:

@Override
public void beginContact(Contact contact) {
    fa = contact.getFixtureA();
    fb = contact.getFixtureB();

    if (fa == null || fb == null) return;
    if (fa.getUserData() == null || fb.getUserData() == null) return;

    final Body toRemove = contact.getFixtureA().getBody().getType() == BodyDef.BodyType.StaticBody ?
            contact.getFixtureA().getBody() :
            contact.getFixtureB().getBody();
    Gdx.app.postRunnable(new Runnable() {
        @Override
        public void run () {
            world.destroyBody(toRemove);
        }
    });

}

It removes the FA body, but this body have a pointlight attached.
I want to remove this PointLight attached.
I have no idea how to do this :/.


texts: One pixel lines flash on tile map when camera moves

texts:
I'm writing a simple game using Phaser 3.5.1. I made a 20X20 over world tile map for my hero to walk around on with the camera following the hero. I was able to implement tile based movement using tweens. This works but whenever the camera moves 1 pixel lines flash on the tile map perpendicular to the direction I move. Example uses a static map layer:

As you can see I was also getting some weird artifacts on my sprite even when the camera wasn't moving, but after reading about rounded pixels I was able to eliminate that on my sprite by setting roundedPixels: true in my game config, but now the sprite jitters when the lines appear. Example uses static map layer with rounded pixels:

I also experimented with static vs dynamic layers for my map. When I have a dynamic map layer without rounded pixels the result is the same as my static map layer without rounded pixels.

When I use rounded pixels on a dynamic map everything gets really jittery. Interestingly when the camera doesn't move the map shakes, and when the camera does move the sprite jitters.

Regardless of the map type or rounded pixels setting, the longer the tween's duration the worse the problem gets. In my examples I used 2 second tweens to emphasize the problem.

How do I fix this problem? In a perfect world I'd like to keep using tweens for tile based movement, keep a static map, and just update some config value. If that isn't going to work what approach should I take?

I'm happy to add code to my question if people think it would be helpful.


texts: What does D3DXOptimizeFaces function do?

texts:
I know that this function generates an optimized face remapping for a triangle list, but what actually this optimized remapping is?
The triangle faces are remapped, but based on what?


texts:
I learned at school that the z-axis is up. It is the same in modeling software like Blender. However in many games the y-axis is up.

What is the reason?


texts: SDL2 - show a tooltip at the cursor that displays RGB of the pixel under the cursor?

texts:
I'm writing an SDL2 program, in which I create a SDL_CreateWindow and get its SDL_GetWindowSurface, then I prepare some pixel updates on a separate SDL_CreateRGBSurface and SDL_BlitSurface the result to the window surface before I SDL_UpdateWindowSurface it to the screen.
I would like to have a mouse tooltip feature that would display a dynamic tooltip at the cursor position with some information (such as RGB info of the pixel under the mouse). But the tooltip display should be separate from the pixels of the window surface, not blended into it. Is it possible to do that with SDL2? If so, how would a minimal working example look like? (I googled around but did not see any examples.)


texts:
In creating a video game concept, there are very little video games that offer a 3 team multiplayer FPS (think like Overwatch/Call of Duty but with 3 teams instead of 2). The only 'mainstream' games that offer this are RTS games.

What are the cons of implementing a 3 team multiplayer FPS game?


texts:
I'm making a Mario-Like platformer in Godot, and am going for a N64 style, and I want to lower the resolution of the render, while still having the window being resizable, like in Blender. Is there any way to do this?
Thanks in advance!


texts: Can you export lighting models directly from 3D application to a real time renderer?

texts: is it possible for example to insert lighting in a 3D Model software like 3DSMAX and export an animated model like md5,..etc. and export the lighting too ?


texts: How to create / draw clickable object (such as Button in WinForm) in XNA WP8?

texts:
I am developing a 2D (No 3D in every aspect) Windows Phone 8 turn based tactical games for my college project. I use Monogame.

I want to draw an object similar to Button in windows form, that if the object is tapped / touched, then an event / method started. I am looking for a way to create a similar event like "OnClick" attached on an object, so I know which tile is tapped by the user specifically.

The object is not entirely visible, because I used an empty transparent texture2D (In case you wondered)

Thank you.

(Please feel free to ask anything if my question is not clear enough, and sorry for my jumbled language, if any.)

===============================

FURTHER EXPLANATION :
In front of every sprite, I want to draw a "transparent object" that can run an event when tapped (so it appear like user tapped the character, but behind-code-ly, the "transparent object" which is tapped, because it the one that can receive tap input).

Why I need this kind of object, because if I get the tapped coordinate, the coordinate fetched is relatively based on the viewport, once the map bigger, then it's so hard to calculate the tapped thing. But with the "transparent object", wherever the tile is, I can get which tile is tapped precisely.

I think this also an attempt to make my code as detached as possible by dividing each action into a separate class.


texts:
I make s shader file and drop it on object with material. I wrote this script to run shader when press Space button. All is good except that script not load shader when run the game !! I have to do it manually only !

public Material _shader;
public float timer = 0;

// Start is called before the first frame update
void Start()
{

    _shader = gameObject.GetComponent<Material>(); // Not setting shader !!
    _shader.SetFloat("Vector1_F92326F1", timer);

}

// Update is called once per frame
void Update()
{

    if (Input.GetKeyDown(KeyCode.Space))
    {
        timer += 0.1f;
        _shader.SetFloat("Vector1_F92326F1", timer);
    }

}


texts: LibGDX - Rectangle Collision and Response

texts:
I've been using LibGDX for the past few weeks and I have some problems that I need help on. What I need help on is understanding how to use LibGDX Rectangle class for a platformer.

I found this project on github that seems to be useful.

https://github.com/obviam/star-assault-reboot

I was able to wrap my mind around how this game worked for the most part.

The only thing I can't understand, which is the most essential part of the game, is how the collision detection and response works.

In the project, the BobController class holds the everything that's used to detect collision.

https://github.com/obviam/star-assault-reboot/blob/master/core/src/net/obviam/starassault/controller/BobController.java

I tried going to the website linked in the github project for answers, but it seems to be empty.

Maybe I'm just dumb, but I can't wrap my mind how this works. Even with the comments provided in the project, I still don't understand.

Can someone explain in greater detail how this class handles collision detection and response using the LibGDX Rectangle class.

EDIT:

This is the specific function that I don't understand:

/** Collision checking **/
private void checkCollisionWithBlocks(float delta) {
    // scale velocity to frame units
    bob.getVelocity().scl(delta);

    // Obtain the rectangle from the pool instead of instantiating it
    Rectangle bobRect = rectPool.obtain();
    // set the rectangle to bob's bounding box
    bobRect.set(bob.getBounds().x, bob.getBounds().y, bob.getBounds().width, bob.getBounds().height);

    // we first check the movement on the horizontal X axis
    int startX, endX;
    int startY = (int) bob.getBounds().y;
    int endY = (int) (bob.getBounds().y + bob.getBounds().height);
    // if Bob is heading left then we check if he collides with the block on his left
    // we check the block on his right otherwise
    if (bob.getVelocity().x < 0) {
        startX = endX = (int) Math.floor(bob.getBounds().x + bob.getVelocity().x);
    } else {
        startX = endX = (int) Math.floor(bob.getBounds().x + bob.getBounds().width + bob.getVelocity().x);
    }

    // get the block(s) bob can collide with
    populateCollidableBlocks(startX, startY, endX, endY);

    // simulate bob's movement on the X
    bobRect.x += bob.getVelocity().x;

    // clear collision boxes in world
    world.getCollisionRects().clear();

    // if bob collides, make his horizontal velocity 0
    for (Block block : collidable) {
        if (block == null) continue;
        if (bobRect.overlaps(block.getBounds())) {
            bob.getVelocity().x = 0;
            world.getCollisionRects().add(block.getBounds());
            break;
        }
    }

    // reset the x position of the collision box
    bobRect.x = bob.getPosition().x;

    // the same thing but on the vertical Y axis
    startX = (int) bob.getBounds().x;
    endX = (int) (bob.getBounds().x + bob.getBounds().width);
    if (bob.getVelocity().y < 0) {
        startY = endY = (int) Math.floor(bob.getBounds().y + bob.getVelocity().y);
    } else {
        startY = endY = (int) Math.floor(bob.getBounds().y + bob.getBounds().height + bob.getVelocity().y);
    }

    populateCollidableBlocks(startX, startY, endX, endY);

    bobRect.y += bob.getVelocity().y;

    for (Block block : collidable) {
        if (block == null) continue;
        if (bobRect.overlaps(block.getBounds())) {
            if (bob.getVelocity().y < 0) {
                grounded = true;
            }
            bob.getVelocity().y = 0;
            world.getCollisionRects().add(block.getBounds());
            break;
        }
    }
    // reset the collision box's position on Y
    bobRect.y = bob.getPosition().y;

    // update Bob's position
    bob.getPosition().add(bob.getVelocity());
    bob.getBounds().x = bob.getPosition().x;
    bob.getBounds().y = bob.getPosition().y;

    // un-scale velocity (not in frame time)
    bob.getVelocity().scl(1 / delta);

    }


texts:
I'm facing a problem trying to calculate the AABB on my models after rotation is applied. The rotation is not applied on the vertex positions directly, but in a seperate rotation matrix - just multiplied with the projection matrix and set as uniform. Currently I'm calculating the min/max of the vertexes on all three axes (x, y, z) to calculate the AABB. This works well, as long as the model is unrotated.

AABB calculateAabb() {
    glm::vec3 center, extend;
    glm::vec3 min, max;
    for (size_t i = 0; i < getVertexCount(); ++i) {
      if (positions[i * 3] < min.x){
        min.x = positions[i * 3];
      }
      if (positions[i * 3 + 1] < min.y) {
        min.y = positions[i * 3 + 1];
      }
      if (positions[i * 3 + 2] < min.z) {
        min.z = positions[i * 3 + 2];
      }
      if (positions[i * 3] > max.x) {
        max.x = positions[i * 3];
      }
      if (positions[i * 3 + 1] > max.y) {
        max.y = positions[i * 3 + 1];
      }
      if (positions[i * 3 + 2] > max.z) {
        max.z = positions[i * 3 + 2];
      }
    }
    extend = (max - min) * 0.5f;
    center = min + extend;
    return AABB(center, extend);
  }

The std::vector positions[] contains all vertexes in the order x, y, z - getVertexCount() returns positions.size()/3. My rotation matrix is described by a single angle on the y axis glm::eulerAngleY(glm::radians(angle));.

My question is: is there any way to calculate the AABB for the rotated model without applying the rotation matrix to all the vertexes individually? How can I get min/max values on the axes from a rotated coordinate system?


texts: How do I deal with different "types" of entities in Entity-Component-System model?

texts:
I have CollisionSystem which basically iterates through the array of PhysicsComponent and checks if there was some collision between two entities. But where should interaction code go? And how should I deal with different types of entities? (pseudocode below)

// in collision system
for(e1 in all entities) {
    for(e2 in all entities) {
        if(e1 == e2) continue;
        if(e1 collides with e2) {
            handleCollision(e1, e2);
        }
    }
}

...
// probably in collision system too?
void handleCollision(Entity* e1, Entity* e2) {
    if(e1 has DamageComponent) {
        if(e2 has HealthComponent) {
            e2->HealthComponent->
            reduceHP(e1->DamageComponent->damageAmount);
    //but what if some entities show "Hurt" animation or
    // do some other stuff specific for that type of entity?
        }
    }
    ... // other types of entities
}

What is bad is that this handleCollision code will have lots of if-else conditions as more and more types of entities emerge and the code will be hard to maintain. How can I deal with this?


texts:
I am currently implementing basic shadow mapping in my C++ Custom Engine using GLSL 4.10. It is currently working with basic PCF anti-aliasing and very minimal reduction for unwanted artifacts. Here is a screenshot for reference:

Recently, I have started modifying my shadow map pipeline to reduce shadow acne. After reading through various articles, many suggest either using a bias value, which is subtracted from the depth value being compared to the shadow map

// Shadows
float bias = 0.0005;
vec4 shadowCoordinate = u_worldToShadowMapSpaceTransform * vec4( worldPosition.xyz, 1.0 );
shadowCoordinate.z -= bias;
float shadowValue = textureProj( u_shadowMap, shadowCoordinate );

and or to cull front faces when rendering to the shadow map.

glCullFace( GL_FRONT )
// Render to ShadowMap FBO
glCullFace( GL_BACK )
// Render Scene

Culling front faces reduces most of the shadow acne but creates another problem that none of the articles have mentioned. The screenshot below shows the issue. If you look at the white box in front of horned creature, you will notice the creatures's shadow is cast upon the other side of the box. This is because the front faces of the box are culled which leads the back faces to compare their depth values against geometry to the north of the box.

Naturally, this also leads to these shadows also being cast below the floor as well as above. Here is a screenshot of the bottom of the floor. It is difficult to see but you can see the shadows being cast.

I believe many 3D engines utilize variations of these artifact reduction techniques. So, how do they avoid the shadow casting issue described above?


texts: What are some good resources for creating a game engine in XNA?

texts:
I'm currently a student game programmer working on an indie project. We have a team of eleven people (five programmers, four artists, and two audio designers) aboard, all working hard to help design this game. We've been meeting for months now and so far we have a pretty buffed out Game Design Document as well as much audio/visual concept art. Our programmers are itching to progress on our own end.

Each person in our programming team is well versed in C++, but is very familiar with C#. We have enough experience and skill that we're confident that we will be successful with our game, and we're looking to build our own game engine in XNA as it seems like it would be worth our time and effort in the end.

The game itself will be a 2D beat 'em up style game to be released over xbox live and the PC. It's play style will be similar to that of Castle Crashers or Scott Pilgrim vs The World. We want to design the game engine to allow us to better implement our assets into the game as well as to simplify the creation of design elements/mechanics.

Currently between our programmers, we have books such as "XNA 4.0" and "Game Coding Complete, Third Edition," but we'd still like more information on both XNA and (especially) building a game engine from scratch. What are any other good books, websites, or resources we could use to further map out and program our game engine?


texts: OpenGL: why do I have to set a normal with glNormal?

texts:
I'm learning some basics of OpenGL but I'm wondering why there is a call glNormal to set the normal of vertices.

If I create a simple triangle like this:

glBegin(GL_TRIANGLES);
    glVertex3f(0,0,0);
    glVertex3f(1,0,0);
    glVertex3f(0,1,0);
glEnd();

Shouldn't the normals be defined implicitly by the type of the geometric primitive? If I don't set a normal will OpenGL calculate it?


texts: I'm looking to work over the internet in a team of people to make a game. I'm not looking to make a profit, I just want the experiance. Where can I find similary minded persons?


texts: Do any games support different lighting effects according to whether a surface is wet or dry?

texts:
I've noticed that when driving at night, when the road surface is dry, my headlights appear to illuminate much further than when the road surface is wet. I presume that this is due to the differences in how my headlights is being reflected under wet and dry conditions.

In dry conditions, my headlight will reflect in a diffuse way, producing producing enough scatter to allow me to see the texture of the road for quite a long distance. In the wet however, the thin layer of water over the road surface, combined with the shallow angle of incidence, causes the light from my headlights to be reflected in a specular way and not back scattered to me.

Thinking about this, I realised that I can't remember ever having seen this effect being reproduced in a game.

Has this wet/dry effect been implemented in any game?

If so, what is the name of the technique used to produce the effect?
If not, could this effect be produced without ray-tracing?


texts: How can I let a player post their score to Facebook at the end of the game?

texts: I have an HTML5 game on my site, and at the end, I want the user to have the option of posting their score to their Facebook wall. Is there an easy way to ask to post something to Facebook?


texts: How can I shoot an arrow if I know the shot power and target?

texts:
I am trying to shoot an arrow at a target with a 100% success rate.  Given the initial force applied to the arrow, the gravity, the location of the archer, and the location of the target, how can I do this in Unity?

I have read How can I find a projectile's launch angle?, and it contains the equation I am using:

However, this is only accurate when I am at the maximum distance from the object given its power.  (Above the maximum distance means that the arrow cannot reach the target.)  The closer I move to the target, the less accurate the arrow shot becomes, as it travels past the target.  The angle is increased resulting in the arrow traveling a shorter distance as I'd expect, but it is not increased by enough.

The script spawns an arrow (a simple sphere) and launches it towards a target.  It fires once per second, but the closer to the target the archer is, the more inaccurate the arrow is.  The case of the archer being too far from the arrow is not handled, but that is not my concern right now.

using UnityEngine;
using System.Collections;

public class Archer : MonoBehaviour
{
    public GameObject arrow; //Simple 3D Sphere
    public GameObject target; //Simple 3D Cube
    public float power = 25.0f;
    public Vector3 aim;

    private void Start()
    {
        StartCoroutine(ShootArrows());
    }

    private IEnumerator ShootArrows()
    {
        while (true)
        {
            yield return new WaitForSeconds(1.0f);
            Vector3 spawnPosition = new Vector3(transform.position.x, transform.position.y, transform.position.z);
            GameObject arrowInstance = Instantiate(arrow, spawnPosition, Quaternion.identity) as GameObject;
            arrowInstance.GetComponent<Rigidbody>().AddForce(Aim() * power, ForceMode.VelocityChange);
        }
    }

    private Vector3 Aim()
    {
        float xAim = target.transform.position.x - transform.position.x;
        float yAim = Mathf.Rad2Deg * Mathf.Atan(((Mathf.Pow(power, 2) + Mathf.Sqrt((Mathf.Pow(power, 4) - (-Physics.gravity.y) * (-Physics.gravity.y * Mathf.Pow(HorizontalDistance(), 2) + 2 * VerticalDistance() * Mathf.Pow(power, 2))))) / -Physics.gravity.y * HorizontalDistance()));
        float zAim = target.transform.position.z - transform.position.z;
        Vector3 aim = new Vector3(xAim, yAim, zAim).normalized;
        return aim;
    }

    private float HorizontalDistance()
    {
        float xDistance = target.transform.position.x - transform.position.x;
        float zDistance = target.transform.position.z - transform.position.z;
        float distance = Mathf.Sqrt(Mathf.Pow(xDistance, 2) + Mathf.Pow(zDistance, 2));
        return distance;
    }

    private float VerticalDistance()
    {
        return Mathf.Abs(target.transform.position.y - transform.position.y);
    }
}

My best guess is that I am using the equation correctly, but I am plugging the angle into Unity wrong.  Why is my script giving me inaccurate results?


texts: What is the relationship between ID3D10Buffer and ID3DX10Mesh?

texts:
I'm new to Direct3D, I'm currently learning Direct3D 10 in Uni. I'm confused about buffers and meshes. We've been shown code to draw cubes etc that use ID3D10Buffer. However I've seen some stuff online that uses ID3DX10Mesh to draw cubes.

What's the advantage/disadvantage for each of them? ID3DX10Mesh seems more versatile, I guess this comes with a cost?


texts:
Hi there,
I'm learning the impulse based physics engine these days. Can someone please check my image about solving a contact( a sphere resting on ground) , and please let me know where is wrong.
Thanks for any help!


texts:
I had to force Unreal to use my integrated graphics card because VR wasn't working with my NVidia card.

When I did this, the framerate dropped terribly and it popped up a dialogue "Frame rate's bad, would you like to lower quality?"  Which I said yes to.

Now, I've set it to use my NVidia card again, but it's stuck in this low quality state.  It seems to be tied to the engine, not the project.  All my 4.9 projects run in this garbage state, but my 4.10 projects are fine.

How can I reset the engine player settings for 4.9?


texts: Is there any way for us to use frame-sequential stereo with WebGL without having to boot into Windows and use the DirectX hack?


texts: iOS unity game was ~60mb on testflight but now its +400mb on release, why is that ?

texts:
I really have nothing else to add except that bitcode wasn't enabled, the same game was ~60Mb when we were testing it with TestFlight, after uploading it to the store the game just became 422Mb, why is that ?

Thanks!


texts: 2D Animation based on Time.deltaTime has problems when the game performs long operations

texts:
I animate my 2D sprite using the Update() method:

float timer = 0.0f;
float delayPerFrame = 0.04f;

void Update() {
    timer += Time.deltaTime;
    if (timer >= delayPerFrame) {
        timer = 0;
        // Logic to display the next frame
    }
}

As you can see, it is pretty simple: every 0.04 seconds the next frame will be set.

But sometimes, my game needs to do some exhausting processing (like loading large scenes and whatnot), which causes a tiny little lag in the game. When this happens, my sprite begins with a wild, fast animation. Then eventually it resumes at a normal pace.

I imagine this is because the lag caused the Time.deltaTime value to skyrocket for a period of time. I am also under the impression that Update() is called too often during such period (although that shouldn't matter).

I don't want to use existing animation features of Unity. My game is already built under this particular piece of logic, so I'd like to fix it.

Using FixedUpdate() doesn't help. I can also confirm that Time.deltaTime does indeed peak at the beginning.

Note that this occurs only after doing an exhaustive operation. If you spawn a sprite of these in the middle of the game, everything will go smoothly. But if you spawn them immediately after doing something like loading a large scene, then they will have some sort of boost at the beginning.


texts:
I have been experimenting with Apple's new SceneKit for fun, but I cannot seem to figure out how to input vertex data without loading a .dae file.

Does anybody who has been testing SceneKit have any idea how to set or modify vertex data?


texts: Spine + MonoGame > viewMatrix / camera offset

texts:
we switched from frame by frame animations to Spine (this animation software).

The issue I am facing now, that it am unable to fit it in our coordinate system. (simple 2D game) I guess there is an issue with the projection or some other matrix-related stuff that I am not really good in. (It works perfectly in an empty project, Example provided here: https://github.com/EsotericSoftware/spine-runtimes/tree/3.7/spine-monogame
It's probably a one-liner, but I cant figure it out.
Target in this case I want to draw the tree at world position 100,100 - so the top left corner.

This is my sample class for spine objects:

public class SpineObject
    {
        private SkeletonRenderer skeletonRenderer;
        private Skeleton skeleton;
        private AnimationState state;
        private SkeletonBounds bounds = new SkeletonBounds();
        private string assetsFolder = "Content/Animations/";

        public SpineObject()
        {
            skeletonRenderer = new SkeletonRenderer(Orbs.graphics.GraphicsDevice);
            skeletonRenderer.PremultipliedAlpha = false;

            String name = "Objects/tree1/tree1";
            String atlasName = "Objects/tree1/tree1";

            Atlas atlas = new Atlas(assetsFolder + atlasName + ".atlas", new XnaTextureLoader(Orbs.graphics.GraphicsDevice));

            SkeletonJson json = new SkeletonJson(atlas);
            json.Scale = 1;
            SkeletonData skeletonData = json.ReadSkeletonData(assetsFolder + name + ".json");
            skeleton = new Skeleton(skeletonData);
            AnimationStateData stateData = new AnimationStateData(skeleton.Data);
            state = new AnimationState(stateData);
            state.SetAnimation(0, "animation", true);

            skeleton.X = 100;
            skeleton.Y = 100;
        }

        public void Update(GameTime gameTime)
        {
            state.Update(gameTime.ElapsedGameTime.Milliseconds / 1000f);
            skeleton.UpdateWorldTransform();
            state.Apply(skeleton);
        }

        public void Draw(Matrix viewMatrix)
        {
            ((BasicEffect)skeletonRenderer.Effect).Projection = Matrix.CreateOrthographicOffCenter(0, Orbs.graphics.GraphicsDevice.Viewport.Width, 0, Orbs.graphics.GraphicsDevice.Viewport.Height, 1, 0);
           ((BasicEffect)skeletonRenderer.Effect).View = Orbs.camera.GetViewMatrix();

            skeletonRenderer.Begin();
            skeletonRenderer.Draw(skeleton);
            skeletonRenderer.End();
        }
    }

The Draw-Call looks like this:

[...]
Animations.SpineObject tree1 = new Animations.SpineObject();
Camera2D camera = new Camera2D(GraphicsDevice.Viewport);
Matrix viewMatrix  = camera.GetViewMatrix();
[...]

protected override void Draw(GameTime gameTime)
{
    spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, SamplerState.PointClamp, null, null, null, viewMatrix);
    //Draw Map Layers and Stuff
    tree1.Draw(viewMatrix);
    spriteBatch.End();
}

I guess the tree is beeing drawn somwhere far off, so how do I get the trees X/Y value to be on par with the worlds coordinates?


texts:
I'm a beginner in game development and as a little project I thought I should try to do a top-down racer game much like the good old Slicks n Slide.

I've seen several tutorials and questions about steering and car physics but most is more complicated than what I need and uses box2d with wheels turning and so on.

I want it to keep simple and only want three buttons. Accelerate, turn left and turn right.
And my "car" is for now just a circle :-)

My question is how to do the steering. If someone can explain it simple to me I would be very thankful.
I know I need to use sin and cos to get the steering angle but I haven't figured out how.


texts: "Breakout" script fails to trigger win after destroying the last brick

texts:
The behavior I want is that when all the bricks are destroyed, the last brick's OnCollisionEnter2D handler calls SimulateWin(), triggering the next level.

For some reason SimulateWin() is never called.

using UnityEngine;
using System.Collections;

public class Brick : MonoBehaviour {

    public static int brickCount = 0;
    public int maxHits;
    public int timesHit;
    private LevelManager levelmanager;

    void Start ()
    {
        timesHit = 0;
        levelmanager = GameObject.FindObjectOfType<LevelManager>();
    }

    void OnCollisionEnter2D(Collision2D col)
    {
        timesHit++;
        Debug.Log("Collision happened with " + col.gameObject.name);

        if(timesHit >= maxHits)
            Destroy(gameObject);

        if(GameObject.FindObjectOfType<Brick>() == null)//Not entering this if
            SimulateWin();//this is never called
    }

    void SimulateWin()//This is the function that is supposed to be called when all the bricks are destroyed.
    {
        levelmanager.LoadNextLevel();
    }

}


texts: How to implement pixel level collision detection?

texts:
I'm developing a simple game engine for practise purpose, and I used codes like this to do collision detection (fake code):

bool PhysicalObject.isCollideWith(rect: PhysicalObject) =>
  x + width >= rect.x && rect.y <= y + height &&
    x <= rect.x + rect.width &&
    y <= rect.y + rect.height

But this treats all objects as a rectangle.
What I want is to detect collision when two objects are overlapping on pixel level (I used java.awt.Graphics to draw my game objects).

What's the best way of doing that? Can I create a two-dimension array that represent each pixel and store the pointer to the game object that the corresponding pixel belongs to?


texts: How to setting firebase remote config for unity?

texts:
lets to the point, so i want to make some configuration with my game to show Ads but I avoid to update game version too much, because of that I choose firebase remote config with this I can update setting/configuration without update the game version.
there is document for this but not very clear for newbie like me, you can check it here https://firebase.google.com/docs/remote-config/use-config-unity
I already make the script like on doc, but I don't understand how its work on show data because error string format, which is what I know on this firebase console is int format

the script like this :
public static _FirebaseRemoteConfig instance;

    private void Awake()
    {
        instance = this;
    }

    Firebase.DependencyStatus dependencyStatus = Firebase.DependencyStatus.UnavailableOther;
    // Use this for initialization
    void Start()
    {
        Firebase.FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task =>
        {
            dependencyStatus = task.Result;
            if (dependencyStatus == Firebase.DependencyStatus.Available)
            {
                InitializeFirebase();
            }
            else
            {
                Debug.LogError(
                    "Could not resolve all Firebase dependencies: " + dependencyStatus);
            }
        });
    }

    public void InitializeFirebase()
    {
        System.Collections.Generic.Dictionary<string, object> defaults =
            new System.Collections.Generic.Dictionary<string, object>();
        defaults.Add("config_test_string", "default local string");
        defaults.Add("config_test_int", 1);
        defaults.Add("config_test_float", 1.0);
        defaults.Add("config_test_bool", false);

        Firebase.RemoteConfig.FirebaseRemoteConfig.SetDefaults(defaults);
        Debug.Log("Remote config ready!");
    }
    public void FetchFireBase()
    {
        FetchDataAsync();
    }
    public void ShowData()
    {
        Debug.Log("maxCountToShowAdmob: " +
            Firebase.RemoteConfig.FirebaseRemoteConfig.GetValue("MaxCountShowIntersitialAds").LongValue);
    }

    // Start a fetch request.
    public Task FetchDataAsync()
    {
        Debug.Log("Fetching data...");
        System.Threading.Tasks.Task fetchTask = Firebase.RemoteConfig.FirebaseRemoteConfig.FetchAsync(
            TimeSpan.Zero);
        return fetchTask.ContinueWith(FetchComplete);
    }

    void FetchComplete(Task fetchTask)
    {
        if (fetchTask.IsCanceled)
        {
            Debug.Log("Fetch canceled.");
        }
        else if (fetchTask.IsFaulted)
        {
            Debug.Log("Fetch encountered an error.");
        }
        else if (fetchTask.IsCompleted)
        {
            Debug.Log("Fetch completed successfully!");
        }

        var info = Firebase.RemoteConfig.FirebaseRemoteConfig.Info;
        switch (info.LastFetchStatus)
        {
            case Firebase.RemoteConfig.LastFetchStatus.Success:
                Firebase.RemoteConfig.FirebaseRemoteConfig.ActivateFetched();
                Debug.Log(String.Format("Remote data loaded and ready (last fetch time {0}).",
                    info.FetchTime));
                break;
            case Firebase.RemoteConfig.LastFetchStatus.Failure:
                switch (info.LastFetchFailureReason)
                {
                    case Firebase.RemoteConfig.FetchFailureReason.Error:
                        Debug.Log("Fetch failed for unknown reason");
                        break;
                    case Firebase.RemoteConfig.FetchFailureReason.Throttled:
                        Debug.Log("Fetch throttled until " + info.ThrottledEndTime);
                        break;
                }
                break;
            case Firebase.RemoteConfig.LastFetchStatus.Pending:
                Debug.Log("Latest Fetch call still pending.");
                break;
        }
    }


texts: In Unreal Engine 4, how do I get the component's "game object" via C++?

texts:
I have an ACharacter instance with a weapons component that inherits from UActorComponentattached to it. I'm currently writing code that instantiates a weapon actor and attaches it to the ACharacter instance.

What I'm having trouble with is finding out how to get a reference to the ACharacter from the weapons code. In Unity, this would be a simple this.gameObject or FindComponent<Character> call, assuming the component belongs to the same transform.

Thank you!


texts: Use of FlxG.camera.follow to follow a character vertically

texts:
I am developing a prototype for a game in Flixel in which a character floats upward continually to traverse the level. I would like to have a "tall" layout for levels and set the FlxG.camera to follow the character as he floats upward. My issue is in understanding the proper use of FlxG.camera. I have my game constructor coded as follows:

package
{
    import flash.display.Sprite;
    import org.flixel.*;

    [SWF(width="640",height="480",backgroundColor="#000000")]
    public class MyGame extends FlxGame
    {
        public function MyGame()
        {
            super(320,240,PlayState,2);
            forceDebugger = true;
        }
    }
}

In the override of create() in the PlayState.as file I attempt to set the camera to follow the player as follows:

public var TheClimber:BalloonHero;

        override public function create():void
        {
            /*set background color*/
            FlxG.bgColor = FlxG.BLUE;

            /*Set data for player*/
            TheClimber = new BalloonHero(FlxG.width/2-5,480);

            /*Add camera and set it to follow The Climber*/
        //which will automatically set the boundaries of the world.
        FlxG.camera.setBounds(0,1280,640,1280,true);
        FlxG.camera.follow(TheClimber,FlxCamera.STYLE_PLATFORMER);

            /*add player to the game*/
            add(TheClimber);
        }

I assumed this would set the camera bounds to twice the height of the SWF background(i.e. the FlxG height) and then scroll the background along with the specified FlxObject(TheClimber in this case) until it had reached the height of the game. However, I must be going about it incorrectly because when the zoom is 2 and the game height 720 the camera starts at the top of the screen with the player character not visible at the bottom of the game height.
Is there a way to start with the camera/game focused on the bottom of the game object(FlxG.height) ? Or am I going about this the wrong way and have other issues with the way I am using the camera? Thanks in advance.


texts: How could I prevent a player from cheating by taking a picture with their phone?

texts:
I'm making a game with a primary mechanic of a very limited amount of time that you can see a maze, and must navigate it blindly as much as possible to conserve your torch fuel. It's possible you could snap a photo with your phone and then beat every level.

My initial thought is, "so what?" if someone wants to cheat, they are just taking the fun out for themselves. But I'd like to add a leaderboard to the game, which would make cheating even more enticing to some players who value bragging rights over having fun.

The obvious answer is that there is NO way to prevent this.... but is there? I am trying to find an out-of-the-box idea that renders cheating nearly impossible or pointless.
Any ideas?
Curious if anyone has any thoughts first without altering your perspective by playing my game first. Let me know if you want the link and I'll give it to you.
Thanks!


texts: Game Editor - When screen is clicked, how do you identify which object that is clicked?

texts:
I'm trying to create a Game Editor, currently just placing different types of Shapes and such. I'm doing this in Windows Forms while drawing the 3D with XNA. So, if I have a couple of Shapes on the screen and I click the screen I want to be able to identify "which" of these objects you clicked.

What is the best method for this? Since having two objects one behind the other, it should be able to recognize the one in front and not the one behind it and also if I rotate the camera and click on the one behind it - it should identify it and not the first one.

Are there any smart ways to go about this?


texts: Back button press on Windows Phone 8.1 Monogame

texts:
I am developing a simple game for windows phone and I got stuck when at the handling the back button press.

I have been searching for a while on google but I have not found anything that could work for me. I have seen a function GamePad but i couldn't find on which namespace is this function located, and if it is working on WP8.1.

So my question is, how can I set up a function in which I can handle some code when user press back button.

Thanks.


texts: Best Practices for Texturing Large Objects

texts: Kind of a 3D graphics newbie here.  This is the biggest prop I've ever tried to texture, and I'm kind of stumped.  How do you get a decent resolution on large meshes like this without exporting enormous maps?  Texture atlases?  Tiling textures?  And what's the best way to set up the UVs, if so?


texts: How to change the Android NDK jni calls dynamically?

texts:
Some people are using NativeActivity for working with Android projects exclusively in C++, but this also carries some disadvantages, so I, like many others, decided that I'd use instead a Java glue code; just a single Java file wrapping all things I need from C++, where pretty much everything runs.

With this said, as far as I know, using this Java code forces me to implement the native function calls in Java, where the Java calls a function that is actually called within the C++ part of the project, with the JNI.

In C++, the native function being called has a prototype like this:

JNIEXPORT void Java_com_package_name_nativeTouchDown( JNIEnv*  env, jobject thiz, jfloat x, jfloat y );

My problem is that I started working with scripts exclusively and would like to find a way to not having to recompile the C++ code anymore. So when I want to make a new project, I just copy-paste my C++ compiled code and change the scripts and be allowed to change the package name of the app without any recompilation.

Is this possible somehow? At the point I am at, I simply have to recompile my C++ to conform to a new package name (the one in the format com.company.game). Can't I make C++ fully abstracted from this package name or change it dynamically?


texts:
For fun I am trying to replicate the mechanics from The Floor is Jelly. So far I have successfully created "jelly islands/blocks" which are represented by an array of points and then drawn by using quadratic curves between the points. I am also able to get the jelly effect by having each point hold a velocity value as well as a relationship with its neighboring points to allow the springyness effect.

The above works well and gives a good representation of how the actual game seems to do it.

The part that I am kind of stuck on is how to resolve collisions with the character. I can successfully detect when my character (currently just a square represented by 4 points) comes into contact with the jelly island. However, I cannot think of an efficient way to make it "stick" to the ground and then smoothly interpolate along the curve once a force is applied to the jelly that causes it to move. Also, I want the character to stick to the ground unless the user "jumps" which means that the character should follow the ground through it's wobbles rather than go up into the air.

I could pass the character controller the array of points representing the island that it is currently colliding with, but then iterating through all of the points and finding the points closest to the character seems like a lot of work to do on each frame. In addition I am still not sure how I would get the correct position of the character along the curved ground (particularly when it is wobbling).

Any suggestions are appreciated

Update

Clarification as I fear that I wasn't clear enough above. What I mean when I say that I can successfully detect when my character comes into contact with the jelly island is that I am currently using the Point in Polygon algorithm to detect when the jelly island is not moving/wobbling this breaks of course once the jelly island has a force applied to it.

To fix this I have been looking into breaking the island into many line segments along the curves (how collisions with quadratic/bezier curves are usually handled), but I'm afraid that this will be too much work to do on each frame. In addition I am still stuck on the problems described above.


texts:
I am taking Computer Graphics course this semester and we have a video game competition. I am making racing game with simulated dynamics. Our professor told us that we don't have to do much of a modelling but since we haven't started the gaming part and since I have free time I want to model the car.

My question is firstly which software do you recommend to design game components? I know Maya right now. Secondly, if I design the car or any other part, what should its polygon count in order to run game smoothly? I can design pretty much everything but I assume that it is hard to design low-poly models.


texts: Difference between unity scripting backend IL2CPP and Mono2x

texts:
IL2CPP is a Unity-developed scripting back-end which you can use as an alternative to Mono when building projects for some platforms. Note - IL2CPP is only available when building for the following platforms:

Android AppleTV, iOS*, Nintendo 3DS, Nintendo Switch, Playstation 4
Playstation Vita, WebGL* ,Windows Store, Xbox One

I have a project(unity 5.2) which has switched for Android deployment. I tried to switch my scripting backed from Mono2x to IL2CPP and its showing me that

  IL2CPP on Andriod is experimental and unsupported

So, my simple question is that if it is still not supported then why the option has included, what is the fundamental difference between IL2CPP and Mono2x. Why I switched to IL2CPP scripting backend ? what are its pros and cons?

I have also checked in unity 5.5.2 there is not IL2CPP option in windows platform deployment.


texts: Unity: Apply an Image Effect on one layer only

texts:
Please consider this simple scene.

It’s composed of 3 different game objects. 1 background image + 1 static character image + 1 small part (with the pet) that is changed at runtime to perform an animation.

The Background is rendered using a dedicated camera. The character (static + anim) is rendered using another dedicated camera. Both camera are set to Depth Only with a different culling mask (each camera renders only its part). Note that the camera in charge of the character has a greater depth than the one in charge of the background (i.e. Character is rendered after the background).

I need to apply an image effect only on the character camera, but I can’t manage to find a way for this effect to not affect the background.

Example here with a Vortex effect on the character camera.

How would you do such a trick?


texts: Use constant force to hold something in position

texts:
This may actually be more of a Physics.SE question but since im doing this in Unity I figured I'd ask here.

I am playing around with the Constant Force component and have a sphere constrained with a linear configurable joint (y-axis free). With one key I apply a force in one direction to get it moving, but then when i press another key, I want to stop it and hold exactly in place by using an opposite force. So even if some other rigid body hits the sphere, it wont move until I remove a force.

Unfortunately, Unity doesnt allow more than one constant force on a gameobject (probably a good reason, not sure exactly) and I know if I do a net force, that it would just end up being 0, which would kind of work but the sphere would move if it gets hit.

Another thing I tried was to take the spheres current force and constantly flip it from positive to negative every FixedUpdate but that didn't seem to work at all.

I know the quick and easy way would be to just set velocity to zero, but I see tons of comments saying that modifying velocity directly breaks the physics, is bad form, etc. and I want to do this as properly as possible.

The best way I can describe what I'm trying to do is like that science experiment where you take a ping-pong ball and use a blower to push just enough air to counter gravity and the ball seems to hover in place. My only difference is that my constraint is side to side instead of up/down.


texts: How to move around in a map and remember position?

texts:
I am working on sound labyrinth game. My game is about a person getting trapped in the basement and the only way to navigate and get out is through sound. I have created a map over the basement and for each square there has to be a sound.

The player starts in b5 with an intro sound and then has to move forward using the arrow keys. I've created this bit of code that plays a sound when forward arrow (keycode === 38) is pressed:

var thriller=new Audio("thriller.mp3");

document.addEventListener('keydown',
function (background) {
    if (background.keyCode === 38){
        thriller.play();
    }
}, false);

My question is:

How does the code know in which square the player is situated? Is there some smart way in which I can systematize the squares and the sounds they represent?


texts: Armature's bone can't be rotated in Unity when I'm trying to rotate its chest toward its looking direction?

texts:
I want to rotate my character's chest, so its looking direction will be visualised correctly.

But I think that the animation controller doesn't let me.

I logged its rotation before and after I set it, and after setting, it's correct, but next frame before I would set it, it's always snapped back.

How could I make my character's animation transformed, based on its looking direction?

This is the code:

Debug.Log(Chest.localRotation.eulerAngles);
Chest.localRotation = Quaternion.Euler(90, 90, 0);
Debug.Log(Chest.localRotation.eulerAngles);


texts:
I'm making a top down 2D game in Unity, here's my doubt: how can I add "hole" tiles to it, so the player could fall (something like Zelda: Link to the past, or the water tiles in Enter The Gungeon)?

The solution I thought is to put tags on each tile (ground, hole, trap, etc), put the player on Z = -5 and use the 3D Physics.Raycast to check in which tile the player is. But that doesn't seem optimized, I would need to spam colliders in every tile and use the Raycast at each frame. Can you guys give me better alternatives?

Thanks a lot! :)


texts:
When I was younger I used to play games a lot for hours. I would say I got addicted to them. Now I'm a software developer and was wondering if games are explicitly designed to be addicting?

Game developers are interested in keeping their users playing as long as possible. I've read about Operant Conditioning and Virtual Skinner Boxes. According to psychologists, most games use a fixed reward system to get the player hooked at first. For example, you can level up pretty fast in beginning. Then reward frequency gradually drops, but player keeps playing because they are hooked. In the end, you switch to variable reward frequency, which means rewards occur randomly and rarely. By this stage, the player might not even enjoy the game, but still play in order to get his reward fix and the resulting good feeling from it. This is very similar to how rats are conditioned in Skinner boxes.

Rewards can be in the form of social status recognition in the game world, working hard for a virtual item therefore giving it great value when acquiring it, feeling in control and power that are not met in the real world, escaping to somewhere else, being able measure progress to some goal and getting instant feedback. If the player abstains from the game, a punishment is applied, i.e losing social status or items. After a while, the rewards will be associated with the game itself and therefore even the sight of the game can evoke craving, much like in case of Pavlov's dog

In addition, there is another research which states that the immersive nature of video games, the rich visual stimulus from realistic graphics, the complex thinking required for playing, great autonomy and fast feedback loop can result in increased dopamine levels in the brain, and create a sense of flow. Combined with an effective rewarding system, games can stimulate the feel good centres of the brain. This means that after several sessions, the player needs to play longer in order to achieve the same dopamine levels as before. Some even experience euphoric feeling and relief from withdrawal when they play. They replace real world with game world and focus on in-game motivations only. Players may stop showering for long time, have reduced hygiene, become socially isolated, drop out of school, become overweight, withdraw from their family, have dreams about the game, think and plan about the game while doing other activities, stop doing non game related activities, have trouble concentrating.

References:

http://www.cracked.com/article_18461_5-creepy-ways-video-games-are-trying-to-get-you-addicted.html

http://www.betabunny.com/behaviorism/Conditioning.htm

http://www.world-science.net/exclusives/081111_gaming.htm

Can a game be simply too fun to resist?


texts: Is there a simple way to make a connected Xbox controller vibrate with Monogame? I know that GamePad.SetVibration is not implemented but it seems like this would be a common enough problem that there would be an easy answer.


texts: Is it possible to control what script is active on what sprite/object in Unity?

texts:
I have 2 objects, and I have a script which makes the player change their characteristics. I applied the script to both, and as you'd expect, pressing X button does the color, size, translation change effect on both objects at the same time.

Now how can I give the player the choice thanks to a key input, to be able to choose which item to apply the script to?

I am trying to make it work like a toggle..

if (toggle == 1) { // player can only change color of item 1 }

else if (toggle == 0) { //player can only change color of item 2 }

So what's the syntax to be able to select if a script is enabled or not on 2 different sprites?


texts: Proper way to maintain Vertex Buffer Objects

texts:
I've started learning WebGL, currently I'm building a 2D lighting system, but there is some confusion going on inside my head.

How the lighting works is based on this tutorial http://archive.gamedev.net/archive/reference/programming/features/2dsoftshadow/default.html (probably the most linked article of the genre).

My question is about the proper way to store/create/update the Vertex Buffer Objects of the polygons.

Currently I have something like:

//-- during initialization of each polygon
//build vertices from the provided points
//[...]
//create the VBO
this._VBO = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, this._VBO );
gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.DYNAMIC_DRAW );

//-- during rendering of each polygon
gl.bindBuffer( gl.ARRAY_BUFFER, this._VBO );
gl.enableVertexAttribArray( program.aVertexPosLoc );
gl.vertexAttribPointer( program.aVertexPosLoc, 3, gl.FLOAT, false, 0, 0 );

The vertices array is created only one time at the top of the file, and reused for each new polygon, the motive to do that is to avoid the creation of various Float32Arrays per object.

//top of file
var vertices = new Float32Array( 20 * 3 ); //maximum of 20 points

It's okay to have one VBO for each object? I was thinking about the possibility of a single VBO, but I don't understand how I can make it work with only one.
The number of vertices can vary between one polygon and another, so how I'm going to store that?

Currently I'm not taking into consideration textures, however, answers that already take they into account are welcome.


texts:
I'm making an infinite runner game in Unity 3D. I have it so that platforms spawn and move backwards toward the player and they are destroyed once past the player. Over time when the platforms are spawned, the position they're spawned at gets more and more inaccurate. Sometimes they over lap slightly and sometimes there are small gaps in between them. And as the game is continuously played, it gets worse and worse. You can watch the video below to see what I mean. This is the script I use to spawn the object
 public GameObject[] objectSpawned;

 public PlatformKiller myPlatformKiller;

 void Start()
 {
     myPlatformKiller = GameObject.Find("PlatformKiller").GetComponent<PlatformKiller>();
 }

 private void Update()
 {
     if (myPlatformKiller.readyForSpawn)
     {
         int rand = Random.Range(0, objectSpawned.Length);
         Instantiate(objectSpawned[rand], transform.position, transform.rotation * Quaternion.Euler (-90f, 0f, 0f));
     }
 }

Here is a video so you can see what I'm talking about: https://youtu.be/eASouQlTsqs
Also, I know the exact unit size for each platform is 11.92. I know this because I added a c# script to each one that shows me the vector3 values. There are originally 20 platforms. And to know exactly where to spawn the object I did 11.92*20 = 238.4. And the first platform is at -4.78. So I subtracted that from 238.4 and got 233.62. So a z position of 233.62 is the correct place to spawn the object. I just wanted to include that in there so you know that the spawner gameobject is in the right place. Please let me know if there is any additional information about this that I can give you. Everything should theoretically work I think, so I seriously have no idea what to do. Thanks for your help!
readyForSpawn is set in my PlatformKiller script shown below:
public bool readyForSpawn;

void Update()
{
    readyForSpawn = false;
}

void OnTriggerEnter(Collider target)
{
    if (target.tag == "Floor")
    {
        readyForSpawn = true;
        Destroy(target.gameObject);
    }
}

And that script is attached to PlatformKiller Game Object:


texts: Why am I not getting an sRGB default framebuffer?

texts:
I'm trying to make my OpenGL Haskell program gamma correct by making appropriate use of sRGB framebuffers and textures, but I'm running into issues making the default framebuffer sRGB.

Consider the following Haskell program, compiled for 32-bit Windows using GHC and linked against 32-bit freeglut:

import Foreign.Marshal.Alloc(alloca)
import Foreign.Ptr(Ptr)
import Foreign.Storable(Storable, peek)
import Graphics.Rendering.OpenGL.Raw
import qualified Graphics.UI.GLUT as GLUT
import Graphics.UI.GLUT(($=))

main :: IO ()
main = do
    (_progName, _args) <- GLUT.getArgsAndInitialize
    GLUT.initialDisplayMode $= [GLUT.SRGBMode]
    _window <- GLUT.createWindow "sRGB Test"

    -- To prove that I actually have freeglut working correctly.
    -- This will fail at runtime under classic GLUT.
    GLUT.closeCallback $= Just (return ())

    glEnable gl_FRAMEBUFFER_SRGB
    colorEncoding <- allocaOut $ glGetFramebufferAttachmentParameteriv
        gl_FRAMEBUFFER gl_FRONT_LEFT gl_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING
    print colorEncoding

allocaOut :: Storable a => (Ptr a -> IO b) -> IO a
allocaOut f = alloca $ \ptr -> do
    f ptr
    peek ptr

On my desktop (Windows 8 64-bit with a GeForce GTX 760 graphics card) this program outputs 9729, a.k.a. gl_LINEAR, indicating that the default framebuffer is using linear color space, even though I explicitly requested an sRGB window. This is reflected in the rendering results of the actual program I'm trying to write - everything looks washed out because my linear color values aren't being converted to sRGB before being written to the framebuffer.

On the other hand, on my laptop (Windows 7 64-bit with an Intel graphics chip), the program prints 0 (huh?) and I get an sRGB default framebuffer by default whether I request one or not! And on both machines, if I manually create a non-default framebuffer bound to an sRGB texture, the program correctly prints 35904, a.k.a. gl_SRGB.

Why am I getting different results on different hardware? Am I doing something wrong? How can I get an sRGB framebuffer consistently on all hardware and target OSes?


texts: ThreadAffinity being changed by OpenGL / ChoosePixelFormat

texts:
If I change thread affinity and then create the window used in my OpenGL game it changes the thread affinity to something else. I tracked down the exact API call (ChoosePixelFormat) which changes it by calling setThreadAffinityMask after and before all the API calls. Strangely enough it is only the first call to ChoosePixelFormat which exhibits this behaviour. Is this when the OpenGL driver initializes itself and perhaps changes the thread affinity?

Has this been seen by anyone else and is there a reason why it is happening? For what it's worth I have a Radeon 290.


texts: LibGDX - Check if currently on Android/Desktop

texts: I'm using LibGDX and flixel-android to build a Desktop/Android game. It feels like there should be a way of checking to see if you're currently being run on an Android device, the Desktop, and so on, but I can't find it anywhere. Am I supposed to just pass it down from the individual launchers? Surely LibGDX can just tell me?


texts:
I have a Unity3D Game for Android, in this game I'm using the Unity IAP System, all works fine, but I'm not able to get if the player doesn't have any of the three subscriptions that I have available.
My current code is this:

  public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
    {
        // Purchasing has succeeded initializing. Collect our Purchasing references.
        Debug.Log("OnInitialized: PASS");
    m_GooglePlayExtensions = extensions.GetExtension<IGooglePlayStoreExtensions>();
        // Overall Purchasing system, configured with products for this application.
        m_StoreController = controller;
        // Store specific subsystem, for accessing device-specific store features.
        m_StoreExtensionProvider = extensions;
    Dictionary<string, string> Dict = m_GooglePlayExtensions.GetProductJSONDictionary();
    foreach ( Product item in controller.products.all)
    {

        if (item.receipt != null)
        {
            if (item.definition.type == ProductType.Subscription)
            {
                print("Subscription");

                string json = (Dict == null || !Dict.ContainsKey(item.definition.storeSpecificId)) ? null : Dict[item.definition.storeSpecificId];
                SubscriptionManager s = new SubscriptionManager(item, json);
                SubscriptionInfo info = s.getSubscriptionInfo();
                if (PlayerPrefs.GetInt("VIP") == 1)
                {
                    if (info.getProductId() == ProductVIP)
                    {
                        if (info.isSubscribed() == Result.False)
                        {
                            PlayerPrefs.SetInt("VIP", 0);
                        }
                    }
                }
                else if (PlayerPrefs.GetInt("VIP") == 2)
                {
                    if (info.getProductId() == ProductGVIP)
                    {
                        if (info.isSubscribed() == Result.False)
                        {
                            PlayerPrefs.SetInt("VIP", 0);
                        }
                    }
                }
                else if (PlayerPrefs.GetInt("VIP") == 3)
                {
                    if (info.getProductId() == ProductDVIP)
                    {
                        if (info.isSubscribed() == Result.False)
                        {
                            PlayerPrefs.SetInt("VIP", 0);
                        }
                    }
                }
            }

        }

When a player buy any subscription, I change the value of the Int "VIP" That is saved in the PlayerPrefs, so the game can know if has a subscription and which one.
The code its supposed to get if is not subscribed, if yes, changes the VIP value to 0, indicating that has not active subscription


texts: Predictive firing (in a tile-based game)

texts:
I have a (turn-based) tile-based game, in which you can shoot at entities.

You can move around with mouse and keyboard, it's all tile-based, except that bullets move "freely".

I've got it all working just fine except that when I move, and the creatures shoot towards the player, they shoot towards the previous tiles.. resulting in ugly looking "miss hits" or lag.

I think I need to implement some kind of predictive firing based on the bullet speed and the distance, but I don't quite know how to implement such a thing...

Here's a simplified snip of my firing code.

class Weapon {

public void fire(int x, int y) {
  ...
  ...
  ...
  Creature owner = getOwner();
  Tile targetTile = Zone.getTileAt(x, y);

  float dist = Vector.distance(owner.getCenterPosition(), targetTile.getCenterPosition());

  Bullet b = new Bullet();
  b.setPosition(owner.getCenterPosition());

  // Take dist into account in the duration to get constant speed regardless of distance
  float duration = dist / 600f;

  // Moves the bullet to the centre of the target tile in the given amount of time (in seconds)
  b.moveTo(targetTile.getCenterPosition(), duration);

  // This is what I'm after
  // Vector v = predict the position
  // b.moveTo(v, duration);

  Zone.add(bullet); // Now the bullet gets "ticked" and moveTo will be implemented
  }
}

Movement of creatures is as simple as setting the position variable.

If you need more information, just ask.


texts: Unity Deactivating Keyboard Input Interpolation

texts:
I'm working on a game in Unity, and it is a little jarring to use with keyboard controls. I'm using the built in Input Manager, where I have a set of axes mapped to the left and right keys. When the player is using the keyboard instead of a joystick, I'd like it to simply be -1 when hitting left, 1 when hitting right, and 0 otherwise, but this isn't the case. I've found that for the first few frames of the button being held, Unity automatically builds up to the value-- for example, if I'm holding right, the value wouldn't go straight from 0 to 1, but rather from 0, to 0.25, to 0.5 and so on, continuously up to 1. Can I deactivate this? If so, how?
Thanks in advance.


texts: How can I remove the 'already played' moves from the 'available moves' list?

texts:
List<int> boardmove = new List<int>();
            boardmove.Add(0);
            boardmove.Add(1);
            boardmove.Add(2);
            boardmove.Add(3);
            boardmove.Add(4);
            boardmove.Add(5);
            boardmove.Add(6);
            boardmove.Add(7);
            boardmove.Add(8);

            int rand = rnd.Next(1, count);

            int num_one = boardmove[rand];

            boardmove.RemoveAt(num_one);

            count--;

I  am trying to implement a computer player for my tic tac toe game. I am  using a list to move the computer player, I want to index in the list and then remove the value I have selected. I want to select a unique value from the list each time.

            List<int> boardmove = new List<int>();
            boardmove.Add(0);
            boardmove.Add(1);
            boardmove.Add(2);
            boardmove.Add(3);
            boardmove.Add(4);
            boardmove.Add(5);
            boardmove.Add(6);
            boardmove.Add(7);
            boardmove.Add(8);

            int selectedIndex = rnd.Next(0, boardmove.Count);

            int selectedMove= boardmove[selectedIndex];
            Console.WriteLine(selectedMove);

            boardmove.RemoveAt(selectedIndex);
            Console.WriteLine(selectedIndex);


texts:
I have tried Hiero but it has NEVER worked for me. Is there an alternative application for creating fonts for cocos2d?

Thanks


texts: How can I call Schedule() on interface that inherits from IJob

texts:
So I have a voxel terrain engine, and I have an interface that all meshing jobs should inherit from. That looks like this (simplified from the actual):
public interface IMesherJob : IJob
{
    VoxelDataVolume<byte> VoxelData { get; set; }

    NativeArray<MeshingVertexData> OutputVertices { get; set; }
    NativeArray<ushort> OutputTriangles { get; set; }
}

One example of a meshing job is marching cubes, which looks like this: public struct MarchingCubesJob : IMesherJob
So here's my question: If I have a reference to an IMesherJob, can I somehow call Schedule on it? If I have a reference to MarchingCubesJob, I can call Schedule on it:
This works:
MarchingCubesJob myMeshingJob = GetMeshingJob();
JobHandle handle = myMeshingJob.Schedule(voxelCount, 64)

But this does not work:
IMesherJob myMeshingJob = GetMeshingJob();
JobHandle handle = myMeshingJob.Schedule(voxelCount, 64);

I noticed that Schedule() is an extension method for T where T : struct, IJob so that might be interfering with it, but it should still work because IMesherJob inherits from IJob


texts: Can learning how to do empirical research help a game developer?

texts:
I know this may be an odd question, but I have the opportunity to take a graduate class that teaches how to do empirical research.

I've taken a Human-Computer Interaction class in the past where it was important to perform empirical studies to find out how users interact with your application and study what improvements can be made. I can see where doing the same type of empirical studies might be useful when developing a game.

Also, we get to choose the type of empirical research we do which I would choose to do on either computer graphics or game development. Would a class like this potentially be helpful for a wanna-be indie game developer?


texts: how to move a char value "down" in a two dimensional array?

texts:
I managed to move it up, left and right but when i try to move it down it goes to the last Y position in the array instead of the Y position below it.

the code i wrote to move it up, left and to the right works!

the name of the array is "mapa[h][b]", the "help" variable has the same value as the values i want to move but as an int instead of a char, the variable "i" is for the Y position and the variable "j" is for the X position

//movement upwards
         for (i=0;i<h;i++){
            for (j=0;j<b;j++){
                if(mapa[i][j]==help){
                    aux=mapa[i-1][j];
                    mapa[i-1][j]=mapa[i][j];
                    mapa[i][j]=aux;
                    break;
                    break;
                }
        }
        }
//movement to the left
        for (i=0;i<h;i++){
            for (j=0;j<b;j++){
                if(mapa[i][j]==help){
                    aux=mapa[i][j-1];
                    mapa[i][j-1]=mapa[i][j];
                    mapa[i][j]=aux;
                    break;
                    break;
                }
        }
        }
//movement to the right
        for (i=0;i<h;i++){
            for (j=0;j<b;j++){
                if(mapa[i][j]==help){
                    aux=mapa[i][j+1];
                    mapa[i][j+1]=mapa[i][j];
                    mapa[i][j]=aux;
                    break;
                    break;
                }
        }
        }

And as I said before, this part works, what I did its just to exchange the value I want to move with the one on the position I want to move it to, to locate the value I want to move I use the for() cycles to "scan" the array and the if() is meant to find it, when the if() finds the wanted value I add one to the Y or X position, but when i try to move it down using the same logic

for (i=0;i<h;i++){
        for (j=0;j<b;j++){
            if(mapa[i][j]==help){
                aux=mapa[i+1][j];
                mapa[i+1][j]=mapa[i][j];
                mapa[i][j]=aux;
                break;
                break;
            }
    }
    }

it just moves to the bottom of the array regardles of its current location on the Y position


texts: Character Controller pulling Table in Unity Engine

texts:
I have setup a scene with one GameObject that has CharacterController component (Player) and another one Cube that represents Table with RigidBody and BoxCollider components.

Now, when I get close to this table I can press E and grab the table. Now I can pull or push table. What I do is when I press E key on keyboard I just attach this "table" to the Player gameobject with table.transform.SetParent(player.transform); Everything works great except when I add second cube that should prevent table to be moved any further.

As you can see, if I pull table in the direction of the arrow at some point, table will collide with blue cube. However, if I keep pressing S (for backward movement), player will continue to move, but table will not be moving (because I froze rotation on table's rigidbody component intentionally). What I want is to prevent player movement if the object that is currently being pushed or pulled cannot move any further...

Any ideas how to accomplish this?

EDIT:

public void PlayerMovement()
{
    float horizontal = Input.GetAxis("Horizontal") * MovementSpeed;
    float vertical = Input.GetAxis("Vertical") * MovementSpeed;

    if (_isMovingObject)
    {
        horizontal = 0f;
        float ppoDistance = Vector3.Distance(transform.position, _pushPullObject.transform.position);
        float diffDistance = ppoDistance - _pushPullObjectDistance;

        // distance between object and player is greater than at the start meaning pulling object
        // bumped into collider while pulling backward, but we are now trying to move forward
        // so wee need to restore diffDistance to 0
        if (diffDistance > 0.001f && vertical > 0f)
        {
            //transform.position += transform.forward * diffDistance;
            _pushPullObject.transform.position -= transform.forward * diffDistance;
        }

        // same thing but move backward after hitting obsticle while moving forward
        if (diffDistance < -0.001f && vertical < 0f)
        {
            //transform.position -= transform.forward * diffDistance;
            _pushPullObject.transform.position += transform.forward * diffDistance;

        }

        // stop backward movement if we hit something with pulling object
        if (diffDistance > 0.001f && vertical < 0f)
            vertical = 0f;

        // stop forward movement if we hit something with pull/push object
        if (diffDistance < -0.001f && vertical > 0f)
            vertical = 0f;
    }

    Vector3 forwardMovement = transform.forward * vertical;
    Vector3 rightMovement = transform.right * horizontal;

    characterController.SimpleMove(forwardMovement + rightMovement);
}

This is what I came up with. I calculate original distance at the time of parenting table to Player object, then I keep track if that distance changed...


texts: Event handling on own UI implementation in XNA

texts:
I´m creating a game in XNA with my own UI and its controls/components.
Currently I have some problems with the event handling. Let me tell me the way I do it right now.
Every object is handles as a component (also the form itself). Each component can implement an interface with a container which can contain a list of components (and so on and so on).
An example:
I have a form. On this form there is a TabControl. In this TabControl there are different TabPages and in these pages there are buttons.

I now have to handle my events that when I click on the button, the overlaying controls should not fire an event (like OnClick etc.).

How can I easily do that? I have a current function which runs recursively but only on two levels depth or something.

Here is my current function which is not working as expected:

private Boolean HandleComponentList(IComponentList parent) {
foreach (var singleItem in parent.Components.OrderByDescending(i => i.ID).Where(singleItem => singleItem.Visible))
{
    // Cast item to IComponentList.
    var castedList = singleItem as IComponentList;
    // If list is not null (so it implements IComponentList), call HandleComponentList for Components in this control first.
    if (castedList != null)
    {
        // If an event has been raised, break function.
        var eventFound = HandleComponentList(castedList);

        if (eventFound)
            return true;
    }

    // Only fire events if control is enabled.
    if (singleItem.Enabled)
    {
        // look for events.
    }
}

return false;

}

Would be great if someone has some suggestions!
Thank you!


texts:
I'm working on a game where enemies continually spawn with more and more health based on how long you've been playing. As the enemies take damage, I'd like their sprite to get darker and darker, until they die.

Here's what I've got so far:

    enemy_array[i].health -= damage;
    healthcolor.setTint(0x000000, enemy_array[i].health*0.1);
    enemy_array[i].transform.colorTransform = healthcolor;

Predictably, this is making enemies get less black as they take damage. What I need is to convert the decreasing enemies' health into an increasing number between 0 and 1.

I have absolutely no idea where to begin. It's entirely possible I have tunnel vision, but I'm hoping someone here might have an idea for how to accomplish this.

Thanks for your time.


texts: Is there some best practices to serialize objects to file on mobile devices in Unity using C#. I've tried to search it myself, but found only this link. However, it looks like here they are trying to cache AssetBundles. I'm new to Unity, but I have some experience in iOS (swift) development. Here we have opportunity to cache some objects(variables) in local storage, to avoid overusing network. So I wanted to create some static class (for example Storage), which caches variables to file permanently and return them by some key.


texts: How to obtain the currently bound texture ID in an openGL ES 2.0 project

texts:
In my game, I have:

GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texID);

Where texID is an integer returned by my setTexture() method.  Let's say, in this instance it's 1.

When I bind my textures during rendering calls, I don't want to bind this texture every single call.  Because I use different atlases of various textures and it's pretty wasteful to keep re-binding a texture when it's not required.

So, I would like to do something like this (Pseudo code)

if (texID != *currentTexture*){
    GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texID);
}

Therefore, if the texture I want to use is the same as the one already bound, the call to re-bind it will be ignored.

I can't work out how to get the ID of the texture that is currently bound.

I've tried

GLES20.glActiveTexture();

But this doesn't return the textureID, it returns the texture Units

Help appreciated

Edit

I've tried the suggestion below but I'm getting the folowing errors:

When hovering over the underline, this is the error:

I had searched this site and the wider web for a couple of hours before posting here but couldn't find a proper usage example, just this out of context snippet.


texts: XNA Line to Rectangle Collision return first pixel

texts:
I have the following code:

    public static bool LineIntersectsRect(Point p1, Point p2, Rectangle r)
    {
        return LineIntersectsLine(p1, p2, new Point(r.X, r.Y), new Point(r.X + r.Width, r.Y)) ||
               LineIntersectsLine(p1, p2, new Point(r.X + r.Width, r.Y), new Point(r.X + r.Width, r.Y + r.Height)) ||
               LineIntersectsLine(p1, p2, new Point(r.X + r.Width, r.Y + r.Height), new Point(r.X, r.Y + r.Height)) ||
               LineIntersectsLine(p1, p2, new Point(r.X, r.Y + r.Height), new Point(r.X, r.Y)) ||
               (r.Contains(p1) && r.Contains(p2));
    }

    private static bool LineIntersectsLine(Point l1p1, Point l1p2, Point l2p1, Point l2p2)
    {
        float q = (l1p1.Y - l2p1.Y) * (l2p2.X - l2p1.X) - (l1p1.X - l2p1.X) * (l2p2.Y - l2p1.Y);
        float d = (l1p2.X - l1p1.X) * (l2p2.Y - l2p1.Y) - (l1p2.Y - l1p1.Y) * (l2p2.X - l2p1.X);

        if (d == 0)
        {
            return false;
        }

        float r = q / d;

        q = (l1p1.Y - l2p1.Y) * (l1p2.X - l1p1.X) - (l1p1.X - l2p1.X) * (l1p2.Y - l1p1.Y);
        float s = q / d;

        if (r < 0 || r > 1 || s < 0 || s > 1)
        {
            return false;
        }

        return true;
    }

This code checks to see if a line intersects a given rectangle. But I need to find a way to get the position of the first pixel colliding between Point 'p1' and Point 'p2'.

Any help is appreciated.


texts: Map not loading after building Quake 2 from source

texts:
I'm a big fan of the game Quake 2. Recently I've decided to spend some of my free time for digging into the Quake 2 source code. There are 2 versions of the full game code, 3.19 and 3.21 (including the game exe as well as the game dll).
As regards to the Q2 Mission Packs, the source files for both The Reckoning and Ground Zero are for version 3.20 as the filename suggests (xatrixsrc320.exe and roguesrc320.exe)
I've compiled the 3.21 exe and 3.20 xatrix dll and when I run quake2 +set game xatrix I'm getting the following message in the game console:

... Dropped frame 21 > 20 ...

...and the map/game isn't loading.
How do I allow the map/game to be loaded?


texts: Error detecting collision with another instance of the same actor?

texts:
I have a project where after a certain time interval 2 NPCs are generated in different locations on the map.

Each of them collides with a collision box that defines its "class" (red or blue):

When 2 NPCs collide it was to be verified a condition (if the "class" of the involved ones is different) and from there both are destroyed, but nothing happens:

I put a print right after the Cast To NPC to see if it was happening and when they are generated the impression appears four times.

Blueprint:

Result in game:

I'd like to know how to set a cast only between two instances of the same actor.

Image showing that nothing happens when it (two instances of the same actor) collide:

I did the test with both codes (printing and destroying both).

EDIT 1 (I was being redundant)

In the code of destruction, I can simply put it to destroy itself only, because as it will run in both instances, the two will destroy themselves:

I'd still like to know how to correctly detect the collision between two instances of the same actor, but now I know that the code will be running twice, once in instance A and again in instance B.


texts:
Possible Duplicate:
  Cross-Platform Audio API Suggestions

I have gone down this road a few times, and always decided to put it off. I am finally to the point I need to choose an Audio library and stick with it. I switched physics engines 3 times which caused quite a bit of wasted time, so I would like to be set when I pick an Audio lib. I will be falling into the "indie" section as far as licensing goes. Here is what I have so far..

FMOD - Quality Middleware, success has gone to their heads and it seems they did away with the indie license recently. Price range seems to go from Free - 3000$ - 6000$ which pretty much excludes this.

BASS - So far this is what I am leaning towards. Simple API, great feature list, and quite a bit more. The pricing structure looks somewhat similar to FMOD, but I will need to pull out the Euro to Dollar calculator, and figure out if the Shareware license would be applicable to Digitally Distributed Content.

IrrKlang - Pricing looks fair, features seem generic. Pretty much coming down to a battle between this and BASS. I have heard good and bad things.

The other libraries such as OpenAL, PortAudio, Audiere, etc. were considered, but I am looking for something more drag and drop rather than something I am going to be basically writing my own front-end for. I am curious though, I remember stumbling across another library or two a few months ago on par with FMOD/BASS/etc that were fairly new. No matter how hard I look now, I cannot find them. Hopefully someone here knows what they might be called.

Anyways, basically just looking for feedback from other member's experiences, thoughts, and so on.


texts: OpenGL - render to texture - read data to CPU - data are upside down

texts:
I am using render to texture and I want to read data back to CPU side of the program. I am using PBO to do this. However, if I save content of texture to the file, data are vertically flipped (upside down). Is this a normal behavior, or I have something incorrect?

PBO init:

glGenBuffers(1, pboID);

glBindBuffer(GL_PIXEL_PACK_BUFFER, pboID);
glBufferData(GL_PIXEL_PACK_BUFFER, texture->info.rawDataSize, 0, GL_DYNAMIC_READ);

glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);

PBO readback:

glBindFramebuffer(GL_FRAMEBUFFER, texture->GetRenderTarget()->GetFrameBufferID());

glReadBuffer(texture->GetAttachement());

glBindBuffer(GL_PIXEL_PACK_BUFFER_ARB, pboID);
glReadPixels(0, 0, texture->info.width, texture->info.height, texture->info.glFormat, GL_UNSIGNED_BYTE, 0);

glBindBuffer(GL_PIXEL_PACK_BUFFER_ARB, pboID);
void * textureData = glMapBuffer(GL_PIXEL_PACK_BUFFER_ARB, GL_READ_ONLY_ARB);

//save tetxure data to file

//unlock PBO and FrameBuffer

I know that texture coordinates are "flipped" in comparison to DirectX, so during rendering on the screen, I am flipping the y-coordinate as well (y = y - 1). But how to download texture data "non-flipped"?


texts:
I've been dabbling with XNA for a couple of days now. This chunk of code doesn't work as I expect. The goal is to render sprites individually and composite them on another rendertarget.

P = RenderTarget2D(with RenderTargetUsage.PreserveContents)
D = RenderTarget2D(with RenderTargetUsage.DiscardContents)

for all sprites:
{
    graphicsDevice.SetRenderTarget(D);
    <draw sprite i>

    graphicsDevice.SetRenderTarget(P);
    <Draw D>
}

graphicsDevice.SetRenderTarget(null);
<Draw P>

The result I get is - only the last sprite is visible. I'm sure I'm missing some piece of information about RenderTarget2D. Any hints on what that might be?


texts:
I'm trying to create a triangular touch surface for iOS where the user can drag around a point inside this triangle. Using information from this page, it is easy to figure out if the dragged point is inside or outside the triangle. However, I want to clip the point to the triangle edges if the user drags outside the triangle.

This is easy for side AB and side AC, because I just have to set vectors u or v to zero respectively if the user's finger drags outside of these edges. However, I'm not sure how to find point p, on side BC. I need to find this point of intersection if the user drags their finger outside of edge BC.


texts: Unity 2D: Position Child Object to center of Parent Object

texts:
What I'm trying to achieve is snapping a child object to the center of its parent object after dragging and dropping it.

The moving object successfully follows the mouse, and drops. It also successfully selects a dynamic parent when it moves over a new node.

What it does NOT do is then snap to the center of its parent. It instead jumps all over the screen and snaps to nothing.

Here is all of my code:

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

public class Object_Moveable: MonoBehaviour {

 private Vector2 mousePos;
 public float moveSpeed;
 public float offset = 0f;
 private bool following;
 private GameObject SelectedNode;

 // Use this for initialization
 void Start() {
  following = false;
  offset += 10;
 }

 void Update() {

  if (Input.GetMouseButtonDown(0) && ((Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position).magnitude <= offset)) {
   following = true;
  }

  if (following) {
   transform.position = Vector2.Lerp(transform.position, Camera.main.ScreenToWorldPoint(Input.mousePosition), moveSpeed);
  }

  if (Input.GetMouseButtonUp(0)) {
   following = false;
   //Attach (Node, 0, 0);
   transform.localPosition = SelectedNode.transform.position;
  }
 }

 void OnTriggerEnter2D(Collider2D trigger) {
  if (trigger.tag == "pipenode") {
   transform.SetParent(trigger.transform);
   SelectedNode = trigger.gameObject;
  }
 }
}


texts: Algorithm for simulating collision between circles of different mass

texts:
First of all, I'm not sure if this is the right site for this question, as it's actually a game I'm developing. However, I thought that this would be a common thing to need to know in games, so I put it here.
I'm programming a physics simulation in which I have a list of balls that are moving around. They have different masses and radii. I am trying to find an algorithm to make them bounce off each other when they collide. I've googled the problem and found lots of solutions for when the balls are the same mass (such as billiards), but none for different mass balls. It's not essential to the question but I'm programming this in JavaScript using p5.js


texts: Raycast does not detect child layer if parent layer is set to ignore

texts:
I have a LineRenderer that ignores certain Layers based on a Raycast using LayerMask.
I have a cube with a collider on a Layer which is ignored because of the LayerMask.
I have a smaller object inside the cube that is a child object of the cube and is on a layer that is not set to be ignored. I need the Raycast to hit the smaller object.

When this smaller object is un-parented from the larger cube, the LineRenderer behaves like I want it to: the hit data informs me it is being hit by the Raycast, but this does not hold true if the smaller object is a child of the cube.

Is there a way of having this behaviour without having to un-parent the smaller object? It's like the smaller object is inheriting the parent's Layer, despite being on it's own Layer - does this sound like what is happening?


texts: Continuously get keyboard input from user and remember last character [Java]

texts:
I want to write a Snake game in Java. How can I continuously monitor input and if user pressed W set variable Char lastDirection = 'w'; //hence, Direction.UP?

I know about the Scanner method: Scanner scan= new Scanner(System.in);... But then user would have to hit enter each time he presses the button. Document Listener (Swing) seems better, but then I would have a long string of user input saved somewhere that I don't need. What is the right method for listening to keyboard and remembering the last character?


texts: Quaternion camera in 3D space with Pitch and Yaw

texts:
I am having trouble implementing a quaternion camera that can fly freely in 3D space with only Pitch and Yaw rotations.

It works fine except when you look up or down and then try to look left or right (Yaw).
Then the camera gets a roll effect which is incorrect.

Here is how I handle Pitch and Yaw:

void Camera::rotate(const int& inPitch, const int& inYaw){

//Look Up and Down
if (inPitch != 0)
{
    quat qPitch = angleAxis((float)inPitch * 0.003f, vec3(-1.0f, 0.0f, 0.0f));
    mQuaternion = qPitch * mQuaternion;
}

//Look Left and Right
if (inYaw != 0)
{
    quat qYaw = angleAxis((float)inYaw * 0.003f, vec3(0.0f, 1.0f, 0.0f));
    mQuaternion = mQuaternion * qYaw;
}

mQuaternion = normalize(mQuaternion);
mat4 reversedView = inverse(mat4_cast(mQuaternion));
mLeft = normalize(vec3(reversedView * vec4(-1.0f, 0.0f, 0.0f, 0.0f)));
mUp = normalize(vec3(reversedView * vec4(0.0f, 1.0f, 0.0f, 0.0f)));
mDirection = normalize(vec3(reversedView * vec4(0.0f, 0.0f, -1.0f, 0.0f)));
}

And this is how I update my ViewMatrix:

void Camera::onUpdate(){
if (mIsMoving[move::MOVING] == true)
{
    ///Position is handeled with flags in each direction
    ///to enable moving in muliple directions at once

    if (mIsMoving[move::FORWAD])
        mPos += mDirection*mVelocity;

    if (mIsMoving[move::BACK])
        mPos -= mDirection*mVelocity;

    if (mIsMoving[move::LEFT])
        mPos += mLeft*mVelocity;

    if (mIsMoving[move::RIGHT])
        mPos -= mLeft*mVelocity;

    if (mIsMoving[move::UP])
        mPos += mUp*mVelocity;

    if (mIsMoving[move::DOWN])
        mPos -= mUp*mVelocity;

    ///Rotation
    mViewMatrix = mat4_cast(mQuaternion);
    ///Translation
    mViewMatrix = glm::translate(mViewMatrix, -mPos);
}
}


texts: Sharing a texture resource from DX11 to DX9 to WPF, need to wait for DeviceContext.Flush() to finish

texts:
I'm following these instructions on TheCodeProject for rendering from DirectX to WPF using D3DImage.

The trouble is that now that I have no swap chain to call Present() on -- which according to the article shouldn't be a problem, but it definitely wasn't copying my back buffer.

An additional step that I have to take before I can copy the texture to WPF is to share it with a second D3D9Ex device, since D3DImage only works with DX9 (which is understandable, as WPF is built on DX9). To that end, I've modified some SlimDX code to work with DirectX 11.

I tried calling DeviceContext.Flush() (the Immediate one) at the end of each render cycle, which kind of works -- most of the time it'll show my renderings, but maybe for maybe 3 or 4 out of 60 frames each second, it'll draw my clear color instead. This makes sense -- Flush() is non-blocking; it doesn't wait for the GPU to do its thing the way SwapChain.Present does.

Any idea what the proper solution is?

I have a feeling it has something to do with my texture parameters for the back buffer, but I don't know.


texts:
As your game get's bigger and bigger, you will use more and more different shader effects.
Let's take an easy example:

I have clouds in my voxel-based world, and I want to give it a blue-ish tint with a shader. Do I create a new shader, disable the default shader, enable the cloud-shader, draw the cloud, disable the cloud shader and enable the default one again?

If your game starts to get huge, how on earth can you use 300 shader effects enabled for 1 voxel and disabled for the other?

I know the question may sound strange, but it really makes me think.

I now have a Vertex- and Fragmentshader, for the matrix calculations, and basic lighting. If I want to add a shading-effect for for example water blocks, what to do?

I hope someone can help me with this mystery.


texts: How to access entites from scripts in an entity-framework?

texts:
I'm developing on a simple libGDX-based Game and im using the entity-component-system ashley.

For non-generic but custom behaviour (e.g. the Player Movement), I'm using "scripts" instead of reuseable and generic Entity-Systems. Therefore I've got an ScriptComponent and a ScriptSystem which runs init() and update() on all scripts related to an entity.

At some point I want to generate a map, counting game-related-properties etc.
that brings me to the point where I'm confused about how to access those porperties from any script.

In other Engines/Enviroments like Unity3D the GameObjects (the entities) brings functionality to find other entities like FindGameObjectsWithTag(...).

But how can I realise that in ashley? Also should it be possible in an Entity-Framework to access specific entities in general?

Edit: Additional information

Here comes a simple example-usecase. This is very notional example I've just created for that post. I just wanted to demonstrate, that I thing there is a need of an "main Game Object" in a game which also uses a entity-component-framework like ashley. So I thought a correct way is, to let this main-game-object be an entitiy too which holds the main script. But I'm not sure, if this is a good approach.

Here I demonstrate this with having a PlayerScript which just sets the lives for the player accordingly to the difficulty level of the game (maybe set by the player on the main-menu-screen). This PlayerScript is attached to the ScriptComponent of the player entity.

public class PlayerScript extends Script {

 int playerLives;

  public void init() {
     GameEntity entity = getTheEntityByName("game"); // this method doesn't exist
     GameScriptComponent gsc = scriptComponentMapper.get(entity);
     GameScript mainGameScript = gsc.getScriptByName("game");
     if(mainGameScript.getDifficulty == "easy")
     playerLives = 999;
  }
}