texts: sfml/opengl, two objects of same class are sharing variables

texts:
whenever I use the none-default constructor, it only adds to the coordinates of the previous class(in an array)

wall_1x1 wall[2] = {
    wall_1x1(0, -2, 0), //first argument is x, second z, and third ry
    wall_1x1(1, -2, 0)
};

the second object in the array will be behind the first object(by -2 z) and if I give the first object an ry of 90, all the other objects will have the same rotation.

#pragma once
#ifndef WALL_1X1_H

#include <GL\glew.h>
#include <SFML\Graphics.hpp>

class wall_1x1 {

public:
  wall_1x1();
  wall_1x1(float x, float z, float ry);
  ~wall_1x1();
  void up();

private:
  float m_x;
  float m_z;
  float m_ry;
  GLuint tex;
  sf::Image data;
};

#endif

and the .cpp class:

#include "wall_1x1.h"

GLfloat verts[] = {
  0, 0, 0,
  1, 0, 0,
  1, 1, 0,
  0, 1, 0
};

GLfloat coords[] = {
  0, 0,
  2, 0,
  2, 2,
  0, 2
};

wall_1x1::wall_1x1() {
  m_ry = 0;
  m_x = 0;
  m_z = 0;
}

wall_1x1::wall_1x1(float x, float z, float ry) {
  m_ry = 0;
  m_x = 0;
  m_z = 0;

  m_x = x;
  m_z = z;
  m_ry = ry;

  data.loadFromFile("wall1.png");

  glGenTextures(1, &tex);
  glBindTexture(GL_TEXTURE_2D, tex);
  glTexImage2D(
    GL_TEXTURE_2D,
    0,
    GL_RGBA,
    data.getSize().x,
    data.getSize().y,
    0,
    GL_RGBA,
    GL_UNSIGNED_BYTE,
    data.getPixelsPtr());
}

wall_1x1::~wall_1x1() {
}

void wall_1x1::up() {
  glEnableClientState(GL_VERTEX_ARRAY);
  glEnableClientState(GL_TEXTURE_COORD_ARRAY);
  glVertexPointer(3, GL_FLOAT, 0, verts);
  glTexCoordPointer(2, GL_FLOAT, 0, coords);
  glBindTexture(GL_TEXTURE_2D, tex);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
  glTranslatef(m_x, 0, m_z);
  glRotatef(m_ry, 0, 1, 0);
  glDrawArrays(GL_QUADS, 0, 4);
  glDisableClientState(GL_VERTEX_ARRAY);
  glDisableClientState(GL_TEXTURE_COORD_ARRAY);
}

and the important parts in main:

wall_1x1 wall[2] = {
    wall_1x1(0, -2, 0),
    wall_1x1(1, -2, 0)
};
....

wall[0].up();
wall[1].up();


texts: Reading mesh data back from OpenGL vs storing two copies

texts:
I'm wondering if whether it's a good idea or not to keep a copy of vertex data in the main memory or just read it back via glGetBufferSubData (or glMapBuffer/glMapBufferRange).

The reason why I'd do this is so that I can keep only what's needed in the VRAM (and resource which may be needed very soon in the main memory) but not have to go back and load the resource from the disk again.

The concern that I have is that, with the draw optimized flags (GL_XXXX_DRAW) is that they aren't optimized for reading back (since there's a seperate flag for that). So if it's not very fast, it kinda defeats the whole purpose.

The other option is storing a second copy and just delete the VBO when I'm done (no reading it back), but I dislike this because it requires more memory usage than might be necessary.

Which option is preferred? Is there another way? Maybe something I'm missing?


texts: How can I implement a "fast-forward" feature in my game?

texts:
How can I implement the fast forward feature for my tower defense game like in http://fieldrunners.com/ and other TD games?

I am using Unity 3D. Would there be something to manage fewer frames per second or some kind of manually set fast movement of enemies and tower firing speed, et cetera?


texts: How can I ensure a radius variable doesn't get reduced below 0?

texts:
For some reason when I'm using the mouse to change the radius in the Update, the minimum radius is -1 even if I set the range in the top of the script to be 0,50 and even if I check that the xradius is be 0 or higher it's still getting to -1.

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

[RequireComponent(typeof(LineRenderer))]
public class DrawCircle : MonoBehaviour
{
    [Range(0, 50)]
    public int segments = 50;

    public bool circle = true;
    [Range(0, 50)]
    public float xradius = 15;
    [Range(0, 50)]
    public float yradius = 15;
    LineRenderer line;

    public float drawSpeed = 0.3f;

    void Start()
    {
        line = gameObject.GetComponent<LineRenderer>();

        line.positionCount = (segments + 1);
        line.useWorldSpace = false;
    }

    private void Update()
    {
        if (xradius >= 0)
        {
            if (Input.GetAxis("Mouse X") < 0)
            {
                xradius = xradius + 1;
                CreatePoints();
            }
            if (Input.GetAxis("Mouse X") > 0)
            {
                xradius = xradius - 1;
                CreatePoints();
            }
        }
    }

    private void CreatePoints()
    {
        if (circle == true)
            yradius = xradius;

        float x;
        float z;

        float change = 2 * (float)Math.PI / segments;
        float angle = change;

        for (int i = 0; i < (segments + 1); i++)
        {
            x = Mathf.Sin(angle) * xradius;
            z = Mathf.Cos(angle) * yradius;

            line.SetPosition((int)i, new Vector3(x, 0.5f, z));

            angle += change;
        }
    }
}

In the Update I did:

if (xradius >= 0)

But yet when using the mouse for the minimum radius it set both xradius and yradius in the sliders to -1 not sure how can it be -1 if I set the range in both xradius and yradius to be 0,50

You can see in the screenshot in the Inspector in the right both Xradius and Yradius are -1


texts:
I'm using Pygame (just started), and I'm struggling to find how I set the position of the window to fill my entire monitor screen.

I can move things around within the screen / surface. I can make the screen the right size to fill my monitor (can drag it with my mouse to the right place), but can't find how to set the top-left corner of the surface to the top-left corner of my monitor. I'm using sprites.


texts: Text independent of screen resolution in Unity?

texts:
I have the following code that depends on the resolution of the user's display:

void OnGUI()
{
    GUI.Label(new Rect(432, 525, 9000, 9000), ("Hello!"));
}

And of course, the location of the text changes in devices with different resolutions. How can I make the text independent of screen resolution in Unity?


texts: How to make a bar showing the "percentage" of a maximum

texts:
so Im making a game and I need a 'bar' to show how much time has passed in ms (dont worry about the time 'mechanics' I only work with the correct numbers). So lets say that the bar is 128px wide and that I want the timer (the time passed since start in ms) to be displayed within that bar properly, so that e.g. if the time passed is half way of the maximum, then the bar should be half full. Could anyone please tell me the formula because I cant remember/find it.

(btw. all variables needed are the curTime, maxTime and the progress of the bar/the max bar width)


texts: How can I obtain a HBITMAP or HICON from a Direct2D bitmap?

texts:
Is there any way to obtain a HBITMAP or HICON from a ID2D1Bitmap * using Direct2D? I am using this function to load the bitmap.

The reason I ask is because I am creating my level editor tool and would like to draw a PNG image on a standard button control.

I know that you can do this using GDI+:

HBITMAP hBitmap;

Gdiplus::Bitmap b(L"a.png");
b.GetHBITMAP(NULL, &hBitmap);

SendMessage(GetDlgItem(hDlg, IDC_BUTTON1), BM_SETIMAGE, IMAGE_BITMAP, (LPARAM)hBitmap);

Is there any equivalent, simple solution using Direct2D? If possible, I would like to render multiple PNG files (some with transparency) on a single button.


texts: I've done hobby development in Java for a couple of years now, and I've just started learning C++. I understand syntax fairly well, but I'm extremely confused as to many structural facets of a typical program, namely shipping images/textures with the executable. Do I extract them to a data directory? Or do I encode them into the executable? And if the latter is the case, how do I include them in the compilation process? I'm sorry to ask such a basic question, but I'm having a particularly hard time finding the answer on Google.


texts: What happens when Time.time gets very large in Unity?

texts:
As it is said here :

Time.time

The time at the beginning of this frame (Read Only). This is the time in seconds since the start of the game.

And as I know the time is stored in float. So, my question is what will happen when the value of time becomes very large? Can it overflow? Will it lose precision and cause bugs? Will the game just crash or what?


texts: Handle shared vertices in mesh deformation

texts:
I have a cube-sphere made from 6 planes. I am deforming each of the plane vertices using this code (C#):

aPlane.transform.aPoint(vertices[i]).normalized * this.radius + (randomFloat));

This gives me large gaps where my planes join.
How can I separate between shared and non-shared vertices, adding the randomfloat to shared/non-edge vertices only.

Pseudo code could be (C#):

Vector3[] vertices = mesh.vertices;
//maybe add int[] tris = mesh.triangles?
if (vertice is shared)
add randomfloat;
else deform without randomfloat;

I'm quite certain I need to create an array and add triangle vertices and check if the vertices belong to one triangle or two/more triangles.

Everything is generated from code and this is for a hobby project. I already have planet generators from the Asset store but if I use those I might as well just slap together Asset store content and put my name on it.


texts: How do I create a message box that fires a callback on button press?

texts: I need to create a message box with an "OK"-button. When the user touches the button, it should execute a callback. I'm new to this and couldn't find any articles in the docs.


texts: Get the address of a matrix in GLM library

texts:
Is there a way to get the address of a matrix from a GLM matrix?

I'm using opengl 4 and glm library though I can't seem to find anything, which might help.


texts: Can I display text in SFML without setting a font?

texts:
I'm trying to render text without setting a font.

#include <SFML/Graphics.hpp>
#include <iostream>
using namespace std;
string culoare;
int main()
{

    sf::RenderWindow window(sf::VideoMode(800, 600), "Window");
    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }
        sf::Text text;
            //atext.setFont();
            text.setString("HelloWorld");
            text.setCharacterSize(20);
            text.setStyle(sf::Text::Bold);
            text.setColor(sf::Color::White);
            text.setPosition(0,0);
            window.draw(text);
            window.clear(sf::Color::Green);
            window.display();
    }

    return 0;
}

This just make a green window, but doesn't display text.


texts:
Does anyone know of a good lightweight sprite animator solution? I've created a couple of spritesheets using TexturePacker, but I'd like to, for example, create an XML file that tells me frames one through three are part of animation X, and frames 4 through 6 are part of animation Y.

I am primarily a OSX developer.


texts: Unity Mask shows black content in world space canvas (Vuforia)

texts:
So I've built my scroll rect, like this reference tells me to do : http://docs.unity3d.com/Manual/script-ScrollRect.html

-> Scroll View (Rect Transform with scroll rect attached)
---> Viewport (Image + Mask attached)
-----> Content (Image attached)

In scene view it looks like I want it to look like, but in play mode it looks like this, which is the correct shape, but obviously not the correct content :

Update : My Canvas

Update : The Image is getting displayed normally, when I disable the mask.

Update : The source of this problem seems to lie in Vuforia (Image/Object Tracking library) since Vuforia appends a ClippingMask to the cameras


texts:
I've asked a question how to implement Fog Of War(FOW) with shaders. Well I've got this working. I use the vertex color to identify the alpha of a single vertex.

I guess the most of you know what the FOW of Age of Empires was like, anyway I'll shortly explain it:

You have a map. Everything is unexplored(solid black / 100% transparency) at the beginning. When your NPC's / other game units explore the world (by moving around mostly) they unshadow the map. That means. Everything in a specific radius (viewrange) around a NPC is visible (0%transparency). Anything that is out of viewrange but already explored is visible but shadowed (50% transparency).

So yeah, AoE had relatively huge maps. Requirements was something around 100mhz etc. So it should be relatively easy to implement something to solve this problem - actually.

Okay. I'm currently adding planes above my world and set the color per vertex. Why do I use many planes ? Unity has a vertex limit of 65.000 per mesh. According to the size of my tiles and the size of my map I need more than one plane. So I actually need a lot of planes. This is obviously pita for my FPS.

Well so my question is, what are simple (in sense of performance) techniques to implement a FOW shader?

Okay some simplified code what I'm doin so far:

// Setup
for (int x = 0; x < (Map.Dimension/planeSize); x++) {
    for (int z = 0; z < (Map.Dimension/planeSize); z++) {
         CreateMeshAt(x*planeSize, 3, z*planeSize)
    }
}

// Explore (is called from NPCs when walking for example)
for (int x = ((int) from.x - radius); x < from.x + radius; x ++) {
    for (int z = ((int) from.z - radius); z < from.z + radius; z ++) {
        if (from.Distance(x, 1, z) > radius) continue;
        _transparency[x/tileSize, z/tileSize] = 0.5f;
    }
}

// Update
foreach(GameObject plane in planes){
    foreach(Vector3 vertex in vertices){
       Vector3 worldPos = GetWorldPos(vertex);
       vertex.Color = new Color(0,0,0, _transparency[worldPos.x/tileSize, worldPos.z/tileSize]);
    }
}

My shader just sets the transparency of the vertex now, which comes from the vertex color channel


texts: What skills does a hobbyist gamedev team need?

texts:
In the industry, people with various skills and talents all work together on a team. They are most often specialised in their field.

However, this is unpractical for a hobbyist team. All people in such a team need some skill in various fields and people have to wear many hats. Which skills are crucial for an average hobbyist team (without taking any game specific details into account)? Detail some tasks that people with such a skill would be required to do. What other skills are usefull but not necessary? Are there any skills that can more easily be combined (for example, the game designer can more easily do the marketing then an artist?).

A good answer to this question can be used to complete a team, based on missing skillsets or available time of current teammembers, or just to get more insight of the dynamics of a hobbyist team.


texts: Getting Started With Web-based Games....Can I Reasonably Target Flash And Silverlight And HTML5?

texts:
I come from a .NET background and I've done a few simple things in Silverlight.  I'd love to adopt that and make my site and games Silverlight only; but I hear it has a fairly low install base.

I know Flash has a much higher install base.

I also know that everyone seems to say that HTML5 is the way things should be heading; but there is still a bit of a bumpy road ahead.

Short of maintaining three code-bases; are there any cool tools that would allow me to write once and end up with three versions of the same game?  I'm guessing the answer is 'No' but from a theoretical standpoint, I can't think of any reason why it wouldn't be possible.


texts: Who has ownership of publicly developed projects?

texts:
After seeing the comments on selling an idea to developer for a game, the general concencus is that without a game, or atleast a demo, it’s not going to happen. So…someone (yes, Noctrine, I am looking at you) suggested that it might me an interesting idea to turn it into a “public” project.

A few people have asked if I minded if they turned some of my concepts into models, something I always have agreed on. They tell me that it would be to use as work for their portfolio or for practice. Still waiting on those, but that is another story.

If I do this, set up a group to help starting modelers and programmers practice or get stuff for their portfolio, after everything is said and done, who has ownership of the project. I ask in case we end up with an actual demo and a studio get’s interested. Who do they buy it from?

I have no issue with paying accordingly to all participants, but in the legal aspect, who owns it before a publisher buys it?


texts:
Commands may have different target type; like NONE, COORD, UNIT.
Some example commands may be: Attack (target UNIT), Move (target COORD), AttackMove (target COORD), Stop (target NONE), UseAbility (target ability.getTargetType).
Commands will be executed by UI or AI.
So in an OOP approach here, what methods should my Command interface have?
For the command execution has access to the target the command wants.


texts:
I'm writing a shmup and I'm working on implementing things like level design and achievements. I have a trigger system that I've implemented which allows me to do basic things and can assist the basic level workflow. However, as it is, this isn't really flexible enough to recognize some other things, such as:

Determine when an enemy is killed vs. removed from the game
Not taking damage during some period of time
Killing enemies using a particular weapon
Killing enemies in a particular order

Whereas the triggers I have available now basically poll for information, these need to look through a series of events to understand whether the condition is met. So I've conceived a StatisticManager class which would be able to take and store all these events, and provide queries so that new triggers could be written to test for these things. For example, a trigger might ask for an ordered list of enemies killed during some time period, and then determine whether a particular sequence of kills is met.

The design raises a lot of concerns, though, such as determining when to discard / archive data, and how to get statistical data from previous game sessions. Certainly efficiency is a concern.

So my question is: Does my StatisticManager idea seem appropriate for my needs? What other designs should I consider?


texts: Google Play Services somehow authenticates without internet connection

texts:
This question is asked in the context of the Google Play Services plugin for Unity.

Following the documentation for the Google Play Services plugin for Unity, I called the Social.localuser.Authenticate() function in my game to check if the player is authenticated (ie: logged in to google play services).

Here is the authentication code that I am currently calling:

void Awake ()
{
    PlayGamesPlatform.Activate();

    Social.localUser.Authenticate((bool success) => {
        if (success)
        {
            GetLeaderboardData("FirstLoad");
        }
        else
        {
            loadingText.text = "Failed to connect to Google Play Services.";
            StartCoroutine("WaitAndStart");
        }

        authenticated = success; //success returns true even without an active internet connection
    });
}

This works fine with an active internet connection. However, if the player has logged in before, and then launch the game without an internet connection, this function somehow returns true. It doesn't make sense (at least not to me) that the player can authenticate without an active internet connection. Does anyone know if this was intended? (Or if I made a mistake of some sort somewhere?)

Should it have been indeed intended (and the method is checking against a cache of some sort), is there no method to check if the player has an active connection to google's servers? Something along the lines of PlayGamesPlatform.CheckConnection()?


texts: Is it okay to use STL in my iPhone C++ 2d game?

texts: I've read a couple posts on the subject and it sounds hairy. But I think people are talking about using STL containers for Objective-C objects. I'm using pure C++.


texts: Best data types for DNA, edibles and creatures

texts:
So I am making a sort of continuous evolutionary system in the Unity3D engine. Currently I have a DNA class that has values that gets applied to a Creature object on initializing e.g.:

public class DNA{
    public float maxSpeed;
    public float foodWeight;

    public DNA(float maxSpeed){
        this.maxSpeed = maxSpeed;
        this.foodWeight = foodWeight;
    }
}

Where every Creature has a public DNA variable that gets set when instantiating a population of Creatures via a GameManager class. In this "ecosystem" I want to have the creatures crave for food and try to avoid the poison.

My question isn't about the reproducing or natural selection part, but more about what the best kind of data type for each object is. Since I want the project to have expandable amount of Creatures, sorts of food etc.
Is the best way to handle all data via one GameManager, or should I seperate it in for example CreatureManager, FoodManager etc.?

Maybe a PopulationManager of some sorts?

Is the current setup for the DNA data optimal?
Also, currently I have food and poison just as two prefabs and detect collision (and add or substract health whether it's food or poison via tag), wouldn't it be smarter to create a struct for food and poison so I can later on expand on this?

Sorry if any of the given information is unclear or a bit vague, please say so if this is the case! I would be glad to clarify and add any needed information.
Thank you for reading through the entirety of my question, thanks for your time! :)


texts: Unity HDRP draw order doesn't change when asset is set to higher priority?

texts:
I don't like the way that light got baked into part of my mesh.
It might make sense for me to try to blacken that area of the lightmap in Photoshop, but first I tried to just hide it with a probuilder object that uses an unlit black material:

I changed the priority of this object from 0 to 1, higher than any object in this scene, or at least the floor object, but it does not draw over the floor in Game View. I tried using a higher number and setting it beneath the floor instead of intersecting it, but it is just being rendered the usual way. Also note that I have a UI Canvas component being drawn in ScreenSpace, in case that has anything to do with it.
How can I get this object to render in front of the floor while it is intersecting the two front faces, like in the picture?


texts: What is the most common method for providing gamepad support in an OS X game? I've been using an IOHIDLIB wrapper named DDHIDLib https://github.com/Daij-Djan/DDHidLib and it seems to be working but I find it odd that there isn't something more recent.


texts: 3D position of an arbitrary UV coordinate

texts:
I have a UV map for a 3D mesh that encodes "links" between pairs of UV coordinates. I have previously defined this links (or pairs), one to one. The links are enconded using the function rgb_color(u1, v1) = (u2, v2, 0.0). Therefore, in the fragment shader, given UV coordinates of the current fragment, I can get the UV coordinates of the fragment "linked" with the current one.

What I want to do is to draw this links in the 3D space(i.e. draw a line between the current fragment with texture coordinates (u1, v1) and its "link" texture coordinate (u2,v2). As far as I know this is a hard problem to solve because in the fragment shader you cannot access to the 3D coordinates (u2,v2).

Edit: Notice that the UV map is fragmented, therefore you cannot just draw this lines in the UV domain.

Do you have any idea how to approach this problem?


texts: I need my timer to go up every 30 seconds

texts:
I wrote code for a jackpot to increase from one date to the next, and it works beautifully. The client wants the numbers to stay put for a while, and then increase.

This is the code:

if (timerRunning1)
{
    timerValue1 += Time.deltaTime * 14.4 * (timerValue1F - timerValue1)
                / (finish1 - start).TotalSeconds;

    Jack1.text = timerValue1.ToString ("F2");

    //PlayerPrefs.SetFloat ("Jackpot1", float.Parse(Jackpot1.text));
    //PlayerPrefs.SetFloat ("Jackpot1f", float.Parse(Jackpot1F.text));

    if (timerValue1 > (timerValue1F - 0.1))
    {
        timerRunning1 = false;
        print ("ALTO");

        PagPrincipal.SetActive (false);
        Victoria.SetActive (true);

        Debug.Log ("FUNCIONA!!!");

        Invoke ("apagavictoria", 10f);

    }
}

I tried WaitForSeconds(30f), and it didn't work. How can I make my timer go up every 30 seconds?


texts:
I have two colliding boxes, How i can calculate contact information like (contact normal, contact point and penetration) .

Is there any simple algorithm .

Note: i'm using XNA .


texts: How can I create a 'flaming' effect like in Ocarina of Time's title screen?

texts:
I'd like to recreate a flaming effect like the one from the logo on the title screen of the N64 game 'The Legend of Zelda: Ocarina of Time,' shown below:

A quick look into the textures used in the ROM provide a single 32x32 texture that looks similar to the effect but I don't know how that image (assuming that's the right one) is transformed into the effect seen on the logo.

How can I implement something similar?


texts:
I found a sample about how to run a HLSL code with DirectCompute.

https://code.msdn.microsoft.com/windowsdesktop/DirectCompute-Basic-Win32-7d5a7408

This is the HLSL script I want to run

https://github.com/zachsaw/MPDN_Extensions/blob/master/Extensions/RenderScripts/SuperRes/SuperResEx.hlsl

It doesn't seem the same as the BasicCompute sample. First, the main function's name is called "main" instead of "CSMain". Second, it uses data types like float2, float3 and float4 while BasicCompute uses standard data types. So, is it the same or something else?

Will DirectCompute run this script or it has to be done through other means?


texts: What are the factors that determine the default frequency of a shader call?

texts:
After i have been played for some days with various vertex and fragments shaders seems clear to me that this programs are called by the GPU at every and each rendering cycle, the problem is that I can't really quantify this frequency and I can't tell if is based on some default values or not because I don't have a big collection of hardware right now to do extensive tests.

For what i know the answer could be really trivial like "it's the same of the refresh rate of your monitor", but i would like some good answers on that to be clear on this.

For instance looks really odd to me that all the techniques used to control the amount of FPS that i have seen until now uses a call for the OpenGL function glutGet(GLUT_ELAPSED_TIME) to retrieve a value in ms about when the rendering started but I have to relies on the CPU to do the math. Why I can't set an FPS value in OpenGL if OpenGL clearly has a counter and a timer/clock?

PS
I'm referring to OpenGL 3.0+


texts: Graphic/Animation tools and workflow for iPhone/iOS game development

texts:
I've got some experience producing Flash games, and for all Flash's faults I find the designer/developer workflow pretty decent.

I can set up a template FLA with placeholder movieclips and code to that independently of a designer/animator doing their thing. When it comes time for integration, I can either compile their animations into my project by using a SWC or by loading SWF's at runtime.

I've had a quick look, but I can't see any tools that offer a similar workflow for iOS game development. Could anyone producing iOS games shed any light on how they're handling designer/animator/developer workflow?


texts:
I've decided it's time to implement serialization in my simple engine but this has caused me many headaches for the past couple of days/weeks. My engine uses an entity/component based approach similar to what is described in the T=Machine blog.

To keep it simple, my first goal was to implement serialization of entities. Since I'm going to use Lua for scripting, I thought it would be nice to serialize entities into Lua tables. Unfortunately, I find the information that is available on serialization in C++ is rather scarce. After many days of thinking I found one approach which is working for my implementation and is described here.

In essence, I have an EntityManager class from which I request new entities. This class holds entity as well as pointers of type BaseComponent from which all components derive. Because I store components as base pointers, I couldn't use a friend class for serialization, but had to make the BaseComponent inherit from a Serializable class, which has pure virtual serialization methods.

So, this is not that bad, I just have to inherit from the Serializable class and implement the serialization method. To support deserialization though, I have to do a few tricks according to the last link. That is, I have to include a static object inside each component whose sole purpose is to populate a map from component names to constructors. Here is a generic example (and please ignore any possible errors),

/* Base.h */
struct Base: public Serializeable{
    static std::map&ltstd::string, std::function&ltBase*(void)&gt &gt deriveds;
    virtual ~Base(void){}
};

/* Derived.h */
template&ltclass T&gt
struct add_map_entry{
    explicit add_map_entry(std::string name){
        Base::deriveds[name] = [](void) -> Base* {
            return new T;
        };
    }
}

class Derived: public Base{
public:
    int x;
    int y;
    Derived(void){
        std::cout &lt&lt "Derived created" &lt&lt std::endl;
    }
    void serialize(std::ostream&);
    static add_map_entry&ltDerived&gt adder_;
};

Then in the implementation file I also have to initialize the static map of the base class as well as the static object of each derived class.

I find this quite a mess and although it could probably be improved with the use of macros, I can't help to wonder if there are better ways. How do you handle this kind of formatted serialization?

PS: Please don't recommend changing to a more flexible programming language :) !


texts: What is the difference between OpenGL, SDL, DirectX, GLFW, GLUE?

texts:
I have not work with graphics yet but I'd like to know its concepts at some high level overview.

I was told that OpenGL and DirectX are somehow programmed into my graphics card, and I can use GLFW, SDL etc. to get access to those and manipulate them, by creating kind of different graphics objects.

Analogy:

OpenGL - programming language

SDL - framework

Please, correct me politely.


texts: Clamping camera forward and backward vector in Unity3D

texts:
My perspective camera is rotated on the x axis. I've implemented a zoom with the scroll wheel and it works great.

I'm trying to limit the zoom, however. My solution right now is to take the relative scale of the transform.forward y and z components and clamp the y and z position of the camera by using Mathf.Clamp and multiplying the minZoom and maxZoom floats by the corresponding transform.forward component. It works well, except it limits the y axis, so when I translate around I can't go below a given y due to my clamp with is ideally meant to affect the zoom only.

Is there a way to clamp the forward and backward movement of the camera? I've been looking everywhere but can't find a thing.

Thanks.

Code

public class ClickManager : MonoBehaviour

{
    public float dragSpeed = 2;
    public float minZoom = 0.5f;
    public float maxZoom = 5.0f;

    private Vector3 dragOrigin;

    private float lerpPercentBack = 0; // value between 0 and 1 representing percentage of lerp
    private float lerpPercentForward = 0;
    private bool isLerpingBack = false;
    private bool isLerpingForward = false;

    void Update()
    {
        float scroll = Input.GetAxis("Mouse ScrollWheel");

        if (Input.GetMouseButtonDown(1))
        {
            dragOrigin = Input.mousePosition;
            return;
        }

        if (scroll > 0)
        {
            isLerpingForward = true;
            lerpPercentForward = 0;
        }
        if (scroll < 0)
        {
            isLerpingBack = true;
            lerpPercentBack = 0;
        }

        if (isLerpingBack)
        {
            scrollLerperBack();
            lerpPercentBack += 0.05f;

            if (lerpPercentBack >= 1.0f)
            {
                lerpPercentBack = 0;
                isLerpingBack = false;
            }
        }

        if (isLerpingForward)
        {

            scrollLerperForward();
            lerpPercentForward += 0.05f;

            if (lerpPercentForward >= 1.0f)
            {
                lerpPercentForward = 0;
                isLerpingForward = false;
            }
        }

        //Debug.Log(lerpPercent);

        /*if (!Input.GetMouseButton(1)) return;

        Vector3 pos = Camera.main.ScreenToViewportPoint(Input.mousePosition - dragOrigin);
        Vector3 move = new Vector3(pos.x * dragSpeed, pos.y * dragSpeed, 0);

        transform.Translate(move, Space.World);

        Debug.Log(scroll);*/

    }

    void scrollLerperBack()
    {
        transform.position -= Vector3.Lerp(transform.forward, Vector3.zero, lerpPercentBack);
    }

    void scrollLerperForward()
    {
        transform.position += Vector3.Lerp(transform.forward, Vector3.zero, lerpPercentForward);
    }

    void LateUpdate()
    {
        Vector3 pos = transform.position;

        pos.y = Mathf.Clamp(pos.y, minZoom * transform.forward.y,
            maxZoom * transform.forward.y);
        pos.z = Mathf.Clamp(pos.z, minZoom * transform.forward.z,
            maxZoom * transform.forward.z);
        transform.localPosition = pos;
    }

}


texts: Handle states in character in functional programming way

texts:
How to handle any change of state of a character with functional programming?

If I'm using functional programming the character should be stateless, in my understanding. With that said, I should instantiate a new character every time a position, for example, is changed. Is this correct? This doesn't sound very efficient, but I might be wrong. I'm tinkering before start implementing and wanted to be sure this is the right way.

Thanks.


texts: Level Select World Map with layers of images for score and completion

texts:
I'm working on an android game that will have a "world map" for selecting which level to play.  Some examples of other games that implement what I'm trying to do are: Angry Birds, Kingdom Rush, and Candy Crush.  In these various implementations the world map is scrollable, zoomable and tapping on a map node either takes the player immediately to the appropriate level, or displays an info box/page from which the player can view their score or play the level.

I implemented a world map for my game using the ImageMap library. The implementation I have is scrollable, zoomable, and selectable.  It feels like I'm almost there, but I have a problem yet to solve.

How should I go about showing information for each node?  I'd prefer to show the completion directly on the world map (Kindom Rush does this) instead of showing all of the information in a new page or pop-up view.

The information I want to show for each node is:
    + An icon if the level is locked
    + another icon if the level is unlocked, but not completed
    + possibly another icon for a completed level
    + possibly a "star" panel for completion score (1,2 or 3 stars)

I don't really need to know how to setup the data structure, so much as how to display it efficiently in the Activity. What is the best way to get this done?  So far I haven't had much luck with layering images on top of the image map (so they would all zoom and scroll together) and I can't imagine that I'd really want to create a separate image for every possibly combination of node status.

In case anyone cares, I'm basing my game off of the Replica Island code base.

Any tips would be greatly appreciated. Even a high level answer may help me get started in the right direction.


texts:
How can I take screen coordinates (or alternatively world coordinates on the 'primary' parallax plane) and find out what world coordinates they translate into when taking parallax depth into account?

I want to be able to tell if a rectangle is under the mouse cursor. I'm using libGDX and the ParallaxCamera class from the tests module. This means depth is modelled in two dimensions, where 1 == primary plane, 0 == pinned to the screen, 0,5 == scrolls at half the rate of the primary plane.

This is trivial in the primary parallax plane, as libGDX's camera has a handy unproject method. However, I can't find any examples that use the 'parallax matrix', as this is typically passed into a SpriteBatch#setProjectionMatrix rather than being used in internal camera calculations.

I don't understand the mathematics enough to figure this out. If anyone reading this can link to any very basic explanations of the mathematics behind projecting things with parallax depth into screen space and vice versa, I'd be really grateful to read it.


texts: How do I draw a 2d plane and rotate camara (To be a board) in a 3d XNA game?

texts:
I am trying to create a simple board game, but the 3d part of this is really killing me.

From what I can gather I have created a plane, but it never moves even though I turn the camara, but that partially makes sense as I only turn the camara with a 3d model, but in my head that makes 0 sense, in my head if I turn the camara it should affect ALL my models? But with this code the camara only "cares" about the 3d cylinder, the plane is just completely still

private void OnDraw(object sender, GameTimerEventArgs e)
    {
        SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.CornflowerBlue);

        foreach (ModelMesh mesh in cylinderModel.Meshes)
        {
            foreach (BasicEffect effect in mesh.Effects)
            {
                //effect.World = Matrix.CreateRotationX((float)e.TotalTime.TotalSeconds * 2);
                effect.View = Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up);
                effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10000.0f);

                effect.EnableDefaultLighting();
            }

            mesh.Draw();
        }

        //cameraPosition.Z -= 5.0f;
        _effect.World = Matrix.CreateRotationZ((MathHelper.ToRadians(((float)e.TotalTime.Milliseconds / 2) % 360)));
        foreach (EffectPass pass in _effect.CurrentTechnique.Passes)
        {
            pass.Apply();

            SharedGraphicsDeviceManager.Current.GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleStrip, _vertices, 0, 1, VertexPositionColor.VertexDeclaration);
        }
    }

Is there a way to get the camara to affect all models?


texts:
the fragment shader is working so strange, can someone explain me whats going on.

this one compiles fine but crashes when i use it-

#version 330 core
const float PI = 3.14159265359;
out vec4 coloroutfinal;

in vec3 fragpos;
uniform vec3 lightpos;
uniform vec3 camerapos;

vec3 wi;
vec3 normal;
float cosT;
uniform vec3 lightcolor;
vec3 incidentlight;

uniform float metallic;
uniform float roughness;
uniform vec3 albedo;
uniform float ao;

vec3 fresnel(float cosT,vec3 Fo);
float ND(vec3 H,vec3 N,float roughness);
float G(vec3 L,vec3 N,vec3 V,float roughness);

void main()
{
  coloroutfinal=vec4(1.0);

}

vec3 fresnel(float cosT,vec3 Fo)
{
  return Fo+(1.0-Fo)*pow((1-cosT),5);
}

float ND(vec3 H,vec3 N,float roughness)
{
   float roughness4=pow(roughness,4);
   float cosT=max(dot(N,H),0.0);
   float cosT2=cosT*cosT;
   float num=roughness4;
   float denom=cosT2*(1.0-roughness4)+1.0;
   return num/denom;
}

float GP(float cosT,float roughness)
{
roughness-=1.0;
   float r2=roughness*roughness;
   float k=r2/8;

float num=cosT;
float denom=cosT*(1.0-k)+k;
 return num/denom;

}

float G(vec3 L,vec3 N,vec3 V,float roughness)
{
  float cosTL=max(dot(N,L),0.0);
  float cosTV=max(dot(N,V),0.0);

  float GL=GP(cosTL,roughness);
  float GV=GP(cosTV,roughness);
  return GL*GV;
}

but this one is just the same as above but no function definitions but works fine(renders my object in white)-

#version 330 core
const float PI = 3.14159265359;
out vec4 coloroutfinal;

in vec3 fragpos;
uniform vec3 lightpos;
uniform vec3 camerapos;

vec3 wi;
vec3 normal;
float cosT;
uniform vec3 lightcolor;
vec3 incidentlight;

uniform float metallic;
uniform float roughness;
uniform vec3 albedo;
uniform float ao;

vec3 fresnel(float cosT,vec3 Fo);
float ND(vec3 H,vec3 N,float roughness);
float G(vec3 L,vec3 N,vec3 V,float roughness);

void main()
{
  coloroutfinal=vec4(1.0);

}

I never call the function so how are they interfearing.
also both the shaders compile and link fine.

can someone point me to the mistake?


texts:
I'm having a problem with post processing in my deferred renderer. When I'm applying an effect like bloom on top of my scene, the bottom of the bloom effect texture leaks into the top of my screen, the top of the texture leaks into the bottom of the screen, the left into the right of the screen and so on. Looks like the uv coords don't get clamped correctly, although I thought I'd have set that all correctly.

The bloom effect in this case is created in a lower resolution and the gets upsampled using linear filtering.

This image shows the problem:

I render the postprocessing effects using a simple quad:

glm::vec3(-1.f, -1.f, 0.f),
glm::vec3(1.f, -1.f, 0.f),
glm::vec3(1.f, 1.f, 0.f),
glm::vec3(-1.f, 1.f, 0.f)

This is the vertex shader I use to render the quad:

#version 430 core

layout(location = 0) in vec3 POSITION;

noperspective out vec2 tex_coord;

void main(void)
{
    tex_coord = POSITION.xy * 0.5 + 0.5;

    gl_Position = vec4(POSITION.xy, 0.0, 1.0);
}

And of course in the fragment shader I'm doing something like this:

#version 430 core

uniform sampler2D uTexture;

noperspective in vec2 tex_coord;

out vec4 frag_color;

void main(void)
{
    frag_color = texture(uTexture, tex_coord);
}

The effect got rendered into a frame buffer object which got set up like this:

glGenFramebuffers(1, &_filterFbo);
glBindFramebuffer(GL_FRAMEBUFFER, _filterFbo);

// filter texture
glGenTextures(1, &_filterTexture);
glBindTexture(GL_TEXTURE_2D, _filterTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, _effectWidth, _effectHeight, 0, GL_RGB, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _filterTexture, 0);

I really don't know what's the problem here, I hope anyone got an idea.

Thanks in advance


texts: Calculate angle between player and end point

texts:
I have such question:

how to calculate angle between player and end point?

Things, which i have:

Player. I have X, Y, Z position of player and his Z-angle (0-360)
Endpoint. I have only X, Y, Z position of end point.

Task:

Rotated player Z-angle to end point.

How i can did this?

Please, help :3


texts: How to properly generate walls simulating perspective around stone in a cave-like level made of squares?

texts:
Long story short. My levels tiles currently look like this:

And i want them to look like this:

My levels are designed as 400x400 squares of proceduraly generated 0's and 1's, 0 representing dirt(walkable by player), 1 represeting stone(impenetrable).
Game itself looks a lot like this.
At first, my method was to run another loop - after generating the world that replaced stone tiles, depending on directions of empty tiles were, with wall. The method doesn't work so bad up to the point where there are 1 wide walls sticking out, which are impossible for it to convert, check picture:

As you can see, in my method, the wall is an another texture, taking one tile itself.
I can't replace air with walls, as that could possibly obstruct a passage. It basically fails every time there are 3 or more dirt tiles directly next to it.
This is the place at which i wondered if i chose the right method or if i should change the whole design for the walls, if so - to what? Should i create some textures for the 1-wides alone? Or maybe i shouldn't generate 1-wides at all? How do games generally deal with this?
I've looked for the answer to my problem, and haven't found it. Probably because it's hard for me to word it(sorry for messy post).


texts: SDL gray scale image from a a color image?

texts: I am new to sdl. I have basically have the following codes which can load the images. I know how to access the pixel as below. What I need it to convert the image to 8 bit grey level and 1 bit monochrome separately. I know it got to do with pixel manipulation. Any hint or idea how to to this? I am not too sure what to set for SDL_CreateRGBSurface and also once I get the pixel what manipulation to be done?


texts: How to get the position in an actor inside a table with LIBGDX?

texts:
Well the title says it all, I want to get the position of an actor inside a table

Button button = new Button(bs);
table.add(button).width(50).height(50);
table.top().center();

By using

button.localToStageCoordinates(new Vector2(button.getX(), button.getY()));

I get a near position but not exact, here is an screenshot, red squares are the positions I'm getting, while the transparent squares are the buttons.


texts:
I'm working on a hobby project (I'm a web/backend developer by day) and I want to create a 3D tile (terrain) engine. I'm using XNA, but I can use MonoGame, OpenGL, or straight DirectX, so the answer does not have to be XNA specific. I'm more looking for some high level advice on how to approach this problem.

I know about creating height maps and such, there are thousands of references out there on the net for that, this is a bit more specific.

I'm more concerned with the approach to get a 3D hexagon tile grid out of my terrain (since the terrain, and all 3D objects, are basically triangles).

The first approach I thought about is to basically draw the triangles on the screen in the following order (blue numbers) to give me the triangles for terrain (black triangles) and then make hexes out of the triangles (red hex).

This approach seems complicated to me since I'm basically having to draw four different types of triangles.

The next approach I thought of was to use the existing triangles like I did for a square grid and get my hexes from six triangles as follows

This seems like the easier approach to me since there are only two types of triangles (I would have to play with the heights and widths to get a "perfect" hexagon, but the idea is the same.

So I'm looking for:

1) Any suggestions on which approach I should take, and why.

2) How would I translate mouse position to a hexagon grid position (especially when moving the camera around), for example in the second image if the mouse pointer were the green circle, how would I determine to highlight that hexagon and then translating that into grid coordinates (assuming it is 0,0)?

3) Any references, articles, books, etc - to get me going in the right direction.

Note: I've done hex grid and mouse-grid coordinate conversion before in 2D. Looking for some pointers on how to do the same in 3D. The result I would like to achieve is something similar to this video.


texts: How decoupled should game logic and rendering be?

texts:
From a data perspective, how decoupled should game logic and rendering be? How much does it have to know about each other?

Take a look at the following example. I'm going to use javascript because that's what I'm most familiar with.

Block

Basically, when the Block.destroy is called, there is a delay before it loses a life

function Block(life, destructionDelay){
    this.life = life;
    this.destructionDelay = destructionDelay;

    this.destructionCountdown = 0;
}

Block.prototype = {
    destroy: function(){
        this.destructionCountdown = this.destructionDelay;
    },

    update: function(){
        if(this.destructionCountdown > 0){
            this.destructionCountdown--;

            if(this.destructionCountdown === 0){
                life--;
            }
        }
    }
}

What was supposed to happen here is when the Block is destroyed, it plays a "being destroyed" animation before it loses a life/destroyed.

As I have been informed, it is ideal for the game logic to know nothing/minimal about the renderer and vice-versa. How do I design these kinds of entities?


texts:
I begin to learning direct3d10 and stuck with multiple passes. As input I have a triangle(that stored in vb/ib) and effect file:

//some vertex shader and globals goes there. skip them to preserve simplicity

float4 ColorPixelShader(PixelInputType input) : SV_Target
{
    return float4(1,0,0,0);
}

float4 ColorPixelShader1(PixelInputType input) : SV_Target
{
    return float4(0,1,0,0);
}

technique10 ColorTechnique
{
    pass pass0
    {
        SetVertexShader(CompileShader(vs_4_0, ColorVertexShader()));
        SetPixelShader(CompileShader(ps_4_0, ColorPixelShader()));
        SetGeometryShader(NULL);
    }
    pass pass1
    {
        SetVertexShader(CompileShader(vs_4_0, ColorVertexShader()));
        SetPixelShader(CompileShader(ps_4_0, ColorPixelShader1()));
        SetGeometryShader(NULL);
    }
}

And some render code:

pass1->Apply(0);
device->DrawIndexed(indexCount, 0, 0);

pass2->Apply(0);
device->DrawIndexed(indexCount, 0, 0);

What I'd expect to see is the green triangle, but it always shows me red triangle. What am I doing wrong?

Also, I've got another question - should I set vertex shader in every pass?

I've added ColorVertexShader1 that translates vertex position by some delta, and 've got following picture: http://imgur.com/Oe7Qj


texts:
I am working on a dust cleaner simulator on Java, in this case the shape of the cleaner is a circular ball.
The program is quite simple, the user puts in the width and length of the "room" and coordinates x and y.
What I want to do and cannot is create a series of commands, each represented by a character. There are three commands that I want to implement:

char 'A' = Move forward 1 meter

char 'L' = Turn left 90 degrees

char 'R' = Turn right 90 degrees

Example of user input AALA, in this case the expected output is that the machine moves 2 meters and then turns left 90 degrees and then moves 1 meter again. Hope I am clear.
As you can see in the code, I have tried to create an array of chars but I don't know what the next step should be...
The code:
public class Cleaner extends JPanel {
/* int lx = 1, ly = 1;
int x = 200, y = 250;

*/
int x, y;
int width = 52, height = 50; // width and height of the "dust sucker"
int lx , ly;

// an array of chars
char[] charArray ={ 'A', 'L', 'R'};

java.util.Timer move; // making the instance of Timer class from the util package
static JFrame frame;

Cleaner()
{

    frame = new JFrame ("Cleaner started!"); // passing attributes to our fame
    frame.setSize (400, 400); // setting size of the starting window
    frame.setVisible (true);

    setForeground(Color.black); // setting color

    move = new java.util.Timer();

    move.scheduleAtFixedRate(new TimerTask()
    {

        public void run()
        {
            if(x<0)
                lx = 1;
            if(x>=getWidth()-45)
                lx = -1; // -1 sets boundry for the dusk sucker
            if(y<0)
                ly = 1;
            if(y>=getHeight()-45)
                ly = -1; // -1 sets boundry for the dusk sucker

            x+=lx; // to make the machine move
            y+=ly;

            repaint();
        }

    }, 0, 5// speed of the machine
            );

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

public void paint (Graphics g)
{
    super.paint(g);
    Graphics2D g2d = (Graphics2D) g;
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.fillOval(x, y, width, height);
}

public static void main (String[] args)
{
    // lx value

    String lxValue =
             JOptionPane.showInputDialog( "Enter lx" );
    // ly value
    String lyValue =
              JOptionPane.showInputDialog( "Enter ly" );

    String xValue =
             JOptionPane.showInputDialog( "Enter x value" );
    // ly value
    String yValue =
              JOptionPane.showInputDialog( "Enter y value" );

     // convert String inputs to int values
      int firstInput = Integer.parseInt( lxValue );
      int secondInput = Integer.parseInt( lyValue );
      int thirdInput = Integer.parseInt( xValue );
      int forthInput = Integer.parseInt( yValue );

         Cleaner cleaner = new Cleaner();

            frame.add(cleaner);
      cleaner.lx = firstInput;
      cleaner.ly = secondInput;
      cleaner.x = thirdInput;
      cleaner.y = forthInput;

}

}

All help is appreciated!


texts: Might this alternate circle-circle collision test help performance?

texts:
Preface: I’m no gaming pro…I code business apps, but I’m experimenting with game coding this Christmas. :-)

I want to detect collisions between 200+ circles of different sizes which are moving at different speeds.

I know I can determine if any 2 circles are actually colliding like this:

// are circle0 & circle1 colliding?
var dx= circle1.x-circle0.x;
var dy= circle1.y-circle0.y;
var rr= circle0.radius+circle1.radius;
var isColliding = (dx*dx + dy*dy) < rr*rr;

In reading about collision testing here on GameDev I understand that performance can be improved by reducing the count of circle-pairs that need to be tested during an animation cycle.

So I’m thinking I can skip the above collision test for any circle-pair that is too far apart to possibly be colliding.

To calculate how many times I can safely skip the collision test I can calculate the separation distance between a circle-pair and divide that distance by the combined speeds of the circles.

// no collision is possible for `var safe` animation cycles
var safe = Math.sqrt(dx*dx+dy*dy)/(circle0.speed+circle1.speed);

Question#1: In general, is it worthwhile to do the “expensive” Math.sqrt once to gain skipping multiple “cheap” arithmetic isColliding tests?

Question#2: What collision testing pattern would you gaming pro’s use to detect collisions between different sized circles moving at different speeds?

BTW, I ask the first question out of inexperience, so I understand the answer may well be: You just have to compare both methods yourself and see which works best for you. 


texts: Why do my LWJGL fonts have dots and lines around them?

texts:
When we render fonts there are weird dots and lines around the text. I have no idea why this would happen. Here is an image of what it looks like:

Our font class looks like this:

package me.NJ.ComputerTycoon.Font;

import me.NJ.ComputerTycoon.BaseObjects.UDim2;

import org.lwjgl.opengl.Display;
import org.newdawn.slick.Color;
import org.newdawn.slick.TrueTypeFont;

public class Font {

    public TrueTypeFont font;
    private int fontSize = 18;
    private String fontName = "Calibri";
    private int fontStyle = java.awt.Font.BOLD;

    public Font(String fontName, int fontStyle, int fontSize) {
        font = new TrueTypeFont(new java.awt.Font(fontName, fontStyle, fontSize), true);
        //font.
    }

    public Font(int fontStyle, int fontSize) {
        font = new TrueTypeFont(new java.awt.Font(fontName, fontStyle, fontSize), true);
    }

    public Font(int fontSize) {
        font = new TrueTypeFont(new java.awt.Font(fontName, fontStyle, fontSize), true);
    }

    public Font() {
        font = new TrueTypeFont(new java.awt.Font(fontName, fontStyle, fontSize), true);
    }

    public void drawString(int x, int y, String s, Color color){
        this.font.drawString(x, y, s, color);
    }

    public void drawString(int x, int y, String s){
        this.font.drawString(x, y, s);
    }

    public void drawString(float x, float y, String s,  Color color){
        this.font.drawString(x, y, s, color);
    }

    public void drawString(float x, float y, String s){
        this.font.drawString(x, y, s);
    }

    public void drawString(UDim2 udim, String s){
        this.font.drawString((Display.getWidth() * udim.getX().getScale()) + udim.getX().getOffset(), (Display.getHeight() * udim.getY().getScale()) + udim.getY().getOffset(), s);
    }

    public String getFontName(){
        return this.fontName;
    }

    public int getFontSize(){
        return this.fontSize;
    }

    public TrueTypeFont getFont(){
        return this.font;
    }
}

What could be causing this?


texts: Play an effect where a sprite touches a trigger

texts:
I have a sprite-based GameObject in Unity to which is attached a RigidBody and a Collider2D. When this GameObject comes into contact with a particular Collider2D Trigger, I want a particle effect to play at the point of contact. This sounds extremely simple to set up and yet I can't seem to find any solution that works, since OnTriggerEnter2D doesn't bother to provide hit coordinates.

Please note that the trigger represents a non-solid space, so adding a solid (non-trigger) collider for hit detection is not a solution.

The sprite is large, so I can't just play the particle effect at its transform position. Raycast is not an appropriate solution for this problem; it doesn't handle nearly enough cases.


texts: Where to show user shot's power on touch screen?

texts:
I want to show user shot power in standart way
(the more user holds finger on the screen the stronger is shot)

Where is the best place to show this icon on touch screen(when I use mouse it's better to show it at the mouse position):

static at screen side or top
at finger position (how to handle clicking at screen bounds? what offset to use to avoid hiding behind finger?)

Will be glad to see any good examples you liked.


texts:
I was wondering how does the stars in night time in minecraft work, are they point sprites? And are they placed on a texture or just randomly placed on some far away location.

EDIT 1:

OK, well, with the imformation gathered concerning the minecraft skybox I now know that the stars are not directly textured onto a sphere but are individial quads placed some set distance (the radius of the sphere) from the player.

The problem is now I will I go about getting a random position on that sphere (not in it and not too far out of it). And how will I get rotation for it to face the player? One user suggested normalising a random Vector3 then multiplying it by the spheres radius which I think, simply won't work. Also another suggested that I use the formular: "1 = x^2+y^2+z^2", I don't know how I would use this to find a random position on a sphere either.

EDIT 2:

OK, I haven't tested this or anything but from all the imformation gathered from PrinceCharles anwser it should be something like this:

            float x = (float)random.NextDouble() * 2 - 1;
            float y = (float)random.NextDouble() * 2 - 1;
            float z = (float)Math.Sqrt((double)(1f - x * x - y * y));

            Vector3 randomPoint = new Vector3(x, y, z);

            if (randomPoint.Length() != 0)
            {
                randomPoint.Normalize();
                Vector3 pointOnSphere = randomPoint * radius;

                                  // Position     Rotation
                stars.Add(new Star(pointOnSphere, new Vector3(0, 0, 0)));
            }

The reason for the "* 2 - 1" is to give the random a range of -1 to 1. I think that is correct...

EDIT 3:

One side of the map:

The other:

Any ideas?

Thanks :)


texts: Android split build - manual obb file download necessary?

texts:
I have an apk built with Unity 5.0.1 that has over 50MB. Google Play does not accept files over 50MB so I have to make a Split Build as covered in the Unity manual:
http://docs.unity3d.com/Manual/android-OBBsupport.html

Now it says that I need to download the obb file manually. On the other hand, elsewhere I read that all apps that are downloaded from the play store are already downloaded with the obb file. So which one is it? Do I have to use the Google Play Obb Downloader or not? Where is the downloaded obb file stored in the filesystem?


texts:
I have pretty much the same controls on the race example of the engine. A AnalogOnScreenControl and a button defined by a Sprite.

The problem is, when I'm using the analog directional, touching the button does not trigger onAreaTouched on the button sprite.

I even tried adding the button to the child scene (controller scene) but it doesn't register the secondary touch on the button.

Am I doing something wrong or is this a bug?

UPDATE

I am doing some debugging and apparently if I touch the control base, it triggers it's onAreaTouched, and if I keep touching the controls and then touch the button (on the other side of the screen) the same onAreaTouched from the control base is triggered. He's the only one receiving the touch event.

I really can't understand why this is happening.


texts: Check if a point is touching a user drawn curve in HTML5 canvas

texts:
I am having trouble detecting whether a ball is colliding with a red curve. The curve below is an example of what a user may draw on to the canvas. I can't think of any fast ways to detect collision between a green ball and the red line here.

I have thought of checking the color of the pixel every tick at the location of the ball, but this is very slow and the round ball will fill more than just the centre pixel. I have also thought about logging every single X, Z point that the curve drawer has inserted and then checking if the ball is near to the point, but this also seems like a bad method.

From a red curve drawn on to the screen by a user, what is the best way to detect whether a point is colliding with the red line? Shall I store every single point of the red curve or check the color of the pixel at the point to see if it is red or not?


texts: Instantiating, Inheritance, Objects and Children basics in Unity

texts:
First off, please understand I am horrendously confused with how to do things in Unity. I might not even be asking the right questions, I'll pose my problem and hope it shows my gap in knowledge.

For my game project (a clicker game), I have a several types of object for the player to interact with. Food, Training Dummies, Enemies etc. As per most games, I need objects of the similar type to have different parameters. eg. blue enemy does 1 damage, red enemy does 2. Unlike most games, I will only be showing one 'interactable' object per scene. once you defeat that enemy, it dies, you get experience and it respawns. once you've eaten the food, it vanishes and you get whatever bonus and then it restocks based on what you have in your inventory.

So, I'd made a base class Enemy (which is a unity script, right? which is just a c# class you can attach to a GameObject?)

Next step, adding my child game objects into the scene when I need them. I think this is where the confusion sets in.

So far I'd placed a GameObject in my scene, set it's layout etc and attached the enemy script to it.
my respawn mechanic (for a single enemy object repeating itself) was to access the canvasgroup component and set the alpha & interactivity off and then back on, the 'new' enemy would also have it's health refilled, the total updated, all inside a single script using one class.
I'm doing it in such a primitive way because I can't quite understand how to correctly create a new child object into my scene and interact with it.

if I make a c# script "BlueEnemyScript" inherit from script "EnemyScript", that's a "child object" in c#?

I create a GameObject (Blue_Enemy) and attach all the components to it including BlueEnemyScript c# script, then drag it into prefabs.

I then have another GameObject called EnemyManage that will instantiate the prefab via a script.

When I instantiate this prefab (is that a Child in Unity?), it will have it's own unique instance of BlueEnemyScript?

If I were to instantiate the non child Enemy, but change it's parameters as part of the method to instantiate it, wouldn't it have the same effect since it has a unique instance of the script?

Do I even need multiple instances because I'll only have one of the same object type active at a time? should I just swap which method inside the object script is being accessed?

Happy to have this question closed, I understand it's a mess.

I read some old questions but they haven't made it much clearer:

Inheritance Hierarchy and Design -- avoiding multiple inheritance
Trying to better understand Unity gameobjects


texts: Unity forward vector flips when upside down. Mario Galaxy style gravity, bad rotation?

texts:
This is a question that I think is best to explain visually, so I will do my best to be succinct here.

What I am trying to do:

Allow the player to run about a world that is spherical, not a flat object. The intended result is going to be much like navigating a planet in super mario galaxy.

My attempt at solving this problem:

Conceptually it is simple. I create a vector from the player to the origin of the planet/world, and use it as the gravity vector. This works great, I know the direction I need to fall towards.

The problem:

When trying to use unity's transform.forward vector, everything is fine until I move slightly off to the side and attempt to circle the planet. At about the south pole, the forward vector points to random places.
I believe this is because of how unity calculates the forward vector, but I don't know how it is done so I can't say.

Should I attempt to calculate it myself? Or should I just store a matrix for my object and do everything manually?

Below are images that hopefully shed some light.

In this image, the forward vector (red ray) points correctly in front. This is at the starting position of the object. The blue ray is the vector toward the planet center

After circling to the bottom of the planet, I just need to move slightly to the side, and the forward vector begins to circle about the blue vector

EDIT for code:

BaseObject class for objects that will react to planet gravity

public class BaseObject : MonoBehaviour {

    public GameObject planet;
    private float gravityConstant;

    public Vector3 TowardOrigin { get; set; }

    void Awake () {
        /// Store the gravity constant
        gravityConstant = Physics.gravity.magnitude;
    }

    void FixedUpdate()
    {
        /// Manually set the force of gravity to point towards the center of the planet
        TowardOrigin = transform.position - planet.transform.position;
        TowardOrigin.Normalize();
        Physics.gravity = -gravityConstant * TowardOrigin;
        transform.up = TowardOrigin;

        ChildFixedUpdate();
    }

    /// <summary>
    /// To be inherited and overriden by child objects
    /// </summary>
    public virtual void ChildFixedUpdate() { }
}

PlayerController class:

public class PlayerController : BaseObject {
    public float speed;
    Rigidbody body;

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

    public override void ChildFixedUpdate()
    {
        if (Input.GetAxis("Vertical") != 0 || Input.GetAxis("Horizontal") != 0)
        {
            Vector3 forwardMomentum = (transform.forward) * (Input.GetAxis("Vertical") * speed);
            Vector3 sideMomentum = (transform.right) * (Input.GetAxis("Horizontal") * speed);

            body.AddForce(forwardMomentum);
            body.AddForce(sideMomentum);
        }
        else
        {
            body.velocity = Vector3.zero;
        }

    }
}


texts: How can I generate random lakes and rivers in my game?


texts: Creating dependent values in the Unity inspector

texts:
I want to create a few values which will be dependent on each other. Specifically, I want total sum of few values always be 100 In unity inspector no matter how I tweak them.

E.G.:

int total = 100;

int one = 20;
int two = 30;
int three = 45;
int four = 5;

How can I make other values adjust automatically if I tweak one of them in Unity Inspector?


texts: How can I implement screen transitions like in the 2D Zelda games?

texts:
I want to implement a screen transition in the style of the 2D Legend of Zelda games (like this). That is, I'd the screen to remain static until the player moves to an exit, at which point the next screen smoothly scrolls into view as the old screen scrolls out of view.

How can I accomplish this?


texts: How to move one object to another object's position

texts:
So I'm want to move one game object (my player) to the position of another game object, on keyDown. I'm just not sure how to reference the position of the object which is where I want my player to move(or teleport) to.

I know a couple different was to move my player, but I don't know what variable or statement I would use to reference the other objects position.

(Also the thing I'm teleporting to is not moving). I really appreciate any help you can give me.

public class GetInCar : MonoBehaviour {
    public GameObject player;
    public GameObject car;
    //public Camera cam1;

    void OnMouseDown () {
        if (Input.GetKey (KeyCode.Mouse0)) {
            player.transform.rotation = car.transform.rotation;
            print("MovedToCar");
            GameObject.Find ("Player").GetComponent<CharacterController> ().enabled = false;

            //cam1.enabled = true;
        }
    }
}


texts:
I'm making a JRPG in libGDX, and I'm working with Screens. I have a main Screen called GameScreen, a screen for battles called BattleScreen and I want to make a screen for managing party members and items, as well as for shops. My question is, how can I draw one of those 3 screens without having to reload the whole game when going back to GameScreen.

GameScreen loads everything when Show() is called, so I'll have to save all information everytime I call another screen, so I can continue when I go back to GameScreen. This of course isn't good, and I'm looking for another way to draw a Screen over another one so that all vars wont be lost, or another solution.


texts: Verb+Noun Parsers and Old School Visual Novels

texts:
Hi
I'm working on a simple old school visual novel engine in Lua. Basically I have most of the code set up besides one important feature. The Text Parser.

Lets get into how words are generally structured.
In the screenshot I input the command "my wish is for you to die"

--How would a human understand this?

my = noun/object

wish = verb

is = connective_equator similar to =

for = connective_object (for all objects of ..)

you = noun/object

to = connective_action similar to do

die = verb

--the computer can then parse this and understand it like this (pseudo example)

my = user

you = get_current_label()

you = "Lost Coatl"

wish = user_command

user_command = for all_objects of "Lost Coatl" do die() end

execute user_command()

What other ways do videogames use text parsers, what would be the simplest way for a newbie coder such as myself?


texts: What's the appropriate way to define configuration settings of game objects for a proper code accessed via C++?

texts:
I defined a lot of configuration and settings of certain types of enemy characters inside header via #define similar to the following.

// --- RULES ---
#define MAX_INC_ATTACK_POINT 50
#define MIN_INC_ATTACK_POINT 0
#define MAX_DEF_PERCENT 0.1f
#define MIN_DEF_PERCENT 0.0f

#define PUNCH_ATTACK_POINT 12
#define PUNCHHARD_ATTACK_POINT 15
#define KICK_ATTACK_POINT 12
#define KICKHARD_ATTACK_POINT 15
#define COMBO06_03_ATTACK_POINT 20
#define COMBO06_04_ATTACK_POINT 5
#define COMBO06_04_01_ATTACK_POINT 15

#define START_MAX_HP 100
#define START_INCATTACK_POINT 0
#define START_DEF_PERCENT 0.0f
#define MAX_ULTIMATE 100

Anyway, c++ experts tend to not recommend to use global states or global variables at all (if necessary). There're some thoughts about global variables here and here.

Now I want to know what's the proper way to define these kind of values to be accessed via its own specific classes later?
Is that a bad design choice if I use like I did it currently?


texts: UniRX, how much of it should I use? for good optimization

texts:
I come from the Front End dev world and I'm taking my baby steps in Unity.

I'm already very familiar with RXJS and glad to see it being re-coded into almost every other big language (there's starting to be quite a few) :

Java: RxJava
JavaScript: RxJS
C#: Rx.NET
C#(Unity): UniRx
Scala: RxScala
Clojure: RxClojure
C++: RxCpp
Lua: RxLua
Ruby: Rx.rb
Python: RxPY
Go: RxGo
Groovy: RxGroovy
JRuby: RxJRuby
Kotlin: RxKotlin
Swift: RxSwift
PHP: RxPHP
Elixir: reaxive
Dart: RxDart

And as I discovered and as you can see, it is available in Unity-flavor.

here's a quick intro :
https://youtu.be/kFoBvjwzbNA

But not every framework or environment or every variable and event is necessarily improved by RX, or is it?

Since I don't quite understand how Unity operates internally (nor do I plan to do that fully, I have a game to make), I'd like to know is it a performance gain or a performance loss, to use UniRX to (for example) store every input my game might need into observables,

and then susbcribe to those observable versions of user Inputs wherever applicable in my C# scripts?,

or does the repeated use of the Update() method to listen to inputs in multiple scripts get interpreted somehow by Unity at compile to automatically optimize the built code and adding my extra RX step would just be a net loss?

What about game state, and, say I'm coding an RTS, unit states?

What about RayCast Hits, should I make those observable?

What UniRX usages are poor practice, and which result in performance gain/optimized code? (especially with my given examples in mind)

The obvious use-case is game UI, obviously, but disregarding that, what could I extend UniRx usages to?

[PS: Since UniRX is a relatively new topic here could someone with 3000+ points create the unirx tag and add it to my question please?]


texts:
screen=pygame.display.set_mode((500, 700))
Shape=['.....',
       '..O..',
       '.OOO.',
       '.....',
       '.....']
ShapeProperites={'x': 250,
                 'y': 50,
                 'Color':Red}

How can I convert this array in Pygame to a shape drawn on a screen with the properties from the dictionary? The list is meant to represent a tetromino. The 0's should be drawn as squares on the screen.


texts:
Hey guys :) Im currently developing a little rpg duengon crawler.
I really want to implement a local and an online multiplayer function, i know how servers are working and how to make them using sockets or kryonet.

But heres my question, i want that when someone, starts a local server in my game, that it starts an runnable jar file which includes the server, is that recommend or just stupid ? Should the server be included in the game or outside in an extra file ? What should i obverse ? :)


texts: How does Unity Inspector handle values changing during play without any thread-locks?

texts:
First of all, I'm a Java coder. Usually, when you write a game, you run it on thread different than the UI one like:

// pseudocode starts
new Thread(new Runnable(){
    @Override
    public void run()
        while(someVolatileBoolean){
            input();
            physics();
            graphics();
        }
    }
}

and then you declare some sort of listener for the input which usually works on application/UI thread so you need to mark it as volatile, atomic or perform a basic synchro using the synchronized keyword (depending on the situation).

Let's take a simple Unity script:

public class SomeMovementScript : MonoBehaviour {

    public Vector3 speed = new Vector3(0.1f, 0, 0);

    void Update () {
        this.transform.Translate(speed * Time.deltaTime);
    }
}

If we then play the game, the object starts to move with speed 0.1f.

Now, when the game is playing, we can change the speed variable through the inspector:

I thought from the UI coder point of view: I'm changing a variable, which is being read each frame by the game thread. How does this happen, that I don't get some sort of ConcurrentModificationException if there's no visible synchronization at all. The variable is public, not being cached in any way.

I know that this question should be asked on SO, but I thought that GD has more users specialized in Unity and it's mechanics.

I came up with immutability. Variable is considered thread-safe if it's state can't change. As components are immutable, and classes like Vector2/3/4 are immutable - it would work. But... You can make your own class [Serializable], mark their fields as public and the class is not thread-safe - but it is visible through the inspector.

How does Unity Inspector perform these real-time updates with all the classes you can think of?


texts:
I've started looking into using Assimp to load in dae collada files into my game.

I believe I've managed to load the file into aiscene.
I am using c++, OpenGL and SFML.

My problem lies with extracting the data from aiscene to use in my game.

My question:

What steps do I need to take to get my model on the screen after I have the data loaded into aiscene?

I don't even know where to start so I would be grateful for any tutorials or books showing this or simple examples?

Thanks very much!


texts: I'm trying to code a if statement in Algodoo that checks if an object has a certain value in a variable called id, and if it has the correct value, it will teleport it and anything with the same value in id to a specific part. How would I code this?


texts: reflecting objects by rendering them to the cubemap

texts:
I have 2 sphere objects and it isn't reflecting the other one. The picture is when it simply reflects the cube map but when I try to render to the cube map the spheres turn out black.
In camera class:
    void switchToFace(int faceIndex) // For Cube Map camera
    {
        switch (faceIndex)
        {
        case 0:
            m_pitch = 0;
            m_yaw = 90;
            break;
        case 1:
            m_pitch = 0;
            m_yaw = -90;
            break;
        case 2:
            m_pitch = -90;
            m_yaw = 180;
            break;
        case 3:
            m_pitch = 90;
            m_yaw = 180;
            break;
        case 4:
            m_pitch = 0;
            m_yaw = 180;
            break;
        case 5:
            m_pitch = 0;
            m_yaw = 0;
            break;
        default:
            break;
        }
    }

In main
static GLuint createEmptyCubeMap(int width, int height)
{
    GLuint textureID;
    glGenTextures(1, &textureID);

    glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);
    for (GLuint i{ 0 }; i < 6; ++i)
    {
        glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr);
    }
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
    glBindTexture(GL_TEXTURE_CUBE_MAP, 0);

    return textureID;
}
main()
{
// stuff
    glm::vec3 spherePositions[] = {
    glm::vec3(0.0f, 0.0f, 0.0f),
    glm::vec3(-1.5f, -2.2f, -2.5f),
    };
    // new cubemap
    Camera reflectionCamera(glm::vec3(0.0f, 0.0f, 0.0f));  // Camera position. Should be on ball

    GLint imageWidth, imageHeight;
    SOIL_load_image(faces[1], &imageWidth, &imageHeight, 0, SOIL_LOAD_RGB);
    GLuint newEnvironment = createEmptyCubeMap(imageWidth, imageHeight);

    GLuint FBO{}, DBO{};

    glGenFramebuffers(1, &FBO);
    glBindFramebuffer(GL_FRAMEBUFFER, FBO);
    glDrawBuffer(GL_COLOR_ATTACHMENT0);

    glGenRenderbuffers(1, &DBO);
    glBindRenderbuffer(GL_RENDERBUFFER, DBO);
    glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, imageWidth, imageHeight);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, DBO);

    glViewport(0, 0, imageWidth, imageHeight);

    for (GLuint i{ 0 }; i < 6; ++i)
    {
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, newEnvironment, 0);

        reflectionCamera.switchToFace(i);
    }

    glBindFramebuffer(GL_FRAMEBUFFER, 0);

    glViewport(0, 0, WIDTH, HEIGHT);

    while(window.isOpen() // SFML)
    {
        glBindVertexArray(sphereVAO);
        for (GLuint i{ 0 }; i < 2; ++i)
        {
            model = glm::mat4();
            model = glm::translate(model, spherePositions[i]);
            glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model)); // modelLoc is location of uniform model
            glActiveTexture(GL_TEXTURE0);
            glBindTexture(GL_TEXTURE_CUBE_MAP, newEnvironment);
            glDrawElements(GL_TRIANGLES, numberOfIndexes, GL_UNSIGNED_INT, 0);
        }
    }
}

The sphereVAO is simply the Vertex Array Object for the sphere and here we bind the texture to the newEnvironment which is supposed to reflect the other object in spherePositions[i]
The picture above is the sphere Position at (0, 0, 0).
But the code results in this:


texts: Pathfinding in Isometric Phaser with Tunnels

texts:
I want to create a 2D isometric game. Currently I'm looking and testing Phaser game engine with isometric plugin. Almost everything at the moment looks possible except few things. I will create a bridge/tunnel in my map so entities could go through tunnel and on the bridge. The simplest implementation of this simulation will be enough.

What kind of trickery I have to use to implement pathfinding algorithm in this situation? And is this event possible in 2D isometric games? What are your suggestions about this type of game overall and my problem?


texts: Distance between two points with staggered isometric coordinate system

texts:
I don't think this exact question has been asked already (I've done a lot of searching but come up empty).. I am trying to work out what would be described as the 'L0 Tile' distance between two points in my game in tiles.

My coordinate system is as below:

And this is the effect I'm looking for when calculating distance from a central point:

The problem is I keep running into boundary conditions when trying to come up with a better solution than just 'walking' between the two positions and counting the steps.

The code I have at the moment only works if the direction between the two points is perfectly vertical, horizontal or diagonal:

if( fIsVertical )
{
    // Vertical distance calculation

    nDistance = nYDifferenceTiles / 2;

}
else if( fIsHorizontal )
{
    // Horizontal distance calculation

    nDistance = nXDifferenceTiles;
}
else
{
    // Diagonal distance calculation (slightly more headache-prone)

    bool fIsPerfectDiagonal = false;

    if( nYDifferenceTiles % 2 == 0 )
    {
        // Irrespective of W or E path these values are always the same

        if( nXDifferenceTiles * 2 == nYDifferenceTiles )
        {
            fIsPerfectDiagonal = true;
        }
    }
    else
    {
        // Values for X when Y is odd are slightly different..

        if( fNorthWestOrSouthWest )
        {
            // Handle the West paths
            if( nXDifferenceTiles == ( nYDifferenceTiles - std::floor( nYDifferenceTiles / 2.0 ) ) )
            {
                fIsPerfectDiagonal = true;
            }
        }
        else
        {
            // Handle the East paths
            if( nXDifferenceTiles == ( nYDifferenceTiles - std::ceil( nYDifferenceTiles / 2.0 ) ) )
            {
                fIsPerfectDiagonal = true;
            }
        }
    }

    // Now we've calculated whether we are on a perfect diagonal
    // line from the origin we can decide how to calculate the distance

    if( fIsPerfectDiagonal )
    {
        // If exact diagonal this works well
        nDistance = std::max< int >( nYDifferenceTiles, nXDifferenceTiles );
    }
    else
    {
       // ? - problem
    }
}

So in the diagram below, the green tiles are correctly calculated but for the red ones I have to fall back to my quick and nasty code to walk the distance.

Despite trying a good few things I'm still no closer to having a simple and quick way of calculating the distance. I'm sure this problem has to have been addressed before and that I'm missing something probably obvious. Please help! :)


texts:
I have a side scroller game made in OpenGL, and I'm trying to center the player in the viewport when he moves. I know how to do it:

cameraX = Width / 2 / TileSize - playerPosX
cameraY = Height / 2 / TileSize - playerPosY

However, I have a problem. The player and "camera" move, but the player moves faster than the "camera" scrolls. So, the player can actually move out of the screen.

Some code, this is how I translate the camera:

public Camera(){
}

public void update(Player p){
    glTranslatef(-p.getPos().x - Main.WIDTH / 64 / 2, -p.getPos().y - Main.HEIGHT / 64 / 2, 1);
}

Here's how I move the player:

public void update(){
    if(Keyboard.isKeyDown(Keyboard.KEY_D)){
        this.move(MOVESPEED, 0);
    }

    if(Keyboard.isKeyDown(Keyboard.KEY_A)){
        this.move(-MOVESPEED, 0);
    }
}

The move method:

public void move(float x, float y){
    this.getPos().set(this.getPos().x + x, this.getPos().y + y);
}

And then after I move the player, I update the player's geometry, which shouldn't matter.

What am I doing wrong here, this seems like such a simple problem, yet it doesn't work!


texts: I have created a gameObject called "Sphere". After 5 secs the gameobject starts rotating. Along with the rotation I need to emit partical from the object. How can I do this?


texts: Why my code changes don't take effect in editor UE4?

texts:
I have a plugin in my project to move around stuff with gizmos(much recommended tool, by the way).
It has quite a few blueprint functions that I use.
I would like to add some functionality to it, though.
So I opened up the related cpp files, namely TransformerPawn.cpp and had a look around, and found a few starting points where I can add GEngine debug messages, to see what is going on...
I chosen a few blueprintcallable functions and went ahead by:

added those debug messages, but they do not take effect at all...
added some other code(move the actor 1000000 units away in tick), but still nothing...
commented out code, but blueprints kept working...

I added the Engine.h header in my cpp. I also tried rebuilding the solution...
And yes I hit compile every time... :D
To test things out I added an empty C++ actor, and added a blueprintcallable function to it to print out debugmessages(GEngine), and it worked as it should be... I can see the debug messages...
EDIT: I use Rama's Victory plugin a lot. I added a custom BP node there, recompiled it, and it didn't work...
But the new plugins available message popped up in the bottom right corner!
So I disabled, and enabled it and it did work. I could see my new BP node. :)
Later on I test it with the above asset and update the post.


texts: Unity 3d 4.6b New GUI system doesn't take touch when already a touch event is occurring in 3d scene

texts:
I know this is beta version but..

I have a Canvas->Button which works fine when I tap it normally.

I have a joystick in my scene which is drawn by separate camera other than mainCamera.

now, while i am operating joystick without leaving it, if I tap on he Canvas->Button - it does not respond. When I lift finger from joystick and tap on it, it works fine.
Same goes for another Canvas->Toggle control.

It has something to do with the layering or anything else...I'm not sure?


texts: How to fill a 2d array with elements of a 1d List

texts:
I have a 2d array for 'Slots' in my inventory screen (slot width: 150px; total slots is based on width and height of inventory panel currently at 1500x600). The slot holds a reference to the pickupObjects that the player has picked up and added to the inventory (these items have been stored in a list).

So I try to make a method which fills the slots using the List of pickupItems. But the problem is that when I iterate through the inventory it will reach a number higher than the width of the first row of slots. I feel like the answer can be simple, but I just can't seem to figure out how to iterate through them and place it into the 2d array. I've solved this very issue in the past but can't remember how I did it.

Here's the code I have for creating the grid of slots, and then the method for putting the inventory in there (even though this method is pretty much empty right now as I am completely out of ideas):

Any help would be massively appreciated. Thanks

void CreateSlotLayout()
{
    panel_rt = GetComponent<RectTransform>();
    panelWidth = panel_rt.rect.width;
    panelHeight = panel_rt.rect.height;
    slotCount_x = (int)(panelWidth / slotWidth);
    slotCount_y = (int)(panelHeight / slotHeight);
    slots = new Slot[slotCount_x, slotCount_y];

    for (int y = 0; y < slotCount_y; y++)
    {
        for (int x = 0; x < slotCount_x; x++)
        {
            Slot slot = Instantiate(slotPrefab);
            slot.transform.SetParent(transform);
            slot.GetComponent<RectTransform>().anchoredPosition = new Vector2(x * slotWidth, -y * slotHeight);
            slots[x, y] = slot;
        }
    }
}

public void FillSlotsWithInventory(Player_Inventory playerInventory)
{
    for (int i = 0; i < playerInventory.GetPickupsList().Count; i++)
    {
          //something like....
          //slots[i?,i?].FillSlot(playerInventory.GetPickupsList[i];
    }
}


texts: What's the best place to showcase my pixel art?

texts:
I recently started learning spriting/pixel art to help propel my game development endeavors and I've gotten to the point where I'd like to start sharing it for comments, critiques and other feedback.

I've got a pretty good awareness of some art sites out there but none of them have really struck me as ideal so I'm looking for suggestions from you guys!


texts: How to colorize certain parts of a model - like RTS games have those team colors?

texts: I am in a need of implementing something we see in RTS games: team colors. Basically, I am looking for a way to colorize certain parts of a model. How would I achieve this? I have no idea where to even begin. Do I need to make some adjustments to the 3d model first?


texts: What would encourage a player to play the both the combat and building aspects of my game?

texts:
I have been planning all of the features for my game idea. It is an RPG fantasy free roam game, in which the main focus of the game is on combat and adventure, though I also want to add in the ability to be a carpenter, shop keeper, brick mason, and/or cook.

Though this is all well thought out, another thought has cane to mind: Why would anyone actually follow through with the average life-style or even begin to think of living a normal life? I thought of how an experienced adventurer might "retire" and go into business for themselves, but what could be some other things that might make a player go for the worker's lifestyle?


texts:
I'm a little stuck on the logic to how i use my path finder efficiently in my game.

This is basically how the game works:

Building generates goods "Factory" > AI transports goods to "Warehouse" on path tiles >
  Warehouse receives goods > AI goes back to Factory.

Now im wondering how I use my path finder efficiently so its checking the "Factory" is connected to a warehouse by path.

So heres my logic im wondering if it can be improved:

User places factory down > game checks path.

Result 1: No path found> Keep checking every frame..

Result 2: Path found > Store path stop rechecking every frame.

The two problems i have is: Well checking every frame is going to hurt the game's performance, secondly if I stop rechecking - it won't know when a faster route may become available or unavailable =/

Is my logic correct or is there a better method?


texts: How important is c# for game programming?

texts:
Possible Duplicate:
  Does C# have a future in games development?

Presently I'm learning c++ and in starting stage of opengl . My ultimate goal is to be game programmer. I want to stick with c++ but my doubt is how important is to learn c# or XNA? What's their future compared to c++ in game development? What about the career prospective?


texts: How to test an android game made in Unreal Engine 4

texts: I have made a android game in unreal engine 4 version 4.12.4 and I want to test it on a real android device and i do have an android tablet but i don't know how to get the exported project onto the tablet for testing so can someone tell me please?


texts: Render problems (black, purple and blue effects) in old GPU and Unity3D 5.6 project on Unity 2018

texts:
Well, I have a PC that has a GPU from 2009, and now I have some problems with a fork.

The project was on Unity 5 (2015) and I have upgraded it to Unity 2018.1.0, without any problems.

But some times, when I updated scripts or changed something in the scene the problem appeared.

Is a rendering problem that only occurs in DirectX 10 (my GPU is a GeForce 9600 that supports up to DX 9.0c, so I don't underatand how this is capable of running DX 10). Because, if I run with -force-opengl all runs fine.

I can go back, but the problem is in the Library folder, because if I use "Assets > Reimport all" or I remove this folder, the problem dissapeared (before, not now).

This is the problem:

https://i.gyazo.com/eb9199b8590fddf416a8323331e20856.mp4

Researching I have worsened it:

https://i.gyazo.com/dbc5d5f19a845ec77e54d64e3cba85cc.mp4

https://i.gyazo.com/939c8fdf5fd4d68e434958e93e68da14.mp4

As you can see, sometimes the problem is blue and purple, and other times is completely black.

The last problem remembers me to: https://forum.unity.com/threads/black-textures-on-some-devices-android-versions.195328/

I have builded the project and there isn't any problem, so the problem is somewhere in the Editor or with a UNITY_EDITOR preprocessor directive.

I don't know what I have to do to fix this. Is like this is very random.

Any help?


texts: How to create a user-friendly magic spell system?

texts:
I'm designing a small 2D top-down open-world survival-ish game with a magic spell system. The way it works so far:

The player receives a "wand" at the beginning of the game
As the player encounters new items and enemies, they gain spells to help them use those items/defeat those enemies

The problem I'm having is designing a way to cast the spells. At first, I just bound different spells to keys 0-10, but very soon the number of spells overwhelmed it, and you also have the problem of lower level spells not being used in the late game but still being bound to the most useful keys.

So, what's the best way to make a user-friendly spellcasting system? I can overhaul the way magic works in my game if needed.

EDIT: Just to clarify, I'm developing for PC in real time with large variation in spell type and purpose, although this question should apply to all platforms.


texts: How can I find the distance from bezier curve anchor points to control points for a circle approximation and their positions

texts:
From the image below, I have represented a circle by a closed bezier curve made of two cubic bezier segments. I am aware that a bezier curve cannot represent a perfect circle.
How can I calculate the distance from the anchor points to the control points based on the distance from both anchor points to give a close approximation of a circle?

Also how can I use the calculated distance to find the positions for the control points?


texts:
To teach myself basic game programming, I am going to program a clone of Pong. I will use the Observer design pattern, with an interface between the input and the game engine. However, I'm not sure what the interface should do. One idea I had was for the input interface to tell the game engine that (e.g.) the screen was clicked, then to let the game engine decide what to do with that information (shoot a bullet, for example). Another idea I had was for the input interface, having caught the mouse click, to tell the game engine to shoot a bullet.

Which method would be better for me to use?


texts: How can I build Goal Oriented Action Planning within an Entity Component System?

texts:
I've been creating an interactive fiction game in javascript that uses an entity component system as described here. The problem I've encountered is in developing the AI system for the game. Ideally, I'd like to use Goal Oriented Action Planning (GOAP) for the AI. Unfortunately, this seems to be at odds with using an ECS, largely because the state pattern doesn't seem to work with such entity frameworks.
Here's a simple example of a series of actions that might be taken to achieve the goal of answering a phone within the game.
Goal: answer the phone when it rings
Walk to desk -> sit on chair -> pick up phone
The route taken to answering the phone might end up differing based on the presence of numerous other preconditions. Maybe there's an obstacle in the way, or perhaps the actor no longer has a chair to sit on. In addition to this, the actor may be given other priorities in a queue.
At the moment, even simple goals are causing headaches with a lot of conditional checks.
I'm wondering, it it possible to implement something like GOAP within such a game, and how would I go about accomplishing this? Or should I give up on using GOAP for some alternative AI system?