texts:
Disclaimer: Somewhat long-winded question & new to developing

In my game I have a class called Item which defines what an item is. It contains several fields like the name of the item, the sprite of the item, the item's ID number, etc. I also have little physical objects on the ground that "represent" items, but they aren't really tied to the Item class in the way I want. I'll get back to this point.

So, when an enemy dies in my game, SpawnItem(Item item) is called. Depending on a randomly generated number, SpawnItem(ItemData.sword) might be called or SpawnItem(ItemData.axe) and so forth. SpawnItem itself just instantiates a generic prefab (that little physical object on the ground), modifies some state like bool itemDropped and int numItemsDropped, makes some calculations to determine where to drop the item, and displays that item's name in a UI label above the item.

I'm currently in the process of making an inventory system, and I've realized something. Those physical objects on the ground that are supposed to be items don't really know that they're items (in the sense defined by the class). A sword doesn't know it's a sword, and an axe doesn't know it's an axe (the game object sword doesn't know that it's a sword Item defined by the class) So when I pick up an item, I can probably do some code gymnastics to get the appropriate sprite to appear in the inventory, but that doesn't seem like a smart solution.

So, my question is how do I get my sword game object (just a sphere on the ground representing a dropped item) to be linked to the sword Item? How do I get the sphere to know that it represents a sword with the ID number "1", the name "Sword", a weight of "1.5" etc. so that I don't have to do awkward code gymnastics? After all, when I'm adding an item to my inventory, I don't really think of it as JUST drawing that item's sprite in the first non-empty slot of the inventory. I would think it's much better to get each game object to know what Item it represents than to just try and get that sprite to show up in the inventory.

I might be overlooking something basic, but understand that I'm pretty new to Unity. Anyway, thanks for the time and help!


texts: AndroidManifest file was deleted by accident

texts: I deleted the AndroidManifest file of my project which was located in Assets\Plugins\Android , so I tried creating new project and copying the Assets and everything but it seems that something is missing ,it's perfectly working in the editor , but as apk there are few things aren't working, I can't figure out why, and there isn't even a Plugins folder in my new project !


texts: Noisy edges, smoothing out edges between faces via fragment shader

texts:
I have a generated terrain, with hexagonal geometry, as per screenshot below:

I then generate biomes, but as you can see the borders between them are really ugly and straight. To hide that hexagonal origin, I would need to smooth out the borders between biomes. This is how it looks now in wireframe with real tringular faces:

What I'm aiming for is something more like this:

Each vertex has attibute that holds the biome type, I can also add special attributes to the vertices on the edge between two biomes, but I just don't seem to be able to figure out how to pull this off in shader code, obviously noise is involved here, but how do I make it continous across multiple faces and entire border of multiple biomes?

I'm rendering with WebGL using THREE.js


texts: Need some general direction for turn-based planning AI

texts:
I'm planning to make a turn-based fleet battle game. While I think I can figure out most of the things I need, I have no idea about the AI handling this sort of game. I need some general direction about how should I deal with it.

None of the things I described below is currently done - except maybe unit movement stuffs.

The combat resembles Frozen Synapse or Steambirds, in which you and your opponent plan their unit's actions and then execute it to see how it resolves. Since the units are naval warships, their movement is restricted by current direction and speed, etc etc. They attack when you order them to do so(not automatic).

I think I can give scores to each move(like Chess AI), depending on its location, direction, possible movement area, known enemy positions and things like that. Then I can use Minimax algorithm to let the AI select the best move.

Now, I'm asking because I can't figure out

which situation should the score be based on. Should the AI make a plan assuming the enemies are all moving straight, predict the best enemy plan based on it, and then write the actual plan based on the prediction? Is it going to demand a lot of processing power? Or is there simpler way using Minimax?
Unlike grid-based tactical games, the area which a unit can move is a (semi-)continual area. If I try to give score to all possible positions, that might take too much processing power. Is there a way to handle this issue neatly?
There might be more efficient/effective alternatives to the Minimax on this particular game which I do not know.

So... i'm asking for general direction about how should I handle the AI. Details will be in when I actually make it.


texts: What new programming languages are being used to develop web-based games?

texts:
I've got around 10 years behind me of casually creating AS1/2/3 games and have found myself wondering recently what other options are available for web-based games.

I have recently found haXe and will probably start coding in that, since it is largely based on AS3/ECMAScript, and I am also aware of JavaScript/jQuery etc and HTML5 being suitable for purpose, but what else is there?

What up and coming languages are being used to develop / are targeted at making web-based games?


texts: Most efficient way of communication between "unfamiliar" game objects?

texts:
Title could look vague, so here's what I actually mean.

Three groups of people are walking in the city. These are Guards, Thieves and Citizens.
Something has happened in the city, Thief have stolen a pocket from a Citizen, the Guard walking around was close enough to see the crime, so now he's chasing Thief.

So here's the question, how that chain would work from execution perspective?
We can imagine there is a some kind of StateCheckingObject placed in the world. When Thief steals a pocket, it's class (or Citizen's class ) would broadcast a message to the StateCheckingObject. After StateCheckingObject is aware of crime it would broadcast message to the Guards walking around making them aware of crime.

Well, broadcasting stuff doesn't look complex, that could be a simple event dispatcher. But how would Thieves, Citizens and Guards hold a reference to StateCheckingObject? And what StateCheckingObject should even look like? Should it somewhere in the level? Should other object access it when spawned with GetAllObjectOfClass(StateCheckingObject)? That could be a heavy task for system since iterating over all level objects is not very efficient.

The issue looks pretty similar to GTA where events are broadcaster to nearby police cars when crime is happening, but what would make a broadcast?

Edit: lilotop suggested a trigger box solution and I've realised I haven't explained the idea why I would want to make state checking system.

Some actions happening in the world should be stored somewhere. I.E. after Citizen got robbed StateChecker would get aware of it and store bool CitizenGotRobbed.
That boolean would later be used in maybe some kind of dialogue adding new branch to guard dialogue.


texts: How to develop a concept to receive funding?

texts:
I have a game concept which I wish to develop but don't have the funding to begin it.

What should I do?


texts:
I am currently working on a 2D game in Unity, I am using Animation Controllers / Animators for the different slots of armor on the character. The scripts set the Animation to the player object and that seems to work out alright for the most part.

However when I walk long distances without stopping it seems like the armor tends to drift away from the player object and I haven't been able to find out why.

// This will update the player and then update all his inventory to match his position.
public void UpdateMovement()
{
    if (IsActive == true)
    {
        float input_x = Input.GetAxisRaw("Horizontal");
        float input_y = Input.GetAxisRaw("Vertical");
        bool playerMoved = false;

        Vector2 movement = new Vector2(input_x, input_y);
        float delta = Time.deltaTime;

        if (movement != Vector2.zero)
        {
            _animator.SetBool("IsWalking", true);
            _animator.SetFloat("x", input_x);
            _animator.SetFloat("y", input_y);
            playerMoved = true;
        }
        else
        {
            _animator.SetBool("IsWalking", false);
            playerMoved = false;
        }

        PlayerController.transform.position += new Vector3(input_x, input_y, 0).normalized * delta;
        Inventory.UpdateMovement(input_x, input_y, delta, playerMoved, PlayerController.transform.position);
    }

   // This code is for each slot to update it's position.
   public void UpdateMovement(float x, float y, float time, bool isWalking, Vector3 pos)
    {
        _animator.SetBool("IsWalking", isWalking);

        if (isWalking == true)
        {

            _animator.SetFloat("x", x);
            _animator.SetFloat("y", y);
        }

        _animator.transform.position += new Vector3(x, y, 0).normalized * time;

        // _animator.transform.position = pos;
    }

So my question is, what is the best approach for layering armor sprite animations on a player in Unity 5?


texts:
Previously I was using simple Texture for sprite based animations, but that did not provide support for images which were not in the power of 2. TexturePacker provides with the ability to load all the images at once, and then fetch the required image from an imageatlas.

That said, I followed a couple of tutorials from the Libgdx wiki and it works well till the loading part. But I suppose during rendering, it is causing some problem. This is how I am loading the images into the texturepacker in my desktop project:

private static final String INPUT_DIR = "../Drop-Android/assets/images";
    private static final String OUTPUT_DIR = "../Drop-Android/assets/image-atlases";
    private static final String PACK_FILE = "pages-info";
    public static void main(String[] args){
        LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
        cfg.title = "Drop";
        cfg.width = 800;
        cfg.height = 480;

        Settings settings = new Settings();
        settings.maxWidth = 512;
        settings.maxHeight = 512;
        TexturePacker2.process(settings, INPUT_DIR, OUTPUT_DIR, PACK_FILE);
        new LwjglApplication(new Drop(), cfg);
    }

Question: Do I have to create pages-info i.e. the PACK_FILE manually in the images-atlases folder? If I do not, it throws File not found exception.

I happen to create pages-info file in the image-atlases folder and the following files are generated: pages-info.png and 'pages-info.atlas'. While, pages-info files is empty, the .png and .atlas files have the images and JSON image data, respectively.

This is what I am using to extract the textureregions out of the pages-info file (which is empty):

TextureAtlas ta = new TextureAtlas(Gdx.files.internal("image-atlases/pages-info"));
        imageOneRegion = ta.findRegion("image1.png");
        imageTwoRegion = ta.findRegion("image2.png");

As expected, it returns a nullpointerexception when drawing the textureregion. I am running out of ideas here, any help and ideas?


texts: (Unity) Serializing Data with Custom Object Stored by Reference

texts:
I have a custom class that I serialize/deserialize to/from file(s), and is not guaranteed to be identical each time the game runs (in this example, a language pack. it's possible to fix a typo manually). As a result, I do not use UnityEngine.Object on it, and deserialize it each load. However, some classes that implement UnityEngine.Object (Monobehavior), have references to it. these references must persist (so that the language stays the same each load)
As per the Unity Scripting page, https://docs.unity3d.com/Manual/script-Serialization.html, this can cause undesired behavior: "If you store a reference to an instance of a custom class in several different fields, they become separate objects when serialized. Then, when Unity deserializes the fields, they contain different distinct objects with identical data."

Naturally, I'd prefer this not be the case. again from Unity documentation linked above: When you need to serialize a complex object graph with references, do not let Unity automatically serialize the objects. Instead, use ISerializationCallbackReceiver [interface] to serialize them manually.

I know how to implement the interface. How do I preserve the reference? (Disclaimer: not an expert in serialization, so if it's a simple fix, I'm sorry. Unity documentation doesn't provide an example for references).


texts: How to design a character animation system?

texts:
I'm searching for suggestions and resources on the possible ways to design a character animation system. I mean a system built on top of the graphics engine (as graphics engine I use Ogre3D, that provide an animation layer), and in strict contact with the logic of the game.

It's for a sports title, so the question is not easy.

Edit: What I'm searching for are suggestions and resources about the action state mechines (or animation state machines), that is build on top of the animation pipeline already provided by the graphics engine. So, a state-driver animation interface for use by virtually all higher-level game code.


texts:
I have a 2D side-view game with object attributes such as x, y, speedX, etc. Now I want to throw a given object from any place on the screen onto a defined goal place, in such a way that its trajectory looks somewhat normal (with gravity, it making a curve and such). Imagine an enemy is destroyed and what he stole flies from him back towards the stolen object's origin. (I do have physics via Box2D in this game, but for this particular need, it seems I require a manual approach; for one thing, the object is allowed to pass other bridges and such for the time it flies back to its main bridge.)

How would I go about this? I've tried moving manually by adjusting towards a target speed and such, but the trajectory and timing looks very unnatural. Thanks!


texts: Need help with rotating sword around player (Unity 2D)

texts:
I'm having an issue with rotating an object around another object in my top-down roguelike in Unity 2D. My goal is to rotate a sword around a player based on joystick input from a controller (as shown in this image).

I have looked around online for any answers, but nothing has helped. All I have so far that is remotely close to what I want is code that keeps the sword attached to the box even when the box moves.
void Update()
{
    transform.localPosition = new Vector3(0, 1.5f, 0);
}

It might be necessary to note that the sword object is a child of the box object. I would appreciate it if anyone could point me in the right direction. Thanks!


texts:
I faced the problem of attaching animation to the enemy. In the Animator window I added a "moveSpeed" (float) condition, so moving animation should turn on when moveSpeed is greater than 0.001. But after prescribing a reference to an Animator in the code, whatever I write further, a message pops up about the presence of compiler errors.
Here's my script:

public int health;
public GameObject explosion;

public float playerRange;

public Rigidbody2D theRB;
public float moveSpeed;

public Animator anim;

// Use this for initialization
void Start () {

}

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

    if(Vector3.Distance(transform.position, PlayerController.instance.transform.position) < playerRange)
    {
        Vector3 playerDirection = PlayerController.instance.transform.position - transform.position;

        theRB.velocity = playerDirection.normalized * moveSpeed;

    }
    anim.SetFloat("moveSpeed") = theRB.velocity;
}

public void TakeDamage()
{
    health--;
    if(health <= 0)
    {
        Destroy(gameObject);
        Instantiate(explosion, transform.position, transform.rotation);
    }
}

What exactly do I need to write for the condition to work and the animation to play?
Thanks for any help!


texts: How can I make scalable(contracting) EditorWindow UI(not in-game UI) like in inspector example?


texts:
I want to make a function like areColliding which takes two polygons as args.
I also want to cover cases like

and the dreaded

because I am trying to create a framework and I think that it should be as accurate as possible.
var polygon1 = [
  [1, 1],
  [2, 5],
  [5, 3],
];
var polygon2 = [
  [1, 1],
  [2, 5],
  [3, 5],
  [7, 4],
  [1, 3],
  [2, 1],
  [1, 0],
];
areColliding(polygon1, polygon2) //=> true
areColliding([[1, 4]], [[1, 2], [3, 4], [5, 6]]) //=> Error
areColliding({}, [[1, 2], [3, 4], [5, 6]]) //=> Error
areColliding([[1,1],[2,2],[3,0]], [[7,7],[5,7],[6,8]]) //=> false


texts:
Why is my code not working?

using UnityEngine;
using System.Collections;

public class NewBehaviourScript1 : MonoBehaviour
{
    public float moveSpeed;
    public Vector3 input;
    public Rigidbody rb;

    void Start ()
    {
        rb = GetComponent<Rigidbody>();
    }

    void FixedUpdate ()
    {
        moveSpeed = 2;
        input = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
        rb.AddForce(input * moveSpeed);
    }
}


texts: In Unity, how do get access to animation clips in selected model from EditorWindow?

texts:
I need to add some animation events or copy them from other models. So I decided to make a EditorWindow. Unfortunately there's not much information about this, and I'm stuck in here.

void OnGUI() {
    GUILayout.Label("Source Object contains Animation Clips", EditorStyles.boldLabel);
    sourceObject = (GameObject) EditorGUILayout.ObjectField(sourceObject, typeof(Object), false);

    if(GUILayout.Button("Copy")) {
        if(sourceObject == null) {
            throw new System.NullReferenceException("Source Object is missing.");
        }

        // Do Copy here

    }
}

What I need to do is:

Extract all animation clips from the selected model(fbx) - it's the source object
Select "AnimationClip" to want to copy. Note that AnimationClip in here is not inside of model, it's seperated AnimationClip that duplicated from original model because basically animation clip from imported model is read-only, so I have to duplicate to update it.

How do I get animation clips from selected fbx model with ObjectField? Any advice will very appreciate it.


texts: Collision Resolution: How to avoid Interpenetration/Tunneling Caused by Prior Collision Handling?

texts:
My game processes world collisions followed by entity collisions. The problem here is that entities can break through walls the next frame when world checks are run again as a result of the prior collision resolution.  For example:

Entity1 is up against a wall and pushing against it
Entity2 runs into Entity1, collision detection resolves Entity1 inside the wall.
World collisions push Entity1 onto the other side of the wall.

What happens is that Entity2 pushes Entity1 into the wall far enough that when the world collision detection attempts to find the shortest distance out of the wall, that position happens to be on the other side.


texts: How do I programmatically access single sprites when Sprite Mode is Multiple?

texts:
Unity 4.3 newly brings an ability to cut up a sprite sheet into multiple individual sprites. This is useful since you then only need one master spritesheet, but nevertheless get references to individual sprites. It's done by setting Sprite Mode to Multiple.

Can all the sprites generated from the master file be programmatically accessed from the Unity Sprite Editor?

For example: I have a spritesheet with a grid of 50x50 sprites. Using the Unity Sprite Editor, I now have 250 sprites: spritesheet_0, spritesheet_1, ..., spritesheet_249. How can I get a handle to spritesheet_102 without having to manually drag and drop it in the Unity editor?


texts: Rotating a 3rd person camera toward a target

texts:
I have a 3rd person camera that doesn't look directly at the player but somewhere in front of him.

When the user enter shooting mode, I want the camera to turn around the player to face the target.

In the image above. "O" is the player (Origin), "L" is the lookat, "C" is the camera position and "T" is the target. I want to rotate the lookat line C->L so that it passes by T (C'->L'->T') around the Origin ("O").

Basically I need to find the angle alpha that I put in red in the picture.

I store my camera position in a structure like such :

struct CameraTarget {
     Quaternion absoluteRotation;
     Vec3 absolutePosition;
     Vec3 cameraOffset;
     Vec3 lookatOffset;
     float FOV;
}

So if I could find the angle I'm looking for I could do something like :

cam->absoluteRotation = cam->absoluteRotation * alpha;

To get the player to always look at the target.

If the lookat was passing by the Origin I could simply do

Vec3 origDir = cam->lookAtOffset - cam->absolutePosition;
origDir.normalize();
Vec3 newDir = cam->target - cam->absolutePosition;
newDir.normalize();
Quaternion q(origDir, newDir); // from->to
cam->absoluteRotation = cam->absoluteRotation * q;

However in the diagram above this doesn't quite work since the rotation is offset from the Origin.


texts: Java Game How to change opacity of an image?

texts:
Hello I have a game where you feed animals. A few minutes after you feed them they do a poo. I want the poo to fade away after a few seconds. I want to know how to change the opacity on the image. How can I do this?

here is my code:

package items;

import java.awt.AlphaComposite;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;

import javax.swing.ImageIcon;

public class poo {

    public int x, y;
    private Image img;

    public int time = 0;
    public int timer = 100;
    public boolean remove;

    public float alpha = 1f;

    public poo(int x, int y) {
        this.x = x;
        this.y = y;

        alpha = 1f;
    }

    public void tick() {
        if (time >= timer) {
            time = 0;
            // remove = true;
        } else {
            time++;
        }
        if (alpha > 2) {
            // alpha--;
        } else {
            // remove = true;
        }

    }

    public void render(Graphics g) {

        ImageIcon i2 = new ImageIcon("res/items/poo.png");
        img = i2.getImage();

        g.drawImage(img, x, y,6,8, null);

    }
}


texts: Cocos2dx v3 Problem with moving Sprite on tilemap after it was scrolled up

texts:
I have a problem I can't solve so far.
I have a scene with tile map on it. And there is a Sprite spawnpoint on map. This Sprite should do MoveTo() action to the point where TouchEnded().

It all works perfectly in the borders of the screen, but after I scroll my map up and do touch again my Sprite stuck in the max Y point of the screen. (Let's say there is max 480px of screen's Y, but 850px of tile map)

Please help!


texts:
I'm building a tile-based game with a similar art style as Stardew Valley, but have a few questions around technique. My understanding is that it's best to store the maps as a byte array of tile ids and render based on that.
But:

In the render loop, is it efficient to simply iterate that byte array every time and pull the tile image from a tilesheet?
How are "overlaid" items typically modeled in these type of games? e.g. In SV, there are often rocks/trees/houses/boundaries that expand over multiple tiles. Should these be treated as items consisting of tiles as well, or as a separate "layer" of individual items that are placed at x/y coordinates?
Is multiple byte arrays with tile properties (e.g. isPassable) more efficient than an array of objects?


texts:
I'm trying to make a camera system where the camera never goes outside the edges of the current room (like Link to the Past or Mega Man, for example)

This is what I have right now:

using UnityEngine;
using System.Collections;
public class CameraFollow : MonoBehaviour {
public BoxCollider roomBounds;
public Player target;
Vector3 velocity;
float halfHeight,halfWidth;
void Start(){
    halfHeight = Camera.main.orthographicSize;
    halfWidth = halfHeight * Camera.main.aspect;
}
void LateUpdate(){
    Vector3 targetPosition = target.transform.position;
    if (targetPosition.x+halfWidth >= roomBounds.bounds.max.x || targetPosition.x-halfWidth <= roomBounds.bounds.min.x) {
        velocity.x = 0;
    } else {
        velocity.x = targetPosition.x - transform.position.x;
    }
    if (targetPosition.y+halfHeight >= roomBounds.bounds.max.y || targetPosition.y-halfHeight <= roomBounds.bounds.min.y) {
        velocity.y = 0;
    } else {
        velocity.y = targetPosition.y - transform.position.y;
    }
    transform.position += velocity;
}
}

It works on a rudimentary level, but the problem is, whenever you're moving out from a wall after the camera's stopped, it snaps a little to the left or the right, and then goes back. Same vertically.

Any idea as to what might be causing this and how to solve it?

P.S. I know there have been a lot of threads about this kind of system (even one 21 hours ago), but none I've found helped me much.


texts: How to get this wavefront .obj data onto the frustum?

texts:
I've finally figured out how to get the data from a .obj file and store the vertex positions x,y,z into a structure called Points with members x y z which are of type float. I want to know how to get this data onto the screen.

Here is my attempt at doing so:

//make a fileobject and store list and the index of that list in a c string
ifstream file (list[index].c_str() );

std::vector<int>faces;
std::vector<Point>points;
points.push_back(Point());
Point p;
int face[4];

while ( !file.eof() )
{
    char  modelbuffer[10000];
    //Get lines and store it in line string
    file.getline(modelbuffer, 10000);
    switch(modelbuffer[0])
    {
        case 'v' :
            sscanf(modelbuffer, "v %f %f %f",  &p.x, &p.y, &p.z);
            points.push_back(p);
            cout << "Getting Vertex Positions" << endl;
            cout << "v" << p.x << endl;
            cout << "v" << p.y << endl;
            cout << "v" << p.z << endl;
            break;
        case 'f':
            sscanf(modelbuffer, "f %d %d %d %d", face, face+1, face+2,  face+3 );
            cout << face[0] << endl;
            cout << face[1] << endl;
            cout << face[2] << endl;
            cout << face[3] << endl;
            faces.push_back(face[0]);
            faces.push_back(face[1]);
            faces.push_back(face[2]);
            faces.push_back(face[3]);
    }
    GLuint vertexbuffer;
    glGenBuffers(1, &vertexbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
    glBufferData(GL_ARRAY_BUFFER, points.size(), points.data(), GL_STATIC_DRAW);
    //glBufferData(GL_ARRAY_BUFFER,sizeof(points), &(points[0]), GL_STATIC_DRAW);

    glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);
    glVertexPointer(3, GL_FLOAT, sizeof(points),points.data());
    glIndexPointer(GL_DOUBLE, 0, faces.data());
    glDrawArrays(GL_QUADS, 0, points.size());
    glDrawElements(GL_QUADS, faces.size(), GL_UNSIGNED_INT,  faces.data());
}

As you can see I've clearly failed the end part but I really don't know why its not rendering the data onto the frustum? Does anyone have a solution for this?


texts: Load order of networked objects in Unity

texts:
I am making a 2D RTS, and am trying to get a multiplayer version working. I've run into some problems with the order that scripts are getting executed. For the host everything runs fine, but when a new client connects, I get a lot of bugs. What's happening is that the objects that I've spawned already are getting loaded into the new client's scene before things they depend on, like the map itself. When I was writing the code, I was thinking that there's no way that something user-created could get get loaded before the map, because the map gets loaded right when game starts, but the order in which UNET loads spawned items seems to be weird like that.

Is there anything I can do to change this, or do I just need to rewrite things so that the loading of spawned items doesn't require the map to be loaded?

Thanks


texts: Quaternion representing rotation from shoulder to hand

texts:
I am provided with 3 quaternions. One for the shoulder, one for the elbow, and one for the hand. What I want is to obtain a single quaternion representing the rotation from the shoulder to the hand, essentially removing the elbow in the process. I have a diagram below to better illustrate this.

Assuming that both of the above sections (forearm and upper arm) are of the same length, how could this be calculated?


texts:
I'm currently trying to render to a cubemap in order to blur it. However the top and bottom faces appear much closer than they should be in the blurred version. I thought the problem came from my transformation matrices but they're just rotations. I'm beginning to believe that it's the way I'm handling the framebuffer that's causing this problem. Here's how I'm doing it :

    unsigned fbo;
    unsigned rt;
    glViewport(0, 0, size, size);
    glGenFramebuffers(1, &fbo);
    glGenRenderbuffers(1, &rt);

    glBindFramebuffer(GL_FRAMEBUFFER, fbo);
    glBindRenderbuffer(GL_RENDERBUFFER, rt);
    glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, size, size);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rt);

    //...
    //enable source cubemap, set projection
    //...

    for(int i = 0; i < 6; ++i) {
        //set rotation
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, target_cubemap, 0);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        //draw cube

(the images below are from the same corder)


texts: How can I track the frame rate on a mobile device?

texts:
I am trying to track the frame rate when performaing certain actions on my mobile device.

Scenario: I open my game via the device browser and run through specific actions.
Preferably would like the frame rate stored somewhere, like a text file. Would settle for visual display if that is not possible.


texts: Animate from end frame of one animation to end frame of another Unity3d/C#

texts:
So I have two legacy FBX animations; Animation A and Animation B.

What I'm looking to do is to be able to fade from A to B regardless of the current frame A is on.

Using animation.CrossFade() will play A in reverse until it reaches frame 0, then play B forward.

What I'm looking to do is blend from the current frame of A to the end frame of B. Probably via some sort of lerp between the facial position in A and the facial position in the last frame of B.

Does anyone know how I might be able to accomplish this? Either via a built in function or potentially lerping of some sort?

EDIT:
Does anyone perhaps know of a way to read bone positions of an animation at a certain frame? Perhaps if I could read that I could fake animations by doing Vector3 lerps.


texts: Fix Unity Line Renderer for pointer drawing a jaggy line

texts:
I think I'm using the standard Oculus setup from the SDK using the OVRCameraRig. I've also got a LaserPointer.

But inside VR on my Rift the line looks like this.

Any idea what I'm doing wrong? It used to be straight. Now it's not. I don't know what I changed.


texts: Find random point on a circle with a radius of x and the players position as center (unity)

texts:
First of all please note that the game is in 3d and Not 2d

The image below is seen from above. What I am trying to do is find a random point 2 - 3 meters around the player.

However I am not quite sure how to achieve it:

I have tried the following:

Vector3 randomPointOnCircle = Random.insideUnitSphere;
randomPointOnCircle.Normalize();
randomPointOnCircle *= radius;
return randomPointOnCircle;

However I am not sure how to set the player as the center?

Star - Player

Square the general ground

Circle - A visual representation of where the points should be around the player


texts: Farseer Circle Body Problems, Please help!

texts:
I have created a circle body class, but in game my player body just passes through it. the circle will not move, only rotate.

however when i create the circle body just straight up, raw in the game1 load content method, without using a personalised class, it works. so im thinking i have done something wrong but i cant for the life of me spot it.

here are the two different implementations, the first is the class and its instance in the game1 class, THAT doesn't want to move the circle around or collide properly, the second is the classless implementation directly in the load content method of the game1 class.

    class CircleBody
{
    Texture2D Texture;
    Vector2 Origin;
    Vector2 Position;
    public Body Circle;

    public CircleBody(Texture2D texture, Vector2 position, World world)
    {
        this.Texture = texture;
        this.Origin = new Vector2(this.Texture.Width / 2f, this.Texture.Height / 2f);
        this.Position = new Vector2(ConvertUnits.ToSimUnits(position.X), ConvertUnits.ToSimUnits(position.Y));
        Circle = BodyFactory.CreateCircle(world, ConvertUnits.ToSimUnits(56 / 2), 1f, this.Position);
        Circle.BodyType = BodyType.Dynamic;
        Circle.Restitution = 0.3f;
        Circle.Friction = 0.5f;
    }

    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(this.Texture, ConvertUnits.ToDisplayUnits(this.Position), null, Color.White, this.Circle.Rotation,
            this.Origin, 1f, SpriteEffects.None, 0f);
    }

here is the above class instanced and implemented in the game1 class:

Variables:

        CircleBody CircleBody;
        Texture2D CircleTexture;

Load Content Method:

    CircleTexture = Content.Load<Texture2D>("Player");
    CircleBody = new CircleBody(CircleTexture, new Vector2(400, 300), world);

Drawing:

    CircleBody.Draw(spriteBatch);

it just doesn't work :(,

HOWEVER it works perfectly when I create it in a different way, as in not through my own class, but raw within the game1 class. here is the code.

Variables:

     Texture2D playerTex;
     Vector2 playerOrigin;
     Body player;

LoadContent Method

    playerTex = Content.Load<Texture2D>("Player"); //
    playerOrigin = new Vector2(playerTex.Width / 2f, playerTex.Height / 2f);
    /* Circle */
     Convert screen center from pixels to meters
    Vector2 playerPosition = ConvertUnits.ToSimUnits(screenCenter);
     Create the player fixture
    player = BodyFactory.CreateCircle(world, ConvertUnits.ToSimUnits(56 / 2), 1f, playerPosition);
    player.BodyType = BodyType.Dynamic;
    player.Restitution = 0.3f;
    player.Friction = 0.5f;

Drawing:

   spriteBatch.Draw(playerTex, ConvertUnits.ToDisplayUnits(player.Position), null, Color.White, player.Rotation,
                playerOrigin, 1f, SpriteEffects.None, 0f);

The first method through the class is obviously the cleaner and perfect way i want to implement the creation of a circle based body sprite combination, but i dont understand why the sprite is not moving, or collidable or seemingly alive in the simulation.

and i really dont see why it works raw in game1 class.

i really hope you can help!!! im sooooo stuck


texts:
Just wondering that how many IK (Inverse Kinematic) bones should you apply to a game character before it starts to go resource hog. Basically should you try to get rid of IK bones and just try to animate without them but using IK bones makes things easier for the animator but might cause unnecessary use of resources and possibly cause bottleneck when calculating bone and mesh translations.

I'm using Blender and couple of animation tutorials are suggesting to use IK controllers and they indeed help a lot but when importing the character into a game they might be plain pointless since they are used only to help the animator.


texts:
I am using Unity. When I try the game out in the IDE everything looks pretty good:

But when I am trying to play the same game on a device the quality becomes a great deal worse and you can see it for yourself:

I am using Xiame Redmi 4X and I do not think that it is because of device.

So, how can I fix it? How can I preserve the quality?

I would like to try out this solution, but there is no Android settings in my Inspector for quality:

I would like to preserve at least colors.

And here are setting for my player sprites:


texts: change sprite color from properties of parent object in inspector

texts:
I have a compound GameObject that is made up of 5 sprites name dot1 till 5.
I'd like to have a little script on the parent object that would allow me to change the colours of the child objects from the unity inspector. I want the colours to change directly in my scene without having to press play. This already happens when I would set the colours directly from the child objects. But I'd like to have the properties visible in my main object and set the colours from there.

So far I'm unable to make the changes visible in scene mode.

    [ExecuteInEditMode]

public class Chain : MonoBehaviour {

    public GameObject dot1;
    public GameObject dot2;
    public GameObject dot3;
    public GameObject dot4;
    public GameObject dot5;

    public Color Color1;
    public Color Color2;
    public Color Color3;
    public Color Color4;
    public Color Color5;

    void Start () {
    dot1.renderer.sharedMaterial.color = Color1;
    dot2.renderer.sharedMaterial.color = Color2;
    dot3.renderer.sharedMaterial.color = Color3;
    dot4.renderer.sharedMaterial.color = Color4;
    dot5.renderer.sharedMaterial.color = Color5;
    }

    void Update () {

    }
}


texts: How can I reorder the order in which the vertices are in an .obj file?

texts:
Blender saves the files with the structure of

All the vertices
All the normals
All the UV

The game to which I want to import the model, only accepts the following order in structure

1 vertex
1 normal
1 UV
1 vertex
1 normal
1 UV

and so on all the time ...

I need any 3d model that you download from the internet or blender with the first structure, be saved in the second structure automatically.

How can I achieve that?

Image examples:


texts: Preventing the mouse from breaking keyboard navigation in UI?

texts:
I am trying to achieve the following, a behavior like Windows Explorer where mouse and keyboard play nice together.

Here's a GIF along explanations:

first I click one of the folders using the mouse
second I click the background area, folder is not focused but still selected
third I move to the next folder below using the keyboard

To sum it up, mouse and keyboard play well together.

Now in Unity it's an entirely different story, here is a fairly simple menu created using the actions in Hierarchy context menu, nothing special:

Here's what happens:

I click one of the buttons using the mouse
I move down to the next button using the keyboard
I click in the blank area, button loses focus
I try to move down to the next button using the keyboard, nothing happens

I have tried a couple of things like disabling Raycast target on images, disabling background panels or making them opaque but without success.

How can one make Unity UI behave like Windows Explorer's one ?

(where clicking in the blank area with the mouse does not break keyboard navigation)


texts:
I am currently developing a prototype game for mobile devices in which the user will see several objects on the screen and will have to touch them one by one in the correct order to win. I guess it that you can say that it is similiar to a Whack a Mole game, but instead of having moles popping up on the screen, I will have several objects moving around.

I am having some difficulties in implementing a collision detection algorithm for this game, thefore I would like your recommendation on what is the best method to use.

For example suppose an object is moving in a given direction, then I could use the SAT to check if it collides with other objects. If it does collides, then it will stop and move in another direction which is randomly chosen.

Another option would be to divide my screen into square or hexagonal tiles. This way I could just check if the tiles are free or occupied before moving the objects.

My game be 2D and will use a top-down ortographic projection and I am developing it using Cocos2d-X and Marmalade SDK. I am not using any physics engine, because my game does not require them (the objects just have to move around, they don't bounce or need any sort of physics behavior).


texts:
In my game, there is a cat that jumps on pillars. When it lands on a pillar, force is applied and it jumps. There are three animation states which are just single image. The states are : idle,up and down.

When cat lands on the pillar, Collision is triggered where i set animation state to idle. Then, force is added and animation state is changed to up. But problem is, this collision and add force happens so fast, the cat switches between down and up without showing idle.

To overcome this, i added an empty child object to pillar. Then added Edge collider set as trigger. This child was placed slightly above the pillar. So when cat hit this, animation state would switch to idle. Then the cat would land on pillar and jump.

This worked except, the trigger is two way. When cat jumps from pillar, it collides with this trigger and state is changed from up to idle. I tried to add platform effector with one way, but the effector cannot be used on a trigger.

So, is there a way i can add a collider to the empty child which will let it go through aftyer setting state to idle?


texts: Cocos2D v3 and Physics simulation on server

texts:
I'm trying to develop a real time multiplayer game using Cococs2d v3. The game is basically a side scrolling racing game. I wanted to develop the client using Cococs2d for iPhone, and the server side using Java.
I've read about real time networking and the difficulties I can encounter, but also how can I overcome it. The most helpful articles I read was Valve's, Glenn Fiedler's game networking article and Gabriel Gambetta's article on fast-paced multiplayer games.
I can attach links to those articles if anyone is interested :)

I have come to the conclusion that the physics should be implemented both on the client side and the server side. Using cocos2d v3 this could be done without any problems on the client side, but how can I use the same physics simulation in my server written in Java?
For example how could the server know if there's a hill the client player is climbing, or if there's an obstacle it need to collide with? The physics engine the client use is written in Objective C..

Am I missing something over here?
If my question is not clear enough, please tell me and I will explain it in more details.

Thanks in advance :)


texts:
I would like to reduce the size of the spritesheet I am loading by only loading the specific sprites I need.  Is there a way to crop and splice images at runtime using javascript?  Creating separate spritesheets for each level is not ideal, as that would mean lots of repeated sprites.

edit for clarification: Say I want to replace the 5 sprites in the top right corner of my spritesheet based on user input.  Is there a way to remove the sprites that are there and replace them with some from a different file?


texts: My orbit code produces the wrong results

texts:
I have a GameObject called "Sun" in the sky. A game object called "GameManager" keeps track of time in the game, it is responsible for updating the hours and days.

For my sun I do something like this to get a percentage to use for the position of the sun on the orbit circle:

 float percentage = (((float)theGameManager.GetHourOfDay() / (float)GameManager.numberOfHoursInADay) * 360.0f);

I have a piece of code that can return the point in a circle if given a radius, an angle and an origin point.

public static Vector3 GetPointInCircle(float radius, float angleInDegrees, Vector3 origin)
{
    Vector3 resultingPoint = new Vector3(0.0f, 0.0f);
    resultingPoint.x = origin.x + radius * Mathf.Cos(angleInDegrees);
    resultingPoint.y = origin.y + radius * Mathf.Sin(angleInDegrees);

    return resultingPoint;
}

I use this function to determine the suns position each frame, as the angle i am passing is just the percentage of the circle, i expect the percentage variable to give increasingly bigger angles that make up 360 degrees. It does.

However when I set the suns new position using:

Vector3 newPos = new Vector3(MathsHelper.GetPointInCircle(sunOrbitRadius, percentage, new Vector3(50.0f, 0.0f, 50.0f)).x,
MathsHelper.GetPointInCircle(sunOrbitRadius, percentage, new Vector3(0.0f, 0.0f, 0.0f)).y, transform.position.z);

transform.position = newPos;

and the resulting behavior is the sun jumping to totally random positions around the circle, often picking ones that are near the start and end of the circle (by hour 4 the y value is already negative, which shouldn't be the case).

I notice if I swap out the percentage variable for Time.time it works perfectly, however this does not give me control over the sun in accordance to GameManagers day tracking and I feel like I am missing something obvious as to me it looks as though the math should work.

Additionally, I am using C# in Unity.


texts:
How do we make a infinite platform generator using prefabs. So ,for example, you have 3 prefabs and it generates a infinite platform by randomly generating the 3 prefabs.

This might come as a shock, but I did search it up and found nothing good or as explanatory.


texts: Best practice for give properties to game objects

texts:
I'm not a noob in Unity although not the most experienced one, but during one of my project a noob question came to my mind! Strange but this never was an issue for me during my old projects... I became confused where should I initialize the basic properties of my agents.
Example: I have some workers (agents) in a strategy game and they can extract resources. For this I can create a script which execute the process, also I need a variable which define the maximum amount of collected resource the agent can carry. Normally I would create this property in the "Extracting" script which is fine, but should I really create for (almost) every properties of an agent in different scripts?
There's some properties which are very general like "HP" for example... the HP can be used in many scripts and has no proper script to define/initialize it, but there's ton of other example...
My idea to organize this thing to create a 'Property' script where I would write all of the properties which need for the given agent type. But in this case I have to connect the script to other ones which would use any property of this agent (by 'GetComponent<>')
Under the hood a GameObject is a class right? There's any way to add some variable (for properties) to the specified GameObject and access these variables from any scripts of which is attached to that GameObject?
What is the proper way to do this?


texts: Vehicle: Boat accelerating and turning in Unity

texts:
I'm trying to make a player-controllable boat in Unity and I'm running into problems with my code.

1) I want to make the boat to accelerate and decelerate steadily instead of simply moving the speed I'm telling it to right away.

2) I want to make the player unable to steer the boat unless it is moving.

3) If possible, I want to simulate the vertical floating of a boat during its movement (it going up and down)

My current code (C#) is this:

using UnityEngine;
using System.Collections;

public class VehicleScript : MonoBehaviour {
public float speed=10;
public float rotationspeed=50;

// Use this for initialization
// Update is called once per frame
void Update () {

    // Forward movement
    if(Input.GetKey(KeyCode.I))
    speed =
    transform.Translate (Vector3.left*speed*Time.deltaTime);

    // Backward movement
    if(Input.GetKey(KeyCode.K))
        transform.Translate (Vector3.right*speed*Time.deltaTime);

    // Left movement
    if(Input.GetKey(KeyCode.J))
        transform.Rotate (Vector3.down*rotationspeed*Time.deltaTime);

    // Right movement
    if(Input.GetKey(KeyCode.L))
        transform.Rotate (Vector3.up*rotationspeed*Time.deltaTime);

}
}

In the current state of my code, when I press the specified keys, the boat simply moves 10 units/sec instantly, and also stops instantly. I'm not really sure how to make the things stated above, so any help would be appreciated. Just to clarify, I don't necessarily need the full code to implement those features, I just want to know what functions to use in order to achieve the desired effects.

Thank you very much.


texts:
So I'm basically trying to get my character to "use" a set of stairs by teleporting from one stairway door to another. Each stairway door will be paired with one other stairway door.

Here's the code, I feel like it should be working...my Debug.Logs are even outputting the correct information. Also FYI, I have the Transform doorPairedWith as public so that I can just drag and drop the stairway door that each one is supposed to be paired with.

 using UnityEngine;

 public class Stairs : MonoBehaviour {

 Player player;

 public Transform doorPairedWith;

 Vector3 doorPairedWithPosition;
 Vector3 playerPosition;

 BoxCollider2D playerCollider;
 BoxCollider2D stairsTriggerCollider;

 bool playerIsNearStairs = false;

 void Start()
 {
     player = Player.instance;

     playerPosition = player.transform.position;
     doorPairedWithPosition = doorPairedWith.position;

     playerCollider = player.GetComponent<BoxCollider2D>();
     stairsTriggerCollider = GetComponent<BoxCollider2D>();
 }

 void Update()
 {
     UseStairs();
 }

 void UseStairs()
 {
     if (playerIsNearStairs == true)
     {
         if (Input.GetKeyDown(KeyCode.E))
         {
             Debug.Log("Attempting to use stairway door named: " + doorPairedWith);
             playerPosition = doorPairedWithPosition;
         }
     }
 }

 void OnTriggerEnter2D(Collider2D collision)
 {
     if (collision.gameObject.tag == "Player")
     {
         playerIsNearStairs = true;
         Debug.Log("Player is near stairs: " + playerIsNearStairs);
     }
 }

 void OnTriggerExit2D(Collider2D collision)
 {
     if (collision.gameObject.tag == "Player")
     {
         playerIsNearStairs = false;
         Debug.Log("Player is near stairs: " + playerIsNearStairs);
     }
 }
 }


texts: How can I handling rendering of entities with an entity/component system?

texts:
I'm implementing an entity system in a game engine which is based on the Artemis framework. My question is, how can I wrap an existing rendering engine (like Ogre or Irrlicht) under this framework?

Should I create a component to wrap each mesh, texture, animation class
and wrap the rendering loop as a system in my framework? What should I do?


texts: Xna GS 4 Animation Sample bone transforms not copying correctly

texts:
I have a person model that is animated and a suitcase model that is not. The person can pick up the suitcase and it should move to the location of the hand bone of the person model. Unfortunately the suitcase doesn't follow the animation correctly. it moves with the hand's animation but its position is under the ground and way too far to the right. I haven't scaled any of the models myself. Thank you.
The source code (forgive the rough prototype code):

        Matrix[] tran = new Matrix[man.model.Bones.Count];// The absolute transforms from the animation player
        man.model.CopyAbsoluteBoneTransformsTo(tran);

        Vector3 suitcasePos, suitcaseScale, tempSuitcasePos = new Vector3();// Place holders for the Matrix Decompose
        Quaternion suitcaseRot = new Quaternion();

        // The transformation of the right hand bone is decomposed
        tran[man.model.Bones["HPF_RightHand"].Index].Decompose(out suitcaseScale, out suitcaseRot, out tempSuitcasePos);

        suitcasePos = new Vector3();
        suitcasePos.X = tempSuitcasePos.Z;// The axes are inverted for some reason
        suitcasePos.Y = -tempSuitcasePos.Y;
        suitcasePos.Z = -tempSuitcasePos.X;

        suitcase.Position = man.Position + suitcasePos;// The actual Suitcase properties
        suitcase.Rotation = man.Rotation + new Vector3(suitcaseRot.X, suitcaseRot.Y, suitcaseRot.Z);

I am also copying the bone transforms from the animation player in the Person class like so:

        // The transformations from the AnimationPlayer
        Matrix[] skinTrans = new Matrix[model.Bones.Count];
        skinTrans = player.GetBoneTransforms();

        // copy each transformation to its corresponding bone
        for (int i = 0; i < skinTrans.Length; i++)
        {
            model.Bones[i].Transform = skinTrans[i];
        }

EDIT:

Unfortunately I can't add screenshots, as this specific project has been lost to time. I still want to know why it didn't work, though.


texts:
I'm busy following this YouTube tutorial for a 2D game in Unity by inScope: https://www.youtube.com/watch?v=-gC1u7qHMY4&list=PLX-uZVK_0K_6VXcSajfFbXDXndb6AdBLO&index=6

I decided to not finish the attacking episode and skipped to the next episode.
But things were not working out so I deleted all my new work so everything will be back to how it was before.

But low-and-behold my attack stopped working. What should happen is whenever I press Left Shift my character should play his attack animation.

I've rechecked the videos again and again but I can't find whats wrong with my script! The script is in C#, and there are no errors in the script. I don't know whats wrong PLEASE HELP!

public class Player : MonoBehaviour
{
  private Rigidbody2D myRigidbody;

  private Animator myAnimator;

  [SerializeField]
  private float movementSpeed;

  private bool attack;

  private bool facingRight;

  // Use this for initialization
  void Start ()
  {
    facingRight = true;
    myRigidbody = GetComponent<Rigidbody2D> ();
    myAnimator = GetComponent<Animator> ();
  }

  void Update()
  {
    HandleInput ();
  }

  // Update is called once per frame
  void FixedUpdate ()
  {
    float horizontal = Input.GetAxis ("Horizontal");

    HandleMovement (horizontal);

    Flip (horizontal);

    HandleAttack ();

    ResetValues ();
  }

  private void HandleMovement(float horizontal)
  {
    myRigidbody.velocity = new Vector2 (horizontal * movementSpeed, myRigidbody.velocity.y);  // vector2 = x-axis - 1, y-axis = 0
    myAnimator.SetFloat ("speed", Mathf.Abs (horizontal));
  }

  private void HandleAttack()
  {
    if (attack)
    {
      myAnimator.SetTrigger ("Attack");
    }
  }

  private void HandleInput()
  {
    if (Input.GetKeyDown (KeyCode.LeftShift))
    {
      attack = true;
    }
  }

  private void Flip(float horizontal)
  {
    if (horizontal > 0 && !facingRight || horizontal < 0 && facingRight)
    {
      facingRight = !facingRight;

      Vector3 theScale = transform.localScale;

      theScale.x *= -1;

      transform.localScale = theScale;
    }
  }

  private void ResetValues()
  {
    attack = false;
  }
}


texts: How to map gamepad inputs for my platformer?

texts:
With keyboard+mouse controls, we seem to have an unspoken control mapping standard, with keys be like WSAD for moving, E for use, mouse button for attacks or interactions, spacebar for jumping, and so on. But I'm unsure what conventions apply to gamepads.
I'm doing the typical platformer game, so my input would be:

movement
sprinting
jumping
attack
interacting
accessing main menu
accessing inventory menu.

How can I map these actions to a gamepad's buttons/sticks in a way that will be intuitive for my players?


texts:
I'm sorry if this isn't the right place for this post, but I don't know where to go.

I'm trying to make a simple game loop but it's already failing

package main;

import javax.swing.JPanel;
import java.awt.*;
import java.awt.image.*;

public class Logic extends JPanel implements Runnable {

/**
 *
 */
private static final long serialVersionUID = 1L;

// Main Game Stuff
private int gWidth = 800;
private int gHeight = 640;
private int scale = 2;

private int fps = 30;

private boolean running;

private Thread thread;
private BufferedImage image;
private Graphics2D g;

public Logic(){
    super();
    setPreferredSize(new Dimension(gWidth, gHeight));
    setFocusable(true);
    requestFocus();
}

public void addNotify(){
    if(thread==null)
    {
        thread=new Thread(this);
        thread.start();
    }
}

public void init()
{
    image = new BufferedImage(
            gWidth, gHeight, BufferedImage.TYPE_INT_RGB
        );
    g = (Graphics2D) image.getGraphics();
    System.out.println("Hello!");
    running = true;
}

private void update() //main logic
{
    //do stuff
}

private void render(Graphics2D g)
{
    g.setColor(Color.BLUE);
    g.fillRect(0, 0, gWidth, gHeight);
}

private void PaintCanvas(){
    Graphics g2 = getGraphics();
    g2.drawImage(image, 0, 0, null);
    g2.dispose();
}

public void run()
{
    init();

    int loops = 0;
    long startTime = System.nanoTime();
    float rate = 1000/fps;
    long lastTime = startTime;
    float waitTime = rate;

    while(running) // game loop
    {
         long currTime = System.nanoTime();
         if(currTime > (lastTime + waitTime))
         {
             waitTime = rate;
             if((currTime - lastTime) > rate)
                 waitTime = currTime - lastTime;

             //-- Paint Canvas --//
             PaintCanvas();

             //-- LOGIC -- //

                update();

             ////////////////
             //-- RENDER --//
             if(loops % 2 == 0)// draw every second frame
             {
                 render(g);
             }
             ////////////////
             loops++;

             lastTime = currTime;
         }

    }
}

}

I keep getting this error:

Exception in thread "Thread-2" java.lang.NullPointerException
at main.Logic.PaintCanvas(Logic.java:67)
at main.Logic.run(Logic.java:93)
at java.lang.Thread.run(Unknown Source)

Why is the image null? I can't for the life of me figure it out. I already declared it in the init() function.


texts: What are some good resources on creating and reading 2D game levels in Java?

texts: Could some resources be listed in relation to the creation and management of simplistic, efficient 2D game levels, that are available for use with Java?


texts:
I recently asked a question about putting a camera at the head of a 3D human model here and it worked out rather well and whatnot, but there is still a problem that bothers me:

How would I contort/warp the mesh of the human model with code? I'd only really have to turn the head a bit using the mouse, and the rest can be animated (i.e. walking, moving arms, speaking, etc).

I was initially thinking about an animation for moving the head in a certain direction, and you would move the mouse and the animation would go along with the mouse movement until it reached the maximum angle (about 85 degrees) on either side of the model.

Is there a better way of doing this, and if so, how can I do it?


texts: Camera Touch Zoom and Pan with world - 2D

texts:
I am doing my first unity2d game and im in need of a little optimization for my camera.

I have a camera which could pan and zoom with the speed i have defined. The problem with that is the speed i defined for panning will be too fast when zoomed in and soo slow when zoomed out. Maybe it could be achieved by having varying speed with zoom level. I dont want that.

Instead, i would like to have the camera used in Clash of Clans (i have seen it only in that).

The camera pans/zooms async with the world.
That is, at any zoom level, if we placed our finger on an object X and started moving, the object X will be right below our fingers all the way. That means the world moves relatively.

Its the same with the zooming.
If we placed two fingers on object X & on object Y and started 'zooming' in or out,
Those two objects will be there right below the fingers all the way.

That is what i would like.

For panning, i tried this and failed :
(Unity C#)

Touch t = Input.getTouch(0); //when touchcount = 1 only

Vector2 prev_touch_position = t.position - t.deltaPosition;

Vector3 resultant_unitvector = (prev_touch_position - t.position) / (prev_touch_position - t.position).magnitude;

float resultant_magnitude = Info.half_height / camera.orthographicSize * (prev_touch_position - t.position).magnitude;
//Info.half_height is calculated during change in orthographic size and is a static variable.

camera.transform.position += resultant_unitvector * resultant_magnitude;

The above code doesnt work as expected on debugging.

It would be a great help for the community if someone could solve this cuz that is some pretty good camera :)
(Include damping after touch release if you could ? :) )
Im just a student by the way :)

Thanks in advance :)


texts: DX11: Alpha blending not working with textured quads

texts:
A bit novice on directx11.
I am rendering some textured quads out of PNG files (with alpha transparency) and get some inconsistency with my alpha blending. I have a background changing color constantly and you can see transparency is there , since in the transparent bits of the texture you can see the background colour below.

However , when it comes to having one texture on top of another it seems to skip the one below and use the background colour instead!

I can provide some code but I don't exactly know where to problem might sprawl from yet.

Any ideas?
Thanks!


texts: Wait for AudioClip finish before destroy Object

texts:
If I Play the gun sound on my "bullet" object, how can I prevent the end of Audio sound if the bullet hit something so it destroy.
To clarify:

Bullet prefab -> Audio Source -> Audio Clip = MachineGun.mp3
PlayOnAwake = true

When I instantiate bullet, MachineGun AudioClip is played.
But the bullet is fast and hit something before the clip is end.
This Kill the machine audio effect making it irrealistic.

How can I tell Unity "Play the sound to the end, despite the object is destroyed".

I've tried

Destroy(gameObject, AudioClip.length)

But it seems not works


texts: Placing sprites properly to form an object

texts:
I'm working with XNA in Visual Studio, and I'm trying to draw this sprite:
https://i.imgur.com/Dy5nSuG.png

Only using this sprite:
https://i.imgur.com/6T8TeTQ.png

My current attempt relies on a matrix boolean, which then gets drawn in a foreach loop:

//Variable
 bool[,] centerPiece = new bool[,] { { false, true, false }, { true, true, true }, { false, true, false } };

//Loop
 foreach (bool b in centerPiece)
            {
                if (b == true)
                {
                    spriteBatch.Draw(squareTex, screenView(), null, Color.White, 0f, IMGCenter(), 1f, SpriteEffects.None, 0f);
                }
            }

While this draws all 5 squares, it doesn't place them as desired (because of they're all being drawn in the screenView() method placement(The center of the screen):

public Vector2 screenView()
        {
            Viewport viewport = GraphicsDevice.Viewport;
            Vector2 screenCenter = new Vector2(viewport.Width / 2f, viewport.Height / 2f);
            return screenCenter;
        }

How do I modify my loop to place the squares correctly, and/or do I need to change my implementation completely to achieve my desired goal?

Note: I need to both be able to access the object as a whole, and also access each individual square, in each individual object.


texts:
I've been embracing Test-Driven Development (TDD) recently and it's had wonderful impacts on my development output and the resiliency of my codebase. I would like to extend this approach to some of the rendering work that I do in OpenGL, but I've been unable to find any good approaches to this.

I'll start with a concrete example so we know what kinds of things I want to test; lets say I want to create a unit cube that rotates about some axis, and that I want to ensure that, for some number of frames, each frame is rendered correctly.

How can I create an automated test case for this? Preferably, I'd even be able to write a test case before writing any code to render the cube (per usual TDD practices.) Among many other things, I'd want to make sure that the cube's size, location, and orientation are correct in each rendered frame. I may even want to make sure that the lighting equations in my shaders are correct in each frame.

The only remotely useful approach to this that I've come across involves comparing rendered output to a reference output, which generally precludes TDD practice, and is very cumbersome.

I could go on about other desired requirements, but I'm afraid the ones I've listed already are out of reach.


texts:
I'm looking to create a simple, "randomly" generated map for a small game.

The game consists of a top-down view of a world, with land-mass and ocean areas.  Think of a simple outline map of the world for example.

The closest thing I can think of that I've seen before was the level-generator for the old SimCity games, or the Civ series, where you can set a preference for single continent versus many islands, etc.

What sort of algorithm would be suitable?  The map will need to be moderately zoomable, so I can have a "whole world" view, and also a more zoomed-in local view, but I think I'll sort that out later.

Initially I don't need any concept of heights, just two areas - land and sea, although I might extend it later.


texts:
I'm wanting to have an object that does random animation in Unity, within the object. Basically, I want a floor that has lights that go through it. I'm trying to figure out exactly what is the best way to make that happen. I know there is such a thing as "Procedural Textures" in Unity, but I'm struggling to understand exactly how to make these textures. There are two basic ideas which I have:

Attach a script to the object that I want to place the texture on. That class should manage the texture in all senses of the word. This seems clunky, because it won't show up in the scene mode. This texture would then be assigned in the Start() function for said script.
There exists tools that make these procedural textures, such as Substance. Currently I don't have much of a budget for game development, so I'd like to stay away from anything with a cost (This is more of a hobby for me right now).

Is this the correct way to think about things, or am I missing something fundamental? There seems to be procedural materials that I can't quite understand how they work. Am I missing something else? Thanks!

EDIT:

What I'm trying to do is to have moving lights go across a floor, either as a part of the floor, or even as contained within the floor. I'm considering using some kind of particle system for it, but I've heard about these procedural textures and I thought it was worth a shot to see if they do something similar. I'm also considering using a randomly generated star skybox using a similar method. Specifically, I'm picturing moving lights going across the floor in this image.


texts: How do I manage textures in memory in OpenGL?

texts:
I'm writing a game engine which is going very fine. However, I'm now posed with handling textures.

My Engine is in 2D, for simplicity reasons mostly to get a good idea of how to work with OpenGL. I do this in C++, and I have a hierarchical set-up when it comes to classes. There's a base class and some other classes derive from that.

So now I'm onto the part where I want to load up some textures and apply them to polygons. The way my engine works in drawing things is like this:

Load up a tile map file and parse it. The tile map contains all the information like events, lights, passability. All very interesting, not. Except the part where it loads a tileset, as defined by the map.
The parser realises the map uses a tileset, which is stored in resources/tilesets/dungeon_interior_cave1.xml, which contains all the information on what textures are used.
It loads the textures as said by the tileset-XML-file, it gives them an ID and then the SceneManager-class knows how to lay out the tiles and what texture to slap onto each of them. Once this is done, it tosses the instance of the SceneManager to the OpenGL renderer.

This might not be the best explanation of how my engine works, but simply put:

SceneManager loads the file resources/maps/dungeon3Interor.msf (msf being a custom map format (MSF stands for M age S cene F ile ). The MSF file refers to a tilset.
SceneManager loads the tile set at resources/tilesets/dungeon_interior_cave1.mts.
SceneManager loads up all the textures from resources/textures/< path_to_textures >
SceneManager tosses itself to the OpenGL render, and OpenGL renders the whole thing.

I think that's the best I can do at explaining. Know that the SceneManager itself contains no OpenGL code, just paths and information that OpenGL needs to know to render the scene.

What I'm interested in, what is the best practice to handle this, and how to handle OpenGL texture storage. I understand OpenGL keeps the textures in it's texture memory, and that I have to use glGenTextures to allocate a texture and that I then swap betwe--.. I actually have no clue.

What's a good way to keep track of all the textures you loaded into the memory and switch between them in C++, preferably using a class or a set of classes to accomplish this.


texts:
I have a simple 2D java game engine running using LWJGL. I have my own vertex and fragment shaders, and I'm able to render quads with textures.

I want to be able to mask one quad using the texture from another quad.
Example:
I have two quads with two different textures mapped to them.
Quad A has a red circle texture.
Quad B has a blue square texture.
I want to use Quad A's red circle texture as a mask such that Quad B will only be visible if it is within Quad A's red circle texture.

Here's an image showing what I want to do:

The problem is that I am always seeing the 'full overlap' no matter the position of the quads. I can never get that partial masking that I'm looking for.

My shader logic is close to this:

#version 150 core
uniform sampler2D texture;
uniform sampler2D maskTexture;

in vec2 pass_TextureCoord;
in vec2 pass_MaskTextureCoord;

out vec4 out_Color;

void main(void) {
     //***other logic here to determine out_Color***

     if(pass_MaskTextureCoord.x != -1 && pass_MaskTextureCoord.y != -1) { //if we have valid mask texture coordinates, we are masking
          vec4 maskColor = texture(maskTexture, pass_MaskTextureCoord); //get the rgba values of the mask texture
          if(maskColor.a == 0) { //if mask texture has no alpha, discard
               discard;
          }
     }
}

Do I need to pass location data of the masking quad into the shader? If so, how do I do that?

EDIT: ilmale's method using the stencil buffer worked for me! All I needed to add was a uniform boolean value to tell the shader if I was drawing a mask or not.

Here's the relevant shader code:

if(isMask) { //if this is a mask, discard where texture alpha is 0
    if(texColor.a == 0) {
        discard;
    } else {
        out_Color = vec4(0, 0, 0, 0); //make the rest transparent, so we don't see the mask texture
    }
}


texts: How can I override the close button near minimize/maximize in such a way that the application doesn't automatically close. I want it to show an exit screen or something like this, so I would like to be able to delay the close and display something on the screen when I press the red close button. At first I thought that I should override the OnExiting() method, but I couldn't get it working. This is my first attempt at creating a fully functional game, so I have no previous experience in game development nor with XNA.


texts: How can I instantiate enemies in a 2D game at a set Viewport Position before my camera enters the room? (Or alternative solution!)

texts:
I'm currently working on a 2D game where I'm trying to pre-populate my level with encounters, I want the enemies already in the room when the player enters. Right now the encounter is triggered upon entering the room when the camera bumps into the collider and the enemies are instantiated at the Viewport position, however because it does it while the camera is moving into the room the position is incorrect. Using hard values isn't an option because the maps could of course change and also I may want them randomly generated at some point. So I guess ultimately the problem is the camera not being in the right position when they instantiate and not wanting enemies to "pop" in once it is.
Is there a way I can I instantiate an enemy at the same point on the screen regardless of resolution in each specific room at the start of the level?
Encounters will have up to 3 enemies and they will always hold the same formation (with spots randomized to add diversity)
Here is my instantiating code:
[SerializeField] public List<GameObject> levelEnemies = new List<GameObject>();
GameObject levelEnemy;
Vector3 enemyPosition;
Vector3 viewportPosition = new Vector3(0.8f, 0.5f, 10f); // Place on the screen I decided I want single enemies to appear
Camera cam;

void Start()
{

    Debug.Log("Enemy Triggered");
    cam = Camera.main;
    enemyPosition = cam.ViewportToWorldPoint(viewportPosition);
    levelEnemy = Instantiate(levelEnemies[0], enemyPosition, Quaternion.identity); //instantiate test enemy at the converted position

    //navigation.DisableNavigation();
}

Here is what my camera collider looks like (Room 1) and my enemy encounter collider looks like (Room 3)

Here's what should be happening when the enemy is instantiated (triggered manually through the editor once camera has been moved fully)

Here is what happens when the camera collider bumps into the encounter collider

Any help in the right direction would be much appreciated or a workaround!
Here is what my camera collider looks like (Room 1) and my enemy encounter collider looks like (Room 3)


texts:
I have recently entered in the OpenGL world. I am very pleased with the performance that I got with opengl compared to those obtained with a SurfaceView and its canvas. At the same time because of the limitation of the images to be in power of two I noticed that the quality of the sprite of my game is a little decreased. I read that we can use mipmap in Android but I have not found a real tutotial.

Are they compatible with Android 2.2+ ?

Which program creates mipmaps?

How do you actually use in code?


texts: How to remove destroyed clones out of the Hierarchy in Unity2D

texts:
I made a 2D edge collider which on contact destroys the other gameobject. When I launch the game all the other gameobjects in fact get destroyed but the clones are still listed in the Hierarchy. How can I get rid of this? Thanks in advance.

The corresponding code is:

using UnityEngine;
using System.Collections;

public class DestroyByBoundary : MonoBehaviour {

void OnTriggerEnter2D (Collider2D other)
{
    Destroy(other.gameObject);
}

}


texts: Repeated nested game objects (UnityEngine.GameObject.gameObject)

texts:
I created a UnityEngine.GameObject and inspect its properties while in debug mode.

GameObject obj = new GameObject();

When I inspect the object, it has a property hierarchy similar to:

active:true
activeInHierarchy:true
..
gameObject:New Game Object (UnityEngine.GameObject)
    active:true
    activeInHierarchy:true
    ..
    gameObject:New Game Object (UnityEngine.GameObject)
      active:true
      activeInHierarchy:true
      ..
      gameObject:New Game Object (UnityEngine.GameObject)

If I execute, something like, in a debugger console:

new UnityEngine.GameObject().gameObject.gameObject.gameObject;

it would still return the same New Game Object.

Is the problem in my debugger or Unity? I'm using Unity 2018.4.11f1.


texts: Why is my RigidBody2D not moving in Unity?

texts:
My problem is when I am pressing A or D, the player does not move. It is very stupid I am sure as you are, but I can not find what I am doing wrong. I could have achieved the effect I want with the help of transform.translate(), but I would like immensely to get what is misunderstood by me in the case.

Here is my code:

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

public class MovementController : MonoBehaviour
{
    public float runningSpeed;
    public Rigidbody2D playerBody;

    void Update ()
    {
        if(Input.GetKey("d"))
        {
            print("Right");
            moveRight();
        }
        else if (Input.GetKey("a"))
        {
            print("Left");
            moveLeft();
        }
    }

    private void moveLeft()
    {
        playerBody.AddForce(Vector2.left * (runningSpeed * Time.deltaTime), ForceMode2D.Force);
    }

    private void moveRight()
    {
        playerBody.AddForce(Vector2.right * (runningSpeed*Time.deltaTime), ForceMode2D.Force);
    }
}

Here is a screenshot of my editor:


texts: Wireframe shader sometimes won't render parts depending on camera rotation

texts:
I'm trying to make a stylized wireframe shader for a game using this method, but it seems to be conflicting with my character controller.
Here's some images to better show what's going on: https://imgur.com/a/f48F3lN
Basically, as I look around, some lines will disappear and reappear. It might have something to do with culling but the face is still visible, so theoretically shouldn't all the vertices still be rendered?
It would also help if you knew of a better method for doing this as well. If it helps, I'm using OpenGL with c++, and my shader code is functionally the same as what I linked to.


texts: Why does writing to a D3DFMT_R32F render target clamp to 1?

texts:
I'm currently implementing a picking system. I render some objects in a frame buffer, which has a render target, which has the D3DFMT_R32F format.

For each mesh, I set an integer constant evaluator, which is its material index.

My shader is simple: I output the position of each vertex, and for each pixel, I cast the material index in float, and assign this value to the Red channel:

int
    ObjectIndex;
float4x4
    WvpXf : WorldViewProjection< string UIWidget = "None"; >;

struct VS_INPUT
{
    float3 Position : POSITION;
};

struct VS_OUTPUT
{
    float4 Position : POSITION;
};

struct PS_OUTPUT
{
    float4 Color : COLOR0;
};

VS_OUTPUT VSMain( const VS_INPUT input )
{
    VS_OUTPUT
        output = (VS_OUTPUT)0;

    output.Position = mul( float4(input.Position, 1), WvpXf );

    return output;
}

PS_OUTPUT PSMain( const VS_OUTPUT input, in  float2 vpos : VPOS )
{
    PS_OUTPUT
        output = (PS_OUTPUT)0;

    output.Color.r = float( ObjectIndex );
    output.Color.gba = 0.0f;

    return output;
}

technique Default
{
    pass P0
    {
        VertexShader = compile vs_3_0 VSMain();
        PixelShader = compile ps_3_0 PSMain();
    }
}

The problem I have, is that somehow, the values written in the render target are clamped between 0.0f and 1.0f. I've tried to change the rendertarget format, but I always get clamped values...

I don't know what the root of the problem is.

For information, I have a depth render target attached to the frame buffer.
I disabled the blend in the render state
the stencil is disabled

Any ideas?


texts: Should Starting a Quick Game via Google Game Services be Iterated?

texts:
I have been following this tutorial for Google Play Game Services.  I am a little unclear as to if the room matching algorithm should be looped or not.  Can I just initialize this process once and let it time out?  Or by iterating through it is it somehow rechecking it?  If anyone had the approximate timeout that would be great as well.

The problem stems from the fact that even when both phones are signing into the Game Services (at virtually the same time, my friend and I logged in), the room is not registering multiple people.  One time my friend's phone even entered the game map, showing that he somehow was able to progress from the room initialization process.

Relevant screen update methods which I am starting this matchmaking process:

@Override
public void update(float deltaTime)
{
    game.options.updateTiles();

    if(!isInitiated)
    {
        startQuickGame();
    }
}

private void startQuickGame()
{
    // auto-match criteria to invite one random automatch opponent.
    // You can also specify more opponents (up to 3).
    if(game.mGoogleClient.isConnected() && !isInitiated)
    {
        Bundle am = RoomConfig.createAutoMatchCriteria(1, 3, 0);

        // build the room config:
        RoomConfig.Builder roomConfigBuilder = RoomConfig.builder(Network.getInstance());
        roomConfigBuilder.setMessageReceivedListener(Network.getInstance());
        roomConfigBuilder.setRoomStatusUpdateListener(Network.getInstance());
        roomConfigBuilder.setAutoMatchCriteria(am);
        RoomConfig roomConfig = roomConfigBuilder.build();

        // create room:
        Games.RealTimeMultiplayer.create(game.mGoogleClient, roomConfig);

        // go to game screen
        this.mRoom = Network.getInstance().getRoom();
        if(this.mRoom != null && this.mRoom.getParticipants().size() >= 2)
        {
        game.setScreen(new MultiGameScreen(game, this.mRoom));
        isInitiated = true;
        }
    }
    else
    {
        game.mGoogleClient.connect();
    }
}


texts: Defining a projectiles speed and angle before Instantiating

texts: I have a 360 degrees shooter object and a projectile to shoot. My projectile has a Rigidbody2D with zero gravity scale. I want it to bounce off of colliders when it gets hit, but when I instantiate it from my shooter I have to write the velocity value in update so it keeps going against the colliders when shot. I figured that I should assign it a velocity in start function, but then it only goes in one direction. How do I fix this?


texts: Player animating the wrong direction once he is rotated

texts:
I have used the scripting root motion move the player when using an 'inplace' animation.

All works correctly until the players rotation is off 0,0,0.
This is expected as the movement is along the transform.z axis but how can I account for the rotation in the script and apply it so the movement is correct in game?

The gorillacontroller script is the script we are trying to fix On playerGorilla. animator is on the playergorilla. The gorilla1 is the gameobject holding the mesh and the bones for the character.

I will also add the transforms are moving this was my silly mistake because I had tool handles in global instead of local.

This makes it even more confusing however because all tranform.z (blue axis) are facing the correct way for the animation to work but the animation is only ever playing in the original direction where the rotation is 0,0,0,0.

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Animator))]

public class RootMotionScript : MonoBehaviour {

    void OnAnimatorMove()
    {
          Animator animator = GetComponent<Animator>();

          if (animator)
          {
               Vector3 newPosition = transform.position;
               newPosition.z += animator.GetFloat("Runspeed") * Time.deltaTime;
               transform.position = newPosition;
          }
    }
}


texts: Why am I getting a "multiple definition of *" error when initializing OpenGL extensions?

texts:
I'm creating a game engine using OpenGL, and I'm initializing the extensions manually, i.e. this:

// .h file
PFNGLACTIVETEXTUREPROC glActiveTexture;
/* .cpp file, initialization function */
glActiveTexture = (PFNGLACTIVETEXTUREPROC) wglGetProcAddress("glActiveTexture");

However, when I compile, I get the following error every time I call an OpenGL extension function:

multiple definition of 'gl[some function]'

Why might this be? It reeks of an include loop problem, but I have include guards everywhere.


texts: OpenGL: Filtering/antialising textures in a 2D game

texts:
I'm working on a 2D game using OpenGL 1.5 that uses rather large textures. I'm seeing aliasing effects and am wondering how to tackle those.

I'm finding lots of material about antialiasing in 3D games, but I don't see how most of that applies to 2D games - e.g. antisoptric filtering seems to make no sense, FSAA doesn't sound like the best bet either.

I suppose this means texture filtering is my best option?

Right now I'm using bilinear filtering, I think:

glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

From what I've read, I'd have to use mipmaps to use trilinear filtering, which would drive memory usage up, so I'd rather not.

I know the final sizes of all the textures when they are loaded, so can't I somehow size them correctly at that point? (Using some form of texture filtering).


texts:
I have made several games but they have all been space invaders or mario style.

Following my last question (thank you for all the great answers) I am trying to write out a plot line and a plan for the events that will take place.

The problem I am having is that my story's tend to resemble things that already exist like films or other games I have played.

The events to feel like a mix of various other games I have played.

So apart form become a more creative person does anyone have any advice. Has anyone written a fairly lengthy story for a game and have pointers or does anyone know any good books on the subject.

Any thoughts would be welcome, story of event ideas to.

FYI the game has a final fantasy style battle system and a pokemon catch/raise system.


texts: What's a good alternative to colored tiles to account for color blindness?

texts:
I have a game with tiles. Each tile is a number, and each number is one of six colors. The color is important to the game play, and I want to make the game available to those who are color blind.

What would be a good representation for these colors so people with color blindness can play as well?


texts: How can I improve rendering speeds of a Voxel/Minecraft type game?

texts:
I'm writing my own clone of Minecraft (also written in Java). It works great right now. With a viewing distance of 40 meters I can easily hit 60 FPS on my MacBook Pro 8,1. (Intel i5 + Intel HD Graphics 3000). But if I put the viewing distance on 70 meters, I only reach 15-25 FPS. In the real Minecraft, I can put the viewing disntance on far (= 256m) without a problem. So my question is what should I do to make my game better?

The optimisations I implemented:

Only keep local chunks in memory (depending on the player's viewing distance)
Frustum culling (First on the chunks, then on the blocks)
Only drawing really visible faces of the blocks
Using lists per chunk that contain the visible blocks. Chunks that become visible will add itself to this list. If they become invisible, they are automatically removed from this list. Blocks become (in)visible by building or destroying a neighbour block.
Using lists per chunk that contain the updating blocks. Same mechanism as the visible block lists.
Use nearly no new statements inside the game loop. (My game runs about 20 seconds until the Garbage Collector is invoked)
I'm using OpenGL call lists at the moment. (glNewList(), glEndList(), glCallList()) for each side of a kind of block.

Currently I'm even not using any sort of lighting system. I heard already about VBO's. But I don't know exactly what it is. However, I'll do some research about them. Will they improve performance? Before implementing VBO's, I want to try to use glCallLists() and pass a list of call lists. Instead using thousand times glCallList(). (I want to try this, because I think that the real MineCraft doesn't use VBO's. Correct?)

Are there other tricks to improve performance?

VisualVM profiling showed me this (profiling for only 33 frames, with a viewing distance of 70 meters):

Profiling with 40 meters (246 frames):

Note: I'm synchronising a lot of methods and code blocks, because I'm generating chunks in another thread. I think that acquiring a lock for an object is a performance issue when doing this much in a game loop (of course, I'm talking about the time when there is only the game loop and no new chunks are generated). Is this right?

Edit: After removing some synchronised blocks and some other little improvements. The performance is already much better. Here are my new profiling results with 70 meters:

I think it is pretty clear that selectVisibleBlocks is the issue here.

Thanks in advance!
Martijn

Update: After some extra improvements (like using for loops in stead of for each, buffering variables outside loops, etc...), I now can run viewing distance 60 pretty good.

I think I'm going to implement VBO's as soon as possible.

PS: All source code is available on GitHub:
https://github.com/mcourteaux/CraftMania


texts: Unity VR player not moving when running in device

texts:
I am following Udemy tutorials for learning VR using Unity and making a game named Ninja Slash. Everything seems to be working fine in the Unity Editor Play mode but when I run my app in a real device, my player doesn't move at all.
I can't figure out what is the problem here.
Here is my Player script.

public class Player : MonoBehaviour {

public GameObject sword;
public float speed = 4.5f;
public float walkingAmplitude = 0.25f;
public float walkingFrequency = 2.0f;
public float swordRange = 1.75f;
public float swordCooldown = 0.25f;

public bool isDead = false;
public bool hasCrossedFinishLine = false;

private float cooldownTimer;
private Vector3 swordTargetPosition;

// Use this for initialization
void Start () {
    swordTargetPosition = sword.transform.localPosition;
}

// Update is called once per frame
void Update () {
    if (isDead) {
        return;
    }

    transform.position += Vector3.forward * speed * Time.deltaTime;
    transform.position = new Vector3(
        transform.position.x,
        1.7f + Mathf.Cos(transform.position.z * walkingFrequency) * walkingAmplitude,
        transform.position.z
    );

    cooldownTimer -= Time.deltaTime;

    if (GvrViewer.Instance.Triggered ) {
        RaycastHit hit;

        if (cooldownTimer <= 0f && Physics.Raycast(transform.position, transform.forward, out hit)) {
            cooldownTimer = swordCooldown;

            if (hit.transform.GetComponent<Enemy> () != null && hit.transform.position.z - this.transform.position.z < swordRange) {
                Destroy (hit.transform.gameObject);
                swordTargetPosition = new Vector3 (-swordTargetPosition.x, swordTargetPosition.y, swordTargetPosition.z);
            }
        }
    }

    sword.transform.localPosition = Vector3.Lerp (sword.transform.localPosition, swordTargetPosition, Time.deltaTime * 15f);
}

void OnTriggerEnter (Collider collider) {
    if (collider.GetComponent<Enemy> () != null) {
        isDead = true;
    } else if (collider.tag == "FinishLine") {
        hasCrossedFinishLine = true;
    }
}}

Here is the screenshot for hierarchy view.


texts: How to make a 'Picture-book Cutscene' in Unity 2D with simple 2D images?

texts:
I'm trying to implement a simple cutscene system in my Unity game, preferably one that allows cutscenes to play at the start and end of each of the levels.

What I was imagining was pretty similar to A Hat in Time's 'storybooks' from it's time rifts, but full-screen and advanced with a single key. The images are simple and comic-like, and I was wondering how to implement such a feature since it feels like it's a bit different to Unity's pre-existing Timeline system, as there isn't many moving parts.

How do I go about approaching this problem? At least, I don't know how to get the project to a state where a person can press a key to turn to the next page (whether or not there's a visual transition to the next is optional) and once it's done, to start the actual level/scene. Do I still use the Timeline for this? I know I could potentially use an empty game management prefab in order to set up when to play the cutscenes, however.


texts: Rotating object around circumference of circle

texts:
I'm trying to get a lens texture to rotate around the circumference of the circle and although I picked the centre of the circle as the rotating point of the lens it doesn't work.

 private float angle;

//Initialize Method
circlePosition.X = vp.X + vp.Width / 2;
circlePosition.Y = vp.Y + vp.Height / 2;

lensPosition.X = circlePosition.X;
lensPosition.Y = circlePosition.Y + 155;

//Load Content Method
circleOrigin.X = Circle.Width / 2;
circleOrigin.Y = Circle.Height / 2;

lensOrigin.X = Lens.Width / 2;
lensOrigin.Y = Lens.Height / 2;

 //Update Method
 angle += 0.005f;

//Draw Method
spriteBatch.Draw(Circle, circlePosition, null, Color.White, 0.0f,
    circleOrigin, 1.0f, SpriteEffects.None, 0f);

spriteBatch.Draw(Lens, lensPosition, null, Color.White, angle,
  circleOrigin, 1.0f, SpriteEffects.None, 0f);


texts: Getting an Object From a List (Unity C#)

texts:
So in Unity I'm making Snake, and to do that I've a list which houses all the tail elements from the Snake (this was implemented by the NoobTuts tutorial on snake just FYI).

I'm find with adding stuff and removing stuff from the list, HOWEVER, I do have an issue with part of the removal.

When I remove an object from the list it's still in the scene, it's just not acting with the rest of the objects still in the list. All I need to do, is just destroy that object.

I'm not sure if you can destroy an object in a list, or if that'll cause an issue, so I've been trying to set a gameobject to the value at the end of the list. However all list methods seem to just return the bloody index value, not the value in the index!

I've had a look through MSDN but can't understand parts of it.

Here's what I have:

else if (ateslow)
    {
        tailExcess = tail.Count - 1;

        //tail.IndexOf(tail.Count - 1);
        tail.RemoveAt(tail.Count-1);
        ateslow = false;
        if (snakeSpeed < minSnakeSpeed)
            snakeSpeed += 0.0f;
    }

So I play on having tailExcess equal the last element in the list, then I plan on destroying tailExcess after having it popped from the list. The rest below that doesn't matter.

What am I missing?


texts:
Game development has lots of fronts... gameplay, physics, graphics, etc. and whenever I look up the answer for this question it's always something vague like: "extended knowledge of c++, c# or whatever".

But what exactly does that mean? Does the gameplay programmers know lots of openGL, directX? maybe lots of vectors, matrices? Do they need to know some network programming?

So what kind of coding and other tasks do gameplay programmers do?


texts: How to process particle effect between UI?

texts:
I'm developing a game with Unity3D. I found that particle effects would penetrate upper hierarchy UI. Can I show the effect when the UI's sibling index bigger then effect's and hide the effect when the UI's sibling index smaller then effect's?

Here is an illustration:


texts: Can one develop an application with Bluetooth support on iOS using Flash Builder 4.5?

texts:
I have heard about Flash Builder 4.5.1. As I have understood, one can make an application using Flex with Flash Builder 4.5.1 and also export the release build for iOS, Android and Blackberry.

Is it possible to include Bluetooth functionality in an application this way?


texts: Processing component pools problem - Entity Subsystem

texts:
Architecture description

I'm creating (designing) an entity system and I ran into many problems. I'm trying to keep it Data-Oriented and efficient as much as possible. My components are POD structures (array of bytes to be precise) allocated in homogeneous pools. Each pool has a ComponentDescriptor - it just contains component name, field types and field names.

Entity is just a pointer to array of components (where address acts like an entity ID). EntityPrototype contains entity name and array of component names. Finally Subsystem (System or Processor) which works on component pools.

Actual problem

The problem is that some components dependents on others (Model, Sprite, PhysicalBody, Animation depends on Transform component) which makes a lot of problems when it comes to processing them.

For example, lets define some entities using [S]prite, [P]hysicalBody and [H]ealth:
Tank:   Transform, Sprite, PhysicalBody
BgTree: Transform, Sprite
House:  Transform, Sprite, Health

and create 4 Tanks, 5 BgTrees and 2 Houses and my pools will look like:

TTTTTTTTTTT // Transform pool
SSSSSSSSSSS // Sprite pool
PPPP        // PhysicalBody pool
HH          // Health component

There is no way to process them using indices. I spend 3 days working on it and I still don't have any ideas. In previous designs TransformComponent was bound to the entity - but it wasn't a good idea. Can you give me some advices how to process them? Or maybe I should change the overall design? Maybe I should create pools of entites (pools of component pools) - but I guess it will be a nightmare for CPU caches.

Thanks


texts: Is there a good way to get pixel-perfect collision detection in XNA?

texts:
Is there a well-known way (or perhaps reusable bit of code) for pixel-perfect collision detection in XNA?

I assume this would also use polygons (boxes/triangles/circles) for a first-pass, quick-test for collisions, and if that test indicated a collision, it would then search for a per-pixel collision.

This can be complicated, because we have to account for scale, rotation, and transparency.

WARNING: If you're using the sample code from the link from the answer below, be aware that the scaling of the matrix is commented out for good reason. You don't need to uncomment it out to get scaling to work.


texts: Is Carmack right about PC performance? And does Windows 8 address his concerns?

texts:
Here John Carmack claims that PCs are still slower that current gen console hardware because of the overhead.

  "A lot of it's driver overhead issues, where there's so much that we
  do in the game, all of this dynamic texture updating where on the
  console we say 'alright, we've got a new page of data', we put that
  page in and update the page table that points to that.

  "On the console that may just be a matter of writing it to memory,
  it's like 'here's the texture, let's calculate exactly where this part
  of the page table is' and then we just poke it right in there," he
  explained.

Is the situation really that dire? And are there any features or changes in Windows 8 planed that will improve the current state of the PC Gaming ?