texts:
I've been creating a small little mobile game on and off for a while now.

Having got all the game mechanics in place I'm now trying to figure out how to organise these into levels to get satisfying pacing.

Are there any good guidelines for this? Or articles on it?

I've got a few variables that I can play with that can make the game more interesting and varied for example:

Number of entities to deal with
Number of kinds of entities
Directions they come from.

I just don't have much of a clue how to pace it.


texts: What is Vector Projection and what is it's use in games?

texts:
Couldn't find a clear enough answer on Google.

I know what vectors are. But what does it mean to project a vector onto another, and what is it used for in games?


texts:
I have this line of code

void Update () {

    float alVal = 0.0f;
    float damping = 1f;
    alVal += damping * Time.time;
    GameObject text2 = new GameObject();

    text2.AddComponent (typeof(GUIText));
    text2.guiText.color = new Color (1f,1f,1f);
    text2.guiText.name = "name";
    text2.guiText.text = "YOLOMF";
    text2.guiText.pixelOffset = new Vector2 (100, 100);

    text2.guiText.color = new Color(1f,1f,1f,alVal);

    Debug.Log (alVal);

}

I want to create a SINGLE TEXT, but I guess the Update() function keeps on making more.

I need that SINGLE TEXT to do an animation of Fade-In that's why it is in Update()


texts: Recommended way to handle sprite assets for different screen densities (Android)

texts:
I am currently working on a 2D game for Android. All of the images that I render were created as SVG's and then exported to PNG's which I have placed in my assets directory. These images are also all sprites that I render using a sprite batcher.

My question is around using different versions of the sprites for devices with different densities. I know that when developing a traditional android app you could place separate directories for separate density levels inside of res and then place the correctly sized versions of the images in question in these sub-directories of res.

What is a good approach when dealing with sprite images in the asset directory? Should I just have one copy of the sprites at a really high density / resolution that I use for everything and I just render them on a coordinate system that is independent of screen size or should I resize the image based on screen density before I process it to create all my texture regions? Or is there another solution entirely?

Currently I have one high resolution set of sprites that I use for everything, it just seems wasteful and inefficient for the lower density devices.


texts: How detect collision between two bodies?

texts:
I'm using LibGDX with Box2D and I've two bodies. I just need to know that they have collided.

So, I just need a boolean output.

Example:

if (bodyA.collision(bodyB) == true) {
   // Do something
}

How can I do this?

If it is too complicated, can I detect if two PolygonShape intersect?


texts:
We are currently working on a 2D platform game, all lot of the game elements have been created and designed. But now it is time to design all the levels.

What I am wondering is: Are there any tools which simplify level design, we prefer designing in basic wireframes, so no actual graphics yet. It would also be neat if the tool would allow layering specific groups;

Background
Platforms
Enemies

I have thought of tools like Visio or Omnigraffle but these aren't specifically meant for game design.


texts:
I've followed a tutorial that uses the XNA 4 SkinnedEffect for my animation on that model . How can i also make a shadow for my SkinnedEffect model ?

Thanks !


texts: Caching the profile image in Unity using Facebook SDK

texts:
Recently for my new game i am implementing the Facebook Login. Currently when i login i show the Profile image to the user.

void UpdateUserNameAndImage(bool isLoggedIn) {
    if (isLoggedIn) {
        FB.API ("/me?fields=first_name", HttpMethod.GET, UpdateUserName);
        FB.API ("/me/picture?type=square&height=50&width=50", HttpMethod.GET, UpdateProfileImage);
    } else {

    }
}

private void UpdateProfileImage(IGraphResult result) {
    if(result.Texture != null) {
        facebookLogin_button.GetComponentInChildren<RawImage> ().texture = result.Texture;
    }

}

The code is normal. I call it after there is successful login from the user.

The problem:
Well the problem is that there should be internet for the profile picture to appear. There must be a call made to the graph api for the image everytime.

I want to show the profile image of the user when there is no internet too.

So i am looking for some kind of cache that Facebook SDK use for the logged in profile that i am not aware of.


texts:
How can I make extremely huge terrains in Unity? It seems like I can set width and length to large values. But the Heightmap resolution only goes up to 4097 and the Detail resolution only goes up to 4048.

Any ideas?


texts:
I am writing a game in Java, I have this long method to move GameBodyObject towards the point:

public boolean moveTowardsPoint(Point p, double stepSize, double minDistance, ArrayList<GameBodyObject> objects,  boolean shouldStepInto) {
    double dx = p.getX() - getPosition().getX();
    double dy = p.getY() - getPosition().getY();

    boolean isClose = true;

    Point lastPosition = getPosition().clone();

    if(Math.sqrt(dx * dx + dy * dy) > minDistance) {
        isClose = false;
        setRotation(Math.atan2(dy, dx));

        // Though the sqrt is expensive operation
        // We check first without using sqrt
        if (shouldStepInto && Math.abs(dx) + Math.abs(dy) < stepSize) {
            if (Math.sqrt(dx * dx + dy * dy) < stepSize) {
                getPosition().setX(p.getX());
                getPosition().setY(p.getY());
            }
        } else {
            getPosition().setX(getPosition().getX() + (stepSize * Math.cos(getRotation())));
            getPosition().setY(getPosition().getY() + (stepSize * Math.sin(getRotation())));
        }

    }

    for(GameBodyObject obj : objects) {
        if(!obj.equals(this)) {
            if (checkCollision(obj)) {
                setPosition(lastPosition);
                return isClose;
            }
        }
    }

    return isClose;

}

checkCollision checks if there is a collision and if yes it returns true otherwise it returns false.

Now if GameBodyObject collides it stops. What if I want this object to walk around the collider? simply to find a path around when the collision occurs. (I don't want to implement any A* or other pathfinding algorithms btw)

Is it possible without pathfinding?

I was thinking that if collision occurs I try to move more to the left, if the collision occurs again I try to move a bit to the right, and then move a more than a littlebit left, and if the collision doesn't occur I move to that direction. But that's bruteforce and very inefficient.

IMPORTANT EDIT:
ALL my GameBodyObjects are circles with getRadius() and getPosition().getX(), getPosition().getY()

EDIT

I've tried to calculat normal vector of vector pointing from me (gameBodyObject1) and the colliding gameBodyObject2. Then I moved towards that normal vector. I got a jiggling bouncing effect which I don't want. The bouncing effect appeared when there was a multiple colliding objects. After moving by the normal I could walk through the objects which is also not wanted effect. Maybe I should check if that new movement creates a collision.


texts: Can flixel or a similar engine be used with reddwarf server?

texts: I like the sgs/projectdarkstar or now known as reddwarf server for a back end game server.  However I am looking for a good front end, preferably 2D.  I was thinking of something such as flixel.  I know there is an AS3 library available for reddwarf, so I am hoping someone already has connected up flixel or a similar engine?   Or if you have a recommendation for another easy client side engine that will connect to reddwarf?


texts: (Unity) Is there a way to automatically create a material for each texture and assign the texture to it?

texts:
I have imported hundreds of textures in my Unity project, and I'd like to create a material for each of them. This would obviously take a lot of time, so how would I go about doing this automatically?

These are just basic textures that I want to assign to albedo on the standard Unity 5 shader. No need for normal maps.


texts: Empty game object (child of player) not changing position correctly when key pressed

texts:
I've made an empty game object which is the child of the player. It is by default on his right side and following his every move, and I want to make it so that every time a directional key is pressed (WASD) it changes position and stays there. But the way I've made it, it's not working as intended and seemingly goes to random positions every time. Here's the script:

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

public class ChangePositionAccordingToKey : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.W))
        {
            transform.position = new Vector3(-0.58f, 3.09f,0);
        }
    }
}

This is probably a dumb question but I am new to coding so I can't figure it out. Any help is greatly appreciated


texts: Apparently, Unity decided to import a bunch of things I already had

texts: I am getting lots of errors ever since Unity decided to reimport plugins and Unity assemblies that were already present in my project. I am not sure what I can now do, what folders to delete to fix this issue, etc. Is there any simple solution to fixing all of these problems? I cannot even click play in the Unity Editor now.


texts: In pixel art, should i keep the same color palette for every sprites?

texts:
The question may sounds weird (and very noobish but i'am :p) but i can't find any answer. When making pixel art, it is often said that a color palette could be 2, 4, 8, 16 or even 256 colors, through it is not recommended. When it comes to the palette choice, is it for a single sprite (like a character, and another palette for the landscape for example) or for an entire game (and in this case i must stick to the same palette for every sprites) ?

Honnestly i think it is for an entire game, but my mind is stuck with the second question implied by this answer: how could i do everything (characters, trees, rocks, explosions, sky...) with only - let's say - 8 colors ? All my sprites looks flat because of this, i can't find a suitable color to make a nice shading.


texts: Controlling loop frequency in a Coroutine

texts:
I want this coroutine to execute continuously and change the colors. But right now it just waits 1 second at the start and then loops the Coroutine very fast.

So my question is how can I loop the Coroutine every 2 seconds.

public class control : MonoBehaviour
{
    public bool gravity = false;
    public bool m_isRunning = false;
    public SpriteRenderer m_spriteRenderer;
    private Rigidbody2D rb;

    private void Update()
    {
        if (gravity)
        {
            rb.gravityScale = 1;
        }

        StartCoroutine("Changecolor", 3f);
    }

    private void Start()
    {
        m_spriteRenderer = this.GetComponent<SpriteRenderer>();
        rb = GetComponent<Rigidbody2D>();
    }

    private IEnumerator Changecolor() <--- this coroutine
    {
        yield return new WaitForSeconds(1);

        int random = Random.Range(1, 4);
        if (random == 1)
        {
            m_spriteRenderer.color = Color.blue;
        }
        else if (random == 2)
        {
            m_spriteRenderer.color = Color.red;
        }
        else if (random == 3)
        {
            m_spriteRenderer.color = Color.green;
        }
        else
        {
            m_spriteRenderer.color = Color.yellow;
        }

        this.StartCoroutine("Changecolor", 3f);
    }

    private void OnMouseDown()
    {
        gravity = true;
    }
}


texts: How can I keep the clicked point under the mouse when rotating? (GLM)

texts:
I have a spherical mesh of radius 1, centered at (0,0,0) in world coordinates. I want to rotate the sphere so that the clicked point remains under the mouse at all times. However, I cannot find an algorithm that does this. The clicked point always drifts away from the mouse. My current algorithm does the following:

Cast a ray to a sphere of radius 1. Find intersection point in world coordinates (Pa).

After the mouse is moved, cast another ray and find a new intersection point. (Pb) since both those 3D points are on a sphere of radius one, centered at the origin, they should have length = 1 but just in case I normalize them both.

Find the rotation axis by doing Pa x Pb. Normalize the resulting axis

axis = glm::cross(Pa,Pb);
axis = glm::normalize(axis);

Find the angle by doing arccosine on the dot product

float angle = glm::acos(glm::dot(Pa,Pb));

Build a rotation matrix from the axis and angle

mat4 rotation = glm::rotate(glm::degrees(angle),axis); <-- This was the mistake glm::degrees is not needed

Multiply the existing model matrix by that calculated matrix:

modelMatrix = rotation*modelMatrix;

The rotations are correct but the clicked point does not stay under the mouse (I am checking by drawing a black square point on the sphere texture when the drag starts). If I click and drag to the right, the initially clicked point drifts to the left (lags).


texts: How do I measure the bounds of a string in PyGame?

texts:
I am trying to position some text on my screen using pygame, and knowing the size of the string would help.

When using C# and XNA I could use SpriteFont.MeasureString("Hello World") to get the size of the rendered string.

Is there any way to do something similar in pygame?


texts: Data visualisation tool based on games played by user

texts: I am a complete beginner in android development and for self-learning purposes thinking of creating a visualisation tool where different progress graphs of user's high score vs time or latest scores among all games will be displayed. The game in observation can be any game selected by user from the list of all games played by him till date. I just want to know is this possible to do in google play games API? If yes how can I do so? i.e. displaying high score or latest score from any game played by him till date?


texts: HLSL: how to get/set effectvariable to an array of structs with Direct3D10

texts:
HLSL Code:

//Lights
struct Light
{
    float3 pos;
    float3 dir;
    int type;
} m_aLights[3];

How can I get/set an effectvariable to m_aLights with Direct3D10?

Thanks


texts:
I made a post yesterday to see if anyone could understand my problem.

However I did not receive much guidance, probably because my question was not clear.

I have worked on it a little more and discovered the actual issue and now have a clearer picture of what is causing the problem.

As you can see from the image, the boxes are projected correctly along their appropriate axis (all components labeled 1 are from the main white box 1 and vice versa).

The problem comes when the box is rotated. (See image 2). Box 1 has been rotated but the corner (projection?) in green clearly does not match the shape of the rotated box 1 and is much much closer to box 2 than it should be. The axis projections have changed and axis 1 is on the far left but axis 3 has gone?

THE CODE CAN BE SEEN ON MY PREVIOUS POST
Separating Axis Theorem Issue

Thank you! ;D


texts: I made a model of a staircase in blender and loaded it into unity. Now my player cant go up the stairs while it can walk up a slope just fine. I have tried puting the stepOffset at different levels,


texts: Shader | Special Effect - Unit selection

texts:
I would like to know how the shaders used to show which unit is selected are made. Here is an image to illustrate.

How the merge effect of the blue circles can be achieved ? I didn't found any explanation concerning this effect. I know that to project those texture I can develop a decal system but I don't know how to create the merging effect.


texts: glCreateShader causes segmentation fault

texts:
I can't create a shader when trying to use shaders with sfml. The function glCreateShader(GL_VERTEX_SHADER); causes a segmentation fault. At first I googled it and found that it does that when the program does not have an opengl context. I tried SDL first but the poor documentation and "look at the header to know what to do" made me go for sfml

the code that causes the seg fault is bellow

    sf::Window App(sf::VideoMode(800, 600, 32), "SFML OpenGL");

// Set color and depth clear value
glClearDepth(1.f);
glClearColor(0.f, 0.f, 0.f, 0.f);

// Enable Z-buffer read and write
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);

// Setup a perspective projection
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

GLuint vertShader = glCreateShader(GL_VERTEX_SHADER);

    //...

I'm including glew, gl.h, sfml-window, sfml-system, using opengl 2.1 on gcc linux.

What is missing?


texts: How to create OpenGL (ES 1.0) texture programmatically?

texts:
I need to draw inside a buffer and then upload it as texture to OpenGL. So basicaly unsigned char* buffer and then call to glTexImage2D().

I will be using Marmalade mobile SDK and OpenGL ES 1.0.


texts: How can I add velocity to the standard CharacterController?

texts:
I have FPS controller from standard asset.  After a long trial and error I figured that CharacterController doesn't respond to AddForce.

So, I have this trigger in the scene which I would like to throw FPS controller upwards.

Now, I know that I need to replace AddForce with adding velocity to the player. How to do that?

I need to use FPS controller component for velocity and add Vector3.up.
So, every game object other which will enter the trigger, will get upwards velocity.

void OnTriggerEnter(Collider other)
{
    other.attachedRigidbody.AddForce(Vector3.up * 100, ForceMode.Impulse);
}


texts: Detect walking on floor - works partially

texts:
I have a set of Gameobject blocks that form a floor with Box Collider and a GameObject with a Box Collider in it.

My first hunch detecting hitting the floor was:

void OnCollisionEnter2D(Collision2D collision) {
    print ("Enter: " + collision.gameObject.tag);
    switch (collision.gameObject.tag) {
        case "Floor":
            isOnFloor = true;
            break;
    }
}

This works well. However, when I want to check whether he left the floor (falling):

void OnCollisionExit2D(Collision2D collision) {
    print ("Exit: " + collision.gameObject.tag);
    switch (collision.gameObject.tag) {
        case "Floor":
            isOnFloor = false;
            break;
    }
}

The GameObject Drops down as soon as I move a little, as I get the OnCollisionExit2D method...

How do I create a constant movement on a floor, and invoke "falling" only if I completely leave it?

Thanks!


texts: Why is my FPS Camera in the Wrong Position by Default?

texts:
I'm using Unreal 4.2, and somewhere a long time ago I must have messed up settings.  I'm trying to mess with a first person shooter, so I create a new project, using the first person template.  When it opens, this is what my character looks like in the viewport.
When I play the game, it looks like this. Clearly the camera position is messed up or something, because I know it's not supposed to show that much of the characters arms, and it looks wrong.  How do i reset the settings, or fix this?  I'm not even sure how i accomplished this. It does this every time I make a project with this template.  Thanks.


texts: Unity's "Stats" window displays bizzare number of triangles and vertices

texts:
In my Unity scene I have:

7-8 Barrels (with lids) each at about 2-400 triangles.
4 planes, each at at the very most 200 triangles
camera, 3 lights, a FPS controller

When I turn on the "Status" button in the lower left view port, it reports "14.1K triangles and 12.k vertices":

I've double checked everything, there's no way the elemens in the scene can amount to so many triangles. The barrels in both Blender and Unity report having the number of triangles I've specified above:

Here's a Blender screen shot:

And here's one from Unity:

I've also checked the Hierarchy panel to see if I haven't accidentally duplicated stuff which might get to be on top of stuff (such as 100 barrels all in the same position so as to look as if there's just one there), and this is not the case.

So my question is: am I misinterpreting the Unity stats window? Is it a bug in the reported triangles count there? Or am I just completely missing how all this works ?


texts: Good Configuration Manager System Design for medium-large sized projects?

texts:
I've create smaller games which simply needed a class which basically opens an INI file (with feather-ini-parser library) with config values for the whole game (rendering ops, music, bindings).

But I want to go to medium-larger projects and my current configuration managing system I used earlier will be getting more complicated when my engine grows. I need a new config manager system and I tried to research but found nothing. My current config manager for 'mid-large games' is this:

The ConfigManager class interface:

    class ConfigManager
    {
    protected:
        class INIFile
        {
        protected:
            std::string id;
            ini_t ini;
        public:
            INIFile(std::string &id, Poco::Path& filename);
            ~INIFile();

            void Destroy() { delete this; }
            std::string& getId() { return id; }
            ini_t& getINI() { return ini; }
        };

        typedef std::vector<INIFile*> INIFiles;
        INIFiles files;
    public:
        ConfigManager();

        bool openConfiguration (Poco::Path& filepath, std::string& id);
        void closeConfiguration(std::string& id);

        void flushConfigsToDisk();

        void getConfiguration(Ogre::String &id, ConfigModule& mod);
        void setConfiguration(Ogre::String &id, ConfigModule& mod);
    };

ini_t is a typedef of an INI Reading/Writting library (feather-ini-parser) this class is instanced in the main Engine class (avoid Singleton use), id is the unique identifier to the file opened like "Input", "MyGameCfg", "Rendering", etc. the ConfigModule is a "section" from the INI file opened and it's structure is:

    class ConfigModule
    {
        friend class ConfigManager;

    protected:
        optValuesVector keyValues;
        Ogre::String section;
        bool is_empty;
        bool nominal;

    public:
        ConfigModule();
        ~ConfigModule();

        Ogre::String getOptionVal(Ogre::String& key);
        Ogre::String setOptionVal(Ogre::String& key, Ogre::String& val);

        bool is_empty() { return is_empty; }
        bool status() { return nominal; }

    };

ConfigModules are "wrapped C++ INI sections" and stored in specific game classes like Input, GameLogic, Rendering classes. Instead to invoking an instance of the ConfigManager every time to get an setting every time, the ConfigManager is ONLY invoked when some of the game classes needed to write configurations and re-parse the config file with the new values.

My Question is: Is this a good approach (at least I feel this system has it's flaws, probably change configuration formats from INI to Lua ) to handle multiple configurations in large games? or there is another better design I can follow?. Thanks.


texts: Alternatives to storing all my entities in an SQL database

texts:
I've been trying to build my entity system based on pure SQL data storage as explained in this post series. The idea is that every entity or component is stored in an SQL table. I created my framework to manage that, only to realize that many SQL queries took more than 10ms, which is unsuitable for use in a game loop.

I first thought the delay was I/O-bound, so I created an in-memory MySQL cluster. This was better, but still not real-time enough for a game loop.

Has anyone built an SQL-based entity system? If so, how did you manage to keep query times manageable?

If an SQL database isn't feasible for performance issues, what data structure could I use to retain the entity system idea and the possibilities of direct SQL requests on components?

I've heard of many MMOs running on SQL. Do they use it for only part of the data or a full entity system? How to separate database-stored and classical memory-stored structures in that case?

Edit for clarification: Yes, all game data is stored in the database. If say I run my physics system it will first get data from SQL, then do its stuff, then insert the updated data back to the database.


texts: Unity C# GameObject Clones Sharing the Same Script When I Don't want them to

texts:
I've been having issues with a game I've been working on for a while. It's a pretty big project. I'm having some issues with two tree prefab game objects sharing code, where I don't want them to.

When the player presses E while facing them, they start searching the tree for items like apples. It was all working well, until I added another tree. Now, when I search one tree, it searches all trees in the scene. Obviously, I don't want that to happen.

I have provided my code, below. What am I doing wrong?

public class Search : MonoBehaviour
{
    public List<Item> items;
    public bool searched = false;
    public GameObject inventory;
    public Inventory inv;
    public Log log;
    public AudioSource takeSFX;
    public GameObject player;

    void Awake()
    {
        inventory = GameObject.Find("  Inventory Master");
        inv = inventory.GetComponent<Inventory>();
    }

    void Start()
    {
        log = GameObject.Find("  Game Master").GetComponent<Log>();
        AddItems();
        items = new List<Item>();
    }

    void Update()
    {
        SearchObject();
    }

    public void AddItems()
    {
        int rand = (int)Random.Range(0, 2);
        Debug.Log(rand);

        for (int i = 0; i < rand; i++)
        {
            items.Add(inv.database.FetchItemByID(0));
        }
    }

    public void SearchObject()
    {
        if (Input.GetButtonDown("Interact"))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit = new RaycastHit();
            Debug.Log("Raycasting");

            if (Physics.Raycast(ray, out hit, 10))
            {
                Debug.Log("Searching");

                if (!searched)
                {
                    this.takeSFX.Play();

                    if (items.Count >= -0)
                    {
                        for (int i = 0; i < items.Count; i++)
                        {
                            this.inv.AddItem(items[i].ID);
                        }
                    }

                    if (items.Count == 0)
                        log.UpdateLog("No items found in search.");
                    else if (items.Count == 1)
                        log.UpdateLog("1 item found in search.");
                    else
                        log.UpdateLog(items.Count + " items found in search.");
                    searched = true;
                }
            }
        }
    }
}


texts: How to draw efficiently large number of objects with alpha blending?

texts:
In a 3D game i have large no. of trees with alpha value.
What is the efficient way to draw all?
What i tried is Taking every tree as a object and draw according to its z value and using billboarding. But large draw calls, hiting performance.


texts: How do I restrict the movement of a point to within a radius of another?

texts:
I have a situation where a sprite's center point needs to be constrained within a certain boundary in 2D space. The boundary is circular, so the sprite is constrained within a radius. This radius is defined as a distance from the center of a certain point.

I've got this code, but it only tells me when the center has overstepped the allowed radius:

float distance = Vector2.Distance(centerPosition, spritePosition));
if (distance > allowedDistance) {
    // Point is outside allowed range
}

I would like to also return the sprite's center to the closest point within that radius whenever it oversteps the bounds.

How can I do that?


texts: How to have an object follow the mouse, even if not clicked in Unity?

texts:
I have this object. I want to click on it and drag it around. Also if I click anywhere on the screen, I want the object to move but keep the distance.

In the script below I made the object follow the mouse, but I can't do the second part.

I have a couple rays for debugging. Any ideas?

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

public class Player : MonoBehaviour
{
    Vector3 playerPosition;
    Vector3 mouseF;
    Vector3 mouseN;

    void FixedUpdate()
    {
        if (Input.GetMouseButton(0))
        {
            setMouseF();
            setMouseN();

            Debug.DrawRay(mouseN, mouseF - mouseN, Color.green);
            Debug.DrawRay(mouseN, (playerPosition - mouseN), Color.red);

            // move the player base on mouse position
            transform.position = mouseF;
        }

        if (Input.GetMouseButtonUp(0))
        {

            // on mouse release, set the new player position
            playerPosition = mouseF;
        }

    }

    void setMouseF()
    {
        Vector3 mouseFar = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10f);
        mouseF = Camera.main.ScreenToWorldPoint(mouseFar);
    }

    void setMouseN()
    {
        Vector3 mouseNear = new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.nearClipPlane);
        mouseN = Camera.main.ScreenToWorldPoint(mouseNear);
    }
}


texts: Is it possible to use C++ with Unity instead of C#?

texts: The title kind of says it all. Is it possible to replace C# with C++ on a game using Unity?


texts:
Well I had a problem with the implementation of my A* algorithm in C# for unity, and I don't realize how to prevent the diagonal movement and the cross walls, I had the next code, the print line's are for debug purposes:

public void FindPath(Vector3 startPos, Vector3 targetPos)
{
   List<Transform> openSet = new List<Transform>();
   HashSet<Transform> closedSet = new HashSet<Transform>();
   openSet.Add(begin.GetComponent<Transform>());

   while (openSet.Count > 0)
   {
      Transform currentNode = openSet[0];

      for (int i = 0; i < openSet.Count; i++)
      {
          if (openSet[i].GetComponent<Cell>().fCost < currentNode.GetComponent<Cell>().fCost || openSet[i].GetComponent<Cell>().fCost == currentNode.GetComponent<Cell>().fCost && openSet[i].GetComponent<Cell>().hCost < currentNode.GetComponent<Cell>().hCost)
              currentNode = openSet[i];
          print("Todo bien despues de agregar el actual al set");
      }

      openSet.Remove(currentNode);
      closedSet.Add(currentNode);

      if (currentNode == end) {
          print("LLEGUE AL NODO FINAL");
          RetracePath(begin,end);
          return;
      }

      foreach (Transform neighbour in grid.GetNeighbours(currentNode.GetComponent<Cell>()))
      {
          if (closedSet.Contains(neighbour.GetComponent<Transform>()) || !neighbour.GetComponent<Cell>().IsOpened)
              continue;

          int newMovementCostToNeighbour = currentNode.GetComponent<Cell>().gCost + GetDistance(currentNode, neighbour.GetComponent<Transform>());
          if (newMovementCostToNeighbour < neighbour.GetComponent<Cell>().gCost || !openSet.Contains(neighbour.GetComponent<Transform>()))
          {
              neighbour.GetComponent<Cell>().gCost = newMovementCostToNeighbour;
              neighbour.GetComponent<Cell>().hCost = GetDistance(neighbour.GetComponent<Transform>(), end.GetComponent<Transform>());
              neighbour.parent = currentNode;
              print("Pase hasta definir los costos");

              if (!openSet.Contains(neighbour.GetComponent<Transform>()))
              {
                  openSet.Add(neighbour.GetComponent<Transform>());
                  neighbour.GetComponent<Renderer>().material.color = Color.blue;
              }
          }
      }
   }
}

The Getneighbours list is in here:

public List<Transform> GetNeighbours(Cell node)
{
    List<Transform> neighbours = new List<Transform>();
    for (int x = -1; x <= 1; x++) {
        for (int y = -1; y <= 1; y++) {
            if (x == -1 && y == -1)
                continue;

            if (x == 0 && y == 0)
                continue;

            if (x == 1 && y == 1)
                continue;

            int checkX =(int)node.Position.x + x;
            int checkY =(int)node.Position.z + y;

            if (checkX >= 0 && checkX < GridSize.x && checkY >= 0 && checkY < GridSize.z)
                neighbours.Add(GridArr[checkX, checkY]);
        }
    }
    return neighbours;
}

I use a Prefab and I really don't know to put the restiction of walls to prevent the algorithm pass over them, to destroy the other prefab walls I use a RayCastHit function.

this return the next image:

The problem with this is it cross my walls and I don't know how to avoid that

Any help?

Thanks


texts:
I noticed that when I was unwrapping and packing UV's in 3DS Max, that about 75% of the map was taken up by a bunch of repetitive small parts, because of their unique shape and inability to fit somewhere else. It's because of this that they turned out the way they did:

This is a problem for me because now I don't have much texture space for the important UV islands such as the sides of the gun handle. The circled part in viewport mode is the section that matches with parts like the one circled in UV editing, and there are a lot of them. I need them to be scaled proportionately because they are already small enough that they'll barely have any pixels on them anyways. Perhaps ovelrap them and use the same part of the texture for every other, or every third ridge? At this point I'm not sure. Any suggestions are appreciated. Thanks!


texts: Do game programming just let all the objects in the program to interact with themselves and what about preventing infinite loop?

texts:
Does game programming use the method of

1) using time as the main controller to let objects interact with each other, so each step, let 1 object send messages to N objects, and the second object to any number of objects, and 3rd, 4th, until all objects done, and that's it, and display the results on screen (or think of it as just a loop that always repeat, with each iteration considered "a tick in time")    (so object 1 call object 2's method, and object 2 cannot call other object's method immediately?  otherwise, there can be infinite loop like (2) below.  but how do you implement: "cannot call other objects until next time?" )

Or,

2) let the objects freely call other objects' methods (send messages to them), with no "Time" concept like the above

Are they both feasible solutions?  But what if in (2), you have stones in a circular tube, and stone 1 pushes stone 2, and 2 pushes 3, and so forth, until stone N pushes stone 1 again, then the program will go into infinite loop and not able to do anything else (say if the program is a single process, single thread)


texts: Are there any web-based interactive fiction engine that allow you to script a game and have it run from a website?


texts: How do I set shape density in PhysX 3.1?

texts:
I'm using PhysX 3.1. I need to give shapes different densities (there are several shapes for my single rigid actor). I know that the shape's density can be set by NxShapeDesc::density in PhysX 2.8, but I can't find such an interface in PhysX 3.1.

I know mass properties can be set in PhysX 3.1 just as the snowman example in the SDK. Is there a direct interface to set density for each shape?


texts: I loaded my textures with FromStream method and I noticed a problem that those textures are being ignored by garbage collector. I even nulled them, called dispose on them and tried to force garbage collector - they're still in the memory. Any ideas why this might be happening?


texts: Linux: find force feedback device for joystick device

texts:
Because SDL 1.3 is still a long way coming I implemented native force feedback (rumble) support for Aquaria:
https://bitbucket.org/panzi/aquaria/

However, I could not find a way to find the according event device (force feedback device) for any given joystick (gamepad) device. I looked in the SDL 1.3 source and I thought this might be how it is done:

std::ostringstream os;
os << "/dev/input/js" << sdl_index;
std::string jsdevice(os.str());
char evdevice[128];
evdevice[0] = 0;

int fd = open(jsdevice.c_str(), O_RDONLY, 0);
if (fd <= 0) {
    std::cerr << "Could not open joystick [" << jsdevice << "]: " << strerror(errno) << std::endl;
    return;
}

if (ioctl(fd, EVIOCGNAME(sizeof(evdevice)), evdevice) == -1) {
    std::cerr << "Could not get event device for joystick [" << jsdevice << "]: " << strerror(errno) << std::endl;
    close(fd);
    return;
}

close(fd);

// ...

But it always just prints this:

Could not get event device for joystick [/dev/input/js0]: Invalid argument

Currently I use an environment variable to indicate the force feedback device that should be used. Does anyone know how to automatically find the correct device? What I've got is the input device as an index (e.g. the 0 in /dev/input/js0) and therefore the path.


texts: How could I implement origin re-base on my large world server?

texts:
I wish to make a game set in space where the world is empty space, mostly empty but continuous (i.e. no sectors with jump gates separating them) and extends to long distances like a few hundred or a thousand kilometres, where players move around at realistic speeds of spacecrafts. I'm thinking of something like "Star Citizen".

One approach I thought of was scaling down everything and moving slowly to effectively make an illusion of large world but this approach tends to suffer with problems in precision of calculations, specifically floating point calculations.  Then I found out about the concept of origin re-basing.

I'm having trouble understanding how I could implement that on the server: clients can have objects relative to their origin but the server needs to have the entire world in the same co-ordinate system since there is only one world on the server in which everything interacts.

How could I manage both client and server coordinates systems on the server for my very large space environment in a realistic way in the perspective of the player?


texts:
I have no idea why I'm getting this error except that it has to do with the includes.

Base class header file:

#pragma once

#include "Player.h"
#include "TestObject.h"
#include <glm\glm.hpp>
#include <GL\glew.h>

class GameObject
{
//unrelated code
};

Derived class header file:

#pragma once

#include "GameObject.h"
#include <glm\glm.hpp>
#include <glm\gtc\matrix_transform.hpp>
#include <glm\gtc\type_ptr.hpp>

class Player : public GameObject
{
//unrelated code
};

error message:

Error   C2504   'GameObject': base class undefined

And here are the includes for both cpp files:

base:

#include "GameObject.h"
#include "Player.h"
#include <iostream>
#include <glm\glm.hpp>

derived:

#include "Player.h"
#include "GameObject.h"
#include <iostream>
#include <glm\glm.hpp>


texts: Unity: How to keep the music muted on reloading the scene?

texts:
I am giving the user a UI button to mute and unmute the ingame sounds but the problem is when I mute the sounds and then when the game ends and the game scene reloads the sounds comes back up which is really annoying.

After some searching I came to know that I need to use DontDestroyOnLoad(transform.gameobject); but it makes the copy of the whole thing and now I have two copies of the same music.

Also I don't know if this is the only way or not but just to mute/unmute an audio source it feels kind of overkill to me since I have a many components attached to my gameobject and then just to mute/unmute it copies the whole thing.

Can someone tell me how to fix that duplicating problem and also is there any simpler way to achieve this?


texts: How does UNO determine how often do +4,+2 & other special cards occur in a deck/game?

texts:
For UNO-like card games, what factors would one consider when they wanted to set a reasonable proc rate of receiving a special card (for example in UNO's case: +4,+2, color-wheel, reverse, skip)? What factors should I consider when designing a similar game?

I understand probabilities etc. are involved in this. I would appreciate if someone can demonstrate the mathematics/concepts behind it.


texts: How are writing shaders different in Unity's scriptable render pipeline vs the standard pipeline?

texts: So I want to start learning how to write shaders because the shadergraph seems very limited at the moment. I've done some research and it seems that I should learn the HLSL language which is used by Unity. I'm becoming confused though how this will carry over between pipelines. I read that standard pipeline shaders aren't supported in URP so I'm confused how the shader language is different in URP if they both use the HLSL language. I was wondering if someone with a better grasp on this could explain the difference between them and if the skills carry over, as most tutorials online seem to be for writing shaders in the standard pipeline. Thanks.


texts: Companion AI with NavMeshAgent causing jittery movement on the X-Axis

texts:
I'm trying to do a companion AI that follows around my player but with a certain distance.
I first tried to self-program the movement behavior. but realized quickly that a NavMeshAgent offers more simple solutions to what I'm trying to achieve.
Now the problem is that my AI doesn't follow around smoothly. It's surely not because of the camera, since my player and my enemy AIs do not have these jittery movement.
My script is as simple as it can get:
private Transform target;
private NavMeshAgent agent;

public Animator partnerAnim;
public GameObject player;

private void Start()
{
    // set target to player transform
    target = GameManager.GM.playerMachine.transform;
    agent = GetComponent<NavMeshAgent>();
}

private void Update()
{
    // Determining wether to play the walk animation or not
    partnerAnim.SetFloat("normalizedSpeed", Mathf.Clamp01(agent.velocity.magnitude));

    agent.SetDestination(target.position);
}

My stopping distance is at 2 and my speed is at 3.5.
No matter how I change these values, the jittery movement won't change.
I also have a rigidbody attached to my NavMeshAgent, and I made sure to turn on isKinematic, and I also removed it to check if that solves the problem, but it didn't.
The weird thing is that it only seems to be a problem when moving along the X-Axis. When I move on the Z-Axis only, my partner is following my player smoothly (I'm guessing this is because I increase the speed of my player on the Z-Axis, but I don't really see the connection with my problem here. If it would be a speed problem, then lowering the speed on my AI would've fixed this, but it didn't.)
Here are the full NavMeshAgent settings:


texts: How do I draw 2D textures with Direct3D 11.1?

texts:
I'm running into trouble trying to figure out the best way to draw textures to the screen using Directx 11.1 (for Metro apps).

In XNA, I used SpriteBatch. Is there something partially comperable?

In the Win8 SDK examples, they used WIC and Bitmap, although it suggests that that is not the best way to draw 2D graphics with the best performance.


texts: HLSL: using "?" operator in Technique section produces branches?

texts:
I recently found that you can do this:

int AnotherShaderConstant = 0;

float4 PixShader(VSOUT input, uniform bool Direction)
{
    float4 color;
    if (Direction)
        color = GoLeft();
    else
        color = GoRight();

    return color;
}

technique First
{
    PixelShader = compile ps_3_0 PixShader(AnotherShaderConstant == 1 ? true: false);
}

And it will work properly, meaning that you can change a shader constant "AnotherShaderConstant" at CPU level and the pixel shader will change it's behavior. The question is, will such move be equivalent to the following code that clearly produces a branch:

int AnotherShaderConstant = 0;

float4 PixShader(VSOUT input)
{
    float4 color;
    if (AnotherShaderConstant == 1)
        color = GoLeft();
    else
        color = GoRight();

    return color;
}

technique First
{
    PixelShader = compile ps_3_0 PixShader();
}

What I am trying to understand is will I recieve shader optimization similar to those that uniform constants provide, or will my code be bluntly submited to the GPU and executed for each pixel effectively resulting in a branch?

I mean the uber-optimized Microsoft's shaders from XNA's simple effects do the following:

int AnotherShaderConstant = 0;

float4 PixShader1(VSOUT input)
{
    float4 color;
    color = GoLeft();

    return color;
}

float4 PixShader2(VSOUT input)
{
    float4 color;
    color = GoRight();

    return color;
}

PixelShader PixelShaders[2] =
{
    compile ps_3_0 PixShader1();
    compile ps_3_0 PixShader2();
}

technique First
{
    PixelShader = PixelShaders[AnotherShaderConstant];
}

Which means that their shader compiler can react to changes in shader constants, will it react in such situation?


texts: XNA Framework sprite vectors and also scaling

texts:
I'm working on making my first Pong game with XNA Framework 4.0. Right now i've put 2 pong paddles and a ball (they have separate classes). In the "Paddle" class i've made a function that returns a Vector2 list of the normals to its edges (i'm going to leave all 4 of them as i'm considering adding rotation and other things in the future).

Right now i'm trying to do my own implementation of the separating axis theorem. My question is:  is there a more efficient method of computing the edges(or the normals to them), other than doing them by hand? Here's my code from the Paddle class:

public List<Vector2> NormalsToEdges()
    {
        Vector2 Edge = Vector2.Zero;
        List<Vector2> lst = new List<Vector2>();

        //take this normal because our reference axes have the origin in the top left corner
        //upper edge
        Edge = (this.paddlePosition + new Vector2(this.Width, 0)) - this.paddlePosition;
        if (Edge != Vector2.Zero)
        {
            Edge.Normalize();
            lst.Add(new Vector2(Edge.Y, -Edge.X));
        }

        //right edge
        Edge = (this.paddlePosition + new Vector2(this.Width, this.Height)) - (this.paddlePosition + new Vector2(this.Width, 0));
        if (Edge != Vector2.Zero)
        {
            Edge.Normalize();
            lst.Add(new Vector2(Edge.Y, -Edge.X));
        }

        //bottom edge
        Edge = (this.paddlePosition + new Vector2(0, this.Height)) - (this.paddlePosition + new Vector2(this.Width, this.Height));
        if (Edge != Vector2.Zero)
        {
            Edge.Normalize();
            lst.Add(new Vector2(Edge.Y, -Edge.X));
        }

        //left edge
        Edge = this.paddlePosition - (this.paddlePosition + new Vector2(0, this.Height));
        if (Edge != Vector2.Zero)
        {
            Edge.Normalize();
            lst.Add(new Vector2(Edge.Y, -Edge.X));
        }

        return lst;
    }

I don't know why but i have a feeling that i'm over-complicating things (considering that i have to update these edges on every update cycle in the main game). For example, if i decide to change the sprite to some convex irregular polygon with 50+ (or 500+) edges will the performance impact be high? (suppose i know all the vertex coordinates and/or that i can actually get the list of edge-vectors somehow, in CCW or CW order).

Second issue. Suppose i want to heighten one of the paddles under certain conditions in the game. I know i can use scaling for this (on Draw) and test the scale factor (like if it's 1.0f i use height/width of the original sprite, otherwise i make a new property that gives the scaled values), but is there a way to actually scale the sprite itself? (so that height/width/etc values will return the scaled versions). I'm asking this because i think it might save additional coding of properties, recalculation of rectangles etc.

All in all, i'm aiming for maximum efficiency.

Thanks


texts: How to set the force applied to RigidBody2D depending on the time user holds touch on screen?

texts:
I trying to make an object jump from 1 point to another point. How far it jumps depends on how long the player holds the touch anywhere on the screen. It jumps when player releases his touch.

At the code below,I able to detect the moment player release his finger.

if (Input.touchCount > 0) {
    Touch touch = Input.GetTouch(0);

    // Handle finger movements based on touch phase.
    switch (touch.phase) {
        // Finger start touching the screen
        case TouchPhase.Began:
            print("Start tapping");
            break;

        // Finger leaving the screen
        case TouchPhase.Ended:
            //when finger release, the object jump
            float rightForce = Time.deltaTime * 10000 / 2;
            float jumpForce = Time.deltaTime * 30000 / 2;
            box2D.AddForce(new Vector2(rightForce, jumpForce), ForceMode2D.Force);
            break;
    }
}

As you can see I able to get the Time.deltaTime which is I assume is how long the player hold the screen.

What I want to do is calculate the rightForce and jumpForce added to the object depending on the Time user hold the touch.

float rightForce = Time.deltaTime * 10000 / 2;
float jumpForce = Time.deltaTime * 30000 / 2;

Because if I use the 2 line of code above, the result will be almost the same everytime.

So what is the correct way to determine the rightForce and jumpForce depending the time user hold touch?


texts: How to allow other games to communicate with my Lua scripts?

texts:
I am planning some small games that will all rely on a single system of Lua scripts to manage some unified data about:

Some achievements that are common to each game.
The player's progress in completing the achievements.

Players would need to have these three parts on their system to play:

This small set of three unifying Lua scripts.
A single data file containing a list of challenges and the status of the player's progress in completing each.
At least one of the small games.

The three Lua scripts manage the player's progress data file:

One script tells the game which challenge the player needs to complete next.
Another script updates the data file with information about the player's progress.
A final script calculates statistical information about the player's progress. A game can check use this script and decide which of this information it will show to the players.

So far, I am having the games execute the Lua scripts and using stdout to communicate information between the games and Lua scripts placed in a bin directory, which seems to work well on Linux, but I need a solution that works equally on Windows, OS X, and mobile devices and that will not be a challenge for players to install. Is this a more preferred method?

Other developers using different programming languages should be able to easily connect their games to this system.
Everything is stored locally, nothing uses the Internet.


texts:
I've made an Android game that uses no/custom game engine. It renders using OpenGL ES 2.0 and optionally uses some extensions for optimization or extra effects. Over the time I have dealt with various issues in OpenGL drivers, I had to implement workarounds or disable usage of some features on some devices. I am still getting reports from users that something does not render correctly on their device, but in most cases I have no way to debug it as it is happening on some strange device that I don't have. I am using AWS device farm for testing and all the devices there render the game correctly...

So I have come with an idea to implement some kind of self-test. It would run shortly after the first start and render off-screen some samples that test the shaders and features I use. The images would be compared to how they are supposed to look like. (I know the comparison must have some tolerance.) If it detects a mismatch, it could send me screenshots and detailed information about the OpenGL environment. Possibly it could even self-heal by disabling some features and trying again.

Was something like that already done in a (mobile) game?

Are there any caveats I should be aware of?


texts: How do I build games with scripted actors?

texts:
The idea

I have an idea for a game. A few games, actually, that can built on top of the same general design.

There is a game world that the player and the other actors exist in. The player can get information from the world about his surroundings. The player can also interact with the world, picking up an object for example.
Now, I would like the same thing to be possible for other, scripted actors. They are the player's competition. Instead of navigating the world and performing actions based on human input, a script should decide what they do.

An example

I want to do this using a 2d world eventually, so I might as well give the example I want to build:

There is a 2d world with objects of various sizes and shapes. Every actor has their own field of view. They get information from the world about the objects in their field of view. For the player, this information is displayed on the screen of the user. The player navigates the world by user input.

Scripted actors navigate the world in a scripted way. They walk in a general direction, they follow a wall or things like that. Their scripts should be able to get the information about the objects in their field of view and act on it. If an other actor is detected in their field of view, they should walk in that direction for example.

All of this should happen in pretty much real-time.

The information gotten from the world (showed to the player, and given to the scripted actors) in this case would be something like a collection of "what", "where", and "in what orientation".

The question

My question is: how I can program this effectively and efficiently?

I am thinking to build this with C and Lua. C++ is also an option.
I would store the game state and display the graphics using C.
The part that I don't know how to handle is the interaction between C and Lua.
Not programming-wise, but design-wise. The interaction between the world and the scripted actors.

Should C provide the Lua actors with information, and then have the Lua actors call C functions that change their direction, move a step forward, etc? Will this work in real-time?

I realize that this question is broad, but I think it's not unreasonable. There are obviously ways to do this and I would like to know some.


texts: How far can you get with Garry's Mod and no money?

texts:
My sixth-grader is very interested in FPS game development but I don't think he has grasped the magnitude of the task ahead. He is a Halo fan and so his current goal is to make a similar game but better. Heh. I am not going to discourage him though.

I gave him a Steam account and by himself he has discovered Garry's Mod and installed tortoise svn to add packs (and play them). He has also downloaded and poked around in the UDK and trials of Visual C++ and SoftImage. When I say "by himself" I mean he has asked his online buddies for advice and suggestions, and he has watched countless Youtube "how-to" videos (the classroom of the future).

Although I am a programmer my expertise does not lie in games. I am having a hard time understanding what Garry's Mod encompasses. How far can he get with it and what additional tools should I help him to get?


texts: Using the Command design pattern for game AI

texts:
I'm trying to learn the Command design pattern and apply it to the game I'm working on. First I read about the general implementation, and I feel like I understand it pretty well. Now I want to know how to use it in games. I started reading this book about design patterns in games and in the section about the command pattern the author says:

  We can use this same command pattern as the interface between the AI
  engine and the actors; the AI code simply emits Command objects.

and

  The decoupling here between the AI that selects commands and the actor
  code that performs them gives us a lot of flexibility. We can use
  different AI modules for different actors.

I'm trying to figure out how this pattern would be used for game AI in practice. I assume there would be an AIEngine class or something like that with GenerateCommand() function. Then the GameActor would ask the AIEngine for a Command whenever it finishes executing the previous one.

What I don't understand is how exactly it would work. In order to generate commands the AIEngine needs to keep track of all the GameActor objects anyway (or at least of the one it's generating the commands for), so what's the point of using commands? At this point the AIEngine could just manage the GameActor objects directly.

I've been trying trying to wrap my head around this for quite a while. If someone could write a example implementation of the AIEngine interfacing with GameActor it would help me a lot. I don't think I'm able to understand it without seeing some code.


texts: Is anyone else having problems launching UE4 4.23.1 on OS X 10.12?

texts:
So I recently switched machines from Windows to OS X (I still have the Windows machine but it's not available to me sometimes so I wanted to keep going while it's processing some other stuff).
UE4 installs fine on my machine but I never actually get it to initialise the engine. Even if I start directly from the .uproject file it doesn't do anything.

Has anyone else had a similar experience and how did you solve the problem?

PS. I verified the 4.23.1 Version already so that's all good.

Edit:
I went to the engine directory and set all flags to 777. So permission is no longer an issue. Problem persists though.


texts: Any hints about the average renderstate changes per frame?

texts:
While answers will vary depending on the case, I'd love to hear about what people have seen in their past experiences.
The question mainly relates to DirectX though if you have some numbers for any other API (OpenGL, consoles etc) I'd be glad to hear them too.

Thanks in advance.


texts: Explicit resource loading in Ogre (Mogre)

texts:
I am just starting to learn Mogre and what I would like to do is to be able to load resources 'explicitly' (i.e. I just provide an absolute path instead of using a resource group tied to a directory).

This is very different to manually loading resources, which I believe in Ogre has a very specific meaning, to build up the object using Ogres methods. I want to use Ogres resource management system/resource loading code, but to have finer control over which files are loaded and in what groups they are.

I remember reading how to do this but cannot find the page again; I think its possible to do something like:

Declare a resource group
Declare the resource(s) (this is when the actual resource file name is provided)
Initialise the resource group to actually load the resource(s)

Is this the correct procedure? If so, is there any example code showing how to do this?


texts: 3D rotation matrices deform object while rotating

texts:
I'm writing a small 3D renderer (using an orthographic projection right now).

I've run into some trouble with my 3D rotation matrices. They seem to squeeze my 3D object (a box primitive) at certain angles.

Here's a live demo (only tested in Google Chrome):
http://dl.dropbox.com/u/109400107/3D/index.html

The box is viewed from the top along the Y axis and is rotating around the X and Z axis.

These are my 3 rotation matrices (Only rX and rZ are being used):

var rX = new Matrix([
        [1, 0, 0],
        [0, Math.cos(radiants), -Math.sin(radiants)],
        [0, Math.sin(radiants), Math.cos(radiants)]
    ]);

    var rY = new Matrix([
        [Math.cos(radiants), 0, Math.sin(radiants)],
        [0, 1, 0],
        [-Math.sin(radiants), 0, Math.cos(radiants)]
    ]);

    var rZ = new Matrix([
        [Math.cos(radiants), -Math.sin(radiants), 0],
        [Math.sin(radiants), Math.cos(radiants), 0],
        [0, 0, 1]
    ]);

Before projecting the verticies I multiply them by rZ and rX like so:

vert1.multiply(rZ);
vert1.multiply(rX);

vert2.multiply(rZ);
vert2.multiply(rX);

vert3.multiply(rZ);
vert3.multiply(rX);

The projection itself looks like this:

bX = (pos.x + (vert1.x*scale));
bY = (pos.y + (vert1.z*scale));

Where "pos.x" and "pos.y" is an offset for centering the box on the screen.

I just can't seem to find a solution to this and I'm still relativly new to working with Matricies.

You can view the source-code of the demo page if you want to see the whole thing.


texts: Adjust Keyboard input to match look direction?

texts:
A concept I am working on uses W,A,S,D for movement and sometimes the camera will be oriented so that the game is side scrolling, where D is forward (moving right), but other times the camera might be behind the player looking forward (Kinda like 3rd person) and In this case, W would need to be forward.

Currently I only have it set up where D is always forward but it gets highly confusing when the camera angle changes at a certain parts.

Is there a simple enough way to figure out how to determine which key would be appropriate for forward? I kinda think of it like making the keys act analogue or something like that, but can't think of a good way. Maybe something like the closer the cameras forward direction is to the players forward direction, interpolate key inputs to match axis?

Also, my camera is following on a spline path so when the direction its looking at the player changes, its not immediately 3rd person. It eases into that, so to make this more complicated, I would think that sometimes a combination of two keys would be forward (D to D&W to W)

Sorry if this is common but I couldn't figure out what to search for.

Edit: I didnt include the detail that its not purely left/right for the side scrolling part, the character can go in all 4 directions (+X,-X,+Y,-Y) but is limited by a small path. Space would be my jump. See pic below:


texts: Libgdx: How to draw the score on the top left?

texts:
I want to keep the score visible on the top left corner of the screen. I have the score talking care of. I just want to display it.

Score: x

The comment on the accepted answer on Stackoverflow suggests that BitmapFontCache is the best way to do it, inside the render method.

BitmapFontCache.draw() doesn't accept strings, so I cannot pass
Score:
BitmapFontCache.draw(batch, x, Align.topLeft); doesn't work either.
Do I have to keep updating the score position?

EDIT

  game.batch.begin();
        cache.setText("Score: " + score, 500,500);
        cache.draw(game.batch);

.........

or even if I placed it outside batch.begin, if I place it directly in, I get

E/AndroidRuntime: FATAL EXCEPTION: GLThread 172645
                  Process: com.mygdx.game, PID: 16727
                  java.lang.NullPointerException: Attempt to invoke virtual method 'com.badlogic.gdx.graphics.g2d.GlyphLayout com.badlogic.gdx.graphics.g2d.BitmapFontCache.setText(java.lang.CharSequence, float, float)' on a null object reference
                      at com.mygdx.game.GameScreen.render(GameScreen.java:129)
                      at com.badlogic.gdx.Game.render(Game.java:46)
                      at com.mygdx.game.Gam.render(Gam.java:20)
                      at com.badlogic.gdx.backends.android.AndroidGraphics.onDrawFrame(AndroidGraphics.java:459)
                      at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1647)
                      at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1352)
E/AndroidGraphics: waiting for pause synchronization took too long; assuming deadlock and killing

Even if I remove score variable and put everything outside batch.begin but inside render I keep getting the same error.

 public void render(float delta) {
        cache.setText("Score: " + 12, 500,500);
        cache.draw(game.batch);


texts: Class design and data structures for a Tower Defense

texts:
I was trying to come up with a structure for a simple TD game that has following elements

Tower
Each Tower has a set of properties like range, damage, health etc
There could be different types of Towers with different attack types. For eg Tower A can perform attackType 1 and 2 and Tower B can perform attackType 3 and 4
Creep
Each Creep has a set of properties like damage, health, bountyPoints etc.
There could be different types of Creeps with different abilities just like the Towers

For now I am trying to come with a good design that is scalable and well structured for the above two game elements

This is the skeleton of a Tower class that I have come up with so far. Please comment and suggest changes. Any design patterns that could make life easier

using System.Collections;
using System;

    public enum TowerType
    {
        tA,
        tB,
        tC
    };

    public class Tower {

        private TowerType type;
        private int damage;
        private int range;
        private int health;

        public Tower(TowerType type)
        {
            this.type = type;
            initializeVariables();
        }

        private void initializeVariables()
        {
            if (this.type != null)
            {
                if (this.type == TowerType.tA)
                {
                    this.damage = 20;
                    this.range = 40;
                    this.health = 50;
                }

                else if (this.type == TowerType.tB)
                {
                    this.damage = 30;
                    this.range = 50;
                    this.health = 60;
                }

                else if (this.type == TowerType.tC)
                {
                    this.damage = 60;
                    this.range = 60;
                    this.health = 80;
                }

            }
        }

        public int getDamage()
        {
            return this.damage;
        }

        public int getRange()
        {
            return this.range;
        }

        public int getHealth()
        {
            return this.health;
        }

        public TowerType getTowerType()
        {
            return this.type;
        }

        public string getType(int value)
        {
            return Enum.GetName(typeof(TowerType), value);
        }
    }

So using enums to define various types of towers. But is this a good design? Each Tower would have different damage, range and health.

What if there are 100 different towers? So in my InitializeVariables() would have a cluster of 100 if else statements. How can I improve on this or is there a better way to implement this?


texts: What's a good Game development platform for a platformer game with these characteristics?

texts:
Yes, I know, the best way to make an indie game is to learn to code. I've got some scripting experience, but I want to do worldbuilding with already-existing tools (and communities surrounding those tools), and I've been really impressed with games like An Untitled Story that were made with pre-packaged toolsets at their core, like Game Maker. :)

So I'm planning to make my game using either Game Maker or something like it.

The basic parameters of my planned game:

2D platformer.
Physics/speed akin to Sonic the Hedgehog.
Large, non-linear world, flowing as seamlessly as possible -- think Super Metroid, but without the forced screen transitions.

The first two points have me leaning toward Game Maker -- Plenty of 2D platformers have been made with it, and there are serviceable, openly available Sonic-the-Hedgehog-style physics engines for it that could be adapted to my needs with minimal muss and fuss.

But the third makes me antsy -- from what limited information I hear, Game Maker has problems with large levels/boards/screens/whateveryoucallthem, thus necessitating transitions between screens.

I want to avoid that if at all possible -- it would, I believe, fundamentally alter the flow of the game.  I understand that generally speaking, the more you have loaded into memory the more things are going to chug (especially for a one-size-fits-all game development platform that isn't a model of efficient coding), but I'm hoping there are systems that can un-load objects that are sufficiently far offscreen and thus better produce seamlessness.

Any thoughts, people? :)  The sooner I can get a basic pre-fab physics engine and world-building program up and running, the sooner I can start prototyping areas and generally tooling around.  Should I be looking at Game Maker, or elsewhere?

(My current plan is to more-or-less build the game prototype-style, then worry about art and sound at the very end once the damn thing is playable.)

EDIT/RESPONSE

To ultifinitus: I might pick up C# for a separate project.

I'm familiar with game dynamics and game design from past projects (Projects that used OOP scripting languages).

The amount of work I'm willing to put into my project is directly proportional to what I can do with what's already out there.

This is where a system like Game Maker appeals to me. :) I've then got the level editor, the physics, etc. all more-or-less taken care of, and the software has a giant enthusiast community that provides various modules, advice, etc.

If I can get most of my game done that way, then once I've got a functional prototype I can happily shell out the cash to pay artists to make the game actually look like something worth a damn.

This is why I'm looking for something like Game Maker. I'm just wondering if Game Maker (or another such system) is the most suitable for what I want to do.


texts: Mesh slicing/knifing with multiple planes

texts:
I have a ginormous mesh which I want to cut with multiple planes.
For simplicity I want to know how to cut a mesh with single plane and repeat the logic.

Consider a X-Y plane of coords (1,1,0,0) = (a,b,c,d), from the equation ax+by+cz+d, which is the equation of the plane.

How shall I use this information to cut a mesh? Any help will be invaluable.


texts: Software engineering theory for hobbyist developers

texts:
In playing around with my hobby projects in various object oriented languages, I have realized that creating good class structure and program architecture is both crucial and not straightforward to effectively develop a program, in particular a game.

I am a self-taught programmer with virtually no formal training, and I've only learned the things which seemed to be of immediate practical use, so I have never really looked into things such as design patterns, software architecture, code organization principles and the like. The resources I find are often limited in scope (most commonly it's a showcase of a single pattern) and/or quite technical (all the UML going over my head doesn't help).

Is there a good resource which explains the important concepts and basics of software engineering, where I can learn about things like when and how to use Components, what kind of class structures are appropriate to what tasks, how design patterns relate to each other and which are useful for what?


texts: How do I achieve this glowing edge shader?

texts:
I came across this example, and wanted to know how to achieve a shader that will give me similar results, i.e. the glowing edges.

How do I achieve this sort of shader?


texts: How can large terrains be represented in multiplayer games?

texts:
To give you a bit of context, I often try and imagine how big games are working, especially networked and multiplayer games. This is how I came to this question: how do big 3D multiplayer games load their 3D, predefined maps? (I am not talking of generated ones, such as in Minecraft, but defined maps that represent, for example, a kitchen).

The most viable hypothesis to me are:

Some basic map terrain is loaded in a .obj file (with just variations of height and of ground material), and then more data (like trees) is added according to another file, stored in a format like xml, which also contains paths to other obj files. This techniques therefore allows modifications of terrain, as well as something like serialization to send data to a new client joining (but it's really heavyweight and hard to implement). Finally, you can base player position on which tile they are, and make easier collision & al (for RTSs for example).
A map containing all data in a single .obj file is loaded by all clients, and they are just allowed to move inside it (is this the case in FPSs like Quake?)

But I think both of these techniques aren't optimized enough for commercial or public use. Do you have any idea of how can these games load their map data?


texts:
Hello guys I'm tryting to make a game in unity of keepy uppies but I can't make the ball bounce to different directions like keft and right only staright up.

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

public class physics : MonoBehaviour
{
    public Rigidbody rb;
    public float force = 10;

    void Start()
    {
        rb.velocity = new Vector3(0, 0, force);
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit, 100.0f))
            {
                if (hit.transform != null)
                {
                    //PrintName(hit.transform.gameObject);
                    if (rb = hit.transform.GetComponent<Rigidbody>())
                    {
                        LaunchIntoAir(rb);
                    }
                }
            }
        }
    }

    private void PrintName(GameObject go)
    {
        print(go.name);
    }

    private void LaunchIntoAir(Rigidbody rb)
    {
        rb.velocity = new Vector2(rb.velocity.x, 3);
    }
}

This is what I have done until now.


texts: A star algorithm implementation problems

texts:
I’m having some trouble implementing the A* algorithm in a 2D tile based game.

The problem is basically that the algorithm gets stuck when something gets in its direct way (e.g. walls)
Note that it only allows Horizontal and Vertical movement.

Here's a picture as it works fine across the map without something in its direct way: (Green tile = destination, Blue = In closed list, Green = in open list)

This is what happens if I try to walk 'around' a wall:

EDIT

Thanks DeadMG, I rewrote the algorithm last week and got it somewhat working.

But the heuristics are still some faulty.

As you can see here it prefers a uneven path on an straight way:

The heuristics function:

float c_astar::GetH(cTILEext TILEX)
{
    short a = 0; short b = 0;
    if(TILEX.Tile.Position.x > Destination.x) a = TILEX.Tile.Position.x - Destination.x;
    else a = Destination.x - TILEX.Tile.Position.x;
    if(TILEX.Tile.Position.y > Destination.y) b = TILEX.Tile.Position.y - Destination.y;
    else b = Destination.y - TILEX.Tile.Position.y;

    float h = a+b;

    //Tie-Breaker
    float dx1,dy1,dx2,dy2;
    dx1=dy1=dx2=dy2 = 0;

    if(TILEX.Tile.Position.x > Destination.x) dx1 = TILEX.Tile.Position.x - Destination.x;
    else dx1 = Destination.x - TILEX.Tile.Position.x;

    if(TILEX.Tile.Position.y > Destination.y) dy1 = TILEX.Tile.Position.y - Destination.y;
    else dy1 = Destination.y - TILEX.Tile.Position.y;

    if(Start.x > Destination.x) dx2 = Start.x - Destination.x;
    else dx2 = Destination.x - Start.x;

    if(Start.y > Destination.y) dy2 = Start.y - Destination.y;
    else dy2 = Destination.y - Start.y;
    float cross = abs(dx1*dy2 - dx2*dy1);

    h += cross*0.001;

    return h;
}

I used the Tie-Breaker as described here. What am I doing wrong?

Regards,
bryan226


texts:
Normally my app runs at 60 fps, But when I add some simple models it decreases to 40fps.

I think v-sync on, which is might be causing it to run slower.

Is there any way to disable v-sync in WebGL?

Would glflush at the end of rendering work?


texts: Generic item collision/reflection in Pong (Flash)

texts:
I am trying to find a good way to handle ball/paddle collisions/reflections in Pong. I've tried the "naive" approach of just checking x and y coordinates against each other, figuring out where the ball hits on the paddle and how to change reflection, etc, but it seems so tedious to do it this way. I feel like I have to check collisions against the front of the paddle, then the sides, etc.

Is there a good, general way I can check for a collision between the ball and the paddle (be it sides, front, etc), ensure the ball doesn't pass through the paddle, determine where the ball touches the paddle in terms of tangency (if we don't allow the ball to move through the paddle), and determine reflection rules based on that point of tangency?

I've already looked into Corey's Detection Kit but it didn't seem to work for my purposes.

Consider the picture at the bottom of this post. Let's say the red ball is where the ball WANTS to appear based on the speed/frame-based update routine for the ball. Using some routine, it determines there is an intersection because either the sprites overlap or the path of travel overlays the paddle. But I really want to bring the ball back up to where it's actually touching the paddle at tangency. Is there a general way to do this?

http://i.stack.imgur.com/Xo99a.png


texts: Is there any documentation comparing/contrasting C++ standard library implementations?

texts:
(This is not game programming per se, but I'm certain if I asked this on SO I'd get told not to prematurely optimize, even though history tells us every large game ends up worrying about these things.)

Is there a document anywhere that summarizes the differences in performance, and particularly memory usage, between different C++ standard library implementations? The details of some implementations are protected by NDA, but a comparison between even STLport vs. libstdc++ vs. libc++ vs. MSVC/Dinkumware (vs. EASTL?) seems like it would be immensely useful.

In particular I'm looking for answers to questions like:

How much memory overhead is associated with the standard containers?
What containers, if any, do dynamic allocations merely by being declared?
Does std::string do copy-on-write? Short string optimization? Ropes?
Does std::deque use a ring buffer or is it crap?


texts:
I have a simple game object (3d object) and I want to detect and run some code when gets clicked/tapped.

I tried OnPointerDown/Up/Click but seems to not be working for 3D Objects. With 2d objects (images with raycast targets) it works fine.

How can I do it with a 3d objects in a simple way? Thanks!


texts: Modifying UV's origin on shader (OpenGL)

texts: Is there a way to change the UV's origin (bottom-left) on shader?


texts: In Unity, how do I add a MeshFilter to an empty GameObject to generate a procedural model?

texts:
My code below is modeled after Unity's documentation.  When I put the script into an empty GameObject, the error I get is:

MissingComponentException: There is no 'MeshFilter' attached to the "myMesh" game object, but a script is trying to access it.

How do I add a MeshFilter (and the other necessary Components) to the empty GameObject in order to generate the model procedurally?

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

public class myMesh : MonoBehaviour  {
    public Mesh mesh;

    void Start(){
        mesh= new Mesh();
        GetComponent<MeshFilter>().mesh = mesh;
    }

}


texts:
Looking at the documentation glGetTexImage(), one can see that there are plenty of available texture formats.

GL_TEXTURE_1D, GL_TEXTURE_2D, GL_TEXTURE_3D, GL_TEXTURE_1D_ARRAY, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_RECTANGLE, GL_TEXTURE_CUBE_MAP_POSITIVE_X, GL_TEXTURE_CUBE_MAP_NEGATIVE_X, GL_TEXTURE_CUBE_MAP_POSITIVE_Y, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, GL_TEXTURE_CUBE_MAP_POSITIVE_Z, and GL_TEXTURE_CUBE_MAP_NEGATIVE_Z

I've only used GL_TEXTURE_2D for the time being.

Is there any place / documentation where one can learn about these other formats ?

PS : and yes, of course, i've googled for it, results are pretty poor


texts: How do I create the formula for calculate the damage of a skill

texts:
I'm trying to calculate the output damage of a skill. The skill can go up from level 1 to 100, it can scale with own levels and the attack of the character.

Here some parameters

Edit:

I need a formula for determine the amount of damage that a skill or ability can do.

I have some data that I don't have create myself, but I just taken from a game.

A character can grow up from lv 1 to 100, and he has a set of skills.

Every skill can go up from lv 1 to (current level of the character)

The skill damage is linear but influenced of character's attack, so more attack the character has and more damage can do the skill.

A character that we call John has the follow parameters

Max stats that John can reach

Level 100
Attack 7337
Skill damage (lv 100) 16574

Minimum stats

Level 1
Attack 71
Skill damage (lv 1) 479

The current stats of John

Level 13
Attack 202
Skill damage (lv 13) 805

When the skill was a previous level

Level 13
Attack 202
Skill damage (lv 12) 788

In theory the skill damage should get 7 points for level, of course with the current amount of John's attack, but is linear.

What I'm trying to do is get the basic damage of a skill plus the correct multiplier


texts: Updating score in collision detection game in XNA

texts:
I created a collision detection game in XNA but I have a problem with the scoring.
As online tutorials says,
I initialised it

score = 0;

This is in the update section to check if the person hit the object

// Check collision with person
                if (personRectangle.Intersects(numberRectangle))
                    personHit = true;

Then in the draw section..

if (personHit)
            {
               score = +score + 1;
               spriteBatch.Draw(greenBackground, mainFrame, Color.White);
            }
            else if (personHit2)
            {
                score = +score - 1;

                //device.Clear(Color.Red);
                spriteBatch.Draw(redBackground, mainFrame, Color.White);
            }

But when the person hits the objects that fall, the score goes up until that object is on the person image.
I don't know if I am clear.
The score doesn't go up by one per hit,  it goes up until that object stops touching the person..

I was wondering how can I fix this so the score goes up by 1 only?


texts: Should I scrap my own leader board and go for the Facebook built in one?

texts:
Currently I'm rolling my own score and leader board functionality in my FB canvas game.
In my game, users can see what score they have, in addition I have a public leader board where everybody can see all scores from all other users.(I also have possibility for each user to set themselves as anonymous in the leader board, if desired)

But now I started thinking; why do I have my own leader board system?
Facebook has this scores API and I started play around with it.
It, of course, integrates well with Facebook, scores and achievement showing up in the ticker and what not.

But it seems that I can't let each user see a public leader board in much the same way I currently have it. But it do let the users see their friends score.
Let's face it, this is all what FB is all about, right? Friends.

So the question is; should i scrap my own leader board and go for the Facebook built in one (and skip the public part of it)?

My gut feeling says yes, but I wanted to hear what other thinks.


texts: Howto apply alpha value (Color) to a sprite in libgdx

texts:
Howto apply alpha to a sprite so it will work.

With the following code, the sprite still is completely visible.

Can someone help me ?

batch.enableBlending();
if (sprite != null) {
    Color c = sprite.getColor();
        c.a = 0;
        sprite.setColor(c);
}
batch.draw(sprite, x, y);
sprite.setAlpha(0f);


texts: In Unity3D, when building to web, model gets distorted

texts:
As the title says, when I build for web, the character model gets distorted, but while in the editor, it's completely fine. Here are the images:

Before, in play mode:

After, in the web build:

As you can see, there is a big distortion in the legs area. This may be because of the model, or that I am not building it to the web correctly. I am not sure. This model is a .blend, and resizing the game window while playing does not reproduce this effect. Even a while back, when I was testing it out, I built it to web, went on the same site as I did when this problem happened to play it, and everything was fine. Any help would be appreciated, since I am really drawing a blank here. Please tell me if you need any info I may have missed. Thank you!


texts:
I'm doing a spaceflight simulator in C++ (using Allegro 5), and I realised that I could just use a physics engine instead of writing my own physics.

So that's what I'm doing.

Since this is going to be a 2D only (for simplicity's sake) simulation, I've looked at 2D physics engines only. And since this will be running on low-end hardware, just not using the z-axis of a 3D engine won't work.

I've narrowed it down to the two big physics engines: Box2D and chipmunk. I'm trying out Box2D now, but the manual says that:

  Box2D works with floating point numbers and tolerances have to be used to make Box2D perform well.
  These tolerances have been tuned to work well with meters-kilogram-second (MKS) units. In particular,
  Box2D has been tuned to work well with moving objects between 0.1 and 10 meters. So this means
  objects between soup cans and buses in size should work well. Static objects may be up to 50 meters big
  without too much trouble.

Obviously I'm going to be using Box2D for objects ranging from 100 m to 1.4e9 m (from a ship to the Sun). However, most of the time I'm going to be flying around in a ship (no collisions), or parked on the surface of a planet. Of course, there will also be accelerations of up to 275 m/s/s (at the surface of the Sun).

Is this order of magnitude going to work with Box2D? Has anyone worked with this kind of stuff in Box2D before? Should I just try another physics engine (suggestions welcome)?


texts: How can I move a ball to a clicked location using physics forces?

texts:
I have a ball as a sphere in my game and I'm viewing it from top down view. The ball is a rigid body.

When I click somewhere on the screen, I want the ball to be moved towards that direction using physics forces.

The ball needs to move only on the X and Y axes, the Z axis can be ignored.

Here is what I tried, but gives me some weird results. The script is attached to the ball:

// Use this for initialization
    void Start () {
        rb = gameObject.GetComponent<Rigidbody> ();
    }

    void Update () {

        //
        Vector3 v3 = gameObject.transform.position;
        Vector3 v3Mouse = Input.mousePosition;

        //
        Vector2 pointA = new Vector2(v3.x, v3.y);
        Vector2 pointB = new Vector2(v3Mouse.x, v3Mouse.y);

        //
        float Angle = Vector2.Angle(pointA, pointB);
        float angleRad = Angle * (Mathf.PI / 180);

        Debug.Log ("Angle: " + Angle);
        //
        float dx = Mathf.Cos (angleRad) * 10;
        float dy = Mathf.Sin (angleRad) * 10;

        //
        if (Input.GetMouseButtonDown (0)) {

            rb.velocity = new Vector3(dx, dy, 0);

        }

    }

What should I do here? When I click on the top of the screen, the ball should move up toward the mouse, and in all the other directions.

Any ideas?


texts: How to set X and Z axis to 0 after transform.rotation in c#

texts:
Recently I start using C# instead of JAVA and I don't know how to set a value in a eulerangle only for one axis.

Maybe I don't need to do that, so better I explain what I'm doing:

I have a 3D object (player) that look at mouse pointer, but when the mouse pointer it's too close to the object, it's change his x and z axis, and I need to set it to 0 to keep standing the object.

In java I just write this after transform.rotation:

transform.eulerAngles.x = 0;
transform.eulerAngles.z = 0;

In C# I can't do that. Is there a simple way to do it? My code is:

Ray ray = Camera.main.GetComponent<Camera>().ScreenPointToRay (Input.mousePosition);
RaycastHit hit_A;
if (Physics.Raycast (ray, out hit_A, Mathf.Infinity, GroundMask)){
    Vector3 rotPoint = new Vector3 (hit_A.point.x - transform.position.x, transform.position.y, hit_A.point.z - transform.position.z);
    transform.rotation = Quaternion.LookRotation(rotPoint);
}

Maybe, as I said, there are an other way to fix this. I'm open to any solution. I searh it on google, but because at my english level I don't understand the results

Thanks you all.


texts: How does this point2LineDist() method works?

texts:
I was browsing Wolf3D JS port and bump into that method :

/**
 * @description calculates distance between a point (x, y) and a line.
 * @memberOf Wolf.Math
 * @param {number} x X coord of point
 * @param {number} y Y coord of point
 * @param {number} a Line angle in degrees
 * @returns {number} Distance
 */
function point2LineDist(x, y, a) {
    return Math.abs( (x * SinTable[a] - y * CosTable[a]) >> 0);
}

I think I understand what it does. It gives shortest distance (green on picture) between a line (from angle) and a (x, y) point.

What is not clear to me is how it works.
I know a little bit of trigonometry, but I am not able to figure out which trigonometry identity or formula it use. The binary shift is (I think) a quick way to convert a float to an int.


texts: How to improve this random number generation in my context?

texts:
In my game there is a word at top of the screen, letters are raining down from top and the user has to touch the letters to complete the word.

Currently I am generating letters randomly (actually random numbers and numbers are the index for the array of letters. e.g: 0=a, 1=b) but the problem is that it takes too much time to get all the required letters to complete the word.

What I want is that the random numbers that I am generating should generate required letters more often so player don't have to spend all day to complete one word.

I have tried following methods:

Detect all the letters in the word (word is always 6 letters long), generate the array of indexes of length 6, assign each index of the array to random number from letter-2 to letter+2 and in the end pick randomly one index from the array to show.
Have a selector variable whose value is in the range [0..2], generated randomly, if selector == 0 then detect letters which make the word and randomly pick one letter, else randomly get any alphabet from a-z.

Both of these methods have not provide me with any help. I will be very happy if you can help me.

Thanks for reading this, I hope you understood the question and I am waiting for the response.


texts:
So I have a game object MapGenerator and 2 attached scripts: MapGenerator.cs and Lexicon.cs.
I need to be able to access a couple variables in Lexicon.cs from MapGenerator.cs, so I imported it with:
void Awake()
{
    GameObject gameObject = new GameObject("Lexicon");
    lexicon = gameObject.AddComponent<Lexicon>();
}

Now, this allows me to pull variables from Lexicon, and I am able to do that successfully for the most part. However, the public fields that are being set from Unity (tiles/sprites) are not being pulled in. They just show up as null.
Example scenario:
public class Lexicon : MonoBehaviour
{
public Tile thiccTile;
public Tile thiccTile2;
public Tile thiccTile3;
private string fact = "Yummy porchop";
private string favoritefact;
private Tile favoritetile;

 public Lexicon() {
  favoritetile = thiccTile2; //this guy is public and set in unity under components.
  favoritefact = fact;
 }

public Tile Favoritetile { get { return favoritetile; } set { favoritetile= value; } }
public string Favoritefact { get { return favoritefact; } set { favoritefact= value; } }

}
Start() {
UnityEngine.Debug.Log(lexicon.Favoritefact); //"Yummy porchop"
UnityEngine.Debug.Log(lexicon.Favoritetile); // null
}

My first thought was it was because I never explicitly call Lexicon(). However, since favoritefact works, im guessing the gameobject stuff is enough? Anyway, how can I fix this?
EDIT: This is where I set the values (Different variable names but you get the idea)


texts:
I want to implement debug render for cocos2d android.So I can view how bodies are created.
Right now I use gdx.jar file for box2d and load that jar file following way.

static {
      System.loadLibrary("gdx.jar");
}

All the desire bodies are created but I need box2d debug renderer. I have search many place for this question but I could not found anything. So please anybody has knowledge regarding this then suggest me.


texts: LWJGL 3 how to convert screen coordinate to world coordinate?

texts:
I'm trying to convert screen coordinate to world coordinate on mouse click event.
For LWJGL 3 there's not GLU utility class is available whereas LWJGL 2 has.

I'm using JOML math classes and wrote following code, but its returning wrong world coordinate, I'm doing something wrong and couldn't figure out.

On program init, I get viewProjMatrix and viewport:

viewProjMatrixUniform = glGetUniformLocation(this.program, "viewProjMatrix");
IntBuffer viewportBuffer = BufferUtils.createIntBuffer(4);
int[] viewport = new int[4];
glGetIntegerv(GL_VIEWPORT, viewportBuffer);
viewportBuffer.get(viewport);

On render loop, I calculate viewProjMatrix:

viewProjMatrix
    .setPerspective((float) Math.toRadians(30), (float) width / height, 0.01f, 500.0f) // define min and max planes
    .lookAt(eye_x, eye_y, eye_z,
            eye_x, eye_y, 0.0f,
            0.0f, 2.0f, 0.0f);
glUniformMatrix4fv(viewProjMatrixUniform, false, viewProjMatrix.get(matrixBuffer));

I convert screen coordinate to world coordinate with following code:

DoubleBuffer mouseXBuffer = BufferUtils.createDoubleBuffer(1);
DoubleBuffer mouseYBuffer = BufferUtils.createDoubleBuffer(1);
glfwGetCursorPos(window, mouseXBuffer, mouseYBuffer);
double x = mouseXBuffer.get(0);
double y = mouseYBuffer.get(0);
System.out.println("clicked at: " + x + " - " + y);

Vector3f v3f = new Vector3f();
viewProjMatrix.unproject((float)x, (float)y, 0f, viewport, v3f);
System.out.println("world coordinate: " + v3f.x + " - " + v3f.y);

Here's the full source code: https://gist.github.com/digz6666/48bb433c83801ea4b82fa194f05b4f02


texts: How can I store information about what cells are connected to others in a 2D array?

texts:
I have a 10x11 array in my game. What is the best structure and way to store the connections between the elements of the array?

Some info about the connections:

they are simple (2 elements are connected or not)
an element can be connected with its 8 neighbours
when I move from one position to another I need to add that connection
when I'm in a position I need to check that element's connections

For example: "the player" is at [6,1]

I need to check for all 8 directions if there is a connection there or not(this function returns a byte or int[8], doesn't matter)
If the player wants to move to [6,2] I dont allow it
If the player wants to move to [6,1] I allow it and store the new connection


texts: In a large space simulation, why is my sun light not reaching the planets?

texts:
I want to create a space simulation, but I'm facing some difficulties when I try to create a realistic sun.

Currently, I've a simple Point Light inside a sphere. But for some reasons, no matter the intensity and the attenuation radius of this light, the other objects in the scene (the planets, for instance) aren't lit any more if their centre are separated by more than 1.5 kilometres approximatively.

(Top) Lit planet, 1.4 km away from the sun.
(Bottom) Unlit planet, 1.5 km away from the sun.

Do you know what can cause this phenomenon? Is there a way to bypass it? If not, how can I create a realistic sun light in a large space simulation?


texts:
I'm working on a 2d adventure game where the player can explore a random generated map. It's working perfectly if I set it to be about 3000x1000 blocks (my array is 3000x1000x2), but this is TOO SMALL. When I want to make a bigger map it trows an OutOfMemory error.

I store my map in a 3d float array where the first two dim shows the position on the world plus I need 2 more data (3rd dim) for each block the type (int blockID) and the stored last update time (float elapsedTime).

Can it be better if I make it 2 separeted 2d array?

This 3d array is the one what is too big and trows OutOfMemory error. The blocks that have made Objects are the ones that can be seen(~32x14 block) the other are just two number ID and elapsedTime.

How should I store the map data?

EDIT:

This code:

   int x = 10000;
   int y = 10000;
   float[][][] ft;
   ft = new float[x][y][2];

It trows OutOfMemory error.