texts: How should I structure my turn based engine to allow flexibility for players/AI and observation?

texts:
I've just started making a Turn Based Strategy engine in GameMaker's GML language... And I was cruising along nicely until it came time to handle the turn cycle, and determining who is controlling what player, and also how to handle the camera and what is displayed on screen.

Here's an outline of the main switch happening in my main game loop at the moment:

switch (GameState)
{
case BEGIN_TURN:
    // Start of turn operations/routines
break;
case MID_TURN:
    switch (PControlledBy[Turn])
    {
    case HUMAN:
        switch (MidTurnState)
        {
        case MT_SELECT:
            // No units selected, 'idle' UI state
        break;
        case MT_MOVE:
            // Unit selected and attempting to move
        break;
        case MT_ATTACK:
        break;
        }
    break;
    case COMPUTER:
        // AI ROUTINES GO HERE
    break;
    case OBSERVER:
        // OBSERVER ROUTINES GO HERE
    break;
    }
break;

case END_TURN:
    // End of turn routines/operations, and move Turn to next player
break;
}

Now, I can see a couple of problems with this set-up already... But I don't have any idea how to go about making it 'right'. Turn is a global variable that stores which player's turn it is, and the BEGIN_TURN and END_TURN states make perfect sense to me... But the MID_TURN state is baffling me because of the things I want to happen here:

If there are players controlled by humans, I want the AI to do it's thing on its turn here, but I want to be able to have the camera follow the AI as it makes moves in the human player's vision.
If there are no human controlled player's, I'd like to be able to watch two or more AI's battle it out on the map with god-like 'observer' vision.

So basically I'm wondering if there are any resources for how to structure a Turn Based Strategy engine? I've found lots of writing about pathfinding and AI, and those are all great... But when it comes to handling the turn structure and the game states I am having trouble finding any resources at all. How should the states be divided to allow flexibility between the players and the controllers (HUMAN, COMPUTER, OBSERVER)?

Also, maybe if I'm on the right track I just need some reassurance before I lay down another few hundred lines of code...


texts: Why is the character not walking right when creating new animator controller for the character?

texts:
I created a new controller called it SoldierController and dragged it to the character Controller under Animator component in the Inspector.

Also unchecked Apply Root Motion

Then attached a new script to the third person character called the script Soldier.

Then I set the Animator controller and I added two new States to it:
Walk and Idle. HumanoidIdle and HumanoidWalk.

Then I did that the default start state will be Idle. Set StateMachine Default State.

Then I did a Transition from Walk to Idle. This way when I press on "W" it starts walking a bit. Then it keep moving the character but without the walking animation.

If I delete this transition and make transition from the Idle to Walk then when I press on "W" it will walk but then if I leave "W" key it's idling.

Then after 2-3 seconds the character will walk on place I mean it will animate walking without moving and I'm not pressing anything it's starting automatic when idling.

The character had another animator controller but I created a new one and using only the new one.

The script:

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

public class Soldier : MonoBehaviour
{
    private bool _isWalking = false;
    private Animator anim;

    // Use this for initialization
    void Start ()
    {
        anim = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update ()
    {
        var x = Input.GetAxis("Horizontal") * Time.deltaTime * 150.0f;

        transform.Rotate(0, x, 0);

        if (Input.GetKey("w"))
        {
            if (!_isWalking)
            {
                _isWalking = true;
                anim.Play("Walk");
            }
            var z = Input.GetAxis("Vertical") * Time.deltaTime * 3.0f;
            transform.Translate(0, 0, z); // Only move when "w" is pressed.
        }
        else
        {
            if (_isWalking)
            {
                anim.Play("Idle");
            }
            _isWalking = false;
        }
    }
}


texts: Data structure for multiple Textures in materials in assimp

texts:
I'm going through assimp documentation regarding  materials. Each material can have multiple textures containing various data (color maps, height maps, etc.) and blending data, etc. I'm trying to understand how to model this efficiently in a data structure, without storing textures for each mesh separately (meaning generating textures and loading the texture (bind and upload to GPU) for each and every mesh in a redundant manner, ignoring that they are re-used).

In this tutorial, they simplify the situation, by just caring about the "1st diffuse color maps". This simplifies the data structure immensely. But, theoretically at least, there can be multiple texture maps for a single material, and textures can be re-used across materials.

I'm trying to understand whether it's common practice to not share any textures between different meshes in a single scene/model.

I have a couple of questions regarding this:

What is the best way to store textures when loading models through assimp? I understand that you can store each texture per mesh per scene (space inefficient but simple). Is there a better way?
I found a few free fbx model that only contains one diffuse color map as a material (similar to the tutorial). Is it common practice for this to happen or did I come across a simplified model?

PS: I understand openGL quite well and I have no problem getting things to render. This question is only concerned about what's practical, efficient and considered best practice.


texts: Is a custom coordinate system possible in Unity

texts:
Is it possible to create a custom coordinate system (i.e the one using double for coordinates or the one dividing the world into 'chunks' of safe size) not constrained by the floating point precision limitations in Unity, and make systems using the built-in coordinate system use that one instead somehow?

Thanks!


texts: Is Scaleform/Flash used in console games for non-UI, game elements?

texts:
I work for Konami as a Flash developer, and got sent some code for a puzzle mini-game from a new, yet-to-be-released Silent Hill game for PS3/Xbox 360.  It was a windows executable, but it was made in Flash, and I saw some GFX (Scaleform) libraries in the source.  I was very surprised by this, as I thought the extent of Flash's reach into console games was simply for UI.  Granted, this was an essentially 2d, UI-centric puzzle minigame, but nonetheless, this was a gameplay useage of Flash/Scaleform in a "next-gen" console title.

My question is, how prevalent is this?  I really want to get into console programming, and if this is something that appears elsewhere, maybe I can apply my Flash/Actionscript skills to getting a job working on console titles.  Anyone have any thoughts or experiences with this?

Thanks!


texts: How to procedurally generate materials with text in Unity

texts:
I'm designing a virtual library that dynamically loads sections of a database and need to display text on the books. As such, I need a runtime interface to somehow load book titles and author and put them on the book covers.

I've looked into Substance Designer to make a procedural material, but the Text Node in the program is not yet supported by Unity. I've also stumbled across TextGenerator in the Unity API, but it seems to be mesh not texture based, and I'm not sure what the performance penalty will be, given I'm rendering a lot of books.

Edit: For now I had some luck creating a child object and using the TextGenerator, since it turns out the mesh is minimal and in fact does create a texture to display the text. I suppose I can use this solution until something better comes up.


texts:
When I hold down a button by mouse for 5 seconds, print a message. How to do this ? I wrote this script but is not working. I don't know if there other methods.

Public float clock;
Public Button out;

public void quit_out_mouse() {
    clock = Time.time;
    if(Time.time - clock > 3.0f )       {
        Debug.Log (" gone !! ");
    }

   }


texts: Calculate an AABB for bone animated model

texts:
I have a model that has its initial bounding box calculated by finding the maximum and minimum on the x, y and z axes. Producing a correct result like so:

The vertices are then stored in a VBO and only altered with matrices for rotation and bone animation. Currently the bounds are not updated when the model is altered. So the animated and rotated model has bounds like so:

(Maybe it's hard to tell, but the bounds are the same as before, and don't accurately represent the rotated/animated model)

So my question is, how can I calculate the bounding box using the armature matrices and rotation/translation matrices for each model? Keep in mind the modified vertex data is not available because those calculations are performed on the GPU in the shader.

The end result I want is to have an accurate AABB the represents the animated model for picking/basic collision checks.


texts: How to add Facebook login to a Unity game without Gameroom?

texts:
I'm trying to implement Facebook login with the Facebook SDK for Unity.  The documentation makes it sound pretty straightforward: call FB.Init and then call FB.LogInWithReadPermissions and use a callback to handle the response.  At no point does it mention any additional requirements, such as specific gaming clients.

Everything works inside the editor, but when I try to run a build, the Init call fails with the error message "Pipe name not passed to application on start.
 Make sure you are running inside the facebook games client."

...yeah.  That's kind of what I'm trying to specifically not do here; this is being built to run on Steam, and I have seen other Steam games offer Facebook authentication, so I know it's possible.  I just don't quite know how, and Facebook's documentation is no help because it doesn't even mention Gameroom in conjunction with these APIs at all!

Does anyone know what the proper way is to set this up?  Using Unity 2019.2.2f1 and Facebook SDK 7.17.2.


texts:
I managed to get working LWJGL in Java, and I loaded a test image (tv test card), but I keep getting weird artifacts outside the image.

Code:

glBegin(GL_QUADS);
glTexCoord2f(0, 0);
glVertex2i(10, 10);
glTexCoord2f(1, 0);
glVertex2i(500, 10);
glTexCoord2f(1, 1);
glVertex2i(500, 500);
glTexCoord2f(0, 1);
glVertex2i(10, 500);
glEnd();

What could be the cause?


texts: How do you incorporate cocos2d with regular iPhone UI widgets?

texts: I want to build a sprite based game using cocos2d. I will be mostly drawing everything in code. I also want to incorporate iPhone UI widgets such as buttons and such. Can these be created to appear on top of the cocos2d canvas? Will this affect the performance of what is drawn/animated?


texts: What happens if I don't call glNormal for some vertices?


texts:
So I'm trying to implement Screen Space Reflections using a Hierarchical z-Buffer in GLSL. I'm following the approach from GPU Gems 5 and the Frostbite presentation linked here ("Stochastic Screen-Space Reflections", Slide 36+).

I believe I have a fundamental misunderstanding how the algorithm works, however there are not many information about this algorithm, besides of the resources I linked.

My current GLSL code looks like this:

vec3 trace_ray(vec3 ray_start, vec3 ray_dir)
{

    ray_dir = normalize(ray_dir);
    ivec2 work_size = SCREEN_SIZE_INT;
    const int loop_max = 250;
    int mipmap = 0;
    int max_iter = loop_max;
    vec3 pos = ray_start;

    // Move pos by a small bias to avoid self-intersection
    pos += ray_dir * 0.004;
    float hit_bias = 0.002;

    while (mipmap > -1 && max_iter --> 0)
    {

        // Check if we are out of screen bounds, if so, return
        if (pos.x < 0.0 || pos.y < 0.0 || pos.x > 1.0 || pos.y > 1.0 || pos.z < 0.0 || pos.z > 1.0)
        {
            return vec3(0,0,0);
        }

        // Compute the fractional part of the coordinate (scaled by the working size)
        // so the values will be between 0.0 and 1.0
        vec2 fract_coord = mod(pos.xy * work_size, 1.0);

        // Modify fract coord based on which direction we are stepping in.
        // Fract coord now contains the percentage how far we moved already in
        // the current cell in each direction.
        fract_coord.x = ray_dir.x > 0.0 ? fract_coord.x : 1.0 - fract_coord.x;
        fract_coord.y = ray_dir.y > 0.0 ? fract_coord.y : 1.0 - fract_coord.y;

        // Compute maximum k for which the ray would still be inside of the cell.
        float max_k_x = (1.0 / ray_dir.x) / work_size.x;
        float max_k_y = (1.0 / ray_dir.y) / work_size.y;

        // Scale the maximum k by the percentage we already processed in the current cell,
        // since e.g. if we already moved 50%, we can only move another 50%.
        max_k_x *= 1.0 - fract_coord.x;
        max_k_y *= 1.0 - fract_coord.y;

        // The maximum k is the minimum of the both sub-k's since if once maximum
        // is reached, the ray is out of the cell
        float max_k = min(abs(max_k_x), abs(max_k_y) );

        // Fetch the current minimum cell plane height
        float cell_z = textureLod(DownscaledDepth, pos.xy, mipmap).x;

        // Check if the ray intersects with the cell plane. We have the following
        // equation:
        // pos.z + k * ray_dir.z = cell.z
        // So k is:
        float k = (cell_z - pos.z) / ray_dir.z;

        // Check if we intersected the cell
        if (k > 0.0 && k < max_k + hit_bias )
        {
            // Move to point of intersection
            pos += k * ray_dir;

            // In case we are at mipmap level 0, we found a match
            if (mipmap == 0) {
                return pos;
            }

            // If we hit anything at a higher mipmap, step up to a higher detailed
            // mipmap:
            mipmap -= 2;
            work_size *= 4;
        }

        // If we hit nothing, move to the next cell, with a small bias
        pos += max_k * ray_dir * 1.02;

        mipmap += 1;
        work_size /= 2;

    }
    return vec3(0);
}

And the result is:

So I'm doing something wrong, its probably not much since the result is not completely off, however, I cannot figure out what I'm doing wrong.

TL;DR: Am I either misunderstanding how the Algorithm works, or if not, what am I missing or doing wrong in my code?


texts: Should I be concerned that my microtransaction based game will often be hacked?

texts:
I used to play Diablo II, both online and offline. The game was so easily “hackable” offline that one could download a program called Hero Editor and, using a nice, comfortable interface, change their character in many ways. However, it was harder to hack the online portion of the game, and many that did were caught. Thus some of the game’s content was restricted to online play, doubling up as a way to promote people playing together.

Now I’m making a mobile TD using Unity, targeting the iOS, Android, and perhaps PC/Mac/Linux platforms initially. Players would slowly earn some rare currency during play that can be used for permanently unlocking exciting (but non-essential) extras, or they can just pay for them.

I’m concerned that if I allow this gradual unlocking to happen offline (without a server to confirm the accrual of said currency), then it’ll be as easily hacked as Diablo II’s offline mode and that many people would simply resort to doing that instead of either playing it through or paying for it. However, I’m also reluctant to force online play, as the mobile environment has significantly lower network stability and this is a relatively long game to be playing in such conditions, so drop-out is very likely.

So my question is: how concerned should I be about the mobile game getting hacked for the purpose of acquiring these unlocks without going through the correct methods? Is it so easy that your average user could do it, like they could for Diablo II, having the potential to significantly damage the game’s bottom-line? Or is it difficult such that only a small percentage of people who are interested enough would bother to try, so I can focus on providing the best UX for all players without worrying about these hackers?

Brownies for anybody who can summarise how it may actually be hacked!


texts:
want to know that how mathf.movetowards works, i tried to play around it and have some issues.
i want to make the camera moves from player to target places along with zooming upon triggered and vise versa, while smooth follow(camera changes target) works, smooth zooming doesn't work.
i place the movetowards code to ontriggerenter/exit, but it doesn't work as intended as it only zoom for frames. However, if i place it at update side, the zooming doesn't work at al.

code provided for more infomation.

public class Disable : MonoBehaviour {
GameObject player;
GameObject Camera;
public Transform placeHolder;
public float smoothTime = 2f;
public float adjustSize;
public float originalSize = 6.5f;
public float targetOrtho;

public Vector3 velocity;

void Awake()
{
    player = GameObject.FindGameObjectWithTag("Player");
    Camera = GameObject.FindGameObjectWithTag("MainCamera");

}
private void Start()
{
    targetOrtho = originalSize;
}

void Update()
{
    Camera.GetComponent<Camera>().orthographicSize = Mathf.MoveTowards(Camera.GetComponent<Camera>().orthographicSize, targetOrtho, smoothTime * Time.deltaTime); //doesn't work

}

void OnTriggerEnter2D(Collider2D other)
{
    if (other.gameObject == player)
    {

        Camera.GetComponent<Camera2DFollow>().target = placeHolder;
       targetOrtho = adjustSize;
       //Camera.GetComponent<Camera>().orthographicSize = adjustSize; //works but only changes the size without smooth
       //Camera.GetComponent<Camera>().orthographicSize = Mathf.MoveTowards(Camera.GetComponent<Camera>().orthographicSize, adjustSize, smoothTime * Time.deltaTime); //works but only did for a few frames( not completely)

    }
}

void OnTriggerExit2D(Collider2D other)
{

    Camera.GetComponent<Camera2DFollow>().target = null;
    targetOrtho = originalSize;
    //Camera.GetComponent<Camera>().orthographicSize = originalSize; //works but only changes the size without smooth
    //Camera.GetComponent<Camera>().orthographicSize = Mathf.MoveTowards(Camera.GetComponent<Camera>().orthographicSize, originalSize, smoothTime * Time.deltaTime); //works but only did for a few frames (not completely)
}


texts: My Maya texture does not render at all in Open GL!

texts:
I uploaded my layered Maya (Maya 2012) Textures via objLoader into my opengl project. I also uploaded 3D textured model. I am able to render a model but not even one texture is showing.
Before pasting any code here, i thought maybe there is some common mistake that we beginners are doing, regarding this issue!?


texts: Implementing David Silver's Cooperative Pathfinding in Real-Time

texts:
I'm currently implementing David Silver's Cooperative Pathfinding algorithm for a 2D game with grid-based movement (all eight directions).

The issue I'm having trouble wrapping my mind around is the Reservation Table with respect to real-time. I've fully implemented the algorithm in its own testbed; however, my implementation is turn-based where everybody is moving at the same speed.

The game I'm trying to integrate the group pathfinding into has real-time movement with units having different speeds.

I've compiled a few considerations I need to take into account and some that could help me implement this:

Enemies do not seek the player's character
However, some enemy units will wander
Enemies will have a different movement speed depending on enemy type
The player moves the avatar by clicking the destination (this initiates a walk)
The player can start start running by double clicking a destination (this can happen in-between grid nodes)
The player has allies that follow the avatar
Allies will run to keep up with the avatar if too far away and start walking again if close enough (this can also happen in-between grid nodes)
Speeds are not perfect multiples of each other

With those in consideration, my current partial solution consists of the following:

Because of consideration 1 and 2, enemies will share reservation tables since I can have them move on the same intervals so their times will match up
Because of considerations 3 and 8, the enemies' reservation tables will differ by movement speeds. I am thinking of doing it this way because I'm not sure how to use one reservation table for all of them if their speeds are not perfect multiples of each other.
Because of the speed-change considerations of 4, 5, 7, and 8, the player's and allies' paths will be recalculated whenever they start walking or start running since that will affect path coordination.
Because paths can be recalculated for the player avatar on the fly, I will need to have two reservation tables specifically for the player (one for walk, one for run). I would also possibly need to have two reservation tables for the allies to share (one for walk, one for run).
Because of the fact that paths can be recalculated in-between nodes, I believe I will have to limit changes of speed to only occur when a unit is directly on a node rather than being able to change speeds in-between nodes as it currently works. Otherwise, I believe I would have to calculated the time it will take to reach the next node and then track that in the reservation table as well somehow.

Finally, here are things I'm wondering about:

I must be not understanding the Reservation Table completely if coordinating units is this difficult. How do I define the time of a node in the Space-Time map if not by how long it takes one unit to get from one node to another?
Is diagonal movement going to be an issue when defining the time of a node in the Space-Time map?
Is there an easier way to handle implementing this short of implementing a different group pathfinding algorithm?
If there is another pathfinding algorithm you recommend, I am all ears, but at this point in development, there most likely isn't any time to implement something new unless coding it as well as integrating it into the game would take less time than jamming the already-coded algorithm into the game.

Feel free to suggest ways of slightly altering how enemies, the player, and the allies move if that will make implementing this significantly easier. I appreciate any help you feel like offering. Thanks for your time!


texts: Unreal Development Kit - What is a good method for accessing a relational database file?

texts:
I'd like to use a SQL Express file or something similar for a UDK demo.

Is there a standard method for accessing data in a local relational database file?

I understand that the best method may involve creating a class library and using the DLLBind feature, but I'm still a bit unclear on how to pass data to controls in the UI (I'd like to populate dropdowns and such with records from the database).


texts: Best way to blend colors in tile lighting? (XNA)

texts:
I have made a color, decent, recursive, fast tile lighting system in my game. It does everything I need except one thing: different colors are not blended at all:

Here is my color blend code:

return (new Color(
       (byte)MathHelper.Clamp(color.R / factor, 0, 255),
       (byte)MathHelper.Clamp(color.G / factor, 0, 255),
       (byte)MathHelper.Clamp(color.B / factor, 0, 255)));

As you can see it does not take the already in place color into account. color is the color of the previous light, which is weakened by the above code by factor. If I wanted to blend using the color already in place, I would use the variable blend.

Here is an example of a blend that I tried that failed, using blend:

return (new Color(
       (byte)MathHelper.Clamp(((color.R + blend.R) / 2) / factor, 0, 255),
       (byte)MathHelper.Clamp(((color.G + blend.G) / 2) / factor, 0, 255),
       (byte)MathHelper.Clamp(((color.B + blend.B) / 2) / factor, 0, 255)));

This color blend produces inaccurate and strange results. I need a blend that is accurate, like the first example, that blends the two colors together.

What is the best way to do this?

Update:
I noticed that the reason simply adding them together and the above isn't working is because the light was spreading onto itself and blending with itself. I am going to try and prevent this by writing the light spread onto one array, a temporary one, not using blend at all, only using the first method. After each light is finished with the recursion process I'll draw it to the main one using a custom pixel shader that will blend the light together properly. This may or may not solve my problem.


texts:
I was just wondering, when simulating physics is it usually a good idea to get the time delta from the last frame and apply the relevant motion equations?

Something like:

void simulate(float dt)
{
    vel += (force / m) * dt;
}

In this case wouldn't there be an accumulated error over time due to precision? For example when trying to simulate a circular motion?

Or would it be better to get the entire elapsed time from the beginning, and then apply the motion:

void simulate(float elapsedTime)
{
    vel = vel0 + (force/m)*elapsedTime;
}

And since this doesn't depend on the previous simulate() steps, it's less likely to cause precision errors?

Thanks!


texts:
I want to create a game where enemies spawn, fly toward the player's ship, and stick to the side of it. The player can then rotate the ship and the stuck enemies will rotate with it.

The way I have this working now, the ship and the enemies are each part of a group and a collision group; when an enemy collides with the ship, it leaves its old group and collision group and joins those of the ship. The player is then able to rotate the ship's group, including the stuck enemies.

But from there, things get weird. If you rotate the ship 90 degrees to the left and then stick an enemy to its right edge, the enemy vanishes and appears at the top edge of the ship. Try to stick another enemy to the same point on the right edge, and it too will teleport to the top of the circle, colliding with the other enemy there. Also, enemies that have been "stuck" won't collide with those that have not.

If I move everything into one collision group, rotating the ship with enemies stuck to it will be reflected onscreen but not in the physics. You can spin the ship around all you like, and the enemies stuck to it will appear to rotate around it, but the non-stuck enemies will act as if they aren't moving.

How can I get a group of physics bodies to act like one body, rotating together and colliding with other objects in the gameworld? Code is below; try it out here.

var game = new Phaser.Game("100%", "100%", Phaser.AUTO, '', { preload: preload, create: create, update: update, render: render });
var debug = false;

var ship, enemy, enemies, shipCollisionGroup, enemyCollisionGroup, spawnEnemy;

function preload() {
    game.load.image('ship', 'simple-ship.svg');
    game.load.image('enemy', 'square-enemy.svg');
}

function create() {
    game.physics.startSystem(Phaser.Physics.P2JS);
    game.physics.p2.setImpactEvents(true);
    game.physics.p2.updateBoundsCollisionGroup();
    game.stage.backgroundColor = '#1C1C1C';

    shipCollisionGroup = game.physics.p2.createCollisionGroup();
    enemyCollisionGroup = game.physics.p2.createCollisionGroup();
    enemies = game.add.group();
    enemies.enableBody = true;
    enemies.physicsBodyType = Phaser.Physics.P2JS;
    ship = game.add.sprite(200, 200, 'ship');
    shipGroup = game.add.group();
    shipGroup.enableBody = true;
    shipGroup.addChild(ship);
    shipGroup.x = 200;
    shipGroup.y = 200;
    shipGroup.pivot.x = 200;
    shipGroup.pivot.y = 200;
    spawn();

    game.physics.p2.enable([ship, enemies], debug);
    ship.body.setCircle(200);
    ship.body.setCollisionGroup(shipCollisionGroup);
    ship.body.collides([shipCollisionGroup, enemyCollisionGroup], collision);

    cursors = game.input.keyboard.addKeys({
        'left': Phaser.KeyCode.A,
        'right': Phaser.KeyCode.D,
        'space': Phaser.KeyCode.SPACEBAR
    });
}

function update() {
    ship.body.setZeroVelocity();
    ship.body.setZeroRotation();

    if (cursors.left.isDown) {
        shipGroup.rotation -= .1;
    } else if (cursors.right.isDown) {
        shipGroup.rotation += .1;
    } else if (cursors.space.isDown) {
        spawnEnemy = true;
    } else if (cursors.space.isUp && spawnEnemy) {
        spawn();
        spawnEnemy = false;
    }
}

function render() {
    game.debug.text('A and D to rotate; spacebar to spawn enemies', 32, 32);
}

function collision(shipBody, impactorBody) {
    var enemy = impactorBody.sprite;
    // enemies.remove(enemy);
    shipGroup.addChild(enemy);
    enemy.body.removeCollisionGroup(enemyCollisionGroup);
    enemy.body.setCollisionGroup(shipCollisionGroup);
    enemy.body.setZeroVelocity();
    enemy.body.setZeroRotation();
}

function spawn() {
    var enemy = enemies.create(700, 200, 'enemy');
    enemy.body.velocity.x = -100;
    enemy.body.setCollisionGroup(enemyCollisionGroup);
    enemy.body.collides([shipCollisionGroup, enemyCollisionGroup]);
    enemy.body.sprite = enemy;
    enemy.anchor.x = 0.5;
    enemy.anchor.y = 0.5;
}


texts: Translating object 2's movement on object 1

texts:
I am moving Object 1 with the translation of the object 2. That is, it should not copy the object 2's position, but instead moving in the same direction/angle as the object 2 is moving. I am stuck at this point where I must add a certain offset if the object is moving Left/Right/Up/Down, since it may be positive/negative floating value. So how do I add an offset to object 1's position?
The problem with the below code is that the object2 comes in position of object1 and then translates which is not what I want.
    public Vector3 offsetPosition;

    public Transform Object2;

    // Update is called once per frame
    void Update () {
        offsetPosition = Object2.transform.position - this.transform.position;
        this.transform.position = new Vector3 (Object2.transform.position.x, this.transform.position.y, Object2.transform.position.z) - new Vector3 (offsetPosition.x * 0.02f, 0, offsetPosition.z * 0.02f);
    }


texts: How to troubleshoot Godot HTTPRequest latency?

texts:
I'm running a Django server on localhost, and Godot 3.2 is my client using HTTPRequest.  If I make an HTTP request with HTTPie (or cUrl), I get a response in under 3 seconds.  The same request is taking 2 or 3 times longer when initiated in Godot in code basically mirroring the example.  I have enabled threads.

What could make Godot take so much longer?

I'm not sure where to begin troubleshooting this.  I know it's a vague question, and I'm happy to post updates as necessary.  I'm logging the time immediately after calling http_request.request() and at the start of the request_completed signal handler.

UPDATE 1: I used strace like this and discovered that I'm getting a lot of read errors with Godot.  The size of the response body is about 1 MB.

% time     seconds  usecs/call     calls    errors syscall
------ ----------- ----------- --------- --------- ----------------
 85.64    9.208080           7   1290272   1235447 recvfrom
 13.07    1.405888         213      6596      5575 recvmsg
  1.29    0.138535        1539        90           sendto
  0.00    0.000060          10         6         3 connect
  0.00    0.000028           9         3           socket
------ ----------- ----------- --------- --------- ----------------
100.00   10.752591               1296967   1241025 total

With HTTPie, I don't get these errors.  Note that this is a single HTTP request, whereas the above statistics for Godot includes 3 concurrent requests.

% time     seconds  usecs/call     calls    errors syscall
------ ----------- ----------- --------- --------- ----------------
 99.72    0.015470           7      2147           recvfrom
  0.09    0.000014           5         3         3 connect
  0.06    0.000009           9         1           getsockname
  0.05    0.000007           2         4           socket
  0.04    0.000006           6         1           getpeername
  0.02    0.000003           3         1           sendto
  0.01    0.000002           2         1           bind
  0.01    0.000001           1         1           setsockopt
  0.01    0.000001           1         1           getsockopt
------ ----------- ----------- --------- --------- ----------------
100.00    0.015513                  2160         3 total

UPDATE 2: The problem only occurs in Godot when I have multiple requests running simultaneously.  The queries are all expensive and read-only.  When I make multiple requests with HTTPie, I see similar delays.  By comparing a single HTTPie request to simultaneous Godot requests, I was comparing apples to oranges.

Now I'm confused because I expect read-only queries to execute concurrently with Postgres.  I expect three 3-seconds queries to take around 3-4 seconds rather than 9-12 seconds.

I'm also confused because all three concurrent requests, when made in Godot, finish around the 11s mark.  If they were operating sequentially due to a lock, I would expect them to finish in a cascading manner (i.e. t+3, t+6, t+9).
What am I missing?


texts:
I am developing a game with libgdx for android.I want use accelerometer for motion control.I am controlling a coin within screen bounds.
I want to apply gravity according to device orientation as you can see in the image.
I know i can use Gdx.input.getAccelerometerX()(or y,z) But i can't understand how to use to get desired result.

Here i have attached two sample image for simple understanding


texts: 2D snake game ( how to rotate snake's head with movement ?)

texts:
I want to know:

how to rotate snake's head with movement
how to make tail prefabs (body) follows head direction.

public class Snake : MonoBehaviour {

    bool ate = false;
    bool isDied = false;
    public GameObject tailPrefab;
    Vector2 dir = Vector2.right;
    List<Transform> tail = new List<Transform>();

    void Start ()
    {
        InvokeRepeating("Move", 0.3f, 0.1f);
    }

    void Update () {
        if (!isDied) {
            if (Input.GetKey (KeyCode.RightArrow))
            {
                dir = Vector2.right;
                //transform.rotation=Quaternion.Euler(0, 0, 180);
            }
            else if (Input.GetKey(KeyCode.DownArrow))
            {

                dir = -Vector2.up;
                //transform.rotation = Quaternion.Euler(0, 0, 90);
            }
            else if (Input.GetKey(KeyCode.LeftArrow))
            {

                dir = -Vector2.right;
                //transform.rotation = Quaternion.Euler(0, 0, 0);
            }
            else if (Input.GetKey(KeyCode.UpArrow))
            {

                dir = Vector2.up;
                //transform.rotation = Quaternion.Euler(0, 0, 270);

            }
    }

    void Move() {
        if (!isDied) {
            Vector2 v = transform.position;

            transform.Translate (dir);

            if (ate) {
                GameObject g = (GameObject)Instantiate (tailPrefab,
                                  v,
                                  Quaternion.identity);

                tail.Insert (0, g.transform);

                ate = false;
            } else if (tail.Count > 0) {
                    tail.Last ().position = v;

                    tail.Insert (0, tail.Last ());
                    tail.RemoveAt (tail.Count - 1);
            }
        }
    }

    void OnTriggerEnter2D(Collider2D coll) {
        if (coll.name.StartsWith("Food")) {

            ate = true;

            Destroy(coll.gameObject);
        } else {
            isDied = true;
        }
    }
}


texts:
Is it good idea to multiply Mouse movement by Time.deltaTime?

float mouseX = Input.GetAxis("Mouse X") * lookSens * Time.deltaTime;

Should we use deltaTime with inputs and when should we use deltaTime with inputs?


texts: How to ignore collisions of triggers after first collision of trigger until OnTriggerExit of first collision of trigger?

texts:
There is are white and red two teams of tank which are auto spawning in certain time interval. both red and white type of tanks have triggers so when red and white tank come close enough, OntriggerEnter() is activated and both types of tank stop moving and start to fire each other. their movement is controlled by navemesh and both type of tanks are navmeshagent. Now What i want is when these two start firing each other both tank's trigger need to ignore collision of trigger with third tank until one of those two tanks die.
Below is my code any help is appreciated thanks.

      public float RBdist;
      public GameObject Rbullet;
      public Transform targetofred;
      public float attackspeedofRtank;
 private void Start()
{
   // rwalktohit = GetComponent<Animator>();
     red = GetComponent<NavMeshAgent>();
    //cube2.velocity = 2f * (cube2.velocity.normalized);
    red.destination = targetofred.position;
//targetofred is the position of house of white tank or base of white tank.

    Rcollider = GetComponent<Collider>();
}
      private void OnTriggerEnter(Collider whitettank)
      {

          if (whitettank.gameObject.tag == "whitetank")//tag of white
// tanks is "whitetank".

        {
          red.isStopped = true;
          twhitetank = whitettank.transform;
          transform.LookAt(twhitetank.position);
          InvokeRepeating("Rfire", 1f, attackspeedofRtank);
         }

      }

private void Rfire()
{

     GameObject Rbulletclone = Instantiate(Rbullet, transform.position ,
    transform.rotation);
     Rbulletclone.transform.position =
   Vector3.MoveTowards(transform.position , twhitetank.position, RBdist);
}

private void OnTriggerExit(Collider whitettank)
{
    if (whitettank.gameObject.tag == "whitetank")
    {
        CancelInvoke("Rfire");
        red.isStopped = false;
    }

}


texts: What design pattern is best for implementing trophies in a game? I am not a games developer, but is it easy for each player's action to check and update conditions that satisfy 50-100 trophies at any time aside from everything that goes on in the game engine? How is it best done?


texts:
I am working on a platform game,When I press the space bar  the object should jump and  when I release the space bar it should come down.

The code I have used for jump is

void Update () {
    transform.Translate(Vector3.right*Time.deltaTime);
    if(Input.GetKey(KeyCode.Space))
    {
        rigidbody2D.AddForce(Vector3.up*3);
    }

    if(Input.GetKeyUp(KeyCode.Space))
       {
        rigidbody2D.AddForce(Vector3.down);
    }

}

But when I release the space bar the object is not coming down


texts: Box Collider 2Ds float just above each other in Unity

texts:
I'm learning 2D Unity and am experiencing a very strange problem. When I have 2 objects both with Box Collider 2D and a RigidBody2D, and one of them is set to be static so it doesn't move, the other one floats just above it. Here's a screenshot so it makes sense

The red box is the one that is not static, the black one is. The red one should sit atop the black one but is floating above it for some reason. I have no idea why. The hitboxes should be right, here are images of them

What can be done?


texts: Inherited property in derived class reference only base class

texts:
[Context] I am developing a game in Unity, and wanted to make a Game Manager. Like many examples out there, it uses a Singletron design pattern. But i have several other Managers, all using Singletron pattern, so i decided to make a Singletron base class and make all the managers derive from it. When trying to access the Instance property declared in Base Class within one method in Game Manager derived class, the Instance property refers to the Singletron base class, which is expected.

But it`s not the behaviour i need. I have tried to look for alternatives, but everytime i found a possible solution, i have to declare the member variables/properties in the derived class, and there would be no need to a Singletron Base Class.

I have also looked for generic alternatives (Singletron < T >) but it was not clear how to use these without the need of another script calling it, which would be nonsense since the Game Manager should be the object to manage the game. I could use something like a root game object to creat the managers is instances, but it feels like a ugly and inelegant solution.

The managers are all coded, and this refactor would improve code maintenance, in future.

[Code from Singletron Base Class]

public abstract class Singletron : MonoBehaviour
{
    public static Singletron Instance { get; protected set; }

    protected virtual void Awake ()
    {
        if (Instance == null) {
            Instance = this;
        } else {
            Destroy (gameObject);
        }

        DontDestroyOnLoad (gameObject);
    }
}

[Pertinent code from Game Manager Derived Class]

public class GameManager : Singletron
{
    public List<GameObject> gameObjectsList;

    public static void SomeMethod()
    {
        foreach (GameObject go in Instance.gameObjectsList)
        {
            go.DoSomething();
        }
    }
}

[Question] What can i do inside Singletron Base Class to make the Instance.gameObjectList refers the actual class (in example, Game Manager Derived Class) so that i could use the gameObjectsList? Should i cast it to the pertinent manager inside the method (which seens like an inneficient option)?

Thanks in advance!

[Edit] Looking into design patterns page in wikipedia, i found another design pattern related to singletron. In my case, each manager follows the singletron pattern, but its somewhat equivalent to my singletron base class following a Multiton Pattern


texts: Should 3D transformations be represented by a 4x4 matrix or a 3x4 matrix?

texts:
Since 3D transformations are represented by 4x4 homogeneous matrices we know that their last row is always (0,0,0,1), and as such the behavior of this final row is implied so long as we know whether or not the transformation is operating on a vector (a 4x1 matrix with a w element of 0) or a point (a 4x1 matrix with a w element of 1).

If we have classes that represent points and vectors separately as 3x1 matrices with implied w coordinates then we can overload the * operator so that its behavior on both classes is separate and thus there is no need to store the final row of the transformation matrix in memory.

Now I can see how this would be a great optimization at first as it increases cache coherency instead of adding what is essentially padding to each transformation matrix. On the other hand, we will have to eventually use a full 4x4 matrix to handle the projection and perspective divide later on so is it worth it to store a transformation matrix as a 3x4 matrix only to later convert it into a full 4x4? Or would a good solution here be to make the projection matrix a 4x4 matrix and make the product of a transformation matrix and a 4x4 matrix another 4x4 matrix?

I'm sorry if this seems basic or like a question that answers itself but I was reading a book on game engine development and it used implications to handle interactions between transformation matrices with points and vectors, and other transformations separately, never multiplying by the final row and using implications instead. But on creation they would still stored the final row as (0,0,0,1) in memory to only be used in multiplication between a transformation matrix and a 4x4 matrix specifically and so I'm mostly just wondering if there may have been a good reason for that or not. Thanks in advance for the help.


texts: Will unlocking the framerate in XNA/MonoGame tell me how efficient my code is?

texts:
I have been unlocking the framerate in MonoGame via:

this.graphics.SynchronizeWithVerticalRetrace = false;
base.IsFixedTimeStep = false;

And using it as a basis for how efficient I am updating and drawing in the game.

At a resolution of 240 x 160 with nothing being drawn or updated except a frame counter I get an FPS value of 9,000 to 11,000 FPS.

If I add all my code back in it drops down to about 1,100 FPS.

Is this a good indication that my code is significantly slowing the GPU down (10x), and should I be concerned? The game is going to run at 60 FPS so I'm still pretty far away from that, but at what point in the unlocked frame rate should I be concerned?

GPU: AMD FirePro W5000 (FireGL V)


texts:
I am looking for a beginner-friendly explanation. The official website's explanation is too short and lead me to more questions than answers:

What is GLEW?

GLEW developer's page says:

  The OpenGL Extension Wrangler Library (GLEW) is a cross-platform
  open-source C/C++ extension loading library. GLEW provides efficient
  run-time mechanisms for determining which OpenGL extensions are
  supported on the target platform.

But what is an extension loading library?

OpenGL's wiki says

  An OpenGL Loading Library is a library that loads pointers to OpenGL
  functions at runtime, core as well as extensions.

What does it mean to load pointers to OpenGL functions?
What is an extension?
What does it mean by "core as well as extensions"?


texts: Factors to consider when building an algorithm for gun recoil

texts:
What would be a good algorithm for calculating the recoil of a shooting guns cross-hairs?

What I've got now, is something like this:

Define min/max recoil based on weapon size
Generate random number of "delta" movement
Apply random value to X, Y, or both of cross-hairs (only "up" on the Y axis)
Multiply new delta based on time from the previous shot (more recoil for full-auto)

What I'm worried about is that this feels rather predicable, what other factors should one take into account when building recoil? While I'd like it to be somewhat predictable, I'd also like to keep players on their toes. I'm thinking about increasing the min/max recoil values by a large amount (relatively) and adding a weighting, so large recoils will be more rare -- it seems like a lot of effort to go into something I felt would be simple.

Maybe this is just something that needs to be fine-tuned with additional playtesting, and more playtesters? I think that it's important to note, that the recoil will be a large part of the game, and is a key factor in the game being fun/challenging or not.


texts: What variables change the number of lightmaps

texts:
I need to know what changes the lightmap size.

For example what changes the lightmap from being 2*1024*1024 to 4*1024*1024 - having larger textures or having larger quads (having more models) or having more lights or does it depends on something else?


texts: How to move the arrow markers 1 unit only?

texts:
I'm new to learning C#. How can I move an arrow one unit at a time?

Here's the code I'm using now:

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

public class ArrowMovement : MonoBehaviour
{
    float directX;
    float directY;

    public float moveSpeed = 5f;

    private Rigidbody rb;

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

    }

    private void FixedUpdate()
    {
        float h = Input.GetAxis("Horizontal") * 100;
        float v = Input.GetAxis("Vertical") * 100;

        Vector3 vel = rb.velocity;
        vel.x = h;
        vel.z = v;
        rb.velocity = vel;
    }
}

I just know how to do basic move


texts: The camera does not capture movements in z-axis

texts:
I want to make a simple drag and drop card in Unity, where the card pops up a bit towards the screen when the drag begins (lifting effect), and then drops down back on the table when the drag ends.

My script looks like this:

public class Draggable : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    void IBeginDragHandler.OnBeginDrag(PointerEventData eventData)
    {
        this.transform.position = new Vector3(this.transform.position.x, this.transform.position.y, this.transform.position.z - 10);
    }

    public void OnDrag(PointerEventData eventData)
    {
        this.transform.position = new Vector3(Input.mousePosition.x, Input.mousePosition.y, -10);

    }

    public void OnEndDrag(PointerEventData eventData)
    {
        this.transform.position = new Vector3(this.transform.position.x, this.transform.position.y, this.transform.position.z + 10);

    }

}

The card is an image, and it is child of the canvas.
The render mode for the canvas is Screen Space - Overlay.

The drag works correctly, but I cannot capture the movements in the z-axis.
It does capture the movements in the z-axis when I change the render mode. However, then the card is too far away in the z-axis, and it moves with an offset with respect to the mouse pointer.

As far as I understood, I need to do something about realtive distances, but I how can I force the mouse pointer to be on z=0 plane.


texts: MySQL Recursive Query (kind of) help to determine tech tree prerequisites

texts:
I'm trying to figure out how to do what I can only call a recursive query (my knowledge of MySQL is extremely limited). The game I'm designing has a tech tree with items to research that will grant you stronger stuff down the line. The prerequisites are broken down in another table, since each tech item can have 0 or more prereqs.

CREATE  TABLE IF NOT EXISTS `tech` (
  `id` INT NOT NULL ,
  `name` VARCHAR(45) NULL DEFAULT NULL ,
  PRIMARY KEY (`id`) );
CREATE  TABLE IF NOT EXISTS `prereq` (
  `src_id` INT NOT NULL ,
  `prereq_id` INT NOT NULL );
INSERT INTO tech (`id`,`name`) VALUES(1001, 'Logic');
INSERT INTO tech (`id`,`name`) VALUES(1002, 'Classical Physics');
INSERT INTO tech (`id`,`name`) VALUES(1005, 'Global Economics');
INSERT INTO tech (`id`,`name`) VALUES(1008, 'Solar Power Collector');
INSERT INTO prereq (`src_id`,`prereq_id`) VALUES (1008,1005);
INSERT INTO prereq (`src_id`,`prereq_id`) VALUES (1005,1001);
INSERT INTO prereq (`src_id`,`prereq_id`) VALUES (1005,1002);
INSERT INTO prereq (`src_id`,`prereq_id`) VALUES (1001,NULL);
INSERT INTO prereq (`src_id`,`prereq_id`) VALUES (1002,NULL);

With this set up, I can query the tables and find that if I want solar power, I need to first research Global Economics:

SELECT t.name, t.id, GROUP_CONCAT(p.prereq_id ORDER BY p.prereq_id ASC)
FROM tech t LEFT JOIN prereq p on t.id=p.src_id
WHERE t.id=1008
GROUP BY t.name, t.id
ORDER BY t.id

What I'm trying to get at is a result set that include the next level of prerequisites, then the next, until we hit nodes that have NULL. So I'm looking for this:

id     name
1008   Solar Power Collector
1005   Global Economics
1001   Logic
1002   Classical Physics

Is this even possible within MySQL? I tried to use a cursor, but was unsuccessful. I could handle this within the actual code, but I'd rather it be done server side somehow.

Any help in pointing me in the right direction would be greatly appreciated!


texts: How to add undulation to a constraint-based chain?

texts:
I have a constraint-based chain composed of segments where each of the terminal segments has a fixed position.

My constraints are set up as follows:

var segments = [segment0, segment1, segment2, segment3, segment4, segment5, segment6]

# terminal segments follow head and anchor
segments[0].global_position = head.global_position
segments[segments.size() - 1].global_position = anchor.global_position

for x in range(4): # iterate 4 times

    for i in segments.size() - 1:
        var desired_distance = 8

        var current_segment = segments[i]
        var prev_segment_position = current_segment.global_position if i == 0 or i == segments.size() - 1 else segments[i - 1].global_position
        var next_segment_position = current_segment.global_position if i == 0 or i == segments.size() - 1 else segments[i + 1].global_position

        # get vector from previous to next and find midpoint
        var prev_to_next = next_segment_position - prev_segment_position
        var midpoint = prev_segment_position + prev_to_next.normalized() * prev_to_next.length() * 1/2

        # move current segment to midpoint
        var vec_to_midpoint = midpoint - current_segment.global_position
        current_segment.global_position += vec_to_midpoint

My question is: How can I implement random undulation in this chain?

In other words, I want the intermediate segments to move smoothly in a random wave pattern, while the terminal segments remain fixed to their positions.

Ideally, I'd set it up with some parameters than I could adjust to control the speed and volatility of the undulation.

I am working in Godot 3.1, but would like an engine-neutral explanation of the technique.


texts: Switching renderer off/on for an object in unity using C#

texts:
I have a GameObject called 'Stone' that is rendered on Game Play. I have attached a C# script called RenderOff to to make 'Stone' invisible on Game Play.

RenderOff.cs

using UnityEngine;
using System.Collections;

public class RenderOff : MonoBehaviour {

    void Start () {

        this.gameobject.renderer.enabled = false;

    }

}

It has errors - Type 'RenderOff' does not contain a definition for gameobject' and no extension methodgameobject' of type `RenderOff' could be found.

What does that mean ?


texts: how could RTT be so slow on my intel card?

texts:
I simply draw something into a render target, and use it as an normal texture. It's always working greate to me with my nvidia video card. But today I found my program ran terribly slow (less than 5 fps) on a intel card.

After running an analyse I found glGenerateMipmapEXT is the trouble maker, it costs most of the cpu time. Here's how I bind a RT texture:

  glBindTexture(GL_TEXTURE_2D, m_textureID);<br>
  glGenerateMipmapEXT(GL_TEXTURE_2D);

without glGenerateMipmapEXT the texture is nothing but pure white pic. Something wrong with my RTT?


texts: How to manage game objects, npcs, items?

texts:
i'm making a small 2D game, designed the maps with Tiled, and adding "basic" world object/items/npcs/mobs to test it a bit and have fun.
Now i have encountered a relatively huge problem, with further development of the world, as our small team has grown by 3 volunteers we have to cover large amounts of
(note most of this data, other than AI, is JSON)

quests
items
npcs
mobs
skills
armor
weapons

we tried to keep track of the editing with revisions, comments, we also used milestones for patching/fixes/hotfixes, and so on.

Our basic tools:

Spreadsheet, which has served well but we discovered that we can't do much with revisions of on a game item or weapon.
we also tried Redmine, but other than issues, this doesn't serve our needs

Can some suggest and alternative way of managing this, or any opens-source tool? that will just make our development a bit easier, than the pain that its right now.

Or is one of those situations that we need to develop a specific tool for our needs?


texts: How to offset particles from point of origin

texts:
Hi I'm having troubles off setting particles from a point of origin. I want my particles to spread out after a certain radius from a the point of origin. For example, this is what I have right now:

All particles emitted from a point of origin. What I want is this:

Particles are offset from the point of origin by some amount, i.e after the circle. What is the best way to achieve this? At the moment, I have the point of origin, the position of each particle and its rotation angle. Sorry for the poor illustrations.

Edit: I was mistaken, when a particle is created, I have only the point of origin. When the particle is created I am able to calculate the rotation of the particle in the update method after it has moved to a new location using atan2() method.

This is how I create/manage particles:
Created new particle at enemy ship death location, for every new particle which is added to the list, call Update and Draw to update its position, calculate new angle and draw it.


texts:
I have a unit vector (direction) which represent a rotation around Y axis,

and would like to turn this into a quaternion to represent the same rotation.

I use GLM library, but interested any library agnostic solution.

Should I pack the direction vector to a matrix then convert to quaternion? Is there a better way?

UPDATE:
As I said the matrix solution works already, but there must be a shorter way, as i don't need all dimension only one (around Y):

glm::quat q = glm::conjugate(glm::toQuat(
    glm::lookAt(glm::vec3(from.getX(), from.getY(), from.getZ()),
                glm::vec3(from.getX(), from.getY(), from.getZ()) + direction,
                glm::vec3(0, 1, 0)
    )
));


texts:
Setting: In our facility we have a 3D laboratory with 3 large displays (two edge-to-edge on orthogonal walls, one on the ground, also edge-to-edge). Its primary use-case is exploring 3D virtual environments. The control device is a Flystick, a 6 direction-of-freedom input device tracked by IR-cameras. One can query the stick's position in the room and its current orientation (rotation matrix).

Goal: I want to write a small tool which enables the user to use the stick as a pointing device to control the mouse cursor on the 3 screens.

Challenge: The stick does not have a pre-defined pointing direction. So even if I know its current rotation matrix I don't know which direction it is actually pointing at. That depends on its initial calibration (which may vary from application to application). So I need to figure out the stick's actual pointing direction on my own.

Plan: When starting my tool, I let the user point to the upper left corner of the first screen. Together with the current position of the stick I can calculate the pointing direction in the room's coordinate system. Now I transfere it into the stick's coordinate system by multiplying its inverse rotation matrix (at that moment) with that vector. This should give me the pointing direction in stick-space.

Now, if I want to determine the spot the user is pointing at for any other position & orientation, I need the stick's current position in room-space (check) and its pointing direction (also in room-space). To get that, I just need to apply the stick's current rotation matrix to the (stick-space) pointing vector which I determined during my calibration.

Results: So much for the plan. The calibration itself seem to work fine; and when only moving slightly from the screen corner the found pointing target seems to be reasonable. But when pointing for example on another screen, the results are totally wrong.

It seems that the stick's pointing direction in room space is incorrect.

Now the question is, is there a flaw in my approach? Did I miss something?


texts: GLSL: define a constant for both vertex and fragment shader

texts:
I have a constant for defining an array in the vertex shader. I want to use this constant also in the fragment shader to define another array of the same size. Naive attempts fail (simply use the constant of the vertex shader in the fragment shader or using a #define from the vertex shader). Is this somehow possible?

The only idea I can come up with is using something like an include statement, which seems to be added (source), but I didn't yet find the time to implement this.

Thank you in advance!


texts: How to debug shaders running on Android 4.x devices?

texts:
I have tried some of the existing inspectors such as RenderDoc and gapid, but none of them can be used with Android 4.x. Latest version of gapid requires Android 6.0 and RenderDoc requires Android 5.0.

But I need to debug shaders in my app running on a Galaxy Tab 3 8.0 (SM-T311, ARM Mali 400), which uses Android 4.2.2. I cannot upgrade its Android version.

The app was made with Unity 2018.4 and targets Android 4, ARMv7. How can I inspect & debug my shaders running on this kind of device?


texts: BEPUphysics collision with generated terrain?

texts: I've got randomly generated terrain which is stored in a indices and vertex buffer.  How do I go about using this for collision in BEPU?  It seems I can do it with a Mesh but it would be a waste to convert it to a Mesh :/.


texts:
I've been reading up how to lay out a game loop that'll work optimally in both great and not so great conditions but I think I've confused a few techniques together... so I have some questions...

Fixed Physics Step: If I fix my physics step because determinism is important in my game, and at some point the game falls behind and needs to catch up, would I need to update multiple times or is there a safe method of updating physics by double or triple steps? If I'm rolling my own physics should I write them in a particular way to facilitate this?
Input: If I need to update multiple times before the next frame should I check the input before updating each time or check once and leave the input for the next tick after that to handle?
Updating: How often do I really need to update a game so no lag is felt by the player? It seems like you can get away with well under 60tps but at what point do players feel the delay? Are there any drawbacks to updating less frequently than rendering?
Networked: If the game is networked through an authoritative server, would all machines have to update their client side predictive movement code at the same rate as the server to avoid constant visible repositioning or would the difference be minimal and virtually undetectable if I resolve potential jittering with smooth position correction?
Interpolation: Would interpolating the position of drawn objects between updates be something I'd only need to do if my game updated at a much slower rate than my fps or is it good to interpolate anyway? What would interpolating involve? Running another partial position update just before the draw or updating the next position in advance and using the partial step percentage (time passed sine last update) to advance positions that percentage between the current and next steps?
Render Timing: Is there a way (or a need) to draw a frame at the last moment before the screen refreshes?
Sleeping: After a draw when I don't yet need to update I should hand the thread back over to the OS, yeah? If I'm making a cross-platform game and some operating systems might wake my thread up a little earlier or later than I've specified is there a chance that might affect the game at all if my physics is fixed?


texts: Finding the components of Proportional Navigation in 2D

texts:
So, I've been scouring this, the Physics Exchange, Wikipedia, and the general web for information about Proportional Navigation, and I can't seem to wrap my head around how to find the individual terms that make up a PN equation, especially in a 2D environment.

Per Wikipedia:

a = N * lambda * V

Where:

a is the normal acceleration, that's fine. It's how much I should accelerate left or right from the missile's current heading.

N is a scaling factor. Sure. No problem there. Just fiddle with it.

lambda is the line of sight rate... What? It's how much the angle between the missile's heading and the position of the target change in an instant? Or something? Given the position and velocity of the target, and the position and velocity of the missile, I feel like this should be easy to figure out instantaneously, without having to 'save' the previous position of the target, but for the life of me I can't wrap my head around it.

V is the closing velocity. That's how fast I want to be going when I reach the target? Yes? Or is it the component of my velocity in the direction of the target? There's not much explaining this term that I can see.

Wikipedia offers another variation of the equation that involves the cross product, which I don't think works in this situation, since the cross product is explicitly 3D.

Wikipedia Article

Related Questions:

Implementing simple proportional navigation for a homing missile

How to Create an Intercept Missile for a Game

Calculating vector to aim for moving asteroid (3D asteroid game)


texts: How to implement explosion in OpenGL with a particle effect?

texts: I'm relatively new to OpenGL and I'm clueless how to implement explosion. So could anyone give me some ideas how to start? Suppose the explosion occurs at location $(x, y, z)$, then I'm thinking of randomly generate a collection of vectors with $(x, y, z)$ as origin, then draw some particle (glutSolidCube) which move along this vector for some period of time, says after 1000 updates, it disappear. Is this approach feasible? A minimal example would be greatly appreciated.


texts: How would one store global context data in an entity component system?

texts:
My question is this:

How would one store global context data, ie. world data information, current world time, etc in an entity component system?

I'm think of working towards building a Dwarf Fortress-style open ended world simulation game in C++. I've build up an entity component style game engine just for fun, and I'm currently trying to figure out how I am going to work in all the features I want. In addition to standard game play (rendering, physics, entity-specific component data, etc), I would also like to have some global contextual data that all relevant systems would have access to (ie, the world data like what year it currently is, whether global warming is happening, Any kind of thing that would be relevant to simulating a world). I had originally thought of making a "world" component, but this seems pointless and difficult if a lot of different systems need access to this logically "global" data.

Would it make sense to have a "world" component or should I store this data some other way?

I'd also thought of simply making this data global, thus giving access to any systems that would want to use it; it seems like a violation of entity-component principles in general, and maybe messy for other reasons, but I thought that it might really work.

The other thing I'd thought of would be to actually embed relevant world-context data directly into the systems themselves. For example, if I had an AgeSystem that "aged" all entities that have a getsWeakerAsTimePasses component or whatnot, then maybe this system could store relevant time data for the world directly as member data that it would use to calculate the passage of time and how much to age and weaken people, etc. This third option was my least favorite, but something that had occurred to me in brainstorming.

Can anyone advise?


texts: how can i set the y rotation of an object equal to another objects y rotation without rotating it on all the rest of the axis

texts:
Here is my attempttransform.rotation = new Vector 3(0,pivot.rotation.y,0);

I don't know what to do can you help in any way?
I have a camera that pivots around the player, but i need the player to rotate around the y axis of the pivot.

thanks in advance .


texts:
I'm trying to make a few game objects (moons) orbit a planet in unity. Basically just picture a planet in the center of the screen, and a few small moons that orbit the planet with a constant velocity. I have gotten this to work nicely using transform.RotateAround(), but I wanted to take advantage of the physics engine that unity provides for realistic "bouncing" of the game objects relative to others as they collide.

I have tried a few things such as Hinge Joints, Configurable Joints, and even just adding forces to try to get it to move in a spherical manner. I can't seem to get it to work correctly though. The configurable joint is the closest that I've come, but it's a bit off and it doesn't stay orbiting. It's likely my lack of knowledge with using rigidbodies in 3d, but I figured someone out there could help get me on the right track. Thanks in advance for any help!


texts: Rotating 2D positions without rotating graphics

texts:
I am working on a basic 2D game from an overhead/fake isometric perspective. Arrow keys move the camera left/right/up/down. The trouble occurs when I tried to add rotation.

I want the player to be able to rotate the camera (or map?) around the camera's center. The sprite positions should move during the rotation, but the sprite graphics should not rotate. For example, the sprites will always point "up" even as their position rotates around the screen.

I thought this was would be easy. Just keep track of the X, Y, and rotation of the camera. However, I am having some issues. Here is a snippet of my code (Go with the Pixel 2d library):

if win.Pressed(pixelgl.Key1) {
    camRot += camRotSpeed * dt
}
if win.Pressed(pixelgl.KeyLeft) {
    camX += camSpeed * dt
}
// similar for other key presses...

// Draw objects
for i, entity := range entities {
    sin := math.Sin(camRot)
    cos := math.Cos(camRot)
    adjustedCamX := camX*cos - camY*sin
    adjustedCamY := camX*sin + camY*cos
    adjustedMatrix := matrices[i].Moved(pixel.V(camX, camY)).Moved(pixel.V(adjustedCamX, adjustedCamY))
    entity.Draw(win, adjustedMatrix)
}

There are two issues: (1) after rotating, using the arrow keys now moves the camera at an angle instead of up/down/left/right and (2) I do not know how to rotate around the screen's center rather than whatever the current orientation is (0,0 in the bottom left?).

Note: The Pixel library makes use of transformation matrices rather than pure coordinates. At first I thought this was good (I can just do a rotation on the entire screen!) but then the graphics rotate as well. As such, I just try to emulate using pure coordinates and ignore the matrix (see the line with adjustedMatrix, the matrices[i] is just that entities' X Y position).

An example of what I am trying to achieve can be seen in the first few seconds of this video


texts:
A comparison of graphics libraries and their respective programming languages. A.K.A. "Which do I pick? With a twist."

I'm a long time professional programmer who never gave up on programming as a hobby. 3D programming has always appealed to me, but after some trial and error I always came back to (and got stuck on) the same question:

Which to choose?

C# with XNA.
C++ with DirectX.
Java with OpenGL.

All three appeal to me:

XNA, because it's managed, of high quality and very complete.
DirectX, because it's de facto standard for large games.
OpenGL, because it's open. It has a proven track record of high quality games built using it. + Eclipse hotswap functionality is sexy.

Keep in mind here that I will:

Use the above library and language for hobby use.
Will want to develop both 3D games and 3D tooling.
Might seek a job in a 3D programming industry.

For the sake of the argument, assume I am equally well versed in C#, C++ and Java. And have no preference for any of the three mentioned libraries. In reality I have a slight preference for one of those three, but the quality of the code I produce in the languages is the same.

Replies with sources as links are preferred! OGRE and Irrlicht (and similar) are also contenders, but not preferred because it introduces additional depencies on other developers.


texts:
i've been working on a 2d game for a bit now, almost all assets made but when ive tried to collaborate everything was quite glitched out, edits weren't saved, nothing was working at all. im not sure quite what the problem was because we were both on the latest version.

maybe i got to something wrong, or did something wrong im not sure. this was a few months ago now and ive been busy but i want to come back to this project. should i start over?


texts: Will lots of haptic feedback kill motors?

texts:
My game centers around joystick oddities, sort of, to make it more interesting.

I've got a cheap $6 joystick that is like a usb PS3 controller. Surprisingly, I find it of great quality, with excellent feedback.

I don't care about it so much, because of the price but I don't want to kill motors in a users expensive joystick.

Basically, it will be running for minutes at a time every once in a while.(Well, not constantly, but almost constantly)

Are these motors really good, and hard to wear down or will I quickly kill them?

Thanks for your time.


texts: Player doesn't jumps in Box2D implementation

texts:
Well, i'm trying to learn andEngine. I was able to successfully implement the move functionality for the player. Now, i'm trying to make the player jump using Box2D. I referred few online tutorials to do this but i am not able to make the player jump. Here's my code:

public class MyActivity extends BaseGameActivity {
@Override
    public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback)
            throws Exception {
         scene = new Scene();
        final float centerX = (CAMERA_WIDTH - back.getWidth()) / 2;
        final float centerY = (CAMERA_HEIGHT - this.back.getHeight()) / 2;

        Sprite backgr = new Sprite(centerX, centerY, back,
                this.getVertexBufferObjectManager());
         rcs1 = new Sprite(85, 250, rc1,
                this.getVertexBufferObjectManager());
         rcs2 = new Sprite(195, 240, rc2,
                this.getVertexBufferObjectManager());
         rcs3 = new Sprite(295, 250, rc3,
                this.getVertexBufferObjectManager());

        ans = new AnimatedSprite(86, 245, ttr,
                this.getVertexBufferObjectManager()) {
            @Override
            protected void onManagedUpdate(float pSecondsElapsed) {
                this.setPosition(pX, pY);
                super.onManagedUpdate(pSecondsElapsed);

            }
        };
        pw = new PhysicsWorld(new Vector2(0, SensorManager.GRAVITY_EARTH),
                false);
        final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(2f,0f, 0.9f);
        body = PhysicsFactory.createBoxBody(pw, ans, BodyType.DynamicBody,
                PhysicsFactory.createFixtureDef(0, 0, 0));
        bodyr1 = PhysicsFactory.createBoxBody(pw, rcs1, BodyType.StaticBody,
                objectFixtureDef);
        bodyr2 = PhysicsFactory.createBoxBody(pw, rcs2, BodyType.StaticBody,
                objectFixtureDef);
        bodyr3 = PhysicsFactory.createBoxBody(pw, rcs3, BodyType.StaticBody,
                objectFixtureDef);

        pw.registerPhysicsConnector(new PhysicsConnector(ans, body, true, true));
        scene.attachChild(backgr);
        scene.attachChild(rcs1);
        scene.attachChild(rcs2);
        scene.attachChild(rcs3);
        scene.attachChild(ans);
        pw.setContactListener(this);
        scene.registerUpdateHandler(pw);
        pOnCreateSceneCallback.onCreateSceneFinished(scene);

    }
private void jump() {

            body.setLinearVelocity(new Vector2(body.getLinearVelocity().x, 12));
                }
}

Please Help!


texts: Finding if 2 polygons intersect using clipper library

texts:
After realising my code was pretty inefficient at checking for polygon overlaps, I've turned to a mentioned library Clipper but finding it difficult to know hot to use it for this operation.

I am using unity Vector2[] for my shape descriptions:

//Square
Vector2[] square = new Vector2[] {
    new Vector2(0,0),
    new Vector2(1,0),
    new Vector2(1,1),
    new Vector2(0,1)
};

I want to be able to do the above boolean comparison of 2 shapes. If anyone knows Clipper well, what methods can I use to do this check?

I've recently tried the following but the result is always true even when the test shapes are completely separate from each other:

public bool CheckForOverLaps(Vector2[] shape1, Vector2[] shape2) {

    List<IntPoint> shape1IntPoints = Vector2ArrayToListIntPoint (shape1);
    List<IntPoint> shape2IntPoints = Vector2ArrayToListIntPoint (shape2);

    List<List<IntPoint>> solution = new List<List<IntPoint>> ();

    c.AddPath (shape1IntPoints, PolyType.ptSubject, true);
    c.AddPath (shape2IntPoints, PolyType.ptClip, true);
    c.Execute (ClipType.ctIntersection, solution, PolyFillType.pftNonZero, PolyFillType.pftNonZero);
    return solution.Count != 0;

}

private List<IntPoint> Vector2ArrayToListIntPoint (Vector2[] shape) {

    List<IntPoint> list = new List<IntPoint> ();

    foreach (Vector2 v in shape) {

        list.Add (new IntPoint (v.x, v.y));

    }

    return list;

}

And the tests:

    //Square
    Vector2[] square = new Vector2[] {
        new Vector2(0,0),
        new Vector2(2,0),
        new Vector2(2,2),
        new Vector2(0,2)
    };

    //Square
    Vector2[] square2 = new Vector2[] {
        new Vector2 (1, 1),
        new Vector2 (3, 1),
        new Vector2 (3, 3),
        new Vector2 (1, 3)
    };

    //Square
    Vector2[] square3 = new Vector2[] {
        new Vector2 (2, 0),
        new Vector2 (4, 0),
        new Vector2 (4, 2),
        new Vector2 (2, 2)
    };

    //Square
    Vector2[] square4 = new Vector2[] {
        new Vector2 (4, 0),
        new Vector2 (6, 0),
        new Vector2 (6, 2),
        new Vector2 (4, 2)
    };

    Assert.IsTrue(tc.CheckForOverLaps(square,square2));
    Assert.IsFalse(tc.CheckForOverLaps(square,square3));
    Assert.IsFalse(tc.CheckForOverLaps(square,square4));

Many thanks.


texts: Navigating to android app settings > permission from unity

texts:
I am trying to rout from my unity application to android app settings permissions. till now I achieved to rout to app settings, But i want to take 1 step more to go inside permission i mean App Settings > Permissions.

Code:

try
        {
#if UNITY_ANDROID
            using (var unityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
            using (AndroidJavaObject currentActivityObject = unityClass.GetStatic<AndroidJavaObject>("currentActivity"))
            {
                string packageName = currentActivityObject.Call<string>("getPackageName");

                using (var uriClass = new AndroidJavaClass("android.net.Uri"))
                using (AndroidJavaObject uriObject = uriClass.CallStatic<AndroidJavaObject>("fromParts", "package", packageName, null))
                using (var intentObject = new AndroidJavaObject("android.content.Intent", "android.settings.APPLICATION_DETAILS_SETTINGS", uriObject))
                {
                    intentObject.Call<AndroidJavaObject>("addCategory", "android.intent.category.DEFAULT");
                    intentObject.Call<AndroidJavaObject>("setFlags", 0x10000000);
                    currentActivityObject.Call("startActivity", intentObject);
                }
            }
#endif
        }
        catch (System.Exception ex)
        {
            Debug.LogException(ex);
        }

Help if it is possible... any help is appropriated. Thank in advance.


texts: How to create a thread in XNA for pathfinding?

texts:
I am trying to create a separate thread for my enemy's A* pathfinder which will give me a list of points to get to the player. I have placed the thread in the update method of my enemy. However this seems to cause jittering in the game every-time the thread is called.

I have tried calling just the method and this works fine. Is there any way I can sort this out so that I can have the pathfinder on its own thread? Do I need to remove the thread start from the update and start it in the constructor? Is there any way this can work?

Here is the code at the moment:

bool running = false;
bool threadstarted;
System.Threading.Thread thread;

public void update()
{
    if (running == false && threadstarted == false)
    {
        thread = new System.Threading.Thread(PathThread);

        //thread.Priority = System.Threading.ThreadPriority.Lowest;
        thread.IsBackground = true;
        thread.Start(startandendobj);
        //PathThread(startandendobj);
        threadstarted = true;
    }
}

public void PathThread(object Startandend)
{

    object[] Startandendarray = (object[])Startandend;
    Point startpoint = (Point)Startandendarray[0];
    Point endpoint = (Point)Startandendarray[1];

    bool runnable = true;
    // Path find from 255, 255 to 0,0 on the map
    foreach(Tile tile in Map)
    {
        if(tile.Color == Color.Red)
        {
            if (tile.Position.Contains(endpoint))
            {
                runnable = false;
            }
        }
    }
    if(runnable == true)
    {
        running = true;
        Pathfinder p = new Pathfinder(Map);
        pathway = p.FindPath(startpoint, endpoint);
        running = false;
        threadstarted = false;
    }
}


texts: Balancing game difficulty against player progression

texts:
It seems that the current climate of games seems to cater to an obvious progression of player power, whether that means getting a bigger, more explosive gun in Halo, leveling up in an RPG, or unlocking new options in Command and Conquer 4.

Yet this concept is not exclusive to video or computer games -- even in Dungeons and Dragons players can strive to acquire a +2 sword to replace the +1 weapon they've been using.

Yet as a systems designer, the concept of player progression is giving me headache after headache. Should I balance around the players exact capabilities and give up on a simple linear progression? (I think ESIV:Oblivion is a good example of this) Is it better to throw the players into an "arms race" with their opponents, where if the players don't progress in an orderly manner, it is only a matter of time until gameplay is unbearably difficult? (4th Edition DnD strikes me as a good example of this) Perhaps it would make most sense to untether the core gameplay mechanics from progression at all -- give them flashier, more interesting (but not more powerful!) ways to grow?


texts: Change rigidbodys default height from floor?

texts:
I am new to unity and I have a few questions:
There is a mesh that has a rigidbody and a box collider that I placed on the scene.
I also added a generic terrain to the scene from the 3D objects menu.
When I put the mesh at a certain height and it drops I notice that it always stops at Y = 0.500000.
How do I change this default value? What controls this? For example, does unity have it so that when any other type of collider hits the terraincollider the other collider automatically updates the rigidbody to be 0.50000 above it and this only happens when it hits a terrain collider?
If this is the case, Is this causing a collision every frame and adjusting it to 0.50000 every frame so it doesnt fall through?
Finally, assuming that the Y = 0.50000 value above the ground cannot be changed, if I wanted something to "hoover" above the ground, would I always need to take that the maximum amount that I can get to the ground is Y = 0.500000?


texts: How to read a data from multiple selected text files in unity

texts:
This question is based off of a previous one.

How to read a data from text file in unity

But I cant get the code to work for my purpose. I want to be able to choose which CSV files needs to be edited instead of just assigning one file.

Here is the code

private void readData()

{
    TextAsset csvFile = Resources.Load("Assets/Resources/Test1.csv") as TextAsset;

    string[] records = csvFile.text.Split(lineSeperater);
    foreach (string record in records)
    {
        string[] fields = record.Split(fieldSeperator);
        foreach (string field in fields)
        {
            contentArea.text += field + "\t";
        }
        contentArea.text += '\n';
    }

I want to access the file using a given link and then write to it. but for some reason it keep saying "Object reference not set to an instance of an object" referring to "string[] records = csvFile.text.Split(lineSeperater);"

I'm new to coding so it might be missing something silly. but as far as i know it should make sense? as csvFile is given the usl, but the url is not being found when its searching for csvFile.text, but then again, i might be completely wrong.

Could someone maybe help me and guide me in the right direction?


texts:
I'm creating a game in Intel XDK, and using their API to get the viewport width and height.  These are coming back at 1122 pixels and 746 pixels, respectively.

When adding my text at 150 pixels down and 100 pixels across its being placed in the center at the bottom.

var canvas= document.getElementById('game');
var ctx = canvas.getContext('2d');
var width = 1122,height = 746;

ctx.fillText(window.innerWidth+' - '+window.innerHeight,100, 150);

That is writing on the screen 1122 - 748, but it's placed at the bottom of the screen. Not 100 pixels down by 150 pixels across. - It's directly in the middle.


texts: Shader Maker version 130 is not supported

texts:
I am trying to compile a vertex shader with Shader Maker and if I try to use the version 130 it says:

  Compiling Vertex Shader
  ERROR: 0:3: '' :  version '130' is not supported

  Compiling Fragment Shader

I need to use the version 130. Now I installed Shader Maker from it's site. I wonder if there is a way to use the version 130, what should I do?


texts: Deactivate current object in array and activate next one by using button click?

texts:
How to deactivate current object in array and activate next one by using button click?

public GameObject[] gameObjects;
private int numOfgameObjects;

void Start()
{

  //current object
  gameObjects[0].SetActive(true);

  int numOfgameObjects = gameObjects.Length;

  for (int i = 0; i < numOfgameObjects ; i++)
  {
      gameObjects[i].SetActive(false);
  }

}

public void NextPrefab_ButtonClick()
{
  // Some Code to deactivate current object and activate next one
}


texts: Unity Change Rotation of Animated Object at Runtime

texts: So I made an animation, but sometimes i nedd to rotate the animation, but for some reason it isnt working. I can change the rotation of the object and then click play and it works perfectly like in the gif, but if I attempt to change the rotation on runtime nothing happens. Why?


texts: Unity 5 Server Side Physics - Alternative to constant position update?

texts:
I am looking into reducing load in client server games for a uni project and am looking at physics. The idea is that if a very low powered device tries to carry out some physics heavy action that it will be very slow, therefore the power of the server can be used.

So using the power of the server, in Unity, an RPC can be sent to the server, the server carries out the physics (say throwing a box into the air) and then transmits the position of the box as it moves back to the client. But this seems to me to be putting alot of pressure on the network.

What I am getting at is, is there a way to have a server carry out physics reactions and send the results of those back (such as a jumping box) in a way that doesn't pressure the network?

All I can think of is that when the box is moving on the server that the position code is sent to the client, and then when there is a new position that is sent to the client again. If an object is moving alot this seems to be alot of position updates sent across the network, taking up bandwidth.

So is there another method instead of constantly sending position updates?


texts: Why is my mesh outside its collision component grid?

texts:
I've created a blueprint (well, two of them, as a test since the first one wasn't working right) with an sphere component around a mesh, as in the picture:

As you can see, the mesh is well placed inside the collision component outer grid lines, but when I place this blueprint in the editor the mesh appears displaced from the grid:

I've checked this is not a merely visual bug of the editor; the collision component is really at different coordinates than the mesh, making all kind of strange collisions and side effects. However, I fail to see why is this happening, or what can I do to solve it. The blueprint is based on a custom C++ class, but I'm not making anything related to position in there. I paste the full code of that class:

#include "FPSBall.h"

// Sets default values
AFPSBall::AFPSBall(const FObjectInitializer& ObjectInitializer)
{
    // Crear una malla
    MeshComp = ObjectInitializer.CreateDefaultSubobject<UStaticMeshComponent>(this, TEXT("Mesh"));
    MeshComp->SetMobility(EComponentMobility::Movable);

    // Crear un component esfèric per a les colisions
    CollisionComp = ObjectInitializer.CreateDefaultSubobject<USphereComponent>(this, TEXT("Envolvent esferic"));
    CollisionComp->BodyInstance.SetCollisionProfileName("Pilota");
    RootComponent = CollisionComp;

    // Valors inicials de transformació
    Velocitat = 0.0f;
    Direccio = FVector(1, 2, 3);
    Rotacio = FRotator(3, 2, 1);
}

void AFPSBall::Shoot(float velocitat, FVector a_on, FRotator spin, FVector hit)
{
    Velocitat = velocitat;
    Direccio = a_on;
    Rotacio = spin;
    CollisionComp->AddImpulse(Direccio * Velocitat);
}

Can anyone point me towards a solution? I could try to fix things in the class constructor, but I fail to see why this is not working out-of-the-box and I don't want to try fixing things that shouldn't be broken to start with.


texts: Does the quality of a video card connected to a monitor used in play mode with Unreal Engine matter?

texts:
I have 3 video cards:

inferior onboard vga (not connected to a monitor)
inferior discreate vga (connected to a secondary monitor)
superior discreate vga  (connected to a primary monitor)

When using Unreal Engine in play mode, should the play window be viewed on the   monitor connected to superior vga?


texts: After a succesful glLinkProgram, should I delete / detach my shaders?

texts:
After I have a linked program, and thinking about defensive programming, should I delete and detach the shaders used to link this program?

If yes, is that going to free any resources? Or do these shader objects only going to be freed after a glDeleteProgram call?

edit: Just for clarification what I am doing is (which is consistent with the answer):

  glCreateShader -> glShaderSource -> glCompileShader -> glCreateProgram -> glAttachShader -> glLinkProgram -> glDetachShader -> glDeleteShader -> draw using this shader program -> and when I don't need this shader anymore glDeleteProgram


texts: Collision detection and response in an Entity System

texts:
More fun with an ES...

Currently, I have a few systems:

Renderer (Renderable attribute, Transform attribute)
Motion (Movable attribute, Transform attribute, Renderable attribute [for bounding boxes, etc])
Input (InputReceiver attribute)
etc.

I'm adding collision detection. My first thought was to add a new system that performs collision. It makes sense to me to keep this isolated from the Motion system since not all things that move or are animated necessarily participate in collision detection - cameras, fog, etc. - but it seems that Collision and Motion are interdependent.

When Motion moves an entity, the transformation needs to be validated with Collision, and the movement either cancelled, or adjusted (bouncing, stopping at a wall, etc.).

An alternative would be to create a Collidable attribute that maintains a reference to a collision object - kd-tree, octree, etc. that is shared among entities that can collide with one another. The Motion system would then check for that attribute, and use it to check or adjust movement.

From a code perspective, that's an acceptable solution. However, from an ECS architecture point of view, it seems that it's pushing logic into the Motion system that doesn't apply to all of the entities that have a Movable attribute.

I could also store a motion vector in the Movable attribute, and have the Collider system adjust Transform as needed, but that'll involve duplicating functionality between Motion and Collider, or a callback from Collider to Motion with some data about the collision location and surface data for bounce/reflection, etc.

This may fall under the heading of "special case hack" but I'd like to get some input from those that have handled this before without creating a ton of edge case code.

The Question
What's a good way to avoid tight coupling between motion and collision systems when it seems that they require knowledge of each other?


texts: Simple collision detection for 2D match 3 gems game

texts:
I'm building simple match 3 game.
I have the parts where I move the gems with the mouse only in the straight X or straight Y, up and down and both sides, no 45 degrees movements on grid.
I'm looking for simple collision detection algorithm for the situation when for example:

a gem is moved up or down or left or right and there is another gem.
How can it detect it touched a gem and which gem it is?


texts: Emulating 3d trajectory in top-down 2d game?

texts:
As the title suggests, I am wondering if it's possible to emulate a 3d arrow trajectory to a top-down 2d game? If you would look at this clip of Age of Empires 2 game, especially when archers are firing from bottom to top. Can the parabola/arc of the trajectory (in that certain view angle) be emulated in a 2d orthographic, top-down game? So that the arrows would look like they're in 3d space. I know it's tricky but I wonder if there's some computation available for this.

If you could point me in the right direction or some sample code I would be very grateful. I've only implemented this projectile motion in a side-scroll view.

Thank you in advance.


texts: How to inform pathfinding of solid objects blocking path?

texts:
I'm sure this has been asked before, but I couldn't find the thread. Let me know if you can locate the duplicate.
So, I have a my level is an array of tiles, where a tile can either be solid or walkable. I then use A-star to path-find my enemies from one location of the floor to another.
The issue is that I also have solid entities. As an example, I may spawn 3 breakable vases at a certain location. They can be larger or smaller than a single tile, and they are just objects in the world, not tiles themselves.
Because they are not a part of the A-star grid (can they? they're larger or smaller than a tile, and their position is not locked to the grid), the path-finding is not aware of their existence, since it only operates on its grid. As a result, sometimes the chosen path for the enemy to follow flows through the solid vases, so the enemy just gets stuck at that location.
Is there a solution that alleviates this problem? I want the enemies to path around the vases (until they're destroyed, of course), instead of just getting stuck trying to unsuccessfully move through them.


texts: Launch Velocity for Simple 3D Projectile

texts:
This is a pretty easy question, but I can't quite figure out the answer. I have:

The initial position of a projectile.
The gravity vector.
The (stationary) target I want to hit.
A maximum launch speed of the projectile.

I want to calculate the initial velocity the projectile must be launched at to hit the target, assuming it follows a ballistic trajectory.


texts: How do you design a record/replay system for a frequently changing game?

texts:
I'm working in a free MMORPG and I have a problem.

I'm (with other people) developing a video recording system for the game. The idea is basically: we record all the packages sent & received with timestamps, plus some local data from the client, and then dump it in a file. For playing the video, we just emulate everything that's on the file. We also have an option to export the video to avi with ffmpeg.

The problem is: when we change between versions of the game, it is hard to maintain backwards compatibility for the video (commands added / removed, function changes, etc). Is there a good way to handle this problem? instead of having a bunch of different players and choose the right one for each version of the video file?

It would be helpful to know how does other games handle this situation.

Thanks for the help, sorry for my english.


texts: Project line segment onto a vertical line

texts:
If I had a vertical line (which its x is 0) and 2 vectors which connected together to form a line segment, would it be possible to "project" the line segment onto the vertical line?

Eg.

If all I had was Vector 1 and Vector 2, would it be find where Vector 3 is along the vertical line?


texts: How can I publish my game (*.aab file) on google play?

texts:
I select arm64 (64 bit) and x86 and amrv7 and select build app bundle in player setting so but when I want publish so I have an error like :
Error
This release is not compliant with the Google Play 64-bit requirement
The following APKs or App Bundles are available to 64-bit devices, but they only have 32-bit native code: 2. Include 64-bit and 32-bit native code in your app. Use the Android App Bundle publishing format to automatically ensure that each device architecture receives only the native code it needs. This avoids increasing the overall size of your app.

I tried following the steps listed in this Stack Overflow post, but the problem remains.
PLease answer me, why no people answer in this web site?


texts: guys! Is it possible to reverse video or apply a rewind in Unity 5? I searched in the web but could not find the solution.


texts: How to calculate collision detection from big rectangle to small rectangle?

texts:
I have big rectangle that can move from side to side, its boundaries can't enter the small rectangle inside it, the anchor point is in the middle of both of them.

Let's say the big rect is 1000 * 1000, and the small one is 200 * 200
in the game the small rect is the "camera" and the big rect is the ground, only the ground moves.

The solution can be in any programming language.

Here is some drawing to show what I mean :


texts: What's the URL of the video showing an EA representative talking about game programming?

texts:
The video shows an EA representative talking about how a programmer can get into the industry by showing some demos (in fact, he shows a physics demo presented by a candidate who wanted a job at EA). The demo shown depicts kind of a ragtime doll made of yellow cobblestones.

I don't remember if I watched on YouTube or Vimeo and I frankly cannot find it after a few hours of work. I just remember the fact that it was taken at a GDC or a SIGGRAPH convention.

Thanks in advance. I'm really frustrated because I'd love to show this video to some fellow developers (coders).