texts: Android canvas.drawColor throws a null object reference

texts:
I have two nearly identical methods, the first to draw a splash screen while assets are loading, and the second to draw all of the assets to the screen.  The first throws a NullPointerException on this line:

canvas.drawColor(Color.argb(255, 0, 0, 0));

Here is my error:

  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.Canvas.drawColor(int)' on a null object reference
  10-19 21:54:56.042 18973-18973/? E/AndroidRuntime:     at com.xyz.123.GameView.drawSplash(GameView.java:76)

Here is my code in full:

package com.xyz.123;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class GameView extends SurfaceView implements Runnable {
    volatile boolean playing;
    Thread gameThread = null;
    private Paint paint;
    private Canvas canvas;
    private SurfaceHolder holder;
    private int screenWidth;
    private int screenHeight;
    private Background1ResourceList background1ResourceList;
    private Background background1;
    private Background background2;
    private Background background3;
    private Context context;
    private SplashScreen splashScreen;

    public GameView(Context context, int screenWidth, int screenHeight) {

        super(context);

        this.context = context;

        this.screenWidth = screenWidth;
        this.screenHeight = screenHeight;

        // Initialize our drawing objects
        holder = getHolder();
        paint = new Paint();

        splashScreen = new SplashScreen(context, screenWidth, screenHeight);
        drawSplash();

        background1ResourceList = new Background1ResourceList();

        background1 = new Background(context,         background1ResourceList.getBackgroundResources(), screenWidth, screenHeight, 0.00f, 0.50f);
        background2 = new Background(context, background1ResourceList.getBackgroundResources(), screenWidth, screenHeight, 0.33f, 0.80f);
        background3 = new Background(context, background1ResourceList.getBackgroundResources(), screenWidth, screenHeight, 0.66f, 1.00f);
    }

    @Override
    public void run() {
        while (playing) {
            update();
            draw();
            control();
        }
    }

    private void update() {
        background1.update();
        background2.update();
        background3.update();
    }

    private synchronized void drawSplash() {
        if (holder.getSurface().isValid()) {
        //First we lock the area of memory we will be drawing to
        holder.getSurface();
        canvas = holder.lockCanvas();
        // rub out the last frame
        canvas.drawColor(Color.argb(255, 0, 0, 0));
        // draw the backgrounds
        splashScreen.draw(canvas, paint);
        // unlock and draw the scene
        holder.unlockCanvasAndPost(canvas);
        } else {
            System.out.println("surface not valid");
        }
    }

    private synchronized void draw() {
        if (holder.getSurface().isValid()) {
            //First we lock the area of memory we will be drawing to
            canvas = holder.lockCanvas();
            // rub out the last frame
            canvas.drawColor(Color.argb(255, 0, 0, 0));
            // draw the backgrounds
            background1.draw(canvas, paint);
            background2.draw(canvas, paint);
            background3.draw(canvas, paint);
            holder.unlockCanvasAndPost(canvas);
        }
    }

    public void pause() {
        playing = false;
        try {
            gameThread.join();
        } catch (InterruptedException e) {

        }
    }

    public void resume() {
        playing = true;
        gameThread = new Thread(this);
        gameThread.start();
    }
}


texts: MonoGame ortho projection axis direction

texts:
I have perfect square screen and I want to capture everything between -1000.0f and 1000.0f, so I create projection matrix like that:

var proj = Matrix.CreateOrthographicOffCenter(left: -width,
                                              right: width,
                                              bottom: -height,
                                              top: height,
                                              zNearPlane: -1.0f,
                                              zFarPlane: 1.0f);

I expect the axes to be X - left >>> right and Y down >>> up, but if I project some points with Vector2.Transform I get following:

(-1000, -1000) is (-1, -1)
(1000, 1000) is (1, 1)

I expect -1 on Y axis to be the top of the screen, but it is actually the bottom. How so? Is there some convention I missed?


texts: Organizing a Transform class to internally use quaternions

texts:
So, I'm interested in building a Transform class similar to the one used in Unity Engine, but in C++. My intent is for it to be user-friendly to change the position, rotation, and scale of a variable by specifying vec3s for each, where the rotation vector specifies Euler angles or some equivalent. However, the math library I have written uses quaternions, and I'd like rotations to be represented internally by quaternions. Since quaternions are a bit difficult to use on their own, or without an axis-angle conversion of some sort, I was wondering what's the best way to do this conversion somewhat efficiently on the fly, so the user doesn't need to fiddle around with quaternions? My current header file is as follows (I haven't written the implementation yet, aside from referencing the private global vectors to the public const ones):

class Transform
{
public:

Transform();
~Transform();

//// Local Information ////

// Position relative to parent
vec3 LocalPosition;

// Scale relative to parent
vec3 LocalScale;

// Rotation about x,y,z axes relative to parent
vec3 LocalRotation;

// Transformation matrix from worldspace to local space
mat4 WorldToLocal() const;

//// Global Information ////

// Position relative to world (const)
const vec3 &WorldPosition;

// Scale relative to world (const)
const vec3 &WorldScale;

// Rotation about x,y,z axes relative to world (const)
const vec3 &WorldRotation;

// Transformation matrix from local space to world space
mat4 LocalToWorld() const;

private:

vec3 _WorldPosition, _WorldScale, _WorldRotation;

// Stores rotation as a quaternion
// ??? Do I need one for global and local? How does this relate to rotation vec3? ???
quat _RotationRaw;

};

All help is greatly appreciated. I'm usually pretty good at solving these issues but I'm at a loss on this one.

Edit: Forgot to mention that I've read over the other GameDev Stack posts on the Unity Transform class, but I couldn't glean any info about this issue from them.


texts: How do I draw long tiled paths in 2D? (Eye of the Beholder style)

texts:
I'm using artwork from the following page:
http://opengameart.org/content/first-person-dungeon-crawl-art-pack

As you can see with the first artwork, the grass field is long. The floor also goes into the distance. I'm most interested in the path.

However,
The floor is really small tile-wise, much like the grass. The floor 118x22 pixels.

I'm supposing that the artwork is layered on top of each other. But how?

Is the method similar to this?
set x to 0, y -= 22
draw path
set x+=20, y -= 22
draw path
...

But as you can see, the tile isn't square, so I don't think this is correct. I'm sure there's some industry standard to doing this. Any thoughts would be great. Thank you.


texts:
I am attempting to create a game where there is a universe of two 16-bit addresses ranging from (-32768, -32768) to (32767, 32767), or in hexadecimal, each value can run from $8000 to $FFFF then 0 to $7FFF, although the universe is probably not going to use the whole 4 billion possible addresses.

What I want is for any location, given the two values, to return a value from 0 to around 15 or 20. Where:

0 is empty space.
1 to 9 are planet technology levels, with a level 1 planet being less developed than 2, which means a level 5 planet can build up to a level 5 hull, warp drive or shield, but to upgrade to level 6 requires going to a level 6 or higher planet, or possibly paying a horribly high price.
10 and above are for anomalies, e.g. black holes, suns and other things which have an effect such as random movement or increase in power.

While the most common value will be zero, the universe should have some minimum non-zero locations, e.g. 10% or 20% or some reasonable number of the locations are planets or anomalies.

Note the alignment factors are not random, the value should be calculated so that -60,12 returns the same planetary value any time it's called. I've seen this done in a simple formula amounting to less than 5 lines of code but that was 30 years ago, and I don't have the math to do the calculations myself.

Any help would be appreciated.


texts: Minimalistic JavaScript sprite manipulation libraries

texts: Are there (or can someone recommend) any minimalistic JavaScript based libraries for sprite(s) manipulation? Preferably DOM oriented.


texts: Seeking Advice: Collision with JBox2d for Top-Down or Isometric Maps

texts:
I Hope I can make this as clear as possible!

Currently working on an action RPG game, very early stages, more just the basic ideas down and written in. So i'll start on with my setup:

Using Java with LibGDX
Map creation is done with TILEd
Style of map: Isometric

Collision Engine? ... well this is where I need a bit of guidance and advice.

LibGdx is linked in with Box2d which makes it . I'd personally love to use Box2D, more because I've played around with it on a platform level and I liked how it operated with force and impulses etc, however, it seems to be created for only platform style games. So I guess one questions is: Can Box2d's properties be easily changed to support a Top-Down collision system or an Isometric collision system?

I have tried to implement Box2d into a top down game before by setting the gravity to zero, but with no gravity, the other entities on the map just float. (You bump into them and they just start... floating!)

What I was originally thinking was once I have my map created in TILEd, I would start adding a collision layer (Or modify the tiles individually) to mark what is passable and what is not. I have seen examples for box2d (again Platform only however) ways to create an Object in TILEd to mark the collidable wall or floor and when loaded it would create the shapes. Box2d would be perfect if it wasn't for the whole floating entity due to zero gravity.

So what I am looking for...

1) Is there a way to create Box2D work on a Top-Down set up without entities floating?

2) If not, what other solutions do I have for collision?

If there is any other information needed for a better response Please let me know!

Thank you!


texts:
I was wondering if anyone had any ideas on how to get per pixel collision detection for the android.  I saw that the andEngine has great collision detection on rotation as well but couldn't see where the actual detection happened per pixel. Also noticed a couple solutions for java, could these be replicated for use with the Android SDK?

Maybe someone here has a clean piece of code I could look at to help understand what is going on with per pixel detection and also why when rotating it is a different process.

EDIT:
Here is something I am working with right now.
public void getBitmapData(Bitmap bitmap1, Bitmap bitmap2){
     int[] bitmap1Pixels;
     int[] bitmap2Pixels;

    int bitmap1Height = bitmap1.getHeight();
    int bitmap1Width = bitmap1.getWidth();
    int bitmap2Height = bitmap2.getHeight();
    int bitmap2Width = bitmap2.getWidth();
    bitmap1Pixels = new int[bitmap1Height * bitmap1Width];
    bitmap2Pixels = new int[bitmap2Height * bitmap2Width];

    bitmap1.getPixels(bitmap1Pixels, 0, bitmap1Width, 1, 1, bitmap1Width - 1, bitmap1Height - 1);
    bitmap2.getPixels(bitmap2Pixels, 0, bitmap2Width, 1, 1, bitmap2Width - 1, bitmap2Height - 1);

}


texts:
What is the best way to, in a grid, to find a path (not necessarily shortest) from a start point to an end point (for both of which the coordinates are known)?

The grid is approximately 60x60, and has some obstacles in it. The coordinates of the start point, the end point, and all of the obstacles are known and easily accessible. Searches such as Breadth-first and A* work, however they seem to do an unnecessarily large amount of "searching" when you should already know where you are going.


texts: How does input work when exporting to Android?

texts:
I know I must add Android sdk , but my question is this :

If I make a game that works with the mouse, for example a puzzle game, then I output my game to Android, do I have to rewrite it to work with the touch screen?


texts:
I'm creating a game with Unity 3D, where has many levels, and I want create a button in all levels, to back to level menu.

Is possible can I create a "scene template" where I can only change one time, and all level scenes inherit template changes?


texts: Approximating a fourth point with a weighted average between three points?

texts:
Given three points \$p_1,p_2,p_3\$, how would one approximate the best positive weights \$(u, v, w)\$ such that \$u+v+w = 1\$ and that the distance between the new \$up_0 + vp_1 + wp_2\$  from \$p_3\$ is minimal?
Basically, the enemy's unit is positioned between several "bases" on a 2d plainand it's easy to tell which is closest or even find the "weights" between two bases \$(t, 1-t)\$ to compute the relative fractions (eg. 0.3, 0.7). How does one find the optimal weights for three surrounding points?


texts:
So I have mainScene and I have LogoScene, I am wondering If i can make logoscene show a logo, then transition to mainscene.

here is what i have

    import org.cocos2d.layers.CCLayer;
import org.cocos2d.layers.CCScene;
import org.cocos2d.menus.CCMenu;
import org.cocos2d.menus.CCMenuItemImage;
import org.cocos2d.nodes.CCDirector;
import org.cocos2d.nodes.CCSprite;
import org.cocos2d.types.CGPoint;
import org.cocos2d.types.CGSize;

import android.graphics.Color;
import android.graphics.Rect;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

public class LogoScene extends CCLayer {
    public static CCScene scene() {
        CCScene scene = CCScene.node();
        LogoScene layer = new LogoScene();
        scene.addChild(layer);
        return scene;
    }

    public LogoScene() {
        super();
        this.init();

    }

        CCSprite pSpNameText = CCSprite.sprite("img/logo_name_textfield.png");
        pSpNameText.setPosition(CGPoint.ccp(1080, 300));
        this.addChild(pSpNameText, 0);
= bingo.getLayout();
            layout.removeAllViews();

        CCDirector.sharedDirector().replaceScene(MainScene.scene());
    }
}


texts:
I've been banging my head against a wall this past while over how I might create menu's and menu components in unity from text file. I would normally just build my own extended panel/label classes etc in c# and then use the properties loaded from file on instances of those extended classes. I have a properties loader but I cant seem to get my head around making a gui class that's dynamic from reading unitys documentation. Has anybody ever tried this?

Here's an example of a menu definition file.

    <GUI_Menu: mainMenu >
    <Atributes>
        <> Type : Menu
        <> Position_X : 0
        <> Position_Y : 0
        <> Height : Vanilla_Property_Screen_Height
        <> Width : Vanilla_Property_Screen_Width
    </Atributes>
    <GUI_Panel: menu >
        <GUI_Button: play >
            <Atributes>
            <> Position_X : 50
            <> Position_Y : 50
            <> Type : Button
            <> Height : 50
            <> Width : 100
                <Description>
                    <> Key : desc_Play
                    <> Description_Address : Main\\Text\\Menu\\desc_Menu.xml
                </Description>
            </Atributes>
            //button action/button data/description
        </GUI_Button>
        <GUI_Button: options >
            //button action/button data/description
        </GUI_Button>
        <GUI_Button: mods >
            //button action/button data/description
        </GUI_Button>
        <GUI_Button: texturePacks >
            //button action/button data/description
        </GUI_Button>
    </GUI_Panel>
</GUI_Menu>

<GUI_Menu: play >
    <GUI_Panel: load-New >
        <GUI_Button: loadSave >
            //button action/button data/description
        </GUI_Button>
        <GUI_Button: newGame >
            //button action/button data/description
        </GUI_Button>
        <GUI_Button: multiplayer >
            //button action/button data/description
        </GUI_Button>
        <GUI_Button: voxelEditor >
            //button action/button data/description
        </GUI_Button>
    </GUI_Panel>
</GUI_Menu>

EDIT:
Note that it is important that the menus are loaded from a definition file that is easy to read and write by a human being as custom menu's and GUI's/components will be supported through modding.


texts:
I'm creating a model/animation viewer in C# using OpenTK for a game's models. Before stating my problem I want to describe a bit what I've accomplished so far in case I'm fundamentally missing something.

First of all I parsed the model skeleton. Like described pretty much everywhere on the web, what I do is to traverse all the hierarchy starting from the root bone and start building up the joint matrices. The game file provides separately translation,rotation and scale vectors. In order to create all the joint matrices I'm using only the rotation values, which I am converting into a rotation matrix and I'm saving it as the localMatrix. I'm saving the translations as joint position (localPosition) and I'm using them later on to calculate the worldPosition of my joints by transforming that using the parent's worldMatrix.

The following methods are responsible for getting the joint world Matrix and its world Position

public Vector3 worldPosition {
        get
        {
            if (parent != null)
                return parent.worldPosition + Vector3.Transform(this.localPosition, parent.worldMat);
                this.worldMat);
            else
                return this.localPosition;
        }
}
public Matrix4 worldMat
    {
        get
        {
            if (parent != null)
                return Matrix4.Mult(this.localMat, parent.worldMat);
            else
                return this.localMat;
        }
}

Using that piece of code I can preview the skeleton perfectly. I also managed to parse the animations. I used the rotation information on each frame in order to update each joints local matrix and therefore I was able to successfully preview the animation on the joint skeleton.

Now the only thing I am missing is to bind the mesh on the skeleton (I'm trying to do that using a vertex shader). Wherever I search on the web, i find that i need to apply the following equation:

I got the blendIndices and the blendWeights so that's not a problem as well.
I'm completely confused with the bone matrices though. If I understand correctly matrix[i] is the joint's world transformation matrix. The other inverse matrix is supposed to transform my vertex back to the bindpose? Since my model is already in the bindpose what do I need this matrix for?

I tried applying just the joint worldmatrices that I have precalculated,  but the mesh was completely corrupted. So I'm definitely missing something.

And second question: I've found some matrices in the model file which seem like they are probably prebaked joint world matrices. In fact I compared their values and they are EXACTLY the same with the ones I'm calculating through traversing the bone hierarchy. Their only difference though is that they also contain translation information. So my question is: Do bone matrices contain translation information as well? If so, then this means that my way of parsing the skeleton is wrong? I just can't thing of another way to use the full matrices (rotation + translation) in order to correctly position the joints.


texts: Unity 2D loading Spritesheet Atlas at runtime from web and using it dynamically

texts:
I am new to Unity (came from AS3/Starling) and just started for 2D games in Unity. I have a spritesheet / texture-atlas (many different sized images packed in a single png) which I want to download at runtime (I can use WWW classes for that) in game .

Than use all those images (in that sprite atlas) and show them up on screen and use them as regular unity sprites, like applying Rigidbody2D or Collider2D etc. I googled for this but mainly what I found is using Unity3D's editor, importing the sprite atlas and using its own sprite editor. Not much on how I would do that in runtime. I am expecting something like what we used to do in Flash or evening in Cocos2d, like we have a related XML file for each sprite atlas and their SDK have functions for reading that sprite in conjunction with that XML.

Any help would be highly appreciated.


texts: FBX SDK Getting Tangents and Binormals From a Mesh?

texts:
How do I import tangent and binormal data per vertex from a FBX Mesh.
I already know how to get Vertices, Normals and UVs but how would I get tangents and binormals?

For example this is how I would get a vertex.

int vIndex = MyFbxMesh->GetPolygonVertex(triangle, vertex);
FbxVector4 Vertex = MyFbxMesh->GetControlPointAt(vIndex);

What about tangents and binormals?
I searched everywhere on the internet and looked in their documentation but I still can't find a way.


texts:
I implemented the Strauss model with the metalness, transparency and smoothness parameters, taking the formulas from the book "Programming vertex geometry and pixel shaders", this is how I implemented it:

float fresnel(float x) {
    float Kf= 1.12;
    float result= 1.0/pow(x-Kf,2.0) - 1.0/(Kf*Kf);
    result/= 1.0/pow(1.0-Kf,2.0) - 1.0/(Kf*Kf);
    return result;
}

float shadow(float x) {
    float Ks= 1.01;
    float result= 1.0/pow(1.0-Ks,2.0) - 1.0/pow(x-Ks,2.0);
    result/= 1.0/pow(1.0-Ks,2.0) - 1.0/(Ks*Ks);
    return result;
}

vec4 Strauss(vec3 L, vec3 N, vec3 V, float smoothness, float metalness, float transparency)
{
    vec3 H= reflect(L,N);
    float HdotV= max(dot(H,V),0.0);
    float NdotL= max(dot(N,L),0.0);
    float NdotV= max(dot(N,V),0.0);
    float k=0.1;

    // Diffuse component
    vec3 diffuse= NdotL * (1.0 - metalness * smoothness) * (1.0 - pow(smoothness,3.0)) * (1.0 - transparency) * vec3(materialDiffuse);

    // Specular component
    float r= (1.0-transparency) - (1.0 - pow(smoothness,3.0)) * (1.0 - transparency);
    float j= fresnel(NdotL) * shadow(NdotL) * shadow(NdotV);
    float reflect= min(1.0,r+j * (r+k));
    vec3 C1= vec3(1.0,1.0,1.0);
    vec3 Cs= C1 + metalness * (1.0 - fresnel(NdotL)) * (vec3(materialSpecular) - C1);
    vec3 specular= pow(-HdotV, 3.0/(1.0-smoothness)) * reflect * Cs;

    return max(lightDiffuse * vec4(diffuse,1.0) ,0.0) + max(lightSpecular * vec4(specular,1.0), 0.0);
}

The parameters metalness, smoothness and transparency are uniforms. I try to vary them, but I cannot get something similar to this result:

This is what I get with roughness 0.9, transparency 0.1 and metalness 0.1 :

It is practically equal to a lambert shader! I tried a lot of parameters combination, but I never get a shiny teapot like it should be.
I also debugged the shader, and it seems like the specular component is zero in many parts of the teapot. I tried to add an if that makes look red all the areas where the specular component is zero, that's the result:

I checked many times the formulas and the implementation, and it seems like I've done all correctly. What's the problem?


texts: Blender object to Unity imported - low quality after scaling

texts:
I've created an object with Blender. Took the default cube and moved two of it's vertices inside, so I got the 'Ramp' shape. Now, I imported this into Unity and this is what happened when I tried to scale it on one axis:

Here's the one after scale:

It's edges are blurry.

Here's the 1:1:1 object, without a scale:

Looks strange to me, cause when I scale Cubes (built into Unity) they're not blurry.

If anyone has a clue, I'd be grateful!


texts: Unity Canvas hover image does not trigger event

texts:
So i have the following setup:

This produces the following UI:

Now on each of the "HudCircle"(Bottom/Right/Left/Top), I have the following components:

As you can see I have a script that has the following code:

    public class HUDAction : MonoBehaviour,  IPointerEnterHandler, IPointerExitHandler
{
    public Color StartColor;
    public Color SelectedColor;
    public Image Image;

    private void Awake()
    {
        Image = GetComponent<Image>();
        StartColor = Image.color;
    }

    public void OnPointerEnter(PointerEventData eventData)
    {
        Image.color = SelectedColor;
        Debug.Log("Over");
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        Image.color = StartColor;
        Debug.Log("Not over");
    }
}

Sadly when playing this scene nothing happens when I hover either of the circles.

Can anyone tell me what I've done wrong?


texts:
I am trying to call a method within a Unity app from an Android activity by using UnityPlayer.UnitySendMessage. I am getting the error "SendMessage: (ObjectName) not found!".

I've confirmed the following:

There is a GameObject in the scene with the name of (ObjectName)
The script is attached to said GameObject
The C# class and filename are named the same as the GameObject
The C# method attempting to be called is public

Here are some code snippets to give an idea as to how this is built:

Unity

using UnityEngine;
using System.Collections;

public class GCMHookBridge : MonoBehaviour {
    void Start () {
#if UNITY_ANDROID
        AndroidJavaClass unityPlayerClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        AndroidJavaObject currentActivityObj = unityPlayerClass.GetStatic<AndroidJavaObject>("currentActivity");

        var mainActivityClass = new AndroidJavaClass("com.unity.unitygcmreceiver.MainActivity");
        mainActivityClass.CallStatic("LaunchActivity", currentActivityObj);
#endif

    }

    public void sendGCMIDToServer(string regid) {
        Debug.Log("Unity Regid: " + regid);
    }
}

Java

The Java class being called here extends Activity. I am not extending UnityPlayerActivity because there is already an Android plugin that does this.

The Unity code above is calling this static method:

public static void LaunchActivity(Activity root) {
    Intent intent = new Intent(root, MainActivity.class);
    root.startActivity(intent);
}

From there the Activity runs as expected until it tries to interact with the Unity instance.

I do this as so:

An AsyncTask is created
UnityPlayer.UnitySendMessage("GCMHookBridge", "sendGCMIDToServer", registration_id) is called

I've wrapped #2 with com.unity3d.player.UnityPlayer.currentActivity.runOnUiThread.

I've called the UnitySendMessage method outside of the AsyncTask thread.

My suspicion is while my Android activity is running, the Unity activity is not, and therefore inaccessible. But from my debugging it looks like the async task thread is allowing the Android activity to exit, and the main unity thread to resume.


texts: How to hide a sprite on trigger when the player enters the trigger zone?

texts:
I am making a roof for my 2D top down survival game, and I want to make it so that the roof disappears when the player enters the building, and re-appears when they leave.
Here is the code I've written so far:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Roof : MonoBehaviour {
    public GameObject roofGameObject;

    void OnTriggerEnter2D(Collider2D collision) {
        roofGameObject.SetActive(false);
    }

    void OnTriggerExit2D(Collider2D collision) {
        roofGameObject.SetActive(true);
    }
}

I got it to work so that, when I go in, the roof it disappears. But when I leave it stays disappeared. How can I fix that?


texts: how to handle the virtual Z axis in 2D games?

texts:
I'm using this paper 2d framework of UE4 where a plane mapped with sprite texture is put in 3d world and therefore appears as 2D when viewed from sideways.

Its all good for games like NES mario where other than jumping you can only move along X axis.

However if you look at games like double dragon and Battletoads they have an isometric perspective and a virtual third co-ordinate axis which points outwards from the screen towards the player, you walk along this with d-pad up and down. It also works for objects in the scene such as a box or ladder which you can climb up and down along this axis, it also affects the game logic say like where your character's landing point would be when you jump.

how would you go about implementing this using 3d planes mapped to 2d textures without making some virtual co-ordinate system of your own?


texts: How to handle normal vector when duplicating vertex?

texts:
I'm currently developing a UV mapping, such as the UVW Map Modifier in 3ds Max (Not Unwrap UVW Modifier).

I split the vertices of the model in the form of a primitive shape (Box, Plane, etc.) and set UV coordinates. However, in the process of duplicating the normal vector, i ran into a problem.
For example, there is a box model with 8 vertices. We need to split the vertices into 24 in order to mapping texture to the 6 sides of the box and set normal vectors separately. In the case of the box, the normal vector calculation is simple. After splitting the vertices, calculate the normal vector for each triangle.
The problem is when this algorithm is applied to the Sphere model. Split the vertices of the sphere model into a Box Shape. (Box Shape is one of the functions of UVW Map modifier). Setting the UV coordinates is fine. The problem is the normal vector setting of the seam vertices.
Simply calculating the normal vector for each triangle, the normal vector of the vertices of the seam is different. (duplicated vertices have the same position). If the normal vector is different, the lighting is not applied properly. Of course, this is solved by calculating the normal vector of the Sphere model before splitting the vertices. However, this method could not be applied to a box model with 8 vertices. The three split vertices of the box must each have a different normal vector.
In summary, split vertices may have different normal vectors or may have the same normal vector. How would you like to solve this? (I used the Box and Sphere model as an example, but in practice it should be applicable to a variety of models.)


texts:
Last month, I experimented a lot in game development using cocos2d for the iPhone, especially on moving and modifying sprites. However, vertices and polygons are still new stuff for me.

I developed an algorithm that creates a set of points. I now want to use them to create my 2D terrain. Here is how it looks like when I connect the points in java, so that you can get the idea

The points are connected with lines. However a real game terrain is a shape that is colored or has a texture overlayed, right? For example:

How could I use my points to create such a terrain?

What I tried so far is I created an array and filled it with my points. I pass this array to this method

void ccDrawPoly ( const CGPoint *  vertices,
    NSUInteger  numOfVertices,
    BOOL  closePolygon
)

  draws a poligon given a pointer to
  CGPoint coordiantes and the number of
  vertices measured in points. The
  polygon can be closed or open

This actually draws a plain shape. But from the blue picture it looks like there is not one shape but many.

Please share you knowledge on how to create 2d game terrain.

Update 03.06.2011

Based on the two good answer I have following result


texts: Show Sprites on Overlap (Shader Graph) [2D]

texts:
I have a character sprite mesh and mesh renderer (The black wavy box). I am hoping to be able to overlay the black box onto the character covering the sprites but I am not sure how to do that.

I looked at this question : Unity: How do I only show parts of objects that overlap [2D]

But this works more as a cover that you can see through. I am hoping to have the variable black mask the sprites of the character but I cant seem to layer these correctly. Is there a way to do this using the LWRP and shader graph?

The over arching idea is to use this as a damage marker. Moving the black box up or down depending on the health lost.


texts:
I'm making a horror text adventure using Twine (snowman version, which uses HTML, CSS, Javascript, JQuery, and Markdown). I wanted to know what the best (easiest) way is, you think, for creating a foggy effect where the text comes in and out of focus (adding/removing blur to lines, words, or characters) based on some criteria (mouseover, text advancement, or time).

Or, just, any way of doing it.

I'm really new to Javascript, just picked it up this week, but with a long history of web design and (bad) hobby coding. (Python, Lua)

I'm interested in understanding the logic behind it, since I intend to spend time on web-based game development, so err on the side of elaboration please.

And of course, let me know if the question is faulty or needs clarification. Thanks!


texts: Calling CCRepeaForever on CCLabelTTF Makes Label Not Show Up

texts:
I have a CCLabelTTF in the top right hand corner of the view.

-(void)scrollScoreLabelAndMonkey{
scoreLabel = [CCLabelTTF labelWithString:@"0000" fontName:@"Marker Felt"
fontSize:30 ];
scoreLabel.position=ccp(420,300);
scoreLabel.color = ccGREEN;
[self addChild:scoreLabel];
}

I simply add this code to the bottom of the above method. However as soon as i add this line, the label doesnt show up at all.

id moveScore = [CCMoveBy actionWithDuration:.7 position:ccp(scoreLabel.position.x + 10, 0)];
CCRepeatForever *scrollScoreLabel = [CCRepeatForever actionWithAction:moveScore];
[scoreLabel runAction:scrollScoreLabel];

Any help is greatly appreciated!


texts:
I have been digging and researching into CDLOD and there are some things I dont understand.

https://github.com/fstrugar/CDLOD/blob/master/cdlod_paper_latest.pdf states:

  The quadtree structure is generated from the input heightmap. It is of
  constant depth, predetermined by memory and granularity requirements.
  Once created, the quadtree does not change unless the source heightmap
  changes. Every node has four child nodes and contains minimum and
  maximum height values for the rectangular heightmap area that it
  covers.

Doe's this mean I calculate every node and child nodes to the finest level at the setup phase (i do not split and unsplit at run)? If so, what's the roughest level I start with? And how do I get the minimum and maximum height from my perlin noise height map for an node area?

Lastly how CDLOD would work, when I zoom in/out into a big planet (up factor)? Can get that into my imagination.


texts: Where is the Mclip matrix & how do I set it?

texts: According to this article, the Mclip matrix will be used, but I didn't find any function in Directx11 to set this matrix. How do I set it?


texts: Can DirectX9 be used without HWND handle?

texts:
I found an excellent code here that does almost everything I need: running an HLSL shader on memory texture to process video frames into another texture buffer without displaying it.
http://www.codeproject.com/Articles/207642/Video-Shadering-with-Direct-D?msg=5092502#xx5092502xx

My question is: can DirectX9 be used to work purely with in-memory data without display and without specifying a HWND handle? What needs to change in the code if not giving it a HWND?

The code I'm writing is a DLL that has no graphical interface.


texts: How can I resize ImageButton ? It show very big on screen . How I know it is an Actor and it is not resizing automatically . I can`t find the method for resizing it. Any ideas?


texts:
I'm trying to implement the Fast Voxel Traversal Algorithm on a uniform grid of axis-aligned rectangles. Having read the paper, I understand how the traversing works, but not the initialization. I've looked around and I did find a readme that overviews the algorithm, but I fail to see how the derive how to determine the index in a data structure (such as an array) that corresponds to the first voxel the ray intersects.
Using the construct presented in the readme, assuming the grid is 2x2 and stored in (going to use Python) an list like so:
+--------+--------+
|        |        |
|        |        |
|  0, 1  |  1, 1  |
|        |        |
|        |        |
+--------+--------+
|        |        |
|        |        |
|  0, 0  |  1, 0  |
|        |        |
|        |        |
+--------+--------+

grid = [[(0, 0), (1, 0)],
        [(0, 1), (1, 1)]]

In the overview, the compute r2 = r and resolve t = 27/32, but I fail to see how they translate that to the index grid[0].
Some other resources I've used to try and understand:

StackOverflow post
Flipcode blog


texts: Why is transform.up behaving differently for different functions?

texts:
Can anyone please explain to me what i'm doing wrong here?

As I see it the raycast is the only one using transform.up correctly, though why not Debug.DrawLine() and _lineRenderer.SetPosition(1, transform.up * maximumBeamLength);

using UnityEngine;

[RequireComponent(typeof(LineRenderer))]
public class LaserBeam : MonoBehaviour
{
    [SerializeField]
    private float maximumBeamLength = 5f;

    private LineRenderer _lineRenderer;

    private void Start()
    {
        _lineRenderer = GetComponent<LineRenderer>();
    }

    void Update()
    {
        _lineRenderer.SetPosition(0, transform.position);
        RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.up);

        Debug.DrawLine(transform.position, transform.up * maximumBeamLength, Color.blue);
        Debug.DrawLine(transform.position, transform.up , Color.red);

        if (hit.collider)
        {
            _lineRenderer.SetPosition(1, new Vector3(hit.point.x, hit.point.y, transform.position.z));
        }
        else
        {
            _lineRenderer.SetPosition(1, transform.up * maximumBeamLength);
        }
    }
}


texts: Proper way to set a RigidBody's maximum velocity

texts:
I am trying to gradually accelerate a GameObject with a RigidBody attached until it reaches a maximum velocity, at which point it becomes unable to gain any more velocity.

I know I can simply reset the object velocity to an arbitrary maximum velocity every frame
if it overshoots, but I've repeteadly heard that manually setting an
object's velocity is a very bad practice in the context of Unity's physics system.
I am also aware that in a physical sense, objects don't have a "maximum velocity" and that such a thing will always be artificial.

I can think of several ways to achieve this, but given these limitations, I would like to know if there's a standard, optimum way to do this.


texts: How to handle a Google Play game's privacy policy

texts:
I am trying to release a mobile game (insert obligatory sellout statement for Chunk of Space) on Google Play, and I'm worried about their privacy policy system. Basically, if you mark your game as "directed primarily towards children," you need to include a privacy policy (mostly to adhere to COPPA regulations). Now, my game isn't primarily for children, but because it's made to appeal to all ages, it's likely that I might have children playing it (or, I might have nobody play it. Hooray for insecurity). The question is, do I need to make the app say that it is "Designed for Families," or can I leave that option unchecked? Will the game not be marketed/available to children if I do not do so? And if I do need to set that option, how might I go about creating the privacy policy? I know there are several privacy policy generators online, so if you've used one or more in the past, could you recommend it to me? And how would I need to modify the policy to allow children to use it?

As for information the app uses, here's a short list:

Anything needed for Unity analytics, IAP, and ads
Anything needed for Google play IAP and ads

That's all that I know it uses, although there might be some additional information that each uses, along with any hidden Google Play and Unity stuff.


texts: Different lighting models in deferred rendering

texts:
I would like to support a few different lighting models in my deferred renderer, such as: Phong OrenNayar and Cook-Torrance, so a small limited set to support a bit more than just a single lighting model.

What i came up with:
The most obvious way seems to simply branch in the shader based on some information stored in a texture during the geometry pass. I have come to learn however that branching in shaders is generally a bad idea (at least that's what i read everywhere). So I came up with a branch-less version by using the stencil buffer to mask each of the few shaders, and rendering each light multiple times, once for each lighting model.
(The stencil buffer could be filled during the geometry pass and then stored in R8, and with some trickery you can use it as well for light masking.)

Now the question is, what is the best way to do this? Did I miss any better techniques? I could not find many usefull sources online.


texts: Good resources for learning modern OpenGL (3.0 or later)?

texts:
I stumble upon the search of a good resource to start with OpenGL (3.0 or later) . Well, I found a lot of books but none of them can be considered a good resource!

Here two examples:

OpenGL Programming Guide (7th edition)
http://www.amazon.com/exec/obidos/ASIN/0321552628/khongrou-20
This is FULL of deprecated material! Almost every chapters begin with a note about that.

OpenGL Superbible (5th Edition)
http://www.amazon.com/exec/obidos/ASIN/0321712617/khongrou-20
This book uses a library created by the author to explain the main arguments, hiding  what you want to learn! I don't want to learn how to use your library! I want to learn OpenGL!

I hope that you understand this is not the same question like "hey I'm not able to use Google... tell me how to learn OpenGL". I've just finished a full and deep search but I can't find a good and complete resource to learn the "new" OpenGL avoiding deprecated topics.

Can someone heading me in the right direction? I know C++ and I have 10 years of experience in development... where I can find a good resource?! I want to spend time on it and I want to learn deeply.


texts: How can I provide a csv file to a player on mobile?

texts: It seems many people do this with regards to game data so they recommend userprefs, but I just want the user to have the file in the end, whether this is the Files app on iOS or choosing a folder to save in on Android or even just attaching the file as an attachment to an email that they can send using their preferred mail app or something.


texts:
I'm working on a few game dev tools which use OpenGL or DirectX to render 3D models (viewing).
Consider your favorite 3D modeling software package (Softimage, Maya, 3DS Max, modo, etc.). Note that the 3D viewport does not sit in a constant render loop pegged at max FPS. It remains idle (0 FPS) until some action is taking place in the viewport such as moving the viewport camera from side to side using the mouse or pressing play for animation. If the viewport is idle, there is no drain on the CPU / GPU. I'd like to use this technique in a couple of tools I'm working on and possibly within the game.
Is there a generally accepted programming technique with OpenGL and/or DirectX (via C++) that will achieve this?
One solution would be to do a standard render loop and check for input 1000s of times per second, but that seems inefficient and hard to manage as you add more and more "events" which would trigger a updated render.
Please let me know if the question is unclear. If I knew how to describe it perfectly I could probably just search google.


texts: Texture being rendered to main frame buffer?

texts:
I'm using Ogre 1.10.12 (openglES2 as render system) to create a manual texture like this:

    rtt_texture = Ogre::TextureManager::getSingleton().createManual("RttTex",
                                                                Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
                                                                Ogre::TEX_TYPE_2D,
                                                                m_size.width(),
                                                                m_size.height(),
                                                                0,
                                                                Ogre::PF_A1R5G5B5,
                                                                Ogre::TU_RENDERTARGET);

m_renderTexture = static_cast<Ogre::GLES2FBORenderTexture *>(rtt_texture->getBuffer()->getRenderTarget());

m_renderTexture->addViewport(m_camera);
m_renderTexture->getViewport(0)->setClearEveryFrame(true);
m_renderTexture->getViewport(0)->setBackgroundColour(Ogre::ColourValue::Red);
m_renderTexture->getViewport(0)->setOverlaysEnabled(false);

then, I bind the texture to the FBO and retrieve the FBO's ID like:

Ogre::GLES2FrameBufferObject *ogreFbo = 0;
m_renderTexture->getCustomAttribute("FBO", &ogreFbo);
Ogre::GLES2FBOManager *manager = ogreFbo->getManager();
manager->bind(m_renderTexture);

GLint id;
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &id);

My concern is that id is 0 so I cannot render this texture outside my display, it's getting visible which I don't want it to be.

Shouldn't be ogre creating an unused frame buffer object when creating a manual texture with the TU_RENDERTARGET parameter?


texts: Which platform (server) use for turn based card game?

texts:
My game will do next:

Dealing 4 cards to every player

Random player is turning over 1 card, after him another (which has
seen card of previous player) and etc.

On the end player with the highest card wins and dealing cards
starts again

I think it would be best that player could choose room in which he would play.
So my question is what type of comunication to use? Over Game center, my custom server or there is some spacialized server for that kind of thing?
UPDATE (added second question):
I have read on severral forums that Game Center has limit up to 4 or 16 players. My game will play over 16 people (for start I'm sure that there will be 30-40 players in same time in game). Or that means that there can be max 4/16 plaers in same match (room)?
UPDATE 2:
My game will have 4 players (exactly 4).
I will set max. timeout 10 seconds and after that if player has not turned card game is over for every player (this is that kind of game). Players can not leave the match and return again later. This is the flow of the game: player 1 plays his card, after that player 2, 3, 4 and than again player 1. Each player has to play and it's not possible to skip someone. And I need to do everything programaticaly; start the match, join the match (autom-match is only available except invite)..
If all of that i can do with Game center, that's great, I will do that then.


texts:
Currently in my project I am using LWJGL and the Slick2D library to render text onto the screen. Here is a more specific example:

    Font f = new Font("Times New Roman",Font.BOLD,18);
    font = new UnicodeFont(f);
    font.getEffects().add(new ColorEffect(Color.white));
    font.addAsciiGlyphs();
    try {
        font.loadGlyphs();
    } catch (SlickException e) {
        e.printStackTrace();
    }

then i use font.drawString to write onto the screen.
This is a quick easy way but it has a lot of disadvantages. for example font.loadGlyphs take a very long time 1-3 seconds. so when i want to change a color or font type then i have to wait 1-3 seconds which means I cannot do it while rendering (ie. cant have different color text on the same screen).

My question is what is a better way of drawing multicolored text onto the screen? I use slick2d only for the text rendering so maybe i can fully get rid of the library and draw text some other way...

If you have an answer please leave a quick short example.

Thanks!


texts: How to implement A.I. for checkers/draughts?

texts:
I saw this checkers game and I wondered how the A.I. was implemented.

How should I implement an A.I. for checkers (draughts, dama, dame)? Are there any known algorithms?

Very thnaks full to all. I m very wonder to see this Tic Tac Toe game tutorial blog post.

So, i want dama game algorithm open source code and blog post..  Is there any helpful link or any doc file..? please let me know..


texts: How do game clients know that a server is running on their LAN?

texts:
In lots of multiplayer games there is the option for LAN play. My question though is how does a client know where a server is on the LAN?

The only ways I can think of

Send out broadcasts over the broadcast address. This has the disadvantage of being filtered sometimes by routers or switches in different network environments.
Attempt to connect to a server on every IP in your subnet. This has the disadvantage of being slow (Especially if the network uses 10.XXX.XXX.XXX for their IPs) and a mini ddos attack, but isn't going to be filtered.

How do games do this especially in other network environments?


texts: How to detect collisions with a material in Unity 5?

texts:
I've got a simple car game with 3 different surfaces: grass, tar and sand. I have a basic skid smoke system, but I want the color of the skid smoke to change depending on the surface, for example on tar it should be a light grey color, on grass it should be a green/brown color and sand should be a light cream color. I have 3 different options for detecting the collisions for those 3 states and they were a whole lot of box colliders, changing the meshes of all the objects (its a modular setup...) to be separated by the surface type and the last one was to use a tag for each surface type. I tried the tag for each surface type but the issue was most blocks had multiple surface type on it...

So I thought what if I could use the materials for the collisions. Afterall, if unity can separate the mesh faces into different sections for different materials (yes I know this technically isn't unity doing this but it can still 'read' it) then would it be possible to say, when my car is on the grass material, make the smoke green/brown. It makes logical sense to me but I just can't think how to execute it. Could someone please enlighten me on either if this is possible, and if so, how to do it, or if it isn't, then perhaps the next best option?

Thanks, Matthew


texts:
I am new to game programming and I am having so much hard time learn on my own. My goal is to make a game with different levels.

so far my plan:
i have 2 classes
1 - main.java
2 - level_01.java
3 - more levels if i want

in my level_01.java:
1- make 2d array of map(done)
2- Do i need to store the make in arraylist or list?????
3- print in paint method?

public class level_01 extends levels
{
    private int map01[][] = {{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
                             {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
                             {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
                             {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
                             {2,2,2,2,2,2,2,0,0,2,2,2,2,2,2}};

    //Is a good idea to store this map in list or arraylist?
    //if yes should I use ArrayList or list?
    //or should i just print the right now?


texts: Fullscreen triangle SV_POSITION and deferred shading

texts:
So I'm trying deferred shading in DirectX11.

I am using the following method (used in the FXAA shader and described here: http://www.altdev.co/2011/08/08/interesting-vertex-shader-trick/) to render a fullscreen triangle for my deferred shading pass.

FullscreenTriangleVSOut main(uint VertexID: SV_VertexID)
{
    FullscreenTriangleVSOut output;

    output.mTexcoord = float2((VertexID << 1) & 2, VertexID & 2);
    output.mPosition = float4(output.mTexcoord * float2(2.0f, -2.0f) + float2(-1.0f, 1.0f), 0.0f, 1.0f);

    return output;
}

And then in the pixel shader, I want a proper texture coordinate to sample my diffuse, normal, position textures from the GBuffer.

In GLSL, I simply do:

ivec2 texcoord = ivec2(textureSize(unifDiffuseTexture) * (gl_FragCoord.xy / UnifAmbientPass.mScreenSize));

But for some reason, in HLSL my SV_POSITION is always (0.5, 0.5). I looked in visual studio 2013 and debugged the pixel shader at various pixels, and yes at all places the SV_POSITION is (0.5, 0.5). Why is this?


texts: How do you make a camera look at a box and ensure all of it is visible?

texts:
In most game engines (Unity, UE4) if we select a model and press F, the camera moves and focuses to the selected model. I want to implement that for my models.

I have a perspective camera and world space bounding box of the model.

How do I calculate the appropriate distance to view the entire model in the camera?


texts: Is it possible or not to share a geometry among many meshes and apply a different shaderMaterial for each?

texts:
I instantiate one PlaneGeometry, then I instantiate 200 meshes sharing this geometry and with their own instance of a given shaderMaterial. Here is a simplified version of the code :

...
var geom = new THREE.PlaneGeometry(10,10,2,2);
var meshes = [];
var material=null;

for (var i=0 ; i<200 ; i++)
{
   var elevations = getElevations(i); //return an array of 9 values, values are different for each mesh
   var mat = new THREE.ShaderMaterial({
               vertexShader : vsAlti, //process displacement on y coordinate of the vertex
               fragmentShader : fsAlti,
               attributes : { elevation :  { type : 'f',value : elevations }}
            };
   meshes.push(new THREE.Mesh(geometry , mat));
}
...

Although the array value of the elevation attributes is different for each mesh, only one is applied for all of them. It looks like only one instance of shaderMaterial is applied to all the meshes. I would rather expect that for each mesh the shader with the matching attribute elevation values would be applied.

Here is the jsFiddle illustrating the problem : http://jsfiddle.net/McNulty/L584j/119/


texts: real time lights and high quality shadows in webgl build

texts: I have a game in which there are a lot of objects constantly moving around and a lot of real time lights with their setting set to highest, I'm building my game as webgl and this is costing me a lot of performance, how can I maintain the high quality and have better performance?


texts: What are some great and useful resources for an Isometric game built on the XNA Framework?

texts:
I'm currently working on an isometric game using the Microsoft XNA Framework. I'm looking of resources that would be of use for making this a successful project, such as isometric engines, physics engines, sprite engines(for isometric games), event handlers for ...

Any input would be greatly appreciated.


texts:
I'm trying to plan out a cover system for a 3D game.

The mechanic

When the player approaches a surface they can take cover behind...
A prompt appears indicating they can enter cover, and what to press to do so.
If the player presses the prompted button, their avatar is locked into a path following the scenery they're taking cover behind.
If the cover is a half wall, the avatar should crouch.
If the player approaches a gap in cover the camera should peek around the corner and
...they should be prompted to jump to the next cover
...otherwise, the player can exit cover by pressing another action button.

As seen from directly overhead (please forgive the side view character):

The plan so far

As far as I know, cover must be either

baked into the level by algorithm
explicitly created by the level designer
somehow handled on the fly

What I think should happen is the environment should be baked into hidden geometry which qualifies as cover. Then, I would detect sphere collisions (blue) with the generated cover areas (purple) to find out when one is in range.

Static geometry would qualify as cover if it were higher than a certain amount from adjacent ground (ie. at least 2.5 feet tall), and another threshold would indicate whether the character should crouch (at least 6 feet for standing cover, otherwise crouch). It seems like this would also be helpful for NPC vision and path finding.

This sphere detection process could be used similarly to locate gaps with cover available on the other side. Finally, once in cover, the player would move tangent to the cover surface (purple regions). Cover surfaces with angles less than a certain threshold would interpolate the current path into the path the player should follow to continue, otherwise they would be counted as a corner. So when the player reaches the end of cover, the angle of the adjacent surface determines that cover has ended and will prevent the player from accidentally breaking cover. They could press a button to move around the corner.

But I prefer not to reinvent the wheel - so is this "correct," or is there some accepted way of doing this that's totally different?


texts: Are ambient, diffuse and specular light or material properties?

texts:
Are ambient, diffuse and specular properties of light or material?

I am doing ray casting in OpenGL, I've managed to create lit sphere using formula

I = L Ka + L Kd (n . l) + L Ks (r . v)^n

but I entered values manually, now I'd like to create objects for light and sphere, but I don't know which of these properties (Ka-ambient, Kd-diffuse, Ks-specular) should be within the light object and which within the material (sphere) object


texts: Determining whether two fast moving objects should be submitted for a collision check

texts:
I have a basic 2D physics engine running. It's pretty much a particle engine, just uses basic shapes like AABBs and circles, so no rotation is possible. I have CCD implemented that can give accurate TOI for two fast moving objects and everything is working smoothly.

My issue now is that i can't figure out how to determine whether two fast moving objects should even be checked against each other in the first place. I'm using a quad tree for spacial partitioning and for each fast moving object, i check it against objects in each cell that it passes. This works fine for determining collision with static geometry, but it means that any other fast moving object that could collide with it, but isn't in any of the cells that are checked, is never considered.

The only solution to this i can think of is to either have the cells large enough and cross fingers that this is enough, or to implement some sort of a brute force algorithm. Is there a proper way of dealing with this, maybe somebody solved this issue in an efficient manner. Or maybe there's a better way of partitioning space that accounts for this?

Here's a diagram:

Object A and B's "areas of effect" cross, they should be checked against each other. But with the way i'm currently checking for collisions does not account for this. Again, i can think of a few solutions to this like actually checking if objects' paths cross once their velocity is higher than x, or something, but that feels like a hack and it's a mess to try and implement.


texts: Specific Physics Lessons and Reference for Game Development

texts: What "Physics stuffs" should I learn in game developments? I'm reading about Verlet Integration, and I'm wondering what other lesson should I learn and if there are available resources can you please provide some link or anything. Thanks.


texts: Set the name of an animation in collada to be used by AssImp

texts:
I am using the collada file format to contain my model and animation but when I use AssImp to load the file the name will be empty for the animation. Where is the name for animation set on the collada file format? The documentation seems to have pointed me to library_animations but I tried setting "name" and "id", but both did not end up setting the animation name.

To get the animation name I am simply doing

        aiAnimation* animation = mAIScene->mAnimations[i];
        auto test = animation->mName;


texts: Implementing DirectX 7 light attenuation in Unity's Universal Render Pipeline

texts:
I am create a modern Unity based client of an old MMO from 2000, and I am working on implementing their lighting system. Based on the data I have reverse engineered, it looks like they used a custom attenuation formula. The original client uses DirectX 7. I have found a reference sheet for DX7 light.
http://developer.download.nvidia.com/assets/gamedev/docs/GDC2K_D3D_7_Vert_Lighting.pdf
The relevant info starts at page 17. In the URP, in Lighting.hlsl, I have set up linear attenuation:
float range = rsqrt(distanceAndSpotAttenuation.x);
float dist = distance( positionWS, lightPositionWS);
half attenuation = 1.0f - dist/range;

Looks good! https://i.imgur.com/5bfJ5fF.png
Everything looks good. Now I am trying to (based on the document) recreate the same linear attenuation. It should look something like this:
// DX 7
float range = rsqrt(distanceAndSpotAttenuation.x);
float dist = distance( positionWS, lightPositionWS);
half c0 = 1.0f;
half c1 = 1.0f;
half c2 = 0.0f;
half d = dist/range;
half attenuation = 1.0f / ( c0 + c1 * d + c2 * d * d );

This should give me linear attenuation according to the doc, but it ends up bleeding light way past the range of the light. So I am convinced the distance is wrong. What kind of value is expected here? Normalized distance? It doesn't specify. I have played around with the distance a lot. Set it to the attenuation in the first code example, to the raw value, and a bunch of other values. No luck: https://i.imgur.com/JWJ0HF2.png
Does anyone have any ideas?


texts: Why does my Win32 call, contained in a class method, fail?

texts:
Using a Direct3D Tutorial, I took the knowledge and encapsulated it into a class. The code builds in MSVC 2010 fine, and I've handled all compiler warnings pertaining to my project with the highest warning levels. When stepping through the code from the entry point, the program fails to RegisterClassEx(&wc). After which, the program is told nicely to exit. Shortly after the unique_ptr's destructor is run (not manually, but after the unique_ptr goes out of scope), the program crashes w/invalid memory access.

My WinMain looks something like this:

std::unique_ptr<Engine> j_engine(new Engine);
j_engine->CreateD3DWindow(title, width, height, fullscreen); //public method of Engine, similar to CreateD3DWindow from the tutorial

while(message looping)
{
// etc
}

//if loop is exited, let j_engine fall out of scope (my program has never reached this point)

The start of my CreateD3DWindow method contains VERY standard window creation code, and does not even contain a shred of a Direct3D call prior to the crash (RegisterClassEx()).

It is essentially:

WNDCLASSEX wc;
hInstance = GetModuleHandle(NULL);
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wc.lpfnWndProc = (WNDPROC) WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = NULL;
wc.lpszMenuName = NULL;
wc.lpszClassName = "SomeName";

RegisterClassEx(&wc); // fails. GetLastError() == "Invalid Parameters". Stepping through WNDCLASSEX struct creation doesn't raise any invalid parameter flags.

I've also tried using ZeroMemory() after declaring WNDCLASSEX wc.

Two things register in my mind as I type this:
1. GetModuleHandle() is being called from inside the class, which exists on the heap and is referenced by a pointer from WinMain. Does this matter? Is it providing a valid handle?
2. WndProc declaration and definition is outside the class and outside the namespace of the class. Does this mean WNDCLASSEX.lpfnWndProc cannot see it? As such:

#includes

LRESULT CALLBACK WndProc()
{
}

namespace xyz
{
class Engine
{
}
}

I'm out of ideas and my problem solving capabilities are waning. Any advice? I will certainly provide more information if necessary.

Specifically, I'd like to know why RegisterClassEx() is failing.

Thank you!

***Mentioned below that GetModuleHandle(NULL) will return a global handle for the given process, so the context of this call in this program should not matter.


texts: How to determine the point of intersection of two lines?

texts:
I have two lines say P1( 0, -1, 0, -1 ) and P2( -1, 0, 0, -1 ). Since I'm working in 2D, there is no Z component. The x,y,z components are normals and the w component is the distance from origin. I am not given the origin or any points on the line.

What method should I use to programmatically determine the point of intersection for these two lines?


texts: Methods of player retention and conversion in MMO games?

texts:
What are other retention and conversion (free to play to paying to spender) strategies in MMOs?

I know some like promotions, social viral, content generation, intentional imbalance, perks and community management.


texts: Sprite character/item less than tile size

texts:
I am starting to work on a 2d top down tile-map game for fun and learning purposes. I have read some great answers here re tile-map size vs character sprite size, pixel density, ppu, screen resolution etc.

A standard route is to set a constant PPU and do characters as 2 tiles (vertically usually). We went with 32x32 pixels for the tile and 32x64 for the character.

Unfortunately, our artist didn't draw the character to fill out that space on the extremes (the feet and head do not touch the vertical edges and there is also space between the character and the horizontal edges) and when Unity slices the sprite-sheet we get smaller characters of 28x53.

I imagine this is a problem for keeping the consistency I outlined above with the tile size.

Is this a problem? If so, are the solutions to this to either change the tile size to 28x28 or ensure that the sprite design actually fills the tile space (that is, touching edges of the 32x64 area)? Must one draw items as always filling out the full tile size or can one make, say potions, in a 32x32 tile but only take up say 12x16?


texts: flip horizontaly (X) a ParticleEffect [Libgdx]

texts:
i got a particle effect thats is inside a group

 shellParticle = new ParticleEffect();
    shellParticle.load(Gdx.files.internal("shell13"),Gdx.files.internal(""));
    shellParticle.getEmitters().first().setPosition(0,0);
    shellParticle.scaleEffect(0.3f);

i need it to flip horizontaly but it just have the function flipY and setFlip(bool X, bool Y)

setFlip(true,false)

just do nothing.  flipY() actualy flip it verticaly.
Also i cant substract its own width*2 beause it dosent have so please help me


texts: SVG textures for 3D game objects in Unity?

texts: Is there a way to make textures using vector graphics and use it for 3d models so that textures would be object size independent and won't get blurry?


texts: How can I name and organize resources at design time?

texts:
I'm having a very hard time trying to figure out a good way to add new resources to my game project in a way that's convenient for designers.

To try and better understand the problem, I'm trying to create a very simple game.  It's in the style of an old text adventure.  The user begins in a room, and at the start of each turn an image of the room is displayed and some text describing the room is printed.  Then several options are shown (in a multiple choice format).  The user picks one and option and the result of the action is printed to the screen.  Then the turn ends and the next turn begins (the new image and description are shown, more options are printed, etc).

This game will require several resources:
    - String tables (to hold the text)
    - Images (Shown in each room)
    - Places (links to the image and description, as well as the list of options)
    - New Game Scenerio (used to initialize game.  Just tells the user where the starting room is)

I would like to create an editor where designers can just start it up and then start adding and editing rooms.

The straight forward approach would be to create a simple, stand alone editor that can load and save independent Place files.  It would use relative file paths to locate the linked images and string tables.  These Place file format would be XML which would later be compiled to a binary form when the final resource archive containing all resources is compiled.

The trouble with using paths, though, is that if you rename and move files (as you likely will as the project get larger), the paths that point to it will break (at well as any relative paths it points to itself).

Relative paths can also be a problem if you need to refer to resources that are in a completely different branch off the root.  For example, let's say I have the following resources in my project:

/item/MagicWand.xml
/place/grassyPlain/castle/DarkTower.xml

If I want to place a MagicWand in my DarkTower, I'd have to use a relative path that looks something like "../../../item/MagicWand.xml".  That's pretty cumbersome.  It would be nicer to use something like "item.MagicWand".

Also, since these resources are going to be compiled, if I need to refer to them from my scripts I will need something to call them.  If my user is in the DarkTower and selects the option "go to the griffon pen", I'm like to be able to do this with code similar to

getUser().setLocation("place.grassyPlain.castle.GriffonPen");

All this suggests importing my resources into some sort of super editor project that knows how to handle all resources and provides names for them (and even provide interactive editors for some of them).  While this would simplify the naming problem, but would be a lot of work - especially if more than one person need to design resources at the same time.  (for multiple users, I'd need a database-like locking mechanism to make sure multiple people weren't renaming things or working on the same file at the same time).  The whole thing would have a look and feel that calls to mind the Flash editor.

My thinking keeps leaning toward this super-duper editor solution, since I've been exposed to tools like this before.  However, this seems like a lot of work, especially for so simple a project.  I can't help but think that I'm over thinking this.  I would like to have a system for managing my game's resource that is simple yet, flexible and which integrates well with my code/scripts.

Does anyone have any thought on what makes a good resource managment/naming system?


texts: How to store variable inside an array unity?

texts:
I was wondering how I can store these anims inside an array, because, the start function will be fired one time. I would like to be able to call these Animators more then one time.

    public Animator anim0;
    public Animator anim25;
    public Animator anim50;
    public Animator anim75;
    public Animator anim100;

void Start () {

        anim0 = GameObject.FindGameObjectWithTag("Campfire0").GetComponent<Animator>();
        anim25 = GameObject.FindGameObjectWithTag("Campfire25").GetComponent<Animator>();
        anim50 = GameObject.FindGameObjectWithTag("Campfire50").GetComponent<Animator>();
        anim75 = GameObject.FindGameObjectWithTag("Campfire75").GetComponent<Animator>();
        anim100 = GameObject.FindGameObjectWithTag("Campfire100").GetComponent<Animator>();

    }


texts:
Alright, I have spent a lot of time on this one, so I need some help. I like the ability to draw pixels directly to the screen, sometimes I do this to trace the path of objects for debugging etc. In SDL 1.2 you could do something sort of like this :

//make screen
SDL_Surface * screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE );
//make surface
SDL_Surface * pSurface = SDL_CreateRGBSurface( SDL_SWSURFACE, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, 0x000000ff,0x0000ff00,0x00ff0000,0xff000000);
//get the pixels
Uint32 * pixels = (Uint32 *)pSurface->pixels;
//set a pixel to red
pixels[ x + ( y * pSurface->w ) ] = SDL_MapRGB(pSurface->format, 255, 0, 0);
//blit to screen
SDL_Rect offset = {0,0,0,0};
SDL_BlitSurface( pSurface, NULL, screen, &offset );

This would result in a red pixel being displayed, you could make a simple line across the screen with a loop. Now SDL2 is really blowing my mind at the moment, here is what I've got:

//setup
window = SDL_CreateWindow("test",SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,SCREEN_WIDTH, SCREEN_HEIGHT,SDL_WINDOW_SHOWN);
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
SDL_SetRenderDrawColor(renderer, 32, 32, 32, 255);
//make surface and texture
SDL_Surface * pSurface = SDL_CreateRGBSurface( 0, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, 0x000000ff,0x0000ff00,0x00ff0000,0xff000000);
SDL_Texture * pTexture = SDL_CreateTexture( renderer,SDL_PIXELFORMAT_RGBA8888,SDL_TEXTUREACCESS_STREAMING,SCREEN_WIDTH,SCREEN_HEIGHT);
//from texture into surface
SDL_LockTexture(pTexture, NULL, &pSurface->pixels, &pSurface->pitch);
//get the pixels
Uint32 * pixels = (Uint32 *)pSurface->pixels;
//set a pixel to red
pixels[ x + ( y * pSurface->w ) ] = SDL_MapRGB(pSurface->format, 255, 0, 0);
//surface back to texture?
SDL_UnlockTexture(pTexture);
//clear the screen, then copy the texture to framebuffer, then update
SDL_RenderClear( renderer );
SDL_Rect renderQuad = {0,0,0,0};
SDL_RenderCopy( renderer, source, clip, &renderQuad );
SDL_RenderPresent(renderer);

This does nothing, except to fill the screen with the RenderDrawColor. What am I doing wrong..?


texts: Are there any good techniques for reducing or smoothing stutter after a longer frame?

texts:
I've been using SDL2 with OpenGL to play around with some very basic game engine development. I'm running everything on a newer laptop with Linux and Intel integrated graphics.

Regardless of whether I have VSync on or off, occasionally a call to SDL_GL_SwapWindow (glxSwapBuffers under the hood) will take ~22-33ms which causes a noticeable stutter in any moving sprites. These long frames happen even if the game loop contains nothing but a call to glClear followed by SDL_GL_SwapWindow, so I'm assuming this is just due to everything running on a relatively underpowered system (and I don't see the long frames or stutter on my desktop with dedicated graphics).

I would have given up here and left it at the laptop not being cut out for OpenGL, but when I look at some indie games running on the same laptop, I'm unable to notice any of these stutter effects leading me to believe there may be a way to eliminate them (or that I'm doing something wrong). A few of the indie games were built with Monogame and at least one is also using SDL2 and OpenGL. I used apitrace to look at the OpenGL calls being made by these games and nothing looks very different from what I'm doing.

I then spun up a very basic Monogame project on my own machine, but still experienced the long frames and sprite stutter. I've tried different variations of fixed and variable game loops / timesteps as well as deltatime averaging to try to smooth over longer frames, but I still have a noticeable stutter.

Is there anything else I can do to eliminate the stutter or the long frames?


texts:
I've been trying to have text rendering in my OpenGL scene using SDL2. The tutorial I came across is this one Rendering text

I followed the same code, and I get text rendering fine. However the issue I'm having is that there is obviously a "conflict" between the OpenGL rendering and the SDL_Renderer used in the code. When I run my scene the text displays but everything else keeps flickering. The following gif shows the issue:

Any idea on how to overcome this while still just using SDL2 and OpenGL, not another library or anything.

Thanks


texts: Is there software that allows remote and collaborative work? How is it called?

texts:
I am currently not in the game development industry and develop my own games using GameMaker, but as a high school student I don't really have the time to make proper titles and actually make money from them. But, I have been thinking. Is there a program/website that, just say you were doing a long distance development with multiple team members in different parts of the world/country, you can upload all your work and with the click of a button anyone else in the "group" automatically downloads it. So for example:

You are a coder working on the physics engine.
There is another coder (somewhere else in the world) that is in your group and is programming the player that relies of the physics engine.
You make a change to the physics engine
Instead of having to email your partner the updated coding file and him having to download it, you save your file to a program that automatically uploads it to a server
Every 5 minutes (or whatever) the server checks if either person has uploaded any new files and automatically downloads them and overwrites them
So in turn your partner stays with continuously updated code and so do you. This could work with any aspect of a game (or any group project).

So is there anything like this? If so, is there a name for it?


texts: Smoothly moving an orbiting object back into orbit

texts:
I have an object that orbits the player's sprite with code that looks like this:

x = player.x + sin(_float) * _radius;
y = player.y + cos(_float) * _radius;
_float += 0.01;

An event can trigger the object to fly away from the player to chase a target. After it hits the target, I would like the object to glide back toward the player and smoothly return to an orbiting path around the player.

Everything I've tried thus far just ends up making it snap to a position abruptly or completely fly away, never to return again.

EDIT: I ended up with a solution that sets the objects velocity to the sin/cos orbit instead of directly setting the x and y coordinates. Thanks for the ideas!


texts: how can I transform a skewed line to a vertical line?

texts:
So, I have a line:

And I skewed it with x += y * cos(angle)

and got something like:

My question is, if I have another line segment with that same skew, how can I transform it so that it is pointing up again like:

I tried just applying a rotation (reverse of the skew angle) to the line's x,y coordinates, but that did not seem to give me the effect I am going for.

How can I do this?

EDIT

So, if I start with a rectangular like:

and I apply:

x1 = x1 + (y2 - y1) * cos(angle);
x2 = x2 + (y2 - y1) * cos(angle);

I get:

I am not quite clear why my x1 is wrong? (as you can see, it extends outside of the rectangle)..

But, regardless of that, this still is not the direction I am trying to skew by... What I really want is something that looks like this:


texts:
In this program, When i draw a hill, a car can road on it's surface, and when I draw another one, the previous hill should remove.

but unfortunately the previous edge collider looks still there.
this is what i've done for delete this collider :

        if(col)
        {
            col.Reset();
            col = null;
            Destroy(col);
        }

unfortunately nothing works :)
col.enabled = false is also doesn't work

this is the code:
i don't know what i have to do to disable the previous collision

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

public class LineFreeDraw : MonoBehaviour
{
    private LineRenderer line;
    private EdgeCollider2D col;
    private bool isMousePressed;
    private List<Vector2> pointsList;
    private Vector2[] pointsArray;
    private Vector3 mousePos;

    // Structure for line points
    struct myLine
    {
        public Vector3 StartPoint;
        public Vector3 EndPoint;
    };
    //  -----------------------------------
    void Awake()
    {
        // Create line renderer component and set its property
        line = new GameObject("Line").AddComponent<LineRenderer>();
        line.material = new Material(Shader.Find("Particles/Additive"));
        line.SetVertexCount(0);
        line.SetWidth(0.9f, 0.9f);
        line.SetColors(Color.green, Color.green);
        line.useWorldSpace = true;
        isMousePressed = false;
        pointsList = new List<Vector2>();
    }
    //  -----------------------------------
    void Update()
    {
        // If mouse button down, remove old line and set its color to green
        if (Input.GetMouseButtonDown(0))
        {
            if(col)
            {
                col.Reset();
                col = null;
                Destroy(col);
            }

            isMousePressed = true;
            line.SetVertexCount(0);
            pointsList.RemoveRange(0, pointsList.Count);
            line.SetColors(Color.green, Color.green);
        }
        else if (Input.GetMouseButtonUp(0))
        {
            isMousePressed = false;
        }
        // Drawing line when mouse is moving(presses)
        if (isMousePressed)
        {
            mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            mousePos.z = 0;
            if (!pointsList.Contains(mousePos))
            {
                pointsList.Add(new Vector2(mousePos.x, mousePos.y));

                line.SetVertexCount(pointsList.Count);
                line.SetPosition(pointsList.Count - 1, (Vector3)pointsList[pointsList.Count - 1]);

                CarIsCollide();
            }
        }
    }

    private void CarIsCollide()
    {

        col = new GameObject("Collider").AddComponent<EdgeCollider2D>();

        // Collider is added as child object of line
        col.transform.parent = line.transform;

        if (pointsList.Count < 2)
            return;

        pointsArray = new Vector2[] { pointsList[pointsList.Count - 2], pointsList[pointsList.Count - 1] };
            col.points = pointsArray;

    }

}


texts: Unity ads displaying only unity products

texts:
i just implemented unity ads on my project and now its only showing a single unity product each times. Can anyone suggest why? Thanks..

Here is some screenshot of the ad
1:
(https://i.stack.imgur.com/oG9vm.jpg)
2:
(https://i.stack.imgur.com/ZrS7x.jpg)

Can anyone tell me if this is even a real ad or just for testing?


texts:
So I used Quixel, and created a great item. I want to view it in Unity with all the maps the problem however is I have 5 maps but only know how to insert 4.

Diffuse
Normal
AO
Specular
Roughness

I don't see a slot for roughness (AKA gloss).


texts:
[I already asked this question on the UDK forums, without much success though.]

I'm using a class derived from AIController to control my pawn in RTS-style. My problem is that the pawn does not have a fixed Location.Z so if his Velocity in X and Y direction changes the Velocity.Z also changes (for whatever reason). I have tried nulling the Velocity.Z in the tick method, using Move to move the character back to a constant height and some other things of which nothing had worked. How can I solve this?


texts: Why don't we assign a class for each gameobject type in unity?

texts:
I used to create games from scratch with C++. There, people would create a "class Bullet", and add functionality to that class so that we can instantiate objects of class Bullet at runtime.

However, in Unity (which I'm new to), we need to create a Bullet GameObject in the editor, and then assign "class BulletBehaviourA : MonoBehaviour" to the Bullet GameObject. I don't really grasp this logic. Why don't we have a class for the Bullet in Unity?


texts: Who makes the art assets for mobile games?

texts: I know how to develop apps for Android but never tried developing games, and I want to start soon. For developing games we need sounds and high quality images (say a background, characters, logos, etc.), so how to create these? For this should we have a separate team? Or a developer can create these using any tools?


texts: How to make something rotate a certain amount over an exact amount of time

texts:
I'm trying to make a plane rotate down a certain amount and 180 degrees horizontally over 2 seconds.

Basically I want it to take the plane 1 second to rotate to a horizontal-facing angle, then take the other second to rotate 180 degrees around to face the other direction.

The formula I'm currently using is:

    //If you're rotating, lower the speed and rotate the plane.
    if (rotate == 1 && rotationPhase > 0) {
        //If in phase 0, figure out which phase you need too go to.
        if (angle > 90 && rotationPhase == 1) {
            //Rotation phase 2 = rotating down
            rotationPhase = 2;
            rotationAngleTime = angle - 90;
        }
        else if (rotationPhase == 1) {
            //Rotation phase 3 = rotating up
            rotationPhase = 3;
            rotationAngleTime = 90 - angle;
        }

        //After phase 0, if in phase 1 begin rotating down, if in phase 2 begin rotating up.
        if (angle > 90 && rotationPhase == 2) {
            transform.Rotate(0, 0, -rotationAngleTime * (Time.deltaTime * (rotationSpeed / 2)));
            angle -= rotationAngleTime * (Time.deltaTime * (rotationSpeed / 2));
            if (angle > 89 && angle < 91) {
                angle = 90;
                rotationPhase = 4;
                rotationAngleTime = 180;
            }
        }
        else if (rotationPhase == 3) {
            transform.Rotate(0, 0, rotationAngleTime * (Time.deltaTime * (rotationSpeed / 2)));
            angle += rotationAngleTime * (Time.deltaTime * (rotationSpeed / 2));
            if (angle > 89 && angle < 91) {
                angle = 90;
                rotationPhase = 4;
                rotationAngleTime = 180;
            }
        }

        //After you have rotated to horizontal in phase 1/2, rotate around to face the other direction.
        if (rotationPhase == 4) {
            transform.Rotate(rotationAngleTime * (Time.deltaTime * (rotationSpeed / 2)), 0, 0);
            rotationAngle += rotationAngleTime * (Time.deltaTime * (rotationSpeed / 2));
            if (rotationAngle > 179) {
                rotationAngle = 0;
                rotationPhase = 0;
                rotationAngleTime = 0;
            }
        }
    }

I've tried many different things, but I can't figure out what to do.

EDIT:
This seems to be a problem with Time.deltaTime. I can get the plane to rotate correctly, but for some reason it's not rotating over the right amount of time. I have a timer being subtracted by Time.deltaTime, and this animation happening, and the animation always finishes about half a second before the timer runs out.


texts:
I have some motion capture data (kinect) that records all body joints (32fps) and I want to take particular positions (for example when a person moves both of his hands up in the sky in celebration form) and find the forces that are being performed on each joint (or each bone). But what I really want is only the inside forces, the forces that the muscles perform, not gravity or wind or any other force. Can that be done using Open Dynamics Engine or Bullet. And if so, how? Is there a tutorial of some kind (I haven't found any yet)

EDIT--
The data that I currently have is xyz coordinates for each joint in each frame (as I said before 32 fps). It's easy to calculate the relative distance each joint made but what I need is the force applied to that joint and bone and maybe joint orientation if the force applied made the joint change orientation. I know that ODE and Bullet can take the dynamics of a 3D world (given by the programmer) and attach them to objects creating real world physics. What I need is to invert this process


texts: Box2D + Love2D (Lua) - Assertion fail with polygon meshes

texts:
When I try to create a triangle collider for my game it sometimes leads to an assertion fail. I use the physics engine that comes with love2d (Box2D). That's the error message that appears when the assertion fails:

love: modules/physics/box2d/Source/Collision/Shapes/b2PolygonShape.cpp:85: b2Vec2 ComputeCentroid(const b2Vec2*, int32): Assertion `area > 1.19209289550781250000e-7F' failed.

Here's an example of a triangle that doesn't cause the error (represented by a table with 3 points): {{258,451},{740,767},{284,597}}

And this one leads to a crash: {{258,450},{222,569},{306,723}}

The bodies of both shapes lie at {0, 0} (upper-left corner of the screen)

Does anyone know a possible reason and/or solution for the problem?

Edit:
I'm not allowed to answer my question right now for some reason so I'll post the answer here before I've forgotten it:
In Box2D, the order of placement of vertices seems to play an important role, since I was able to avoid the crash with the "problematic" triangle in my example from my question just by placing the first vertex between the second and the third one.
Maybe I'll repost the answer when I'm able to provide more information (and am also allowed to do so)


texts: Using normal maps to output world-space normals

texts:
Im using deffered shading and here is my g-pass Vertex shader code:

vec3 T = normalize(vec3(transform * vec4(tangent, 0.0)));
vec3 N = normalize(vec3(transform * vec4(normal, 0.0)));
vec3 B = cross(T, N);
vs_out.TBN = mat3(T, B, N);

And my Fragment shader code...

gNormal.xyz = normalize(fs_in.TBN * (texture(normal, fs_in.uv).rgb * 2.0 - 1.0));

Usually, you would times your light direction and/or view direction with TBN. However, my g buffers are taking up more bandwidth than they should, and i would prefer to get world space normals from the normal map. How should i go about doing so?

EDIT: Apparently, this should output world space... but it isnt. So i guess something here is wrong.

Tangent generation function:

void CalculateTangents() {
        tangents.clear();
        for (int i = 0; i < vertices.size(); i += 3) {
            glm::vec3 edge1 = vertices[i + 1] - vertices[i];
            glm::vec3 edge2 = vertices[i + 2] - vertices[i];
            glm::vec2 deltaUV1 = uvs[i + 1] - uvs[i];
            glm::vec2 deltaUV2 = uvs[i + 2] - uvs[i];

            GLfloat f = 1.0f / (deltaUV1.x * deltaUV2.y - deltaUV2.x * deltaUV1.y);
            glm::vec3 tangent;
            tangent.x = f * (deltaUV2.y * edge1.x - deltaUV1.y * edge2.x);
            tangent.y = f * (deltaUV2.y * edge1.y - deltaUV1.y * edge2.y);
            tangent.z = f * (deltaUV2.y * edge1.z - deltaUV1.y * edge2.z);
            tangent = glm::normalize(tangent);

            tangents.push_back(tangent);
            tangents.push_back(tangent);
            tangents.push_back(tangent);
        }
    }

There is a point light "attached" to the camera (which clearly isnt working) and the reflection is wrong.


texts: Partial mesh culling by checking against the AABB-tree of objects vertices instead of only the AABB of the whole objects

texts:
First thing: this is more of a conceptual question than an implementation oriented one, but still tips about implementation will be very much welcome if you happen to have any (athough I have some experience programming different parts of games, graphics are certainly my weak spot - as you will see).

So, I have an application in which all high-poly objects have their vertices grouped in an object-specific AABB-tree to speed up the narrow-phase of collision detection. Now, it occurred to me the following. Since that structure is already in place, would it be possible to use it for culling parts of objects instead of the usual all-or-nothing approach of the frustum and occlusion culling techniques?

The idea for that is simple in concept. Instead of testing for visibility only using the whole objects' AABB, I would do that first but in the positive cases I would proceed to visibility checks of the sub-AABBs containing that object's vertices. Once identified the sub-AABBs that are visible, only the triangles that are contained in these sub-AABBs would be sent to the GPU for rendering.

Therefore, in a more systematized way, my three related questions are:

1) is such an approach even possible in what regards the way GPU gets and processes the mesh geometry information pulled from CPU?

2) given that in such scenario the CPU would have to break the meshes somehow and pass to the GPU only the vertices that were identified as being in the visible parts of the visible objects, wouldn't that pose additional load on the processing time such that the cost would overcome the gains?

3) most importantly, passing to the GPU only some triangles of a mesh could cause graphically distorted results when shader and texture are rendered for that partially-only rendered object?

I searched quite a bit for academic references on this subject but came almost empty. I would gladly welcome reading suggestions of any sort.


texts: Why does my capsule collider fall without my object (Unity)?

texts:
I've got a player with a rigidbody/capsule collier (gravity enabled) and a plane with a box collider. When the player is on the plane, everything works as expected, the player can walk across the plane with no issue. However, when the player walks off the plane, I want the player to fall. However, what happens instead is that the capsule collider falls but the player just keeps walking in thin air. Why is this happening?

Problem:

Colliders setup:

Code:

void Update () {
    i = 0.1f;
    transform.position = new Vector3(transform.position.x, transform.position.y, transform.position.z + i);
}

Sorry if I'm doing something stupid, I'm new to game development/Unity, I usually program  other things, not 3D games. Just expiermenting a bit to learn.


texts: libgdx ActorGestureListener.pan() parameters not moving actor in smooth line

texts:
I override the pan method in ActorGestureListener to implement dragging actors in libgdx (scene2d).

When I move individual pieces on a board they move smoothly, but when moving the whole board, the x and y coordinates that is sent to pan is "jumping", and in an increasingly amount the longer it is dragged.

These are an example of the deltaY coordinates sent to pan when dragging smoothly downwards:

 1.1156368
-0.13125038
-1.0500145
 0.98439217
-1.0500202
 0.91877174
-0.984396
 0.9187679
-0.98439026
 0.9187641
-0.13125038

This is how I move the camera:

public void pan (InputEvent event, float x, float y, float deltaX, float deltaY) {
    cam.translate(-deltaX, -deltaY);

I have been using both the delta values sent to pan and the real position values, but similar results. And since it is the coordinates that are wrong, it doesn't matter whether I move the board itself or the camera.

What could the cause be for this and what is the solution?

When I move camera only half the delta-values, it moves smoothly but only at half the speed of the mouse pointer:

cam.translate(-deltaX / 2, -deltaY / 2);

It seems like the moving of camera or board affects the mouse input coordinates. How can I drag at "mouse speed" and still get smooth movements?

(This question was also posted on stackoverflow: https://stackoverflow.com/questions/20693020/libgdx-actorgesturelistener-pan-parameters-not-moving-actor-in-smooth-line)


texts:
I want to make a turn-based game where the player is given "opportunities for attack." An image of the in-game sprite character appears when it's the player's turn to attack. The player can mouseover the various parts of the image, which will highlight that specific body part, like so:

The player can then choose to attack that given body part.

To do this, I was thinking of adopting the "grid" method, and put my image within a 2D array... with each region of the body mapped to a certain square, like so:

Or, I could generate a pixelated version of the in-game sprite within a grid to begin with, so I would already have the mappings, like so:

Minecraft Pixel Art

I'm not sure:

how to partition the image up so that each section is represented meaningfully in the matrix
if this is the right way of doing this

Any guidance would be helpful


texts: Machine Learning in AI for benefit analysis round to round in a rummy like game

texts:
For fun I am building the game 5 crowns. Well I've gotten to the point where I am implementing the rules for the computer players.
I've found that my decision tree has so many nodes on it that I wonder if it would be easier to implement an algorithm that would take a small subset of the nodes and infer the rest from that basic subset.

Basically I would like to input a subset of rules.
So the following are the rules for each round

Round number determines which card is wild

Minimum card value is 3 so in round one 3's are wild.

You may only have a specific number of cards in your hand.

The amount of cards in your hand is equal to the value of the card that's wild.

You can draw from the discard pile or the deck.
Your goal is to be the first one to lay down their hand by building sets or runs.

A set or run must have at least 3 cards in it.
Runs can only have cards of the same suite.

After a player lays down their hand each remaining player has one more turn to lay down.
Any cards left in your hand when the round ends are totaled and added to your score.
Higher cards are worth more points.

So if my hand was the following, and it was the first round (I.E. 3's are wild):

hand = [{value: 3, suite: hearts},  //3 of hearts
        {value: king, suite: clubs}, //king of clubs
        {value: 7, suite: spades}]  // 7 of spades

And the card on top of the discard pile is a 5 of diamonds ({value: 5, suite: diamonds})

I would engage in the following thought process:

The 5 has a lower score then the 12 or 7, which would be good if I can't lay down when the round ends.
However, unless someone before me has already laid down, I will have at least one more turn; at which point, if I need to, I can ditch the 12.

There is a high probability that if the player right before me has a 12, they will dump it. Allowing me to pick it up next turn and lay down.

This may not be the first turn and I may of seen the player after me take a 7 or 12.
If I draw a card there is a higher probability of getting something useful (I.E. another 7, 12, or wild). Which would let me go out.

Most human players would accept the risk inherent in keeping the 7 or 12 and draw a card from the deck, instead of taking the 5.

The above logic isn't very hard to implement. It's when you extrapolate it out and have to do the cost/benefit analyses on 13 cards in your hand, that decision making tree becomes a lot more complex. Which would be why I want to look into machine learning to solve this problem.

As a note I have already implemented the logic to determine if you can go out. The above applies to how the computer should evaluate the pro's and cons of a specific action (which card to draw, and which card to discard, and to an extent, when in higher rounds, how to structure the runs/sets needed to lay down it's hand).