texts: Collision detection doesn't work for automated elements in XNA 4.0

texts:
I have a really weird problem. I made a 3D simulator of an "assembly line" as a part of a college project. Among other things it needs to be able to detect when a box object passes in front of sensor. I tried to solve this by making a model of a laser and checking if the box collides with it. I had some problems with BoundingSpheres of models meshes so I simply create a BoundingSphere and place it in the same place as the model. I organized them into a list of BoundingSpheres called "spheres" and for each model I create one BoundingSphere. All models except the box are static, so the box object has its own BoundingSphere (not a member of the "spheres" list). I also implemented a picking algorithm that I use to start the movement. This is the code that checks for collision:

if (spheres.Count != 0)
        {

            for (int i = 1; i < spheres.Count; i++)
            {
                if (spheres[i].Intersects(PickingRay) != null && Microsoft.Xna.Framework.Input.ButtonState.Pressed == Mouse.GetState().LeftButton)
                {
                    start = true;
                    break;
                }
                if (BoxSphere.Intersects(spheres[i]) && start)
                {
                    MoveBox(0, false);//The MoveBox function receives the direction (0) and a bool value that dictates whether the box should move or not (false means stop)
                    start = false;
                    break;
                }
                if (start /*&& Microsoft.Xna.Framework.Input.ButtonState.Pressed == Mouse.GetState().LeftButton*/ && !BoxSphere.Intersects(spheres[i]))
                {
                    MoveBox(0, true);
                    break;
                }

            }

The problem is this:
When I use the mouse to move the box (the commented part in the third if condition) the collision works fine (I have another part of code that I removed to simplify my question - it calculates the "address" of the box, and by that number I know that the collision is correct). But when I comment it (like in this example) the box just passes trough the lasers and does not detect the collision (the idea is that the box stops at each laser and the user passes it forth by clicking on the appropriate "switch"). Can you see the problem? Please help, and if you need more informations I will try to give them.
Thanks


texts: How can I load a picture with alpha channel in JME?

texts:
This code loads a picture into the game:

Picture mypic= new Picture("mypic");
        Texture2D tex = (Texture2D) assetManager.loadTexture("Textures/mypic.png");
        mypic.setTexture(assetManager, tex, false);
        mypic.setHeight(settings.getHeight());
        mypic.setWidth(settings.getWidth());

What have to be modified or add to show properly a picture with an alpha channel?


texts: No more FallbackHand in SteamVR Player prefab

texts:
A few weeks ago when I wanted to test some VR stuff in Unity without an HTC Vive I could add the Player prefab from the SteamVR asset and then fly around while testing the game just like in the editor. I could also interact with something like a Throwable with my mouse.
Now it looks like they changed the asset and when I test the game the first time the SteamVR Input window pops up. I just went with the default settings there and hoped it would work just like before. It didn't.
Now I can still fly around but I can't grab and move anything like a Throwable. This small red ball (the Indicator GameObject) that is placed by raycasting on the GameObject I would interact with also doesn't move anymore when I move. It just stays where I placed the Player prefab.
I already tried it with the most basic example possible. A fresh project, imported the Steam VR asset, added a plane as a floor, added a cube and gave it the Throwable component, added the Player prefab. A few weeks ago this worked just fine.
Do I have to make some settings in the SteamVR Input window? Nothing there looks like it would affect this Indicator GameObject for the NoSteamVRFallback.
What do I have to do to be able to develop for the Vive without a Vive attached to the computer as I did before?

I'm using Unity 2018.2.13f1. When I'm opening an older project that has still the old version of the asset it works as expected. So the version of Unity itself is not the problem and rather the SteamVR asset.
The version of the SteamVR asset in the older project is 1.2.2. Right now it's not working with version 2.0.1.


texts: OpenGL Black rectangle in rendering texture

texts:
I create textures (for example, I just fill the texture color), and render their. But, for some reason, to the upper edge added black rectangle.

Screenshot:

var
Textures: array of GLuint;

procedure LoadTexture(const TextureID: Byte; var Texture: GLuint);
var
//
w, h: Cardinal;
//
Data: PByteArray;
begin
//
if TextureID = 0 then
//
  begin
//
w:=512; h:=512;
  end
                 else
//
  begin
//
w:=128; h:=64;
  end;

//
GetMem(Data, w * h * 3);

//
if TextureID = 0 then
//
FillChar(Data^, w * h * 3, 204)
                 else
//
FillChar(Data^, w * h * 3, 102);

//
glBindTexture(GL_TEXTURE_2D, Texture);

//
glTexParameteri(GL_TEXTURE_2D,
//
GL_TEXTURE_MAG_FILTER, GL_NEAREST);

//
glTexParameteri(GL_TEXTURE_2D,
//
GL_TEXTURE_MIN_FILTER, GL_LINEAR);

//
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8,
//
w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, Data);

//
FreeMem(Data, w * h * 3);
//
Data:=nil;
end;

procedure glInit;
begin
//
glEnable(GL_TEXTURE_2D);

//
SetLength(Textures, 2);
//
glGenTextures(1, @Textures[0]);
//
LoadTexture(0, Textures[0]);
//
glGenTextures(1, @Textures[1]);
//
LoadTexture(1, Textures[1]);

//
glClearColor(1, 1, 1, 0);
//
glShadeModel(GL_SMOOTH);
//
glClearDepth(1);
//
glDisable(GL_DEPTH_TEST);
//
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);

//
glViewport(0, 0, 800, 600);
//
glMatrixMode(GL_PROJECTION);
//
glLoadIdentity;
//
glOrtho(0, 800, 600, 0, 0, 1);
//
glMatrixMode(GL_MODELVIEW);
//
glLoadIdentity;
end;

procedure glDraw;
begin
//
glClearColor(1, 1, 1, 0);
//
glClear(GL_COLOR_BUFFER_BIT or
  GL_DEPTH_BUFFER_BIT);

//
glBindTexture(GL_TEXTURE_2D, Textures[0]);
//
glBegin(GL_QUADS);
//
glTexCoord2f(0, 0);
//
glVertex2f(0,   0);
//
glTexCoord2f(1, 0);
//
glVertex2f(512, 0);
//
glTexCoord2f(1, 1);
//
glVertex2f(512, 512);
//
glTexCoord2f(0, 1);
//
glVertex2f(0,   512);
//
glEnd;

//
glBindTexture(GL_TEXTURE_2D, Textures[1]);
//
glBegin(GL_QUADS);
//
glTexCoord2f(0, 0);
//
glVertex2f(128,   64);
//
glTexCoord2f(1, 0);
//
glVertex2f(256, 64);
//
glTexCoord2f(1, 1);
//
glVertex2f(256, 128);
//
glTexCoord2f(0, 1);
//
glVertex2f(128, 128);
//
glEnd;
end;


texts: Follow Camera to Two objects at different time

texts:
I am developing simple 2D game in unity. I am locked with the camera movement for last two days. I've camera script that is working as follows:

Follow the player to X and Y direction
If player stops moving, Camera must find the nearest enemy and should move to that direction

Both of the above function works fine, but separately.

Camera finds and follows the enemy, when there is no input from player for last 10 seconds.

But after few seconds (When stops following enemy), Camera retains the player's position. That creates unlikely effect in the scene. I want the camera to have a last position and started following player from there.

For your reference I'm writing my Camera Script.

public class MultipleTargetCamera : MonoBehaviour {   public List<Transform> targets;
[ReadOnly]
public GameObject closestEnemy = null;

public EnemyController closestEnemyController = null;

public Vector3 offset;
public float smoothTime = 0.5f;

private Vector3 velocity;

Vector3 camPosition;

// Update is called once per frame
void LateUpdate()
{
    /* if (targets.Count == 0)
         return;*/
    if (!TheGlobals.instance.movingTowardsEnemy)
    {
        MoveCamera();
    }
    else
    {
        MoveAsEnemy();
    }
}

void MoveAsEnemy()
{
    camPosition = new Vector3(transform.position.x + closestEnemyController.xDiff,
            transform.position.x + closestEnemyController.yDiff,
            transform.position.z);
    transform.position = Vector3.SmoothDamp(transform.position, camPosition, ref velocity, smoothTime);
}

void MoveCamera()
{
    Vector3 centerPoint = GetCenterPoint();

    Vector3 newPosition = centerPoint + offset;

    transform.position = Vector3.SmoothDamp(transform.position, newPosition, ref velocity, smoothTime);
}

Vector3 GetCenterPoint()
{
    Vector3 targetPos= new Vector3(targets[0].position.x,
        targets[0].position.y,
        transform.position.z);

    if(targets.Count==1)
    {
        return targetPos;
    }

    var bounds = new Bounds(new Vector3(targets[0].position.x,
        targets[0].position.y,
        transform.position.z), Vector3.zero);

    for(int i=0;i<targets.Count;i++)
    {
        bounds.Encapsulate(new Vector3(targets[i].position.x,
        targets[i].position.y,
        transform.position.z));
    }

    return bounds.center;
}

public void FindNearestEnemy()
{
    GameObject[] gos;
    gos = GameObject.FindGameObjectsWithTag("Enemy");

    float distance = Mathf.Infinity;
    Vector3 position = transform.position;
    foreach (GameObject go in gos)
    {
        Vector3 diff = go.transform.position - position;
        float curDistance = diff.sqrMagnitude;
        if (curDistance < distance)
        {
            closestEnemy = go;
            distance = curDistance;
        }
    }
    closestEnemyController = closestEnemy.GetComponent<EnemyController>();
    targets[0].parent = this.transform;
    StartCoroutine(StopMovingTowardsEnemy());
}

IEnumerator StopMovingTowardsEnemy()
{
    yield return new WaitForSeconds(0.01f);
    TheGlobals.instance.movingTowardsEnemy = false;
}

}

I hope I did explain well. Looking for the answer. Thank you in advance!


texts:
I'd like to implement shadows and reflective surfaces in my OpenGL app.
I already have ideas which I will provide below. But I would like to ask someone more experienced than me before I put too much effort into the implementation. (I'm still very new and so I don't know all options I have on modern graphic cards.)

I would like to know if there are any common improvements or common techniques that would improve the quality and/or performance. (Or even if my idea is completely nonsense)

Shadows

I would render a cube map at the center of each light source in a separate Framebuffer. When rendering the real scene I can lookup the depth information in the the relevant cube map (for each light source) and compare the depth value with xyz-Position of the Fragment. And check if the Fragment is behind an object. Additionally I could also take surrounding depth values into account to render blurred shadows depending on the distance to the object.

For the special case that the light source is stationary I could render all other stationary objects at the beginning. For each frame I still have to render the dynamic objects and reset to the "stationary scene" afterwards.

Reflection

For plane mirrors you could simply mirror the view matrix around the plane and render the scene a second time (with the stencil buffer to clip the rendering process to the mirror surface). Also I should clip the rendering volume with glClipPlane().
I found this technique on Google, so it seems to be very common.

But for arbitrary surfaces I had to think about something different. My idea is to render a cube map at the center of every object that has reflection enabled in its material definition.
When I am in the real rendering process, I would read out the pixel value in the cube map, depending on the surface normal and the fragment xyz-Position.
The problem is that you get an parallax error for near objects because the fragment obviously isn't at the center of the object.
I couldn't solve this problem. (Maybe I could render the normals of the mirror object and then use this to make some transformations while rendering the cube map?)

For stationary mirror objects I could do same trick that I described in the Shadows section.

Instead of cube maps I could also use a single map and transform the Cartesian coordinates to spherical coordinates (phi, theta, r). So that the resulting texture has the dimension phi * theta (r is the depth value). But I don't know which method is generally faster. Also a single map would generate different texture qualities depending on theta. I'm not sure how bad this will be in the result.

The main problem that I have is that this all sounds very performance intensive. Maybe there are tricks I don't know?

An advice would be helpful.
Thanks in advance.


texts:
I am have now this code: http://jsfiddle.net/DK67k/2/ In here is 2D tile map and when you click on tile you get coordinates on alert. But for get precises coordinate you need click on top left tile(tiles is 16x16) and if I click on bottom right tile I am get second tile coordinates.

Maybe anyone have idea how to fix this?


texts:
I'm attempting to create a sphere with terrain (aka planet). I managed to procedurally create an icosahedron, and I am able to subdivide it (yay), but now I'm stuck on terrain.

My current idea was to create a Perlin like "3D Noise Field" and sample density where each of the spheres vertices fall (as a height-map value). this way i should be able to tweak the noise (add octaves, etc) to roughen the "NoiseField" and thus the spheres surface.

pseudo example and result:

public void Terrain(float Scale)
{
    if (Scale < 0.01) return;

    List<Vector3> terrain = new List<Vector3>();
    for ( int i = 0; i < surface.vertices.Count; i++)
    {
        Vector3 vert = sphere.verts[i];
        Vector3 direction = vert.normalized;
        Vector3 newpoint = vert * Sample3DNoise(direction, Scale);
        terrain.Add(newpoint);
    }

    //this line replaces the original shape!
    surface.vertices = terrain;

    Debug.Log("terrain Update");
}

public float Sample3DNoise(Vector3 point, float scale)
{
    //Vector3 direction = point.normalized;

    float u = point.normalized.x * scale;
    float v = point.normalized.y * scale;
    float w = point.normalized.z * scale;

    //poor attempt at 3d noise field
    //PerlinNoise(float, float );
    float x = Mathf.PerlinNoise(u , 0f);
    float y = Mathf.PerlinNoise(0f, v);
    float z = Mathf.PerlinNoise(u , v);

    //the average of the coords, returns "density at this point"
    return (x + y + z) / 3;
}

edit:

so while it appears i was able to achieve this, it's is clearly not the "terrain on surface of sphere" look I was aiming for. Any suggestions on how can I change the "noise field" so my surface is more planet like? or how else can i achieve this?


texts: How to move object on local space not object space in unity

texts:
I am watching this (game dev, space parenting & rotation)
Sebastian Lague video and found that there are three spaces actually (not two) and these are world space, local space and object space.

World space: The static space (0,0,0)
Object space: related to the object space
Local Space: related to the parent of the object

I am amazed that i didn't find the distinction between these two spaces(local and object) on official unity forms but actually it exists. My question is that why there is no Space.Local? I found that there are Space. Self and Space.World.
Space.Self is refer to object space. I can move my object to object space using this

    void Update () {
        transform.Translate(new Vector3(0,0,1) * Time.deltaTime * 2,Space.Self);
    }

And i can move my object to world space using this

void Update () {
    transform.Translate(new Vector3(0,0,1) * Time.deltaTime * 2,Space.World);
}

but there is no support for local space that i could move the object to local space (means move the object related to its parent object). There is a fair distinction between Local and Object space but unity didn't consider it i guess or i am wrong.


texts: Gamemaker's xprevious is the same value as x... Same thing happens for the y variabbles

texts:
So I'm making a tower defense game but for some reason the enemies (which are following a path) have the same xprevious value as their x value. The same is true for their y variables. This also happens when the enemy is not on a path. I double checked that I'm not modifying the x and y previous variables anywhere. Is this a bug in GameMaker?

Thanks,
Philip


texts: Cocos2D SpriteBatchNode vrs. SpriteFrameCache… I do not see any performance difference

texts:
I have tried using both ways...

adding the .png file on the cache with SpriteFrameCache..
adding .plist with spritebatchnode adding the correspoding .png file, I didnt see any performance difference.

In my test I keep adding and adding objects with the same image.. in this case a bullet... eventually the app crashed because it ran out of memory. Same thing happened to both situations with SpriteFrameCache and SpriteBatchNode they both dropped FPS to 30(when its supposed to be 60) and then just crashes...I understand the scenario is not real.And obviously its destiny its to crash if I just keep adding images without destroying objects that are no longer in use...but the question remains.

I saw the same performance issue, however I read that SpriteBatchNode makes only one draw call making it best performance practice. Has anyone tried and can confirm the performance difference and exactly how can you prove this performance difference in code and in the app?


texts: How can I tell how much of a "scratch card" has been revealed?

texts: I have developed scratch card effect.I am now working on reward system, so my question is how will I go on and implement logic which will let me know that the object behind scratch card is now visible??


texts:
I'm attempting to make a game for WebGL. However, everytime I export a build, the font always changes on everything, just like below.

Original

WebGL

My default font is Arial and I have made a separate Arial font file with which I've replaced all instances of Arial font in my game, but it's still turning out like this. Why?


texts: Is it safe to save data OnApplicationFocus and OnApplicationPause on mobile?

texts:
Unity has messages called OnApplicationPause and OnApplicationFocus.  They are called on each MonoBehaviour as the user exits/suspends the application.

I have successfully used this to save data in a regular build, but the save never happens when I am in a development build.  My guess is that it is doing some extra logging in development builds when the application exits, and runs out of time before the save can occur.

This is the code I am using to save:

#if UNITY_IOS || UNITY_EDITOR
    private void OnApplicationFocus(bool focus)
    {
        if (focus)
        {
            EnterApplication();
        }
        else
        {
            ExitApplication();
        }
    }
#endif

#if UNITY_ANDROID && !UNITY_EDITOR
    private void OnApplicationPause(bool pause)
    {
        if (pause)
        {
            ExitApplication();
        }
        else
        {
            EnterApplication();
        }
    }
#endif

private void ExitApplication()
{
    SaveData();
}

I am saving my data using a C# FileStream, not PlayerPrefs.

As you have noticed, I am not using OnApplicationQuit.  This is because I want the application to save as the user backgrounds the app or exits the app.  So please keep this in mind before suggesting I use OnApplicationQuit.  I also believe the results would be the same in terms of failure.

Is it save to auto-save my game state when these methods are called?  Couldn't the operating system take control away before the save completes?  If it is not safe, is there a more performant solution than periodically auto-saving?


texts:
I was wondering, is it possible to Scale(Vector3) a ModelBone without scaling its children. Lets say I got a Bone A at position 1,0,3. And one of its children Bone B is at position 1,0,5 (he is touching Bone A). Could I scale Bone A along Z axis without scaling Bone B, but keep Bone B position and rotation so that he is still touching Bone A.

Thanks in advance


texts:
I have a very simple scene setup. What I want to do is to create a button prefab composed of a sprite and a TextMeshPro object. When I group the sprite and the text under a GameObject, the pivot of the compound object appears very far from the center of the GameObject (please see the attachment).

I can't move the pivot of the text to the center no matter what I do.

Is this an expected behavior?


texts: How do you execute Trigger-collider collision only in one gameobject?

texts:
I'm trying to deal with units (generated from the same prefab) dealing damage to each other on collisions.
Each Unit has both a Collider2D and a trigger on the front, that deals damage to other units that enter it.

I drew a small image (with Paint, sorry) to better illustrate what I mean and want.

The problem I am having is that when a collision occurs (one unit enters the trigger of the other), both units damage each other, meaning Unit 2 also deals damage to Unit 1.

I have seen that you can create a separate gameObject as a child of the unit and attach the trigger to this gameObject.

However, the number of units will be very high so if possible I don't want to double the number of gameObjects used by units.

Also, the amount of damage dealt is calculated from many other parameters from many other scripts on the units and doubling all those references doesn't look like an elegant solution.

Any Ideas?
Thanks


texts:
I'm wanting to have a script that when I click in my scene, my player will rotate and have a force added to it and will travel until it has reached the clicked point in my scene.

Right now I have it working using Vectors and having my player lerp from one point to another. But I want to amend it so I can use physics and get a better sense of my player moving. Like have him speed up to start moving and slowing down as he reaches my target loction

My script now looks like this

public GameObject isActive;
public float speed;
public Ray ray;
public Rigidbody rigidBody;

public Vector3 targetPoint;
// Use this for initialization
void Start ()
{
    targetPoint = transform.position;
}

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

}

void FixedUpdate()
{
    if (Input.GetMouseButton(0))
    {
        targetPoint = Camera.main.ScreenToWorldPoint (Input.mousePosition);
        ChangeRotationTarget ();
    }

    Quaternion targetRotation = Quaternion.LookRotation (targetPoint - transform.position);
    transform.rotation = Quaternion.Slerp (transform.rotation, targetRotation, speed * Time.deltaTime);

    rigidbody.position = Vector3.Lerp(transform.position, targetPoint, speed * Time.fixedDeltaTime);
}

void ChangeRotationTarget ()
{
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    Plane playerPlane = new Plane (Vector3.up, transform.position);

    float hitdist = 0.0f;

    if (playerPlane.Raycast (ray, out hitdist))
    {

        targetPoint = ray.GetPoint (hitdist);
    }

}

However, when I run this, he just slides from one point to another. Regardless of the drag or mass I put in my rigidbody.

Can someone help me make my changes? Or point me in the right direction


texts: Genetic Algorithms - Fitness Function simple maze game

texts:
Trying to lay out the best fitness function for my simple game. I'm just trying to make bots go through a bunch of obstacles in order to reach a point. If they touch an obstacle, they die, they have 10 seconds max to solve the parkour.

I'm wondering which data I should track to make the best fitness function possible.

I thought of tracking:

Time

Distance to exit from position of death or timeout

And my Fitness score would be:

Fitness = Time / (Distance + 1)

But if a bot manages to get to the end of the maze in 10s, I'm scared the following generations will all take 10s or close to it to go through the maze and not try to do it in 3 or 4s for instance.
Because he'll get the best fitness score, so he'll be the parent of most cross-overs.

Yet I didn't manage to get a working example so perhaps I'm worrying for nothing but I'd like some advice on generally how to determine such fitness functions.


texts: If I draw a rectangle, then extrude it, will it be identical to a box? I mean, will bottom face be closed as in box?


texts: How to make an object move outside the map and appear on the other side with a tilemap?

texts:
I have a tilemap where a character moves from tile to tile. I'm trying to make it possible for the character to move outside the screen and reappear on the other side, just like the tunnel in Pacman.

The movement works like following:

Look for which arrow key is being pressed.
Check if the tile where the user wants to go to is walkable. If not, go back to 1.
If walkable, set it as target and start moving towards the tile.
When arrived to the target, go back to 1.

The problem I have is that there're no tiles outside the screen. I've tried to set the target to the tile on the other side of the map if the target doesn't exist, but then the character would move across the whole screen.

I've tried a couple other solutions that either don't work or require lots of additional code in many different files.

Does anyone know a good solution or recommend another approach?

I'm programming in Python with Pygame but know other languages in general. Here's MVCE code for my class:

import pygame
import math

TILE_SIZE = (16, 16)

class Player(pygame.sprite.Sprite):

    def __init__(self, pos, size):
        super().__init__()
        self.rect = pygame.Rect(pos, size)  # Rectangle representing the character's pos.
        self.image = pygame.Surface(size)
        self.position = pos  # In order to have the position in float precision, (x, y).
        self.speed = 80  # Pixels per second
        self.tile_index = (pos[1] // TILE_SIZE[1], pos[0] // TILE_SIZE[0])  # (Row, column).
        self.moving = False
        self.target = self.rect

    def handle_events(self, level):
        key = pygame.key.get_pressed()
        if key[pygame.K_w] or key[pygame.K_UP]:
            self.set_target(level, y_offset=-1)
        elif key[pygame.K_s] or key[pygame.K_DOWN]:
            self.set_target(level, y_offset=1)
        elif key[pygame.K_a] or key[pygame.K_LEFT]:
            self.set_target(level, x_offset=-1)
        elif key[pygame.K_d] or key[pygame.K_RIGHT]:
            self.set_target(level, x_offset=1)

    def set_target(self, level, x_offset=0, y_offset=0):
        tile = level.get_tile(self.tile_index, x_offset, y_offset)
        if tile.is_walkable:
            self.target = tile.rect
            self.moving = True

    def move(self, dt):
        distance_x = self.target.x - self.rect.x
        distance_y = self.target.y - self.rect.y
        # Make sure the player move at 'speed * dt' or distance, depending on the smallest.
        x = math.copysign(min(abs(distance_x), self.speed * dt), distance_x)
        y = math.copysign(min(abs(distance_y), self.speed * dt), distance_y)
        self.position = (self.position[0] + x, self.position[1] + y)
        self.rect.topleft = self.position

    def stop_if_arrived(self):
        if self.rect.contains(self.target):
            self.moving = False
            self.tile_index = self.target.y // TILE_SIZE[1], self.target.x // TILE_SIZE[0]

    def update(self, level, dt, *ignore):
        if not self.moving:
            self.handle_events(level)
        else:
            self.move(dt)
            self.stop_if_arrived()


texts: How can I debug a black screen when testing on a device?

texts:
I have made an Android game with Unity. But, when I opened my game, I see a black screen and a closed game.

It works on a tablet but does not work on mobile phones. I tested it on 2 mobile phones.

On the first phone I installed it on, I see nothing but a black screen and closed game.

On the second one, it installed once and worked, but when I uninstalled it and tried to install it again, I get the black screen and closed game.

What can I do to help me find out what is going on?


texts:
I am experiencing some oddities when loading meshes in Assimp. Some models render perfectly, while others are complete jumbles of triangles.

Some Example Images:

Teapot Correct -
Teapot Actual

Flower Correct -
Flower Actual

OBJ download links:

Teapot.obj -
Flower.obj

I've searched far and wide, and I cant seem to pin down the cause of this. I have noticed while debugging that the value of ai_mesh->mNumVertices differs from what Assimp Viewer or Blender display. ai_mesh->mNumVertices is smaller in the Teapot example by 156 vertices, and larger in the Flower example by 20 vertices. I've considered that Assimp post-processing may be causing the difference here. However, I'm using the EXACT same post-processing flags used in Assimp Viewer, copied directly from the source code. Here is my Mesh Loader:

mesh::mesh(aiMesh *ai_mesh, model* parent_model) : mesh()
{
    name_ = ai_mesh->mName.length != 0 ? ai_mesh->mName.C_Str() : "";

    // Get Vertices
    if (ai_mesh->mNumVertices > 0)
    {
        for (int ii = 0; ii < ai_mesh->mNumVertices; ii++)
        {
            aiVector3D ai = ai_mesh->mVertices[ii];
            glm::vec3 vec = glm::vec3(ai.x, ai.y, ai.z);
            vertices_.push_back(vec);
        }
    }

    // Get Normals
    if (ai_mesh->HasNormals())
    {
        for (int ii = 0; ii < ai_mesh->mNumVertices; ii++)
        {
            aiVector3D ai = ai_mesh->mNormals[ii];
            glm::vec3 vec = glm::vec3(ai.x, ai.y, ai.z);
            normals_.push_back(vec);
        };
    }

    // Get mesh indexes
    for (int t = 0; t < ai_mesh->mNumFaces; t++)
    {
        aiFace* face = &ai_mesh->mFaces[t];
        if (face->mNumIndices != 3)
        {
            std::cout << "[??] Mesh face with not exactly 3 indices, ignoring this primitive.\n";
            continue;
        }

        indices_.push_back(face->mIndices[0]);
        indices_.push_back(face->mIndices[1]);
        indices_.push_back(face->mIndices[2]);
    }
    material_ = parent_model->getMaterial(ai_mesh->mMaterialIndex);
}

And render function, just in case.

void mesh::render()
{
    material_->bind();

    glVertexPointer(3, GL_FLOAT, 0, &vertices_[0]);
    glNormalPointer(GL_FLOAT, 0, &normals_[0]);

    glDrawElements(GL_TRIANGLES, indices_.size(), GL_UNSIGNED_BYTE, &indices_[0]);
}

Thanks ahead.


texts: Use my computer as a controller/keyboard for the PS3

texts: I imagine that I should be able to pair my computer to my PS3 via bluetooth and use my computer as a controller for the menus and for typing. Are there any open source projects that have done this? If not, where should I start to write my own? Maybe just look at the drivers people have written to pair their computer to the PS3 controller?


texts: Unity: Change the type of a Texture2D to "Normal map" through script

texts:
I am making procedural terrains through c# script, and while I achieve to produce a texture, a heightmap and a normalmap to Texture2D, it seems they are not being applied correctly to the material.

the texture (albedo) is applied
the noise map is applied (but as a "default" texture, I think?)
the heightmap is not even selected

The trick I currently use is to also save the Texture2D to files. After generation I manually affect the file normalMap and it goes fine. But you'll understand this is not satisfactory, I want the script to set the normal map correctly.

I suspect this is because the file's texture type is force to normal map. But I cannot see how I can change the type of an in-memory Texture2D through code.

Researches gave nothing fitting my concerns, any help will be appreciated.
Thanks:)

[EDIT]
I tricked by passing a pre-made normal map as parameter, to use instead of the one I generate. Guess what? It works instantly.


texts:
simple map

The map i would like to create is like this one, but simpler , what i want to have is a geographical map indicate high /low and a point that show where am i and  points indicate enemies

Thank you


texts: how to pick up multiple coins with Phaser?

texts:
I have a function that drops coins but I can only pick them up one by one when I click on them. Is it possible to make it so that I can pick up anything that overlaps?

dropCoins: function() {
var coinsNumber = 3;
for (var i = 0; i < coinsNumber; i++) {
  var coin = this.coins.getFirstDead();
  coin.body.collideWorldBounds = true;
  coin.anchor.setTo(0.5, 1);
  coin.reset(this.enemy.x, this.enemy.y - this.enemy.height / 2);
  game.physics.arcade.enable(coin);
  coin.body.bounce.set(0.3);
  coin.body.drag.set(80);
  coin.body.gravity.y = 1500;
  coin.body.velocity.y = -500;
  coin.body.velocity.x = Math.random() * 150 * util.plusOrMinus();
  coin.gold = Math.ceil( game.global.enemyHPTotal * (0.02 + (0.00045 * Math.min(game.global.level, 150))) );
  game.time.events.add(3000, this.removeCoin, this, coin);
}
this.coins.setAll('inputEnabled', true);
this.coins.callAll('events.onInputDown.add', 'events.onInputDown', this.removeCoin);

},

any help is appreciated. thanks


texts:
From what I understand being a level designer and a character/environment/object/etc Modeler are two different jobs, yet sometimes it feels like a Modeler can also do the job of the level designer.  I know this also depends on the scale of the game.  For small games maybe they are one and the same, but for bigger games they become two different jobs.

I understand a background in some modeling could not hurt when it comes to level design, but the question I have is:  Do jobs prefer people who can model for level designing?  This way they can kill two birds with one stone and have someone to create the assets and design the level.

What is your opinion of the training?  Does level design contain skill sets that make them completely different from what a modeler can do, or is this an easy transition for a modeler to become a level designer?  Can you be a bad level designer but a good modeler and vice versa?


texts: Managing data for large number of levels in Unity?

texts:
I am making a Unity game vaguely in the vein of Candy Crush Saga for a client and am moving in circles trying to decide how to manage the data for all of their levels.

In brief, they want to divide the game into multiple regions that each have 100 levels. For example, you might go to the world map, select Teddy Bear Islands, and then go to the winding-path style level select screen similar to King's "Saga" games. My goal is to have the levels be procedurally generated, so the data for each level will consist of dozen or so parameters instead of hundreds of variables. There will only be one scene, and the levels will be built by running the parameters through an algorithm.

The game isn't a match-3, but for comparison, imagine if your level data for a match-3 was just basic parameters like the number of each type of piece and the target score, and each time you started a level it would randomly arrange pieces based on the input parameters (instead of you manually declaring the position of each piece). The data for a level will look something like:

int targetScore
int levelType
float difficultyModifier
int numPieceA
int numPieceB
int numPieceC
int numPieceD

I haven't worked with such a large data set (in terms of the number of levels) in Unity before and am unsure how to structure it. In a less editor-driven engine, I would probably just store all of the levels in XML files. However, since this is a Unity project I feel like I should be making an editor-based solution that will be easier for the client to work with in the future.

With an XML-driven approach, I imagine that I would have an XML for each region containing all of the 100 levels in that region, and each location on the world map would be linked to one of the XML files. When the user selected a region, it would read the levels into an array, and link each of the 100 level buttons to an array index.

For a more editor-driven approach, I might create custom editor windows where the regions and levels can be defined, and then link the region and level buttons to the data from the editor window (I haven't done much with editor windows yet and am not entirely sure how to tackle this approach). Or I could create a serializable LevelData type and a simple MonoBehavior with a public array of LevelData so that the levels could be defined on GameObjects in the inspector.

Each solution has pros and cons, and I'm stuck on what to do. Is there a conventional approach for managing such a large number of levels in Unity? Should I try one of the above approaches, or is there a better solution?


texts: How could I draw text in an 'info bubble' with libgdx?

texts:
I am making an android game using libgdx where there are textures on the screen which represent people. When you touch a person sprite I want a little info bubble to pop above their head displaying some information about them in text form (something a bit like how speech is shown in a comic book). The sprites move and the info should follow above them until it is tapped closed.

I have got something working at the moment, which is really basic. I have rectangle that is part of the ShapeRenderer that is drawn, I then draw the text over the top using the batch draw.

I want the rectangle to have curved edges and resize depending on the size of the text but before I start writing something.

Does anyone have any suggestions on how I should go about it? Should I try and use dialog from scene2d and render my whole game using scene2d? From what I have seen it seems good for menus but I'm not sure about rendering a whole game using it.

Or is there something else?


texts: How can I detect collision between a circle and a rectangle?

texts:
I'm trying to make a clone of brick breaker, one problem that I am running in to is to do with collision. I know how to detect if a collision has happened but I do not know how to check what side of the brick is hit.

Some general background from the program.
all the bricks are just 2 points (x,y) a top right point and a bottom left point. The ball is just 1 point with a radius. for my current collision detection I'm checking if the ball's coordinates are at or in between the two box coordinates.


texts: Baked vs realtime global illumination in unity

texts:
I use unity. So far I know that the baked GI is less GPU processing when the game is played so if possible, I need to use baked GI.

Newbie question: I'm using unity and just curious in the light setting, is there any situation or in what condition that we can turn on both realtime and baked GI at the same time?  Or is it only practical to turn on one of them?


texts: Unity3d texture size different than original png image

texts:
While selecting a png image as a texture for a material in Unity, it shows different size (bigger) than the actual file size, why is this so?
how can I reduce its effective size to make it perform better without loosing much detail.

Size in windows explorer (825 kb)

and this is same image in Unity texture select window (1.3 MB)


texts:
I've seen a merge animation in a mobile game which you can check here;

https://youtu.be/G7l24Wtdcxw

You can observe the animation when the tiles combine.

Can it be done in Unity3d, may be using shaders? Or, do I need to use a 3d app like Blender?


texts:
I'm generating my terrain on the GPU, using diamond square subdivision (no height map involved). How can I anchor the camera's position to always be on top of the generated terrain?

Thanks


texts: How are "game rules" considered as data, in data-driven engines?

texts: I've read the definition of a data-driven game engine, in several places, and one item usually mentioned is the game rules: separating them from the logic of the engine. What is meant by a "game rule"? How could it be considered data?


texts:
I'm wondering if anyone knows some common and efficient ways to do a fast tracer for an instant bullet.

I've seen people speak on forums of using primitive lines with DirectX, but I doubt this is up to "Commercial" standards. I also thought of using some sort of minimal prism geometry encompassing the line and using a shader but even then, I'm not sure how to give it that nice glow and fade.
I'm obviously not looking for any code in specific, just some ideas in general.

Thanks,
Joey


texts: How can I achieve an "8-bit graphics" look?

texts:
I have a strong programming background just not from game development. I only made some pong and snake in high school and I did some OpenGL in college.

I want to make my own game engine. Nothing fancy just a simple 2D game engine. But because I'm kinda old school and feeling retro. I want graphics to look like old 8 bit games (megaman, contra, super mario, ...).

So how were the old games made back then? I want the simplest approach. Were they also using assets (images) like newer engines now do? How do you achieve this kind of rendering using OpenGL?

Keep in mind. Simplest solution. I want to know how it was made back then and how I can replicate that. Doesn't even have to be OpenGL. I can draw on window canvas. I do want to make it from scratch basically.


texts: Blender multiple animations and Collada export

texts:
Say I have a simple mesh in Blender, with two keyframes, like so:

Then, another animation for the same mesh, also with two keyframes:

Theese animations worke fine in Blender and I can switch between them in the Dopesheet, where they are called "actions":

The problem arises, when i try to export this to the Collada format, for use in my game engine. The only animation/action that seems to be carried over, is the one currently associated to the mesh. Is it possible to export multiple animations/actions for the same mesh, to the Collada format?


texts: Detect Sprites, they are in Shape or Not which random draw in Cocos2d

texts:
I have searched a lot on the web and found some helpful links but none solve my question.

Link 1 Link 2

I have written some code, to draw lines with Touch methods, but I still have questions. Here is what I need help understanding.

1 -> Line has been cleared after draw complete (this might go in ccTouchesEnded method /  UIPangesture state End.)
//I am not sure how to draw custom shapes with UIPanGesture or Touch methods.

2 -> Is there any difference between capturing the whole game scenario for collision as like scheduleUpdate method and how do I find out if objects are colliding (these are randomly moving sprites and they have random shapes)?

3 -> How to Check whether a User drawn shape is closed or open (a convex shape or not)?

4 -> How to check random moving sprites inside drawn shape or outside?

Here I have some code, but I am not sure whether it's useful or not.

//This code is in init method

linePoints = [[NSMutableArray alloc]init];
// create a simple rendertexture node and clear it with the color white
rtx = [CCRenderTexture renderTextureWithWidth:winSize.width height:winSize.height];
rtx.position = CGPointMake(winSize.width/2, winSize.height/2);
[self addChild:rtx z:6 tag:101];

brush = [[CCSprite spriteWithFile:@"Line1.png"] retain];
brush.scale = 5.0f;

Draw line by touch move method.

 -(void) ccTouchesMoved:(NSSet *)touchess withEvent:(UIEvent *)event
    {
        UITouch *touchMyMinge = [touchess anyObject];
        CGPoint start = [self convertTouchToNodeSpace:touchMyMinge];
        CGPoint end = [touchMyMinge previousLocationInView:touchMyMinge.view];
        end = [[CCDirector sharedDirector]convertToGL:end];
        end = [self convertToNodeSpace:end];

        NSValue *value= [NSValue valueWithCGPoint:start];
        [linePoints addObject:value ];

        [rtx begin];
        float distance = ccpDistance(start, end);

        for (int i = 0; i < distance; i++)
        {
            float difx = end.x - start.x;
            float dify = end.y - start.y;
            float delta = (float)i / distance;
            [brush setPosition:ccp(start.x + (difx * delta), start.y + (dify * delta))];
            [brush visit];
        }
        [rtx end];
    }

I have attached two screen shots for more clarification.

Please help me about on my technical query.


texts: Sharing the XNA executable of my game on dropbox

texts:
I'm currently making a game and I have my artist living in a different city as me.  We share a dropbox folder so that I can see her art, and I thought it should be easy to copy the debug bin folder into the dropbox so that she can see it.  This doesn't work (I can't even run it), so what could I do?

EDIT:

I run the executable in the dropbox folder, and immediately I get the "game.exe" has stopped working.  So obviously I have XNA installed, but my game can't run in this folder.


texts:
Encountered a strange error when using Direct3D11, feature level 10.0.

If the depth buffer texture is created with the format DXGI_FORMAT_R24G8_TYPELESS, bind flag D3D11_BIND_DEPTH_STENCIL | D3D11_BIND_SHADER_RESOURCE and the depth stencil view format DXGI_FORMAT_D24_UNORM_S8_UINT, everything is correct.
Also, there are no problems when the depth buffer texture format is DXGI_FORMAT_R32G8X24_TYPELESS and the depth stencil view format is DXGI_FORMAT_D32_FLOAT_S8X24_UINT.

However, when the depth buffer format is DXGI_FORMAT_R32_TYPELESS,
and the depth stencil view format is DXGI_FORMAT_D32_FLOAT, the whole geometry is not rendered at all, only the clear color is visible. I used Visual Studio 2015's Graphics Debugger to check if the geometry is rendered as desired, but during the Output Merger stage the whole geometry is discarded because it failed the depth test. Every Direct3D function call returns no error and the Direct3D debugging output reports no error (only INFO messages about creation/destruction of resources). I do not use the stencil functionality at all, and it is disabled.

I use a Windows 7 virtual machine as a developer machine and using DXGI_FORMAT_R32_TYPELESS and DXGI_FORMAT_D32_FLOAT worked flawlessly before I switched from a Windows 7 host to an Arch Linux host, because the old hard-drive started to fail and the operating system was unable to read its own files during boot. After I switched the host operating system, this problem started to occur inside the virtual machine.

Is it possible to have a bug somewhere else in my code?

Is there a limitation when using DXGI_FORMAT_D32_FLOAT and sometimes it may not be possible to use DXGI_FORMAT_D32_FLOAT or the other depth formats on every machine (considering D3D11 feature level 10.0 is available)?

Or is this a bug somewhere else, possibly in VMware player or Linux or Bumblebee (Optimus - Intel HD 4000 + GeForce GTX 650M)?


texts: Billboarding + aligning with velocity direction

texts:
I'm working on a particle system where I'm orientating the billboard using the inverted orientation matrix of my camera. This works quite well and my quad are rotated correctly towards the camera.

But, now I want to to rotate the quads in such a way that they point towards the direction they are going to.

In 2D this can be done by normalizing the velocity vector and using that vector for a rotation around the Z-axis  (where vel.x = cos(a) and vel.y = sin(a)). But how does this work in 3D?

Thanks
roxlu


texts: How can I make a clickable menu in WP 7/8?

texts:
I'm trying to make a clickable menu for my XNA Windows Phone game. If the player makes a tap gesture on a button(rectangle), something will happen. For example, the game will start if you touch the START button.
But I always have difficulties with collision detection. If the player touches a button, the collision is not always working. If the player touches the left border or the top of the button, nothing happens. But on the other hand, if the player touches the area next to the right side or next to the bottom of the button, the collision happens. I want that the collision just happens when the player touches the button, and not when the player touches the area next to it.

What is wrong? How can I solve the problem?
Is there a better way to make a clickable menu?

while (TouchPanel.IsGestureAvailable)
        {
            GestureSample gs = TouchPanel.ReadGesture();
            switch (gs.GestureType)
            {
                case GestureType.Tap:
                     {
                    tapState = new Rectangle((int)gs.Position.X, (int)gs.Position.Y, 1, 1);
                    nextmenu = true;
                     }
                break;
            }

                if (nextmenu == true)
                {
                 if (buttonBounds.Intersects(tapState))
                {
                    jchangetomenu = true;
                }
                 nextmenu = false;
                }
        }


texts: See precision (pr curves) in TensorBoard (Unity ml-agents)

texts:
How could I log and later view the precision values and/or pr curves of my Unity ml-agents onnx model? Precision values don't seem to be logged by default, as TensorBoard doesn't display anything at the moment despite me having a few trained models
Thanks in advance! :)


texts: Packaging HTML5 games as applications for iPhone/Android

texts: Is it possible to package HTML5 game for iPhone and Android as an application or does it have to be accessed through a browser?


texts: How to handle all the customization data for a Loot and Shooter?

texts:
Games like Borderlands, Fortnite, Destiny all have some sort of mechanic where your skills are modifiable by the equipment you carry.

For example in Borderlands, you can equip a pistol with generic damage of 100. The shield you equip also increases the damage of pistols only by 10%. Equipping a class mod increase any gun damage by 25%. And equipping an artifact reduces pistol damage by -10 points (Not a percentage). Your skill tree adds another 5%. And your Guardian rank adds another 2.9% of damage over time of 10 seconds. Moreover, your skill tree gives you the ability to add  5% to your health of the gun damage inflicted on an enemy for 10 seconds.

As you can see the forumla for calculating just gun damage for a pistol has a lot of moving parts.

There can literally be hundreds of possible combinations.

Then you have shields, grenades, and other buffs that are also practically endless with their own individual customization. On top of possibly modifying the other items you have equipped. By increasing your guns reload speed or your magazine size etc...

Is every possible attribute an interface? There may be instances where your equipped shield gives Shotguns a 5% increase in reload speed, but you dont' have a shotgun equipped.

Is there some master abstract character class with every possible key/value attribute? Then when you pick a character like a "Gunner" or "Siren" you inherit from the master character class so you have a base stat to start working with?

I know that some bullets are actual objects that travel through space and not just a ray-cast. Is every bullet equipped with some struct that carries along a bunch of information relevant to the gun that shot it and what it should do?

For example an "acid bullet" might have a base damage, a damage over time, and then a spread chance. On top of stealing 5% of the health of the target to give back to the shooter for x amount of time.

I've beent trying to wrap my head around how to implement such a system. How is such a system implemented?


texts: Any problems with flipping a sprite by scale? (2d Platformer)

texts: I am wondering if there are any problems with flipping a sprite on the x-axis using vector2 to tell which direction it is facing/flip. Though doing this helps me write less code for Ray-cast direction and creating single states with a single animation (using 1 animation player facing right than using 2 animation facing left and right). If there is a better solution please tell me and thanks. Btw I am still pretty new and learning.


texts: How do I find the largest circle possible in a square of pixels using Unity?

texts:
As I am using Unity, I can easily grab a square of pixels of any length. However, I want to find the largest circle possible within that square of pixels.

So for instance, if I had a 40 x 40 square of pixels, how would I get an array of pixels that form a circle inside of the square?


texts:
What sort of tools and techniques are available out there for 3D level creation?

In particular for small teams where you might not have the time and resources to make your level creation tools from scratch. I know you could use Blender or any other 3D modeling app for the geometry, but how do you manage the necessary metadata, triggers, game objects, etc?


texts:
I'm getting index out of bounds errors in my Bukkit plugin, and it's really beginning to piss me off...

I for the life of me can't figure this issue out!

Caused by: java.lang.IndexOutOfBoundsException: Index: 1, Size: 1

This is where I believe the code to be erroring...

for(int i = 0; i <= staffOnline.size(); i++) {
            if(i == staffOnline.size()) {
                staffList = staffList + staffOnline.get(i);
            } else {
                staffList = staffList + staffOnline.get(i) + ", ";
            }
        }


texts: Using Rigidbody.AddForce() twice seems to interfere with logic

texts:
So I created a magnetic effect, where objects are "sucked" into my player.
It works great.

Now I want those same objects to get a little Impulse force when they spawn. This has somehow reversed my magnetic effect? The objects are now pushed away from the player...

All I did was add this Line in Start():

_rb.AddForce(_forwardThrust, _upThrust, _forwardThrust, ForceMode.Impulse);

Full Script here:

public class RandomMagneticForce : MonoBehaviour
{
    private bool _inside;
    private Transform _magnet;
    private Rigidbody _rb;
    private SphereCollider _sphere;
    float radius = 5f;
    [SerializeField]
    private float _delay;
    [SerializeField]
    private float _force = 70;
    [SerializeField]
    private float _upThrust, _forwardThrust;

    void Start()
    {
        _magnet = GameManager.instance.ActivePlayer.gameObject.transform;
        _rb = GetComponent<Rigidbody>();
        _sphere = GetComponent<SphereCollider>();
        _inside = false;
        _rb.AddForce(Random.Range(-_forwardThrust, _forwardThrust), _upThrust, Random.Range(-_forwardThrust, _forwardThrust), ForceMode.Impulse);
    }

    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.CompareTag(Constants.TAG_PLAYER))
        {
            _inside = true;
        }
    }
    void OnTriggerExit(Collider other)
    {
        if (other.gameObject.CompareTag(Constants.TAG_PLAYER))
        {
            _inside = false;
        }
    }

    private void Update()
    {
        if (_delay > 0)
            _delay -= Time.deltaTime;

        if (_inside)
        {
            if (_delay <= 0)
            {
                Vector3 magnetField = _magnet.position - transform.position;
                float index = (radius - magnetField.magnitude) / radius;
                _rb.AddForce(_force * magnetField * index);
            }
        }
    }
}


texts: opengles display human face in iphone and animate it?

texts:
I need to make a human 2D face to 3D face.
I used this link to load an ".obj" file and map the textures. This example is only for cube and pyramid. I loaded a human face ".obj" file.

This loads the .obj file and can get the human face properly as below.

But my problem here is I need to display different human faces without changing the ".obj" file. just by texture mapping.

But the texture is not getting mapped properly, as the obj file is of different model. I just tried changing the ".png" file which is used as texture and the below is the result, where the texture is mapped but not exactly what I expected, as shown below.

The below are my few questions on it :

1) I need to load texture on same model( with same .obj file ) with different images. Is it possible in opengles?

2) If the solution for above problem  is "shape matching", how can I do it with opengles?

3) And finally a basic question, I need to display the image in large area, how to make the display area bigger?


texts:
I have been working for several days to try and figure out how to change a texture whenever a scene2d Table is clicked in libgdx, I am using pixmaps to dynamically change the textures colors instead of changing the texture completely.

everything works fine when i detect key presses so whenever i press 1 the color of the players hair changes to a random color but now i want it to happen when i press a Table.

to change the texture i use this method

public static Texture genDynamicTexture(String path, HashMap<String,Color> colors) {

    //load texture from asset handler
    Texture texture = GameUtils.getGame().manager.get(path,Texture.class);

    //create pixmap from texture
    if(!texture.getTextureData().isPrepared()) {
        texture.getTextureData().prepare();
    }
    //transfer pixel data from gpu to cpu
    Pixmap pixmap = texture.getTextureData().consumePixmap();

    //grey-scale colors
    Color gsHair = toColor(207,31,201);
    Color gsSkin = toColor(207,97,31);
    Color gsShirt1 = toColor(39,207,31);
    Color gsShirt2 = toColor(65,65,160);
    Color gsPants = toColor(90,9,22);
    Color gsShoe1 = toColor(253,255,66);
    Color gsShoe2 = toColor(43,58,50);
    Color black = toColor(0,0,0);

    //loop through pixels in the pixmap
    for(int x = 0; x < pixmap.getWidth(); x++) {
        for(int y = 0; y < pixmap.getHeight(); y++) {
            int pixelColor = pixmap.getPixel(x, y);
            if(pixelColor != 0 && pixelColor != Color.rgba8888(black)) {
                if(pixelColor == Color.rgba8888(gsHair)) {
                    pixmap.setColor(colors.get("hair"));
                    pixmap.drawPixel(x, y);
                }else if(pixelColor == Color.rgba8888(gsSkin)) {
                    pixmap.setColor(colors.get("skin"));
                    pixmap.drawPixel(x, y);
                }else if(pixelColor == Color.rgba8888(gsShirt1)) {
                    pixmap.setColor(colors.get("shirt1"));
                    pixmap.drawPixel(x, y);
                }else if(pixelColor == Color.rgba8888(gsShirt2)) {
                    pixmap.setColor(colors.get("shirt2"));
                    pixmap.drawPixel(x, y);
                }else if(pixelColor == Color.rgba8888(gsPants)) {
                    pixmap.setColor(colors.get("pants"));
                    pixmap.drawPixel(x, y);
                }else if(pixelColor == Color.rgba8888(gsShoe1)) {
                    pixmap.setColor(colors.get("shoe1"));
                    pixmap.drawPixel(x, y);
                }else if(pixelColor == Color.rgba8888(gsShoe2)) {
                    pixmap.setColor(colors.get("shoe2"));
                    pixmap.drawPixel(x, y);
                }
            }
        }
    }

    //transfer pixel data from cpu to gpu
    Texture tex = new Texture(pixmap);
    pixmap.dispose();
    texture.dispose();
    return tex;

}

like i said everything works fine if it is a key press but when i detect it using a Table it does not work ( i have already added it to the stage and am calling stage.act() and stage.draw() )

color.addListener(new ClickListener() {
        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
            return true;
        }
        @Override
        public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
            characterPack.reloadSpriteSheet("Players/greyscale-player.png", 2, 2, characterPack.colors, "skin");
        }
    });

thanks in advance.


texts: Issue translating objects by one unit in the y direction

texts:
I'm currently making space invaders (in OpenGL/SDL) and I'm running into an issue with the movement of the aliens. I have a 2-d vector of aliens (5 rows of 11) and I'm translating each in the x direction by a constant factor times elapsed time. If the right or leftmost alien in the vector hits either side of the screen, I decrement the y position of every alien. For some reason, when it collides the side of the screen, it infinitely translates downward in the y direction.

I thought that this would not happen since I wasn't multiplying the y position by elapsed time, but I think that its probably happening due to the fact that the update() method is being called once per frame. Here is the code for the update function (inside of the enemies class which holds the 2-d array):

void update(float elapsed) {
        //Update positions

        float minX = -5.2;
        float maxX = 5.2;

        bool hitRight = false;
        bool hitLeft = false;

        //if the enemies haven't hit the right side
        if (((enemyVect[0][rightmost]->x) + ((enemyVect[0][rightmost]->width) / 2.0) <= maxX)) {
            for (int i = 0; i < enemyVect.size(); i++) {
                for (int j = 0; j < enemyVect[i].size(); j++) {
                    enemyVect[i][j]->x += elapsed * 0.4 * xDirect;

                }
            }

        }
        //if they've hit the right side
        else if(((enemyVect[0][rightmost]->x) + ((enemyVect[0][rightmost]->width) / 2.0) >= maxX)){
            xDirect = -1;
            hitRight = true;
            for (int i = 0; i < enemyVect.size(); i++) {
                for (int j = 0; j < enemyVect[i].size(); j++) {
                    if(hitRight)enemyVect[i][j]->y -= 0.6; //move each row of enemyVect down to the next level
                }
            }
            hitRight = false;
        }
//if the enemies haven't hit the left side
        if (((enemyVect[0][leftmost]->x) -((enemyVect[0][leftmost]->width) / 2.0) >= minX)) {
            for (int i = 0; i < enemyVect.size(); i++) {
                for (int j = 0; j < enemyVect[i].size(); j++) {
                    enemyVect[i][j]->x += elapsed * 0.4 * xDirect;
                }
            }

        }
//if they've hit the left side
            else if (((enemyVect[0][leftmost]->x) - (enemyVect[0][leftmost]->width / 2.0) <= minX)) {
                xDirect = 1;
                for (int i = 0; i < enemyVect.size(); i++) {
                    for (int j = 0; j < enemyVect[i].size(); j++) {
                        enemyVect[i][j]->y -= 0.6; //move each row of enemyVect down to the next level
                    }
                }
            }
        }

    };

How should I go about making it so that the y position of each alien only gets decremented once right after the collision with either side of the screen?


texts: What are width and height supposed to be in Nez TiledTileLayer?

texts:
The constructor of TiledTileLayer.cs takes 4 simply-named arguments. I'm assuming name is the layer's name but I can't figure out what width and height are supposed to represent.

public TiledTileLayer( TiledMap map, string name, int width, int height ) {}

Is it the width of the map, the width of the tile, the number of tiles? Should I hardcode it or get it from another object?

Thanks


texts: I just started implementing some physics in my game with Bullet Physics and I was just wondering how would i use bullet physics to load in meshes. For my for DirectX I load in x files into a ID3DXMesh. I'd like to know how do I create a mesh in bullet physics instead of using boxes and spheres. I can't seem to find a way to do this. It would be great if someone could help me out. Thank you.


texts:
I am currently working on a project and usually in C++ I use the function.
ByteBuffer glMapBuffer(int target, int access)

usage:

FloatBuffer buffer = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY).order(
    ByteOrder.nativeOrder()).asFloatBuffer();

But in java (lwjgl 3.0.0) this function returns null, because of this reason it throws a NullPointerException.

Anyone any idea how to use this function in java?

There are several functions:

glMapBuffer(int target, int access)
glMapBuffer(int target, int access, ByteBuffer old_buffer)
glMapBuffer(int target, int access, long length, ByteBuffer old_buffer)

I hope this is specific enough, thank you for your help :D


texts: Advanced copying between textures in OpenGL

texts:
I have many RGBA textures in my project. I often copy a part of one texture into another texture using copyTexSubImage2D . I am probably able to copy just a specific channel by setting mask (colorMask).

I would like to multiply (and store) the alpha of one texture by an alpha of another texture. Is it possible to do it somehow without creating and calling shaders?  I am working with WebGL 1.0 (OpenGL ES 2.0).


texts: How to rotate CharacterController on slope

texts:
I'm trying to rotate my characterController player on a slope on the 'x' and 'z' axises, however things aren't going so well.

The player does rotate, but if I move and look in another direction, the characterController will still be on the same axis, and won't look down an up slope, and instead will be looking up a down slope.

void Update ()
{
   Vector3 rotateDirection = (camera.forward * Input.GetAxis("Vertical"))
                           + (camera.right * Input.GetAxis("Horizontal"));

   Quaternion newRotation = Quaternion.LookRotation(
                               new Vector3(rotateDirection.x, 0f, rotateDirection.z));
   transform.rotation = Quaternion.Slerp(
                               transform.rotation, newRotation, rotSpeed * Time.deltaTime);
 }

private void OnControllerColliderHit(ControllerColliderHit hit)
{
      transform.rotation = Quaternion.Euler(hit.transform.rotation.eulerAngles.x,
                   transform.rotation.eulerAngles.y, hit.transform.rotation.eulerAngles.z);
}

Also, it doesn't work at all with spheres and terrain since their rotation is zero. Anyone know how to achieve what I am talking about? Also, the goal is to allow for the 'y' axis to be free and do what it needs to in void Update().


texts: How can I update Display settings from an Options screen without restarting?

texts:
I'm currently creating a 2D RPG in C++11 with Allegro 5 and boost.
My goal is to somehow update my game settings when an option is changed in the Options Menu. I don't want to force the user to restart my game. Other games don't require a restart when changing resolution or going from fullscreen to windowed, so my game shouldn't either. Please see a simplified view of the system below.

Please note that I am not necessarily wanting to directly call my Game object from the OptionsScreen. The dashed line is merely to illustrate the effect I am trying to achieve; to somehow cause an update of the game when an option is changed in a different part of the system.
Detailed explanation

The ScreenManager contains a list of all GameScreen objects currently in existence. These will be various screens in the game including popups. This design adheres more or less to the Game State Management sample in C#/XNA.
The ScreenManager contains a reference to my Game object. The Game object initializes and modifies the game's settings. If I want to change the resolution, go fullscreen, or mute the volume I would do so in the Game class.
However, the OptionsScreen currently cannot access the Game class. See below diagram:

A GameScreen can signal three events, onFinished, onTransitionStart and onTransitionEnd. There is no onOptionsChanged because only one screen does that. The ScreenManager cannot set-up the event handling for that because it handles all screens as GameScreens.
My question is, how can I change my design so that a change in the OptionsMenu doesn't require a restart, but is changed immediately? I would preferably request my Game object to update once the apply button is clicked.


texts: Unity: How to Raycast in a 360 VR video?

texts:
I have set up a basic inverted sphere in unity and am running a 360 video inside it and it is working fine in VR. But i want to raycast inside that video to show information about some objects which are shown in the video.

Is that possible? If yes then i should i go about it?

https://unity3d.com/learn/tutorials/topics/virtual-reality/interaction-vr?playlist=22946

This article says that i need three scripts for it: VREyeRaycaster, VRInput, and VRInteractiveItem

I have seen some people do it on Youtube and I suppose they put 3D objects in their videos behind the objects they want to highlight and then they raycast.

i want to create a virtual tour of some places, the videos of which i will shoot in 360 and import in unity. i have already set up my inverted sphere and a sample video running on it. then i want to pause the video at certain points and show information about some objects on clicks by user.


texts: How to receive a Knock Back when the player touched the enemy

texts:
I'm still new to C#, making my 2D game atm and my problem is how can I give my player a Knock Back when it touches the enemy. How to add it with this code?

public int health;

private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.CompareTag("Enemy"))
    {
        health -= 20;
        //Check for death
        if (health <= 0)
        {
            gameObject.SetActive(false);
        }
    }
}


texts:
I want to use Blender for making models yet realize some of the polygons are not triangles but contain quads or more (example: cylinder top and bottom).

I could export the the mesh as a basic mesh file and import it in to an openGL application and workout rendering the quads as tris, but anything with more than 4 vert indices is beyond me.

Is it typical to convert the mesh to a triangle-based mesh inside blender before exporting it? I actually tried this through the quads_convert_to_tris method within a blender py script and the top of the cylinder does not look symmetrical. What is typically done to render a loaded mesh as a tri?


texts: Procedural Dungeon Generation: Is there a simple algorithm to make sure all of these rooms get connected using minimal corridors?

texts:
Is it possible to get a hive-like structure, connecting all the rooms without having too many corridors? (Too many being 3-4+ corridors coming from a single room)

Below is the output of how my rooms look, basically they randomly placed.

What I'm hoping to get corridor-wise.


texts: A specific but basic tutorial for Corona SDK?

texts:
I have been looking at Corona SDK and it would be helpful if I could see a tutorial/example to accomplish the following:

Load an image as a background/map
Draw a circle on the screen
user can tap elsewhere and the circle moves to that location (this can be repeated)

Does anyone know of any examples out there?


texts: Adobe Air turn based multiplayer Game, sockets vs http bandwidth

texts:
I am developing an Adobe Air multiplayer game for iPad.
It is turn based and not realtime. It is like checkers game.
I want to use a client server model.
I have found 2 options to connect to server so far:  socket connection and http requests

My question is:
Is the bandwidth requirement for socket connection vs http requests different?
I need the game to work with very low speed internet connections


texts:
Sorry for the terrible title, but I really cant think of anything better.. Suggestions welcome.

I am trying to do something like showcased in this video:

http://www.youtube.com/watch?v=CaTI2d0tQME

So basically smoothly change the opacity when looked face-on.

This is my vertex shader so far, the fragment shader is simple as it just multiplies the lightColor with the texture:

#version 430 core

uniform mat4 MV;
uniform mat4 MVP;

layout(location = 0) attribute vec3 vertexPosition;
layout(location = 1) attribute vec2 vertexUV;
layout(location = 2) attribute vec3 vertexNormal;

layout(location = 3) attribute mat4 bufferMatrix; // For per-instance translation

varying  vec2 UV;
varying  vec4 lightColor;
flat varying int InstanceID;

void main(){
    vec4 mcPosition = MV * bufferMatrix * vec4(vertexPosition, 1.0);
    mcPosition = mcPosition / length(mcPosition);

    vec3 mcNormal = vertexNormal;

    vec3 ecNormal = vec3(MV * bufferMatrix * vec4(mcNormal, 0.0));
    ecNormal = ecNormal / length(ecNormal);

    float dotProduct = dot(vec4(mcNormal, 1.0), mcPosition);

    lightColor = vec4(dotProduct);

    gl_Position = MVP * bufferMatrix * vec4(vertexPosition, 1.0);
    UV = vertexUV;
    InstanceID = gl_InstanceID;
}

The base is copied code from a 'phong' shader - that works!.. I have tried everything I could think of, as well as searched google for quite some time.

I think I realize what I need to do mathematically, which is getting the dot-product of the vertex-normal on to the view-to-vertex vector. That is mathematically speaking, another is to do it in GLSL with matrices etc.

I am bad at debugging GLSL code, but right now the lightColor is always 0, no matter where I look at the model from.

Quick Bonus Question: What is the technique in the video actually called - if anything?


texts:
So I want to be able to click on these targets and have them destroy themselves. Right now I have many OnMouse functions all just trying to print something for testing. For whatever reason it doesn't fire. I'm sure theres something simple I'm missing. Anyones help is greatly appreciated. Here is a picture of Unity itself and the code.

using UnityEngine;
using System.Collections;

public class TargetLogic : MonoBehaviour
{

    // Use this for initialization
    void Start ()
    {

    }

    // Update is called once per frame
    void Update ()
    {
        //print("ok");
    }

    void OnMouseDown()
    {
        print("Works");
    }
    void OnMouseEnter()
    {
        print("Enter");
    }
    void OnMouseUp()
    {
        print("up");
    }
    void OnMouseOver()
    {
        print("Over");
    }
}

I also Have tried with a 2d Rigidbody as shown here


texts: How to get smooth transition within slick?

texts: When a player clicks start, my app immediately switches to the first level. My question is how do I incorporate a smooth transition within Slick?


texts: How to render a very large amount of objects in a single call to drawelementarrays() in OpenGL?

texts:
The gist of the situation is as follows. I have hundreds of cubes that need to be rendered. The cubes share the exact same mesh, but they will be rendered at different positions. The position of the cubes is mostly static but can change at any point.

The cube object looks as follows:

class Cube
{
    private:
        static Geometry *mesh;
        static Texture *texture;

        static string Default_Mesh;
        static string Default_Texture;

    public:
        static void make_template(string wavefront_file, string t);
        static void cleanup();

        vec3 position;

        Cube(vec3 p);
        Cube();
        ~Cube();

        void render_cube();
};

My goal is to try to render all cubes in a single call to drawElementArrays() by passing all vertices to the GPU, all Translation matrices to the GPU and then specify that the first 36 vertices use the first translation matrix, the next 36 vertices use the next translation matrix...

But also, even though they share the same geometry, they all have different textures, so I also need to specify the sampler 2D object that each vertiex uses.

Thanks in advance.


texts:
I'm trying to write a shader that only maps a portion of a large texture to my sprite and I'm getting a strange behaviour with my current code.
This is what I have right now:

Texture atlas example (256x256px):

EDIT
I've changed both shaders and I get the following output right now (first image), but I need to zoom the texture so I only render the highlighted portion of the second image, how should I modify the shaders to achieve that?
 ->

These are my current shaders:
Vertex:

uniform mat4 uMVPMatrix;
attribute vec4 aPosition;
attribute vec2 aTextureCoord;
varying vec2 vTextureCoord;
varying vec2 vTextureCoordOffset;
void main() {
    // offset and texSize will be defined as attributes later.
    // They're defined here for test purposes only
    vec2 offset = vec2(128.0, 64.0);
    vec2 texSize = vec2(256.0, 256.0);

    float u = offset.x / texSize.x;
    float v = offset.y / texSize.y;
    vTextureCoordOffset = vec2(u, v);
    vTextureCoord = aTextureCoord;
    gl_Position = uMVPMatrix * aPosition;
}

Fragment:

precision mediump float;
uniform sampler2D sTexture;
varying vec2 vTextureCoord;
varying vec2 vTextureCoordOffset;
void main() {
    gl_FragColor = texture2D(sTexture, fract(vTextureCoord) + vTextureCoordOffset);
}

SOLVED
I solved it changing the fragment shader to:

gl_FragColor = texture2D(sTexture, fract(vTextureCoord) * vZoom + vTextureCoordOffset);

vZoom is calculated in the vertex shader:

vZoom = subTextureSize / texSize;


texts: Altering Animation Playback Given Terrain Information

texts:
Say my character has a jog animation.  Assuming Y is vertical, his feet leave the ground at Y=0 and hit the ground again at Y=0.  This works fine in a world like that of Minecraft, where every surface the player could traverse is flat.

Now say the character is jogging through hilly terrain.  Without any transformations, the animation would break through the ground at certain points.  (As the character's foot is lifted and moved forwards, it would go straight through the hill.)

How do I remove this artifact?  Do I ask the artists to create separate animations depending on the grade of the terrain?  Is there a standard system to resolve animation-world collisions that I'm unfamiliar with?  Or is there another more logical approach I haven't thought of yet?


texts: How can I make sure custom XNA content processors find included files with relative paths?

texts:
MSDN has an example of a custom HLSL effect importer and processor. Here is the importer's code:

public override PSSourceCode Import(string filename,
    ContentImporterContext context)
{
    string sourceCode = System.IO.File.ReadAllText(filename);
    return new PSSourceCode(sourceCode, System.IO.Path.GetFileNameWithoutExtension(filename));
}

In the processor they do this:

    EffectContent effectSource = new EffectContent();
    effectSource.EffectCode = input.SourceCode;
    EffectProcessor processor = new EffectProcessor();
    compiledEffect = processor.Process(effectSource, context);

The sample works okay, however, when you try to import and process an effect file that has #include "otherEffect.fx" directive in it, the build process throws an error "Failed to open source file 'otherEffect.fx'". I presume that is because the relative path of the file is not specified correctly but I don't know where to specify it. Does anyne know this?


texts: Do I have to keep textures in Android games smaller than 1024^2?

texts:
I have read tips in books and article that point out, if you are making a game for Android, make sure your textures are =< 1024^2, or you'll not reach all your potential customers.

I have never found a concrete statistic that proves this claim. What are we talking about, here, 5% of Android devices only support 1024? 10%? 80%?


texts: Unity Shader-Graph randomly tiled sprite

texts:
Lets say I have a shader with a clean white tile. Then I use it on a wall and tile it a few times.

I also have a sprite with numbers.

Now, is it possible and if yes how. To put a random sprite number ontop of the already tiled texture.
Example:
I am pretty sure this can be achieved with shadergraph, but I am hardly an expert and I really dont want to spend a month or more try-erroring my way through...


texts: Right way to get reference from across scene object in unity

texts:
I need a reference for the game-object from another scene but the problem is that the scene object by default is off. So I thought that
I should place its reference in another script and get a reference from it. But it will introduce me to a new script (third script) which means a new dependency. Now here is the triangle to solve the issue (which i don't like and posting here)

First scritp where the refrence is require

The actual refrence (Script/game-object) reside in a separate scene.

The reference holder

My consideration is that this is not the right way to do this job as its required dependency. How can i efficient and more professionally deal with it?


texts: Is there a way to setup a notification from Unreal Engine when it finishes packaging / building my game?

texts:
In Unity I was able to use a post build script to send myself an email when Unity finishes building a game. Is there a way to make a script run when Unreal Engine is done packaging a game?

Or any other way to set up a notification sound or visual prompt in my Windows PC to alert me when it finishes packaging?


texts: How can I convert a tilemap to a Box2D world?

texts:
I want to use Box2D physics and lighting with a .tmx map. How can I "convert" a tilemap to Box2D world? My basic idea is to go through the tiles on the map and create an object for them in Box2D.

I'm using the Tiled map editor for the tilemap, and the target platform is PC.

Firstly, is this a good solution for my idea? Or is this even possible?
Secondly, if yes, then I dont know how to get the tile's position.

My code so far:

public class WorldLoader {
public static TiledMap map;

public static void loadMap(String mapName) {
    map = new TmxMapLoader().load(mapName);
    TiledMapTileLayer collisionLayer = (TiledMapTileLayer) map.getLayers().get("collision");

    for (int x = 0; x < collisionLayer.getWidth(); x++) {
        for (int y = 0; y < collisionLayer.getHeight(); y++) {
            Cell cell = collisionLayer.getCell(x, y);

            if (cell != null && cell.getTile() != null) {
               // float tileX = collisionLayer.getProperties().containsKey("x");
               // float tileY = cell.getTile().getProperties().get("y", Integer.class);

                BodyDef bodyDef = new BodyDef();
                bodyDef.position.set(tileX, tileY);

                PolygonShape shape = new PolygonShape();
                shape.setAsBox(16, 16);

                Body body = GameWorld.world.createBody(bodyDef);
                body.createFixture(shape, 0f);

                shape.dispose();
            }
        }
    }

}

}


texts:
I have a generic HTML5 Canvas GUI Button class and a Scene class. The Scene class has a method called createButton(), which will create a new Button with onclick parameter and store it in a list of buttons. I call createButton() for all UI buttons when initializing the Scene. Because buttons can appear and disappear very often during rendering, Scene would first deactivate all buttons (temporarily remove their onclick, onmouseover etc property) before each render frame. During rendering, the renderer would then activate the required buttons for that frame.

The problem is that part of the UI requires a variable number of buttons, and their onclick, onmouseover etc properties change frequently. An example is a buffs system. The UI will list all buffs as square sprites for the current unit selected, and mousing over each square will bring up a tooltip with some information on the buff. But the number of buffs is variable thus I won't know how many buttons to create at the start. What's the best way to solve this problem? P.S. My game is in Javascript, and I know I can use HTML buttons, but would like to make my game purely Canvas-based.

Create buttons on-the-fly during rendering. Thus I will only have buttons when I require them. After the render frame these buttons would be useless and removed.
Create a fixed set of buttons that I'm going to assume the number of buffs per unit won't exceed. During each render frame activate the buttons accordingly and set their onmouseover property.
Assign a button to each Buff instance. This sounds wrong as the buff button is a part of the GUI which can only have one unit selected. Assigning a button to every single Buff in the game seems to be overkill. Also, I would need to change the button's position every render frame since its order in the unit's list of buffs matter.
Any other solutions?

I'm actually quite for idea (1) but am worried about the memory/time issues of creating a new Button() object every render frame. But this is in Javascript where object creation is oh-so-common ({} mainly) due to automatic garbage collection. What is your take on this? Thanks!


texts:
I am currently creating a c++ program to eventually use in Unity. This c++ program contains references to libraries like OpenCV and dlib, referenced with a include statement which calls in other files, which are installed on my machine. My question is:

How do you compile your c++ project so that it runs in Unity completely self-contained? i.e no reference to external files are needed, and all that are references are included within the program. Is there a specific tool to use, or a useful tutorial on the net?

Thanks for the help.


texts: Extend distance for rendering grass and tree objects on terrain

texts:
I am trying to make an adventure game with a big landscape (made the terrain with terrain tools) with 3D models of grass (that I placed using terrain tools) but it only shows the grass/trees that are within a small area. Here is a pic of what I am talking about:

I would not want to totally remove this because otherwise the framerate will go too low. I just want to make the circle bigger.
thanks (:


texts:
I am writing a turn based rpg game, the fighting process is sent by server which can not change by player. The data of fighting process is an array of round info. Each round info contain what happens in this round in order such as unit A attack unit B.

When client get fighting process data, it needs play animation according to this data. I am try use "action sequence"(a concept in cocos2d, which put all actions in an array, so actions will be executed in their order in that array) to implement this, for example, I make a action let unit move to a point, add it to array, then make a action of target unit be attack, add it to array... after the sequence construct complete, run it. But I found generate the action sequence code is too complex and hard to maintain.

So I want ask is there better way to do this? I also consider add timer in each unit, but it seems hard to calculate the time point of each animation playing.


texts: What uses are there for multiple UV maps on a model?

texts: I'm trying to think of some reasons why there might be more than one UV map on a mesh. Usually I just unwrap the model, and the same UV map works for both the diffuse color texture, the bump map texture, and any other textures I chose to add. Are there any examples of when a model might need more than one UV map?


texts: Worker threads are not being utilized in Time rewind system, is this job system really multi-threaded?

texts:
I am trying to make a simple time rewind mechanic. It's working but it becomes slower as number of game objects increases. I decided to give Job System a shot. My idea is to interpolate between positions and rotations for N game objects in parallel. It is certainly running faster than single thread execution.
However, when I see the profiler, the worker threads are sitting idle.
Here's the screenshot:

And here's the IJob code:
using System;
using System.Collections.Generic;

[BurstCompile]
struct RewindJob : IJob
{
    public int RewindableIndex;
    [ReadOnly]
    public NativeArray<Vector3> positions;

    public NativeArray<Vector3> finalPositions;
    public float currentTime;

    public void Execute()
    {
       //rewind code for interpolating b/w positions
    }
}

and this is how I schedule RewindJob for each entity like this in main thread:
NativeArray<Vector3> finalPositions = new NativeArray<Vector3>(m_Objects.Count, Allocator.TempJob);

for (int i = 0; i < m_Objects.Count; i++)
{
    NativeArray<Vector3> positions = new NativeArray<Vector3>(count, Allocator.TempJob); ;

    TimeRewindable rewindable = m_Objects[i];

    for(int yo = 0; yo < count; yo++)
    {
        positions[yo] = rewindable.m_Transforms[yo].position;
    }

    RewindJob rewindJob = new RewindJob();
    rewindJob.finalPositions = finalPositions;
    rewindJob.positions = positions;
    rewindJob.RewindableIndex = i;

    JobHandle handle = rewindJob.Schedule() ;
    handle.Complete();
    positions.Dispose();
}

for(int i = 0; i < m_Objects.Count; i++)
{
    m_Objects[i].transform.position = finalPositions[i];
    m_Objects[i].transform.rotation = finalRotations[i];
}

finalPositions.Dispose();
finalRotations.Dispose();

What I can understand is it's not real multi-threading but context switching. Can anyone just explain a little bit what's happening? Thanks.


texts:
I am trying to figure out the best way to share an image between OpenGL and OpenCV libraries. I perform a render to texture on OpenGL, so I have and FBO/texture that then I want to pass it OpenCV, where (ideally) I will be some GPU stuff with it.

I know a naive way would be using glReadPixels, but this is obviously way to slow. It requires to copy the data from GPU memory to memory and then load it through cvLoadImage or similar in OpenCV.

I am pretty sure there must be a way to bind or map the memory from OpenCV, so I can "load" an image by just accessing to its FBO pointer or something like that... but I cannot figure out how.

I have goggled a lot about it, and so far I could just find this answer that I don't quite understand. What do they mean by glbuffer.bind();?

Any guess? Thanks.


texts: Is it a bad idea to "map" the mouse position on the screen so that collision detection works regardless of resolution?

texts:
Consider a game who's default resolution is 800x600. Objects with collision masks are placed in a game world of size 800x600. The collision masks can detect when the mouse collides with them.

Now consider we scale the game up to 1024x768 (assume we scale the graphics by simply rendering everything to a layer and then scaling the entire layer up at once). We have two options for making the collisions with the mouse work properly in this new resolution:

A.) Scale up the world to 1024x768 and scale every object's collision mask accordingly.

B.) "Map" the mouse position onto the original world (800x600).

By "map" I mean simply scale the mouse position onto the original 800x600 world. So for example, if the mouse position on the screen is (1024, 768), then the mouse position in the world is (800, 600).

Now obviously, option B requires way less computation and is probably less prone to geometric errors, but it also feels kind of "hackish" to me, like there are unforeseen consequences of going with this method that will be hell to fix later on.

Which method should I go with: A, B, or something else?


texts:
I'm writing a rather simple "ShaderManager" which aids me with loading shaders in Open GL, altough I am having a few issues:

The shaders don't link correctly
The the attributes don't bind

Here's the output of my program:

The shaders did not link correctly.
Could not bind attribute: v_coord3d
Could not bind attribute: v_color
Could not bind uniform: mvp

And here's the relevant code and header file...

void ShaderManager::create_program(std::string name)  {
    GLuint vertexshader;
    GLuint fragmentshader;

    GLint link_ok = GL_FALSE;

    if ((vertexshader = create_shader(name + ".v.glsl", GL_VERTEX_SHADER)) == 0)  {
        print_shader_errors(&vertexshader);
    }

    if ((fragmentshader = create_shader(name + ".f.glsl", GL_FRAGMENT_SHADER)) == 0)  {
        print_shader_errors(&fragmentshader);
    }

    program_values.emplace_back(glCreateProgram());
    program_keys.emplace_back(name);
    glAttachShader(program_values[program_values.back()], vertexshader);
    glAttachShader(program_values[program_values.back()], fragmentshader);
    glLinkProgram(program_values[program_values.back()]);

    glGetProgramiv(program_values[program_values.back()], GL_LINK_STATUS, &link_ok);

    if (!link_ok)  {
        std::cout << "The shaders did not link correctly." << "\n";
    }
}

bool ShaderManager::bind_attribute(std::string shader_name, std::string attribute_name)  {
    GLuint attribute = glGetAttribLocation(get_program(shader_name), attribute_name.c_str());

    if (attribute != -1)  {
        attribute_values.emplace_back(attribute);
        attribute_keys.emplace_back(attribute_name);

        return true;
    }

    std::cout << "Could not bind attribute: " << attribute_name << "\n";

    return false;
}

// bind uniform function is much the same as the above

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

        static GLuint get_program(std::string shader_name);
        static int get_index_of_program_key(std::string program_name);

        static void create_program(std::string name);
        static bool bind_attribute(std::string shader_name, std::string attribute_name);
        static bool bind_uniform(std::string shader_name, std::string uniform_name);

    protected:
    private:
        static std::vector<GLuint> program_values;
        static std::vector<std::string> program_keys;

        static std::vector<GLuint> attribute_values;
        static std::vector<std::string> attribute_keys;

        static std::vector<GLuint> uniform_values;
        static std::vector<std::string> uniform_keys;

        static void print_shader_errors(GLuint *shader);
        static const char* file_read(std::string filename);
        static GLuint create_shader(std::string filename, GLenum type);
};

Here's the code which actually calls the functions:

ShaderManager::create_program("shader");
ShaderManager::bind_attribute("shader", "v_coord3d");
ShaderManager::bind_attribute("shader", "v_color");
ShaderManager::bind_uniform("shader", "mvp");

Another issue I have is that I can't access a string in a vector list with program_names[0], anyone know why?


texts:
I've been getting interested in the Entity/Component style of game programming, and I've come up with a design in C++ which I'd like a critique of.

I decided to go with a fairly pure Entity system, where entities are simply an ID number. Components are stored in a series of vectors - one for each Component type.

However, I didn't want to have to add boilerplate code for every new Component type I added to the game. Nor did I want to use macros to do this, which frankly scare me. So I've come up with a system based on templates and type hinting. But there are some potential issues I'd like to check before I spend ages writing this (I'm a slow coder!)

All Components derive from a Component base class. This base class has a protected constructor, that takes a string parameter. When you write a new derived Component class, you must initialise the base with the name of your new class in a string. When you first instantiate a new DerivedComponent, it adds the string to a static hashmap inside Component mapped to a unique integer id. When you subsequently instantiate more Components of the same type, no action is taken. The result (I think) should be a static hashmap with the name of each class derived from Component that you instantiate at least once, mapped to a unique id, which can by obtained with the static method Component::getTypeId ("DerivedComponent"). Phew.

The next important part is TypedComponentList<typename PropertyType>. This is basically just a wrapper to an std::vector<typename PropertyType> with some useful methods. It also contains a hashmap of entity ID numbers to slots in the array so we can find Components by their entity owner. Crucially TypedComponentList<> is derived from the non-template class ComponentList.

This allows me to maintain a list of pointers to ComponentList in my main ComponentManager, which actually point to TypedComponentLists with different template parameters (sneaky).

The Component manager has template functions such as:

template <typename ComponentType>
void addProperty (ComponentType& component, int componentTypeId, int entityId)

and:

template <typename ComponentType>
TypedComponentList<ComponentType>* getComponentList (int componentTypeId)

which deal with casting from ComponentList to the correct TypedComponentList for you.

So to get a list of a particular type of Component you call:

TypedComponentList<MyComponent>* list =  componentManager.getComponentList<MyComponent> (Component::getTypeId("MyComponent"));

Which I'll admit looks pretty ugly.

Bad points of the design:

If a user of the code writes a new Component class but supplies the wrong string to the base constructor, the whole system will fail.
Each time a new Component is instantiated, we must check a hashed string to see if that component type has bee instantiated before.
Will probably generate a lot of assembly because of the extensive use of templates. I don't know how well the compiler will be able to minimise this.
You could consider the whole system a bit complex - perhaps premature optimisation? But I want to use this code again and again, so I want it to be performant.

Good points of the design:

Components are stored in typed vectors but they can also be found by using their entity owner id as a hash. This means we can iterate them fast, and minimise cache misses, but also skip straight to the component we need if necessary.
We can freely add Components of different types to the system without having to add and manage new Component vectors by hand.

What do you think? Do the good points outweigh the bad?


texts: How to implement Long Polling with PHP and flash?

texts: I'm trying to make a multiplayer game but am a newbie to server side programming except that I know a little PHP. I learnt about this technique called long polling where the server can wait for fresh data to be available and then send it. How does one do long polling using PHP? Are there any libraries available. I'm already using ZendAMF, so how do I make zendamf and long-polling to co-exist?


texts:
In the given diagram, I have the extreme left and right points, that is -2 and 4 in this case. So, obviously, I can calculate the width which is 6 in this case.

What we know:

The number of partitions:3 in this case
The partition number at at any point i.e which one is 1st,second or third partition
(numbered starting from left)

What I want:

The position of the purple line drawn which is positio of average of a particular
partition

So, basically I just want a generalized formula to calculate position of the average at any point.