texts:
In my XNA game I have two objects that collide. When the first object collides with the other it is able to latch on to it and move it about the world. I am having a problem with the math here (Math isn't my strong point). I currently have the second object latch on to the first and move around with it, but I cannot get it to keep it's original direction. So, if the object is facing up it should keep this direction relative to how it is being rotated with the original item.

Any tips on how I could best to achieve this?


texts: Equivalent to Draw() method in Unity project?

texts: I have been using xna/monogame before this. So I read tutorials about unity, made some classes, loaded some sprites, everything "seems" to be going good, but I can't figure out how to add things into the environment, could anyone tell me or guide me to what's the equivalent of Monogame's Draw() method in Unity? Thank you.


texts: What is the simplest way to calculate energy earned based on time?

texts:
A player has 0 energy, and gains 5 every 15 minutes, but has a maximum of 100 energy.

How would I be able to both store this in a database, and then recall the data later, to figure out how much energy the player now has?

The only way that I can think of is to save both the last updated time as well as the energy level at the last update, but that feels like it is not the best way.

Are there alternatives to this that are more efficient or 'better' and feel less kludge-y?


texts: How can I destroy particles on collision with specific a GameObject?

texts:
I wrote a script to manage my Particle System emission. The starting lifespan is set to infinite so that the particle never dies until it reaches a specific collider. I didn't find any method to destroy a specific particle in the Unity Manual.
How can I do this?
Here's the code (updated to show the partial fix)
using UnityEngine;
using System.Collections.Generic;

public class PlayerDamage : MonoBehaviour
{
    private ParticleSystem ps;
    public List<ParticleCollisionEvent> collisionEvents;
    public int attackValue = 1;

    //
    [Range(0.0f, 100f)]
    public int maxParticles;
    public float particleLife;
    public bool neverDies;
    public float particleSpeed = 8.0F;

    void Start()
    {
        ps = GetComponent<ParticleSystem>();
        collisionEvents = new List<ParticleCollisionEvent>();
        //
        var collision = ps.collision;
        collision.enabled = true;
        collision.type = ParticleSystemCollisionType.World;
        collision.mode = ParticleSystemCollisionMode.Collision3D;
    }

    void OnParticleCollision(GameObject other)
    {
        int numCollisionEvents = ps.GetCollisionEvents(other, collisionEvents);

        Rigidbody rb = other.GetComponent<Rigidbody>();
        int i = 0;

        while (i < numCollisionEvents)
        {
            if (rb.CompareTag("Enemy"))
            {
                BaseHealth baseHealth = other.GetComponent<BaseHealth>();

                if (baseHealth != null)
                {
                    Vector3 pos = collisionEvents[i].intersection;
                    Vector3 force = collisionEvents[i].velocity;// * 10;
                    rb.AddForce(force);
                    baseHealth.TakeDamage(attackValue);
                }
            }
            i++;
        }
    }

    void Update()
    {
        var collision = ps.collision;
        collision.maxKillSpeed = particleSpeed;

        Debug.Log("Particles Alive Count: " + GetAliveParticles());

        ps.Emit(maxParticles);
        var main = ps.main;
        main.maxParticles = Mathf.RoundToInt(maxParticles);
        main.startLifetime = particleLife;

        if (neverDies)
        {
            particleLife = float.PositiveInfinity;
        }
        else
        {
            particleLife = 5f;
        }
    }

    int GetAliveParticles()
    {
        ParticleSystem.Particle[] particles = new ParticleSystem.Particle[ps.particleCount];
        return ps.GetParticles(particles);
    }
}


texts: What's a good alternative to buying a console devkit?

texts:
I don't have the cash to stump up for a PS3 or 360 devkit, but the G3, G4 and G5 macs are running with PowerPC chips, which I believe is virtually the same architecture as the 360, and only missing the SPUs from the PS3, so I would like to know which Macs would be good for profiling code with.

I'm after a machine that would give me equivalent timings (not actual timings, but scale the same given difference code) so I'm looking for ones that have about the same cache size and memory bandwidth ratios as the consoles. Are there any specific Macs that have these traits?

The reason I need one is that I'm developing a new programming language for games development that specifically targets the current and potential future of console hardware. One aspect of this is the in-order microcode expanding risc chips at the core of both the 360 and the PS3, and probably the next generation too, which is why I want a PPC based mac, as I'd heard that places like where I work used to use Macs as pretend 360 devkits until the hardware design was in a fit state to send out prototype 360s.

At a later date, I'll want to get my hands on an FPGA (as that's the only other route I can see consoles heading any time soon), and a cluster (as they are good practice for ensuring your task scheduling and separation are up to scratch), but for now I just need to know if there is a sweetspot machine that had very similar specs to the current consoles' CPU and memory bandwidth.


texts:
So my problem is that I have a nice green glass material in blender which I imported to UE4 (4.8.1) but in the editor the material was just a simple green colour.

I have no idea what I should do to fix this problem.

I appreciate any help. If you need any more details or pictures, let me know.

Thank you

Glass in blender:

Material in blender:

Glass in UE4:

Material in UE4:


texts:
In my game I use particle effect for various purposes. In that I detect the completion of the particle effect. Basically I want to do something after completion of the particle effect. But the problem is that I didn't able to find the particle effect completion. So any community member please help me.

EDIT : I was creating particle effect using following code

    pointParticleEmtitter = new PointParticleEmitter(pX, pY);

    particleSystem = new ParticleSystem(pointParticleEmtitter, maxRate,
            minRate, maxParticles, mParticleTextureRegion.deepCopy());

    particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE);
    particleSystem.addParticleInitializer(new ColorInitializer(0f, 0f, 1f));
    particleSystem.addParticleModifier(new AlphaModifier(1, 0, 0, 0.5f));
    particleSystem.addParticleModifier(new ExpireModifier(0.5f));
    gameObject.getScene().attachChild(particleSystem);

Using above code the particle effect was started but when finished that I want to detect. After finishing effect I want to remove the object from the scene.


texts: When tracing how do I tell if I hit a wall or floor?

texts: I perform a trace and when it hits the world I get a location and the surface normal.  Does anyone have a good way to find out if I hit a wall or a floor?


texts:
I'm working on a little app for a school project , which should be manipulating 3D objects. And i'm stuck with the rotation , as i'm facing what i think is called the gimball lock ?
here's a video I uploaded that clarifies my problem :
https://youtu.be/MT8nTAkvD6k

Now , from what I have understood , multiple rotations change the orientation of the object , but keep the X , Y , Z axis fixed , is that it ? Without knowing a lot about openGL , i thought that some projections like these would be enough :
say Alpha is the angle following the rotation around X; The new Y and Z (let's Call them Y' and Z')axis would have this equation :

Y'=cos(Alpha)Y+sin(Alpha)Z

Z'=-sin(Alpha)Y+cos(Alpha)z

Based on this , i wrote this code (this method displays the teapot)

void Teapot::PrintObj()
{
        glLoadName(_NameStack);
        glPushMatrix();
        Translated();
        RotatedX();
        RotatedY();
        RotatedZ();

glColor3ub(_Color.red,_Color.green,_Color.blue);
glutSolidTeapot(2);

if(_Selected){WiredTeapot();Guizmo();}

        glPopMatrix();
};

Now this is the RotatedX method :

void Object3D::RotatedX()
{
rotY.x=0;
rotY.y=cos((angles.x/180.0f)*3.141592);
rotY.z=sin((angles.x/180.0f)*3.141592);

rotZ.x=0;
rotZ.y=-sin((angles.x/180.0f)*3.141592);
rotZ.z=cos((angles.x/180.0f)*3.141592);

glRotated(angles.x,rotX.x,rotX.y,rotX.z);
}

all the variables are declared within the class : the rotX , rotY and rotZ are the 3 vector axis , every time the object undergoes a rotation , these axis are modified;

The RotatedY method now :

void Object3D::RotatedY()
{
rotX.x=cos((angles.y/180.0f)*3.141592);
rotX.y=0;
rotX.z=-sin((angles.y/180.0f)*3.141592);

rotZ.x=sin((angles.y/180.0f)*3.141592);
rotZ.y=0;
rotZ.z=cos((angles.y/180.0f)*3.141592);
glRotated(angles.y,rotY.x,rotY.y,rotY.z);
}

Same thing , if this method is called it means that the object is rotated around the Y axis , hence the modification of the X and Z axis position.

and now the RotatedZ :

void Object3D::RotatedZ()
{
rotX.x=cos((angles.z/180.0f)*3.141592);
rotX.y=sin((angles.z/180.0f)*3.141592);
rotX.z=0;

rotY.x=-sin((angles.z/180.0f)*3.141592);
rotY.y=cos((angles.z/180.0f)*3.141592);
rotY.z=0;
glRotated(angles.z,rotZ.x,rotZ.y,rotZ.z);

I'm really struggling to make this work ; I've looked on the net and saw things like Quaternions (i don't even know what that is).

Thanks for helping me !


texts: Screen Space Reflections: Artifacts problem

texts:
I'm trying to implement a simple (so far) screen space reflections shader. Below is my code:

const int numBinarySearchSteps = 100;
const int maxSteps = 400;
const float rayStep = 0.01; // 25;
const float minRayStep = rayStep/2.5;

vec3 BinarySearch(vec3 dir, inout vec3 hitCoord, out float dDepth, out int hit)
{
    float depth;

    for(int i = 0; i < numBinarySearchSteps; i++)
    {
        vec4 projectedCoord = projectionMatrix * vec4(hitCoord, 1.0);
        projectedCoord.xyz /= projectedCoord.w;
        projectedCoord.xyz = projectedCoord.xyz * 0.5 + 0.5;

        depth = texture2D(depthMapTex, projectedCoord.xy).x;

        vec4 viewSpaceDepth = inverse(projectionMatrix) * vec4(projectedCoord.xy, depth * 2.0 - 1.0, 1.0);
        viewSpaceDepth.xyz /= viewSpaceDepth.w;

        dDepth = viewSpaceDepth.z - hitCoord.z;

        if(dDepth < 0.0)
            hitCoord += dir;

        dir *= 0.5;
        hitCoord -= dir;
    }

    vec4 projectedCoord = projectionMatrix * vec4(hitCoord, 1.0);
    projectedCoord.xyz /= projectedCoord.w;
    projectedCoord.xyz = projectedCoord.xyz * 0.5 + 0.5;

    hit = 1;

    return vec3(projectedCoord.xy, depth);
}

vec4 RayCast(vec3 dir, inout vec3 hitCoord, out float dDepth, out int hit)
{

    dir *= rayStep;

    float depth;

    /*vec4 projectedCoord = projectionMatrix * vec4(hitCoord, 1.0);
        projectedCoord.xyz /= projectedCoord.w;
        projectedCoord.xyz = projectedCoord.xyz * 0.5 + 0.5;

        depth = texture2D(depthMapTex, projectedCoord.xy).x;

    return vec4(vec3(depth),1.0);*/

    for(int i = 0; i < maxSteps; i++)
    {
        hitCoord += dir;

        vec4 projectedCoord = projectionMatrix * vec4(hitCoord, 1.0);
        projectedCoord.xyz /= projectedCoord.w;
        projectedCoord.xyz = projectedCoord.xyz * 0.5 + 0.5;

        depth = texture2D(depthMapTex, projectedCoord.xy).x;

        float zNear = 5.0;
        float zFar = 2000.0;
        float z_n = 2.0 * depth - 1.0;
        float z_e = 2.0 * zNear * zFar / (zFar + zNear - z_n * (zFar - zNear));

        /*vec4 viewSpaceDepth = inverse(projectionMatrix) * vec4(projectedCoord.xy, depth * 2.0 - 1.0, 1.0);
        viewSpaceDepth.xyz /= viewSpaceDepth.w;*/

        dDepth = -hitCoord.z - z_e;

        if(dDepth > 0.0){
            if (dDepth >= length(dir)) {
                // Inconclusive
                hit = 2;
                return vec4(0.0);
            }
            return vec4(BinarySearch(dir, hitCoord, dDepth, hit), 1.0);
        }
    }
    hit = 0;
    return vec4(0.0, 0.0, 0.0, 0.0);
}

vec3 ssr()
{
    // Reflection vector
    vec3 reflected = normalize(reflect(normalize(viewSpacePosition), normalize(viewSpaceNormal)));

    // Ray cast
    vec3 hitPos = viewSpacePosition;
    float dDepth;

    int hit;  /* 0 = no hit, 1 = good hit, 2 = nonsense hit */
    vec4 coords = RayCast(reflected /** max(minRayStep, -viewSpacePosition.z)*/, hitPos, dDepth, hit);

    vec3 color;
    if (hit == 1) {
        color = texture2D(colorMapTex, coords.xy).rgb;
    }
    else {
        color = vec3(0.0);
    }
    return color;
}

So far, all it does is just return the color of every pixels purely specular reflection, or black if there is no reflection on the screen or if the reflection ray passes behind an object.

My issue is that I get these bizarre artifacts where the pixel gets a color (dDepth >= length(dir)), even though dDepth is supposed to be way larger than length(dir). I've been stuck on debugging this for ages now and I'm wondering if anyone can see the mistake?

This is the scene using just a simple shader (to the right), and the scene running only the SSR-shader (on the left)

Extremely thankful for any help!!!
Simon


texts: How do I calculate the visible area of a big isometric map?

texts:
I have a simple isometric map of 128px x 128px, tile in a 2D field [xxxx][xxxx] I have a problem with my calculating. I need to get startx:[0], startY[0] and endX[20], endY[10], if I know the screen width and height, and the camera offset like this:

(not effective for big maps)

This is my current code:

starti = (-camera.xOffset - tileWidth) / 64;
int endi = (-camera.xOffset + camera.width + tileWidth) / 64;
int startj = (-camera.yOffset - tileHeight) / 64;
int endj = (-camera.yOffset + camera.height + tileHeight) / 64;

Point start = twoDToIso(new Point(startx,starty));
Point end = twoDToIso(new Point(endx, endy));
for (int i = start.X; i < end.X; i++)
{
    for (int j = start.Y; j < end.Y; j++)
    {

This does not work; it will create something like this:

It does something, but when I move and my offset is changed, it does not work at all. How do I calculate the visible lines on a big isometric map?


texts: How can I deactivate and activate a button?

texts:
I have a code that keeps a gameObject between scenes, the theme is that this gameObjecte has as a child a button, which I can change the linerenderer color, besides changing the image of the button according to the selected color and thus keep the data between scenes. then when I change to the next scene I deactivate the button with the meteodo "dehabilitar()"  and in the others it is not necessary, then when I change to the next scene I deactivate the button and it is not shown, but when I go back to the next scene and call the function " habilitar() "the button is not displayed. If someone can help me in what I have bad in the code or what I lack?

PS: I did different methods to activate and deactivate the button but the same thing always happens and I leave it like that for a while.

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

namesp

ace DigitalRubyShared
    {
        public class CambioColor : MonoBehaviour
        {

            public Button mybutton;
            public LineRenderer p1;
            public LineRenderer p2;
            public Sprite colorRojo;
            Color Rojo = new Color(1, 0, 0, 1);
            public Sprite colorAzul;
            Color Azul = new Color(0, 0, 1, 1);
            public static int counter = 0;

            public static bool estado = false;

            public static CambioColor estadoCambioColor;

            void Awake()
            {
                if (estadoCambioColor == null)
                {
                    estadoCambioColor = this;
                    DontDestroyOnLoad(gameObject);
                }
                else if (estadoCambioColor != this)
                {
                    Destroy(gameObject);
                }

            }

            void Start()
            {
                mybutton = GetComponent<Button>();
                p1 = GetComponent<LineRenderer>();
                p2 = GetComponent<LineRenderer>();

                counter = 2;
            }

            public void changeColor()
            {

                counter++;

                if (counter == 1)
                {
                    mybutton.image.overrideSprite = colorAzul;
                    //mybutton.image.sprite = colorAzul;
                    p1.startColor = Azul;
                    p1.endColor = Azul;
                    p2.startColor = Azul;
                    p2.endColor = Azul;

                }
                if (counter == 2)
                {
                    mybutton.image.overrideSprite = colorRojo;
                    //mybutton.image.sprite = colorRojo;
                    p1.startColor = Rojo;
                    p1.endColor = Rojo;
                    p2.startColor = Rojo;
                    p2.endColor = Rojo;

                    counter = 0;
                }

            }

            public void dehabilitar()
            {
                if (estado == false)
                {
//mybutton.enabled = estado;
                    mybutton.gameObject.SetActive(estado);
estado = true;
                }
            }

            public void habilitar()
            {
                if(estado == true)
                {
//mybutton.enabled = estado;
                    mybutton.gameObject.SetActive(estado);
                    estado = false;
                }

            }

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

            }
        }

    }


texts:
I am using DirectX10, June release and I am trying to

#include <DirectXCollision.h>

so that I can use the bounding objects, however it does not seem to be there. Am I missing something basic?


texts:
I have a multi-monitor setup with two displays, both 1920x1200. In games, I can only select resolutions > 1920x1200 (like 2560x1200) which makes games unusable.

Full screen doesn't work either because it switches one display to 800x600 which means I can't reach the close button... I have to kill the game and then, I have to restore my desktop because all windows are moved/resized.

How can I force SDL to use any resolution that I want?


texts:
I'm having trouble finding any well-developed open source Collectible Card Game projects.

I want to find projects to learn from and port to a mobile platform.


texts:
Given three points on the same Y plane;

A ship
A point along the ships heading
A mouse cursor

How can I find which direction and angle the mouse cursor is from the ships heading?

I have a limited turn speed on the ship - so I can not simply point the ship at the mouse, but tell it to steer left or right until it faces in the same direction of the mouse.


texts: Mesa: Howto enable OpenGL 3.x functionality via extensions?

texts:
How can I enable OpenGL 3.x functionality via extensions? I'm new to OpenGL development under Linux. Currently I have:

#define GL_GLEXT_PROTOTYPES
#include <GL/osmesa.h>
#include <GL/glu.h>

My problem with Mesa and OpenGL 2.x is that I get an OpenGL "invalid value" error here:

glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA32F_ARB, width, height, 0, GL_RGBA, GL_FLOAT, NULL );

because of GL_RGBA32F_ARB, it seems.

Background: I need the texture for a framebuffer object, and GL_RGBA32F_ARB for float data without clamping. My program works well using OpenGL 3.0 if I create the context with GLX.


texts: Why does my model render differently with different BasicEffect instances?

texts:
I'd like to understand why I get a completely different result when I replace the effects of a model (as suggested by How To: Draw a Model with a Custom Effect) with a BasicEffect that I instantiate myself:

var basicEffect = new BasicEffect( game.GraphicsDevice );
basicEffect.EnableDefaultLighting();
foreach (var mesh in _modelHead.Meshes)
    foreach (var part in mesh.MeshParts)
        part.Effect = basicEffect;

My goal is of course to use an effect of my own later, but for the moment I'd really like to understand what's going on!? What is different with the predefined BasicEffect from the one I instantiate myself? When I inspect the properties of the two instances they seem to be all the same.

How it looks with the "default" BasicEffect
How it looks when I instantiate a new BasicEffect


texts:
I am currently working on a tower defense game, and I am having trouble figuring out how to implement the cost of turrets, upgrades, and the gain from completing a level, killing an enemy. Below is a summary of the requirements:

  There are multiple types of turrets, each turret has different properties, such as reload speed, range. Each upgrade has multiple levels.
  Each turret can have multiple types of ammo, each ammo type can have different upgrades, such as blast range, damage, addons. Each upgrade has multiple levels
  The sources of income are

  killing enemies, each enemy has a different value
  completing a level

My problem is with balancing everything so the game is at least playable, or in the right direction to get balanced by testing it. I know there is no magic formula for this but I believe people with experience will know where to start, and what process to follow. So my questions are:

1- is there a method to calculate the cost of turrets, upgrades? what factors should I take into consideration?
2- Should I use two different currencies for upgrades and turret purchases?
3- How to calculate the upgrade cost as the upgrade level increases? i.e. when the user purchases more of the same upgrade.


texts:
I have a list of if functions (checking if various spots in the room are empty) in one event. I want to check them ALL with an else statement (if none of the spots are cleared), and display a message.
How would I do this?


texts: Where can I see example sell-sheets for a game?

texts:
So my long term one-man indie project is turning into a two-man indie project, and I feel I need to take a step back and at least have a "sell-sheet" as a basis for the game design.

Does anyone have any good templates or tips?


texts: ASSIMP OpenGL collada and Skeletal Animation

texts:
first of all i would like to say that i read everything out there and still did not figure it out quite yet.

In my project i need to implement a skinning technique, but before going there i need to get the standar Linear Blend Skinning working.

I'm using assimp to load my model. For testing purposes my model is a cylindre with a single mesh and 2 bones. There are no animations, the goal of my demo is to manually move the bones.

I read every tutorial/article outhere about assimp and skeletal animation. So i think i got the loading part right. I got the mTransformation from the nodes and got the offsetMatrix from the meshes with the same name (i used a map to store the bones/names).

i did some printing to verify my structure and i'm loading the correct info, i'm getting identity matrices everywhere (wich i think is normal since there is no animation and it's just a simple mesh).

The part i could not figure out still , is how i apply these transformations to my vertices. This point affects the loading too ,when i apply a scale/translation on a mesh in blender i can't get it in my renderer.

in my bones i store 2 matrices and i have a third one that represents the final transformation. I did not understand how i would compute this one, i saw some people using and inverse of the root transform and i have a hard time coding something i don't understand.

struct Weights
{
    uint vertexID;
    float weight;
};

struct Bone
{
    Bone():parent(nullptr){}
    ~Bone()
    {
        for(auto p: children)
                delete p;
    }

    std::string name; // bone name

    QMatrix4x4 nodeTransform; //Transformation of the node
    QMatrix4x4 offsetMatrix;    // Going into the bone's space
    QMatrix4x4 finalTransfrom; // where we store the final transfrom

    QVector<Weights> boneWeights; // bone wheights

    Bone *parent; // pointer to the parent node nullptr if root
    QVector<Bone*> children; // storing pointers to the children
};

thank you for help !


texts: Issue with removing sprites on collision

texts:
I'm trying to make a very simple collision detection procedure just for test purposes.
The problem is with the send/receive information between functions

I have these lines on the update method (could be later implemented for checking what kind of subclass node is)

CCSprite *sprite = [background spriteCollisionWithRect:player.boundingBox];
if (sprite!=nil) {
    [sprite removeFromParentAndCleanup:YES];
}

and this is the spriteCollisionWithRect method

-(CCSprite*)spriteCollisionWithRect:(CGRect)bounds
{
    for (CCSprite *sprite in _spritesArray) {
        if (CGRectIntersectsRect(sprite.boundingBox, bounds)) {
            return sprite;
        }
    }
    return nil;
}

Now, this way not all the sprites are removed. It only works occasionally. But if I remove the node inside the collision method instead of returning it, it works nicely.

-(CCSprite*)spriteCollisionWithRect:(CGRect)bounds
{
    for (CCSprite *sprite in _spritesArray) {
        if (CGRectIntersectsRect(sprite.boundingBox, bounds)) {
            [sprite removeFromParentAndCleanup:YES];
        }
    }
    return nil;
}

Why is this?


texts: 2D sprite sorting and draw order relative to camera rotation

texts:
I'm having trouble working out how to recalculate 2D sprite sorting / draw order based on camera rotation.

In the example below:

Screen 1 shows a non-rotated typical "top down 2D" scene, where the grey objects can be sorted based on their screen Y position, drawn from top to bottom, so in this case B, A, C.

Screen 2 shows the situation after the player/camera rotates clockwise, with the original screen up vector (green) and the new up vector (red). In this situation, sorting by object Y position will not work, because A should now be drawn after C.

What I need to do is to sort the objects not only by their Y position, but also relative to the new up vector and/or camera rotation, but I'm unsure how to handle this.


texts: Why does my RigidBody collision fail depending on which entity is moving?

texts:
I am working on a UDK project and have a collision problem.

I have a Crate which is a kActor with RigidBody physics and my player who is a Pawn. When my player moves and collides with the crate, the event Bump is called, as expected.

However, when my Crate collides with the Pawn when the Pawn isn't moving, the Bump event is not called. In this case, the crate goes through my Pawn without any collision. How can I make this collision case work such that it raises the Bump event?


texts: Flow/design of steering behaviors implementation

texts:
I am implementing some simple steering behaviors like: follow the leader, separation, cohesion and flee(from the leader when he walks in our direction - aka spread the group for him).

I am having issues with design of this system. I know how each of this behavior works separately but I simply can't do it with "if ladder" (as I did up to know). Can someone lead me on how to concatenate/normalize/multiply the forces and how to join them in one resultant force ?

EDIT

What I am exactly talking about is: for now I have something like so :

if(leaderGoingAtMe)
    makeSpaceForhisMovement()
else if(followTheLeader)
    goto(positionBehindLeader)

if(separation)
    addSeparationForce()
if(cohesion)
    addCohesionForce()

if(velocity > maxSpeed)
    clamp(velocity, maxSpeed)

Which is EXTREMELY bad in my opinion but I have no idea how to improve it.


texts: Unity3D-2D: Setting Time.timeScale to 0 for a certain public prefab until positioned?

texts:
So I have a button in my game which spawns a "tower" at a given location. The tower, when spawned, acts normally and I can drag it around using my drag script.

I wonder how can I set the Time.timeScale to 0 when I first spawn the tower (only for that prefab) UNTILL I click again to set it's position.


texts: I'm writing a simple 3D engine myself and I cannot figure out how to make one object face another. The problem begins with identifying which direction the target object is in relation to the second. Actually rotating an object is not a problem, but essentially identifying the direction a particular object is facing (let's say, by identifying the global direction a key facet is facing) is a problem.


texts: How can i get component script from FirstPersonCharacter?

texts:
In the Hierarchy i have a FPSController and as child of it FirstPersonCharacter.
I can get script that attached to the FPSController but not from the FirstPersonCharacter.

What i want to get is the Blur script from the FirstPersonCharacter.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.Characters.FirstPerson;

public class FadeScript : MonoBehaviour
{
    public CharacterController firstPersonCharacter;
    public FirstPersonController fpc;
    public float fadeDuration = 5;
    public float speed;

    private Material material;
    private float targetAlpha = 0;
    private float lerpParam;
    private float startAlpha = 1;
    private bool rotated = false;

    void Start()
    {
        material = GetComponent<Renderer>().material;
        SetMaterialAlpha(1);

        fpc.enabled = false;
    }

    void Update()
    {
        lerpParam += Time.deltaTime;

        float alpha = Mathf.Lerp(startAlpha, targetAlpha, lerpParam / fadeDuration);
        SetMaterialAlpha(alpha);

        if (alpha == 0)
        {
            fpc.enabled = true;

            if (rotated == false)
            {
                fpc.GetComponent<FirstPersonController>().enabled = false;
                fpc.transform.localRotation = Quaternion.Slerp(fpc.transform.rotation, Quaternion.Euler(0, 0, 0), speed * Time.deltaTime);
            }

            if (fpc.transform.localRotation == Quaternion.Euler(0,0,0))
            {
                fpc.GetComponent<FirstPersonController>().enabled = true;
                firstPersonCharacter.GetComponent<Blur>
                rotated = true;
            }
        }
    }

    public void FadeTo(float alpha, float duration)
    {
        startAlpha = material.color.a;
        targetAlpha = alpha;
        fadeDuration = duration;
        lerpParam = 0;
    }

    private void SetMaterialAlpha(float alpha)
    {
        Color color = material.color;
        color.a = alpha;
        material.color = color;
    }
}

I can get scripts from the FPSController like this:

fpc.GetComponent<FirstPersonController>().enabled = true;

But i can't get the Blur script from the firstPersonCharacter.
I tried before instead:

public CharacterController firstPersonCharacter;

With GameObject:

public GameObject firstPersonCharacter;

But Blur is not exist. When i make GetComponent The Blur is not exist.


texts: How do you make use of all texture units on today's graphics cards?

texts: I saw a review of the GeForce GTX 460 graphics card.  It has 56 texture units.  I'm not that knowledgeable about graphics effects.  But, the ones I know use around 3 or 4 texture units.  In this graphics card case, that would leave a lot of texture units idle.  How are these graphics cards with so many texture units used?


texts: Unity + Texturepacker: Pivot point in weird positions

texts:
When my designer sends me the spritesheets done with Texturepacker and I open them with the Sprite editor, i notice that the pivot point is in extremely weird positions. Way above the spritebox that it is attached to.

I told him to put the pivot point "Bottom center" instead "center", and the pivot moved to positions not so exagerated, but still outside the spritebox.

I thought that someone (my designer or me) had something misconfigured, but then I opened the example spritesheet that came with Texturepacker, and I noticed that the pivot point was also in weird positions

As you see the pivot point is under the spritebox. And as I say, this is because the pivot point is set to "Bottom center". If I set it to "Center", it goes even weirder positions.

What is going on? Is something misconfigured here?


texts: How to render axometric/isometric tiles that are a 2d array in logic, but inclined 45º visually?

texts:
I am making a tile-based strategy game which i plan to have 2.5D visuals in an axometric/isometric fashion.

Right now i'm programming it's logic and rendering it as a literal 2-dimensional array (perfect squares, like an isometric top-down-view).

In short, i have something like this:

And i want to turn it to something like this:

Do i keep going on the 2d-array logic?

Is it all just a change in rendering behavior, as i'm thinking it is? or 2d-array is the wrong approach for my objective and I should change before it's too late?

What are the ways of doing it, anyways? How should i apply the 2.5D axometric/isometric view (45º rotation to the side, and 45º rotation upwards)?


texts:
I'm trying to implement gravity and the ability for the player to jump in my 2D LibGDX game. At the moment, I have two handlers: One for gravity and one for keyboard input

@Override
public boolean keyDown(int keycode) {
    // Jumping
    if (keycode == Input.Keys.SPACE) {
        player.getVelocity().add(0, 32);
    }
    return false;
}

@Override
public void update(float deltaTime) { // Update is called every frame
    // Gravity handling
    player.getVelocity().add(0, -50 * deltaTime);

    // Update the position of the player
    player.getPosition().add(player.getVelocity().scl(deltaTime));
}

I thought this would work well, however the jumping is very jittery and abrupt. I would like to make it more smooth.


texts:
I have two objects: a player and a wall.
The player is passing through the long side of the wall but it collided with the short side of the wall.
I want the player to collide with whole wall.

Here is the code:


texts: Why does Avatar Mask not work as expected?

texts:
I have 2 layers: The base layer, and an upper body layer.
On the upper body layer, I have an avatar mask because I only want to affect the upper body.
However, this mask doesn't work as expected.
Here is what it looks like:

This is what is looks like when the upper body layer has a weight of 0:

And this is with the upper body layer with a weight of 1 and with the Avatar Mask:

As one can see, the lower body is affected. The avatar mask doesn't seem to have an effect.
Is that a bug in Unity, or is there anything I could still check?
Thank you!


texts: Repeating a mesh instead of stretching it

texts:
I would like to put acoustic foam into a case object:

To do that, I have created a foam object:

Now I'm having a really hard time to cover the case in Unity with this object:

I have to adjust multiple foam objects absolutely exactely besides each other. This is really time taking.

I was thinking that it would be great that if I could use scaling, and instead of scretching, Unity would repeat the object.

Is that perhaps somehow possible?

Thank you very much!


texts: DX11: Drawing with index buffer not working?

texts:
For our student project I've been tinkering with an OBJ-loader in order to import models into our application.
It loads without issues, and drawing it kind of works without index (the model is obviously not represented correctly because I'm not using an index buffer)
However, drawing with DeviceContext->DrawIndexed shows nothing on screen.

Without indexed drawing

With indexed drawing

Buffer creation method:

void ObjectLoader::CreateBuffers()
{
    //Index buffer
    D3D11_BUFFER_DESC iBufferDesc;
    memset(&iBufferDesc, 0, sizeof(iBufferDesc));
    iBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
    iBufferDesc.Usage = D3D11_USAGE_DEFAULT;
    iBufferDesc.ByteWidth = sizeof(DWORD);

    D3D11_SUBRESOURCE_DATA indexData;
    indexData.pSysMem = &ind;
    pDevice->CreateBuffer(&iBufferDesc, &indexData, &pIndexBuffer);

    //Vertex buffer
    D3D11_BUFFER_DESC bufferDesc;
    memset(&bufferDesc, 0, sizeof(bufferDesc));
    bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    bufferDesc.Usage = D3D11_USAGE_DEFAULT;
    bufferDesc.ByteWidth = sizeof(TriangleVertex) * this->NumberOfVerts();

    D3D11_SUBRESOURCE_DATA data;
    data.pSysMem = tva;
    pDevice->CreateBuffer(&bufferDesc, &data, &pVertexBuffer);
}

Draw method:

void ObjectLoader::Draw()
{
    if (pDevice == nullptr)
        return;

    UINT32 vertexSize = sizeof(float) * 5;
    UINT32 offset = 0;

    pDeviceContext->IASetVertexBuffers(0, 1, &pVertexBuffer, &vertexSize, &offset);
    pDeviceContext->IASetIndexBuffer(this->pIndexBuffer, DXGI_FORMAT_R32_UINT, 0);
    pDeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

    pDeviceContext->DrawIndexed(vIndex.size(),0 , 0);

    //pDeviceContext->Draw(this->NumberOfVerts(), 0);

}

Index data is initially stored in an unsigned integer array before being passed to D3DD11_SUBRESOURCE_DATA

//index array
UINT* ind;

What the hell am I missing? I've looked at several books on indexed drawing and it seems pretty straight-forward. At first I thought the winding order was reversed but I checked this by simply reversing the index array; same result.

If you need more code let me know, but I feel this should suffice.

Thanks in advance!


texts: Switching between levels, re-initialize existing structure or create new one?

texts:
This is something I've been wondering for quite a while.
When building games that exist out of multiple levels (platformers, shmups etc) what is the prefered method to switch between the levels?

Let's say we have a level class that does the following:

Load data for the level design (tiles), enemies, graphics etc.
Setup all these elements in their
appriopate locations and display them
Start physics and game logic

I'm stuck between the following 2 methods:

1: Throw away everything in the level class and make a new one, we have to load an entirely new level anyway!

2: pause the game logic and physics, unload all currents assets, then re-initialize those components with the level data for the new level.

They both have their pros and cons. Method 1 is alot easier and seems to make sense since we have to redo everything anyway. But method 2 allows you to re-use exisiting elements which might save resources and allows for a smoother transfer to the new level.


texts: Blender books for advanced character animation and modeling?

texts:
I've been messing with Blender on and off for over a year, and am now ready to put a lot of sweat into making a great model for an iPhone app I'm working on. I want to learn tips and tricks on how to make great looking models and how to animate them as well.

I know how to do key-frame animation, I just want to learn how to do it well. For instance, I have made a model that walks, but I want to improve it. I want to learn how make its movements realistic.

Does anyone have any resources that could help me with this?


texts:
Hello there Firends ,
I'm developing a Virtual Reality game in Unity. As in every VR game , i have 2 cameras for stereo rendering.
I want to show the same object in each camera having different color/contrast ratio> The effect is similar to the one shown in this image :

the grid in the center here is the same in each side but each camera is seeing it differently.i.e. its grey in the left and black in right (you will notice the black grid if you look closely)
here is another example :

(source: wired.co.uk)
How do i get this effect ? Any suggestions ?


texts: How can an Entity trigger changes to the world in C++?

texts:
I'm writing a simple physics based game in C++ using SFML. I want to trigger a scene change when my playerCharacter collides with a door. Since C++ does not have any native Event Sender/Listener system, I'm not sure how I should organize my architecture such that entities can trigger events within the world, or within other entities they are not colliding with directly. These are the only ways I can think of;

Entities all have a reference back to the scene/world. This is what I'm doing currently but I keep hearing it's horrible design.

Have the scene/world call methods on the entities to check if they are making changes. This seems like a terrible solution, I would have to check for any possible change.

I integrate a premade C++ Event system. I'm happy to do this, I just want to first make sure there isn't a more simple approach I'm missing.

Interfaces between classes. I keep hearing this a solution, but I don't know how ti really solves anything. If my Entity and Scene objects both have references to the interface, and have to base functionality around that- isn't that just as bad?

Messaging system. This actually seems like a good approach, but I'm not sure if it's intended to be a comprehensive solution. Here it is in detail:
How to implement the interaction between engine parts?

Please let me know if you have any solutions for this specific issue, or perhaps some sort of class diagram that circumvents this issue completely. I've been looking a while and haven't found a solution for this issue. How do the major engines do it?


texts: timing rendering to monitor screen update

texts:
I have an application with a very light rendering loop, taking a predictable and small time to execute. Right now, I have two solutions. The first solution uses Vsync: after a screen update, my application renders one frame immediately and then waits for the next screen update. This adds approximately one frame of latency. The second solution simply renders continuously, consuming the whole CPU and relying on OpenGL-style triple buffering to catch the correct frame.

Is there a way for me to acquire the monitor screen update timepoints, preferably through some kind of callback? My current workflow is GLFW with OpenGL, but other solutions are welcome too. I wish to produce a hybrid solution: after a screen update, it should wait for nearly an entire frame, render one frame, and then the screen update will catch this just-rendered frame. GLFW's glfwSwapInterval is almost what I want, but it works in the opposite way, by swapping the buffer right after the screen update instead of before.

With the screen update timepoints, I will be able to implement what I want, by measuring confidence intervals around my rendering loop's execution time and waiting for the correct duration.


texts: Unity / How to add a shader to a material via c# script?

texts:
I found already some things - but those seem not quite what I need. (perhaps outdated functions?)

https://docs.unity3d.com/ScriptReference/Material-shader.html

here, it seems you can add a shader to a renderer:

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    public Shader shader1;
    public Shader shader2;
    public Renderer rend;
    void Start() {
        rend = GetComponent<Renderer>();
        shader1 = Shader.Find("Diffuse");
        shader2 = Shader.Find("Transparent/Diffuse");
    }
    void Update() {
        if (Input.GetButtonDown("Jump"))
            if (rend.material.shader == shader1)
                rend.material.shader = shader2;
            else
                rend.material.shader = shader1;

    }
}

well - i dont have a renderer. i only have a material.

and there is no "material.setShader" , only a material.setTexture"

sooo can anyone solve this mystery of how to add a shader to a material via script?


texts: What is wrong with my smooth shading code?

texts:
I am having trouble getting smooth lighting to work in Java Monkey Engine.

My terrain is voxel-based, with an iso-surface generated via Marching Cubes over the data field.

Up until now, I have been simply calculating the triangle-face normals, and using only those when creating the mesh for each chunk. This produces the faceted look typical of this approach.

Now, I am iterating over each triangle in the chunk, and adding the triangle-face-normal to each vertex normal in the triangle. Vertices are shared between triangles. As I understand it, this should smooth out the lighting, and reduce the faceted look. I am not seeing these results.

Here is a snippet which illustrates the vertex normal processing:

        for( UUID blockId : chunk.blockIds )
        {
            Block block = BlockStore.getInstance().getBlock( blockId );

            FastTable<Triangle> blockTris = block.getTris();
            if( blockTris == null )
                continue;

            for( Triangle tri : blockTris )
            {
                javax.vecmath.Vector3f triFaceNormal = (javax.vecmath.Vector3f)( tri.norm.clone() );

                tri.getVert0().norm.add( triFaceNormal );
                tri.getVert1().norm.add( triFaceNormal );
                tri.getVert2().norm.add( triFaceNormal );
            }

            for( Triangle tri : blockTris )
            {
                tri.getVert0().norm.normalize();
                tri.getVert1().norm.normalize();
                tri.getVert2().norm.normalize();
            }
        }

Then the blocks/triangles for this chunk are iterated over again, and the component values of all the vertex normals are added sequentially to the "normal buffer", which is fed into the mesh creation.

Here is what the mesh data looks like, using the JME ShowNormals material, which color-codes things according to normal direction. You can clearly see the facets:

And here is the code which builds the chunk mesh, after the buffers have been populated:

        chunkMesh.setBuffer( VertexBuffer.Type.Index, 1, BufferUtils.createIntBuffer( uberIntBuf ) );
        chunkMesh.setBuffer( VertexBuffer.Type.Position, 3, BufferUtils.createFloatBuffer( uberVertBuf ) );
        chunkMesh.setBuffer( VertexBuffer.Type.TexCoord, 2, BufferUtils.createFloatBuffer( texBuffer ) );
        chunkMesh.setBuffer( VertexBuffer.Type.Normal, 3, BufferUtils.createFloatBuffer( uberVertNormBuf ) );

        TangentBinormalGenerator.generate( chunkMesh );

        chunkMesh.updateBound();

You can see in this screenshot, that the individual triangles do have some blending, indicating that the summation of a vertex's surrounding triangle-face normals, into the vertex normal, is having some effect.

I'm not sure what I am doing wrong.


texts: Why does flipping 1 texture region cause an identical texture region to also be flipped? (libGDX)

texts:
Sorry for the bad title. I didn't know how else to explain it.

The following is a portion of my code:

public class AssetLoader {

    public static TextureAtlas spriteSheet;

    public static TextureRegion hill, hillTop, hillBottom, rabbitJumped, background1, background2, water, spikes, playButtonDown, playButtonUp, dust;

    public static void load() {
        spriteSheet = new TextureAtlas(Gdx.files.internal("data/SpriteSheet.txt"));

        background1 = spriteSheet.findRegion("background");
        background2 = spriteSheet.findRegion("background");

        TextureRegion[] runFrames = {spriteSheet.findRegion("Frame01"), spriteSheet.findRegion("Frame02"), spriteSheet.findRegion("Frame03"),
                spriteSheet.findRegion("Frame04"), spriteSheet.findRegion("Frame05"), spriteSheet.findRegion("Frame06"),
                spriteSheet.findRegion("Frame07"), spriteSheet.findRegion("Frame08"), spriteSheet.findRegion("Frame09"),  };

        runningAnimation = new Animation(.03f, runFrames);
        runningAnimation.setPlayMode(Animation.PlayMode.LOOP);

        background2.flip(true, false);

    }
}

For some reason, the texture Region background1 is also flipped. Any help would be appreciated.

Some irrelevant code was ommitted.


texts:
I am trying to learn A* path finding. I am using this library - https://github.com/qiao/PathFinding.js

But there is one thing I don't understand how to do.

To find a path from player.x/player.y (player.x and player.y are both 0) to 10/10 I use this code

var path = finder.findPath(player.x, player.y, 10, 10, grid);

This gives an array of where I need to move, but how do I apply this array to my player.x and player.y?

The path structure looks like this

path = [[0, 0], [1, 0], [1, 1], ..., [10, 10]]


texts:
I read GPU Gems 3 from NVidia about procedural terrain.
It's quite interesting but not applicable for me because I only read the online version without the shipped DVD so I'm not able to download the source for these samples (I got a shrinked version only). The shaders are split into Vertex, Geometry and Pixel Shader which I can't use because I'm using the SharpDX Toolkit and I don't have the possibility to use these shaders.

Now I thought of using the methods of NVidia to implement my own terrain generation - which is created by hand in a Editor-View - without random noise etc.
What I want to do is to send my chunks (List<VertexPositionNormalColor>) to a shader which creates the triangle list on the gpu without the need of generating it on the cpu.
At the moment I have a list of possible connections (comparable to Marching Cubes) which is populated while runtime on the cpu which takes up much memory and time.

The idea what I want to do now is to create a RenderTarget3D holding all positions per chunk and generating the triangle list afterward. The generation is based on my own algorithms for vertex generation.
Things you might help me with are:

How do I generate a RenderTarget3D in SharpDX Toolkit which stores my VertexPositionNormalColor (which will be changed to VertexPositionColor after I finished the generation on the gpu) - finished.
How can I load the positions out of the RenderTarget3D to generate the vertices?

Can I use the Geometry Shader for this and how?

Some information which might help: SharpDX Toolkit; custom terrain (not generated); Chunks are used to separate the positions

If you need anything to help me with this problem tell me what you need.

Edit #1:
I managed to get the texture3d generated as I want them to be created but I have a problem with the geometry shader. The code for the geometry shader:

[maxvertexcount(36)]
void mainGS(point gsInput input[1], inout TriangleStream<psInput> Stream) {
    float4 position = input[0].position;
        bool anyNot = false;

    for (int i = 0; i < connectionPositionCount; i++) {
        anyNot = anyNot | !hasConnection(position, connectionPositions[i]);
    }

    if (anyNot) {
        for (int i = 0; i < connectionCount; i++) {
            if (
                hasConnection(position, connections[i][0]) &&
                hasConnection(position, connections[i][1]) &&
                hasConnection(position, connections[i][2]) &&
                (connections[i][3] == 13 || !hasConnection(position, connections[i][3]))
                ) {
                    psInput vec1 = (psInput)0;
                    psInput vec2 = (psInput)0;
                    psInput vec3 = (psInput)0;

                    vec1.position = mul(mul(position + connections[i][0], World), View * Projection);
                    vec2.position = mul(mul(position + connections[i][1], World), View * Projection);
                    vec3.position = mul(mul(position + connections[i][2], World), View * Projection);

                    vec1.normal = float3(0, 1, 0);
                    vec2.normal = float3(0, 1, 0);
                    vec3.normal = float3(0, 1, 0);

                    vec1.color = isSet(position + connections[i][0]);
                    vec2.color = isSet(position + connections[i][1]);
                    vec3.color = isSet(position + connections[i][2]);

                    Stream.Append(vec1);
                    Stream.Append(vec2);
                    Stream.Append(vec3);
            }
            Stream.RestartStrip();
        }
    }
}

The Tkfxc throws three errors on Stream.Append(vecX): emitting a system-interpreted value which is not written in every execution path of the shader.
How can I fix this error in the shader above?


texts: SDL2 Draw scene to texture. SDL2 RenderTexture like SFML

texts:
I've been developing a 2D Engine using SFML + ImGui.

The editor is rendered using ImGui and the scene window is a sf::RenderTexture where I draw the GameObjects and then is converted to ImGui::Image to render it in the editor.

Now I need to create a 3D Engine during this year in my Bachelor Degree but using SDL2 + ImGui and I want to recreate what I did with the 2D Engine.

I've managed to render the editor like I did in the 2D Engine using this Example that comes with ImGui.

But I don't know how to create an equivalent of sf::RenderTexture in SDL2, so I can draw the 3D scene there and convert it to ImGui::Image to show it in the editor.

If you can provide code will be better. And if you want me to provide any specific code tell me.

Thanks!


texts: I am trying to make this effect for buttons. i.e the middle one is bigger and is selected. the buttons can be moved left or right by swapping with finger. Does anyone have any idea how to do it?


texts: Occasional lag-spikes in performance in heavily optimized game (profiler screenshots included)

texts:
So I've been working on a mobile-based platformer for a few years now. I've spent more than a year optimizing the game for mobile as much as I could. Almost every single one of my meshes are using Mobile/Diffuse shader. When I test the performance of my game (on my phone) with the profiler, the frame rate stays at clean 60 fps for the most part. The CPU time fluctuates between 16 ms and 17 ms. The rendering statistics are also excellent, with draw calls fluctuating between 18 and 25, triangles fluctuating between 1.0k and 2.0k and vertices fluctuating between 2.0k and 3.1k. Below is a screenshot of the Rendering profiler when the game is running smoothly. I believe that for a mobile device, these should be very good numbers.

However, every now and then, I see a spike in the profiler window (see below):

According to the profiler, the spike is being caused by Render.OpaqueGeometry.

Under normal scenarios (when the performance is smooth), Render.OpaqueGeometry takes between 1 ms and 2 ms of CPU time. However, as you can see in the screenshot above, Render.OpaqueGeometry is taking 5.36 ms of CPU time and the total CPU time has jumped to 24.16 ms.

Based on my observations, this spike shows up once or twice per minute. Sometimes, several minutes go by without any spikes. And in very rare occasions, the spike can show up 3 times in a single minute (although I don't think that happened the last couple of times I tested it).

So why do you guys think this is happening despite the game being heavily optimized? I read in a post in Unity Answers that Render.OpaqueGeometry spikes are frequent in all games and it's nothing to worry about. But do you think 2 spikes per minute is too frequent for a simple platformer?


texts: How to run around another football player

texts:
I have finished a simple 2D one-on-one indoor football Android game. The thing that it seemed so simple to me, a human being, turned out to be difficult for a computer: how to go around the opponent …

At the moment the game logic of the computer player is that if it hits into the human player will step back few points on the pixel greed and then try again to go towards the ball. The problem is if the human player is in-between then the computer player will oscillate in one place, which does not look very nice and the human opponent can use this weakness to control the game.  You can see this in the photo – at the moment the computer will go along the red line indefinitely.

I tried few ideas but it proved not easy to do it when both the human player and the ball are constantly moving so at each step computer would change directions and “oscillate” again. Once when the computer player reaches the ball it will kick it with certain amount of random strength and direction towards the human’s goal.

The question here is how to formulate the logic of going around the ever moving human opponent and how to translate it into the co-ordinate system and frame by frame animation… any suggestions welcome.


texts: Using latest TiledMap, how do you get a specific tile from x and y index?

texts: Seems basic enough, but I can't seem to find the answer: I am trying to implement collission detecton and for that I need the properties of the tile the player is currently entering. I am using gdx.maps.tiles.TiledMap, which does not have a getCell(int x, int y) like the older TileMap had. Any help on this specific issue or just some general advice on how to do this will be much appreciated!


texts: Domain distortion on a spherical texture (planetary surface)

texts:
I am experimenting with procedural techniques to generate planetary terrain. I have close to zero knowledge so I started with something simple, using perlin noise and domain distortion.
My goal is to wrap these textures on a sphere model (using openGL) so I tried to use spherical coordinates and it was partially successful (I learned from https://ronvalstar.nl/creating-tileable-noise-maps).
As long as I don't apply domain distortion I obtain the expected result with no discontinuity at the poles or anywhere:

But when I do apply the domain distortion, I get this:

You can see there are discontinuities at the poles, and also at a meridian.
I'm not sure to understand why the domain distortion is breaking my spherical mapping, I tried to apply a modified formula from here: https://iquilezles.org/www/articles/warp/warp.htm but it looks like the way I define the position vector is wrong in this case.
I do not know if spherical coordinates are adapted to this kind of problem. Can you please confirm this is the most efficient way to go?
If you have something else to suggest, please share. I have been reading a lot of things about cubemaps, (u, v) texture mapping, procedural texturing etc but did not really understand everything and how it might help me, also for the most part it looked quite sophisticated (intimidating for me).
Here is my code (the buggy part I guess is under the "# --- WARP (domain distortion) ---" line:
import numpy as np
from noise import pnoise3 as perlin3
from noise import pnoise2 as perlin2
import matplotlib.pyplot as plt
import noise
from PIL import Image
import time

# --- transformation X, Y (cartesian) -> a, b, c (spherical) ---
def spherical(x, y, naxis):

  fNx = (x + 0.5) / naxis
  fNy = (y + 0.5) / naxis

  fRdx= fNx * 2 * np.pi
  fRdy = fNy * np.pi
  fYsin = np.sin(fRdy + np.pi)

  a = naxis * np.sin(fRdx) * fYsin
  b = naxis * np.cos(fRdx) * fYsin
  c = naxis * np.cos(fRdy)

  return a, b, c

# --- MAIN ---
def procedural(naxis, WARP, octaves, persistence, lacunarity):

  t0 = time.time()
  M = []

  for i in range(len(WARP) + 1):
    M.append(np.zeros((naxis, naxis)))
  M = np.array(M)

  # --- perlin noise on spherical coordinates ---
  M[0] = np.array([[perlin3(float((spherical(i, j, naxis)[0]) / naxis),
                            float((spherical(i, j, naxis)[1]) / naxis),
                            float((spherical(i, j, naxis)[2]) / naxis),
                            persistence = persistence, lacunarity = lacunarity, octaves = octaves)
                            for i in range(naxis)] for j in range(naxis)])

  # --- WARP (domain distortion) ---
  # f( p + f(p) )
  # p: spherical(i, j) -> a, b, c
  # components:  f( a + M[w-1] )
  #              f( b + M[w-1] )
  #              f( c + M[w-1] )

  for w in range(1, len(WARP) + 1):
    M[w] += np.array([[perlin3(float((M[w-1][i, j] * naxis * WARP[w-1] + spherical(i, j, naxis)[0]) / naxis),
                               float((M[w-1][i, j] * naxis * WARP[w-1] + spherical(i, j, naxis)[1]) / naxis),
                               float((M[w-1][i, j] * naxis * WARP[w-1] + spherical(i, j, naxis)[2]) / naxis),
                               persistence = persistence, lacunarity = lacunarity, octaves = octaves)
                               for i in range(naxis)] for j in range(naxis)])

  # --- normalization [0, 1] ---
  for n in range(len(WARP) + 1):
    M[n] = (M[n] - np.min(M[n])) / (np.max(M[n]) - np.min(M[n]))

  return M

cm = 'coolwarm'

naxis = 1024
WARP = [0.5, 1, 0.5]
#WARP = []
octaves = 24
persistence = 0.5
lacunarity = 2

R = procedural(naxis, WARP, octaves, persistence, lacunarity)

# --- save jpeg ---

im = Image.fromarray(R[-1] * 255)
im = im.convert('RGB')
im.save("your_file.jpeg")

fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(R[-1], cmap = cm)
plt.show()


texts: How can I obtain the file size of a Unity build at runtime?

texts:
I'm wondering if it is possible to obtain the filesize of a game's build at runtime.
Searching this topic only yields results for reducing the build size, which is not at all what I'm looking for.


texts: I am making a game in Unity. I have an object e.g. cube. I want to release air from it like fan so that when other cubes come closer, it throws them away. What velocity,force etc I will need to do that?


texts: What's an appropriate difficulty scale for weapon efficacy vs difficulty to obtain?

texts:
I'm writing up a design document for a voxel based adventure game, similar to minecraft, but fixing a lot of fundamentally broken game mechanics, or at least updating those mechanics to be more suited to an adventure game.

I'm considering creating a weapon scale from 1-10, where weapons at 1 are least powerful, and weapons at 10 are most powerful. I was considering making the materials to make the weapon most common for the level 1 weapons, and 10x less common for the most powerful weapon, but if you look at minecraft, diamonds only occur in 0.1% of blocks and they still feel too common, unless you're prone to dying of course.

In keeping with the adventure focus, would it be better to have the higher tiers of weapons only come from monster drops, or from a combination of a rare monster drop and a mineable item, or are there other common game mechanics I could use to have a super powerful weapon that's also hard to get, but worth your time to get?

To state the question another way, for the time investment, should a weapon that's 10x as powerful take 10x as long to obtain, or 20x or higher? Are there any studies that show any correlation between "fun" in how long players will grind for an item and an appropriate time investment scale for obtaining equipment?


texts: How to calculate move while avoiding deep copy

texts:
Suppose in a turn-based game, I have an object holding the current status of the game (like players, board information, positions of pawns, things like that). Now I want my AI to calculate the best move (or at least a good move).

My first try was to determine all allowed actions and generate a new game object for each action the player or computer could do. Then I would repeat the process for all resulting game objects. This would yield a form of tree with all the future possibilities, from which the AI simply could select the optimum.

But it turns out that this approach is cruelly slow, mostly to me deep copying the game object thousands of times and holding thousands of copies of the game object in the memory.

I am now searching for a better approach to calculate a good move. Are there technics for this type of problem. I am aware that this probably depends on the kind of choices the player or AI has to make in the game. But I am more interested in general technics used to tackle this kind of problem.

Any help is appreciated. If this question is more appropriate for somewhere else (for example StackOverflow), please move it there. Thanks!


texts:
I have a problem with multiple stages and listeners in libGDX. I have GameScreen with gameStage (contains game elements), uiStage (score label and pause button) and pauseStage (resume, restart and exit buttons).

And I have InputMultiplexer to which I add pauseStage, uiStage and anonymous listener in constructor. In result when user touches pause button, game stops and pause buttons appears on the screen. When he touches screen in other place, it's handled as control of the game character.

But there is a problem - when playing, I don't draw pauseStage but still when I click in the area when buttons from pauseStage would be if they were visible, this click is not handled. I tried a lot of ways but it's not working. How to "pause" pauseStage buttons listeners while playing or do something to make pauseStage invisible?pauseStage.getRoot().setVisible() isn't working...


texts: Camera Rotation (for mouse look) with LookAt does not work as expected (Local/Global)

texts:
My code for rotating my 3D fps camera isn't working as expected.
I expect that the X-axis does rotate with the Y-axis, but it ain't so.

I made some pictures to explain it better, I think its doing global rotation instead of local rotation.
But I searched in the internet and used code for local rotation and it was still the same result.

Image

Normal Position
Rotated on Y-Axis
Rotated on X-Axis (how it is)
Rotated on X-Axis (how it should be)

And this is my rotating code:
X-Axis

float sx = sinf(x);
float cx = cosf(x);

up.y = up.y*cx - up.z*sx;
up.z = up.y*sx + up.z*cx;

center.y = center.y*cx - center.z*sx;
center.z = center.y*sx + center.z*cx;

Y-Axis

Math::Vector3f f = Normalise(center - eye);

float sy = sinf(y);
float cy = cosf(y);

center.z = eye.z + f.z*cy - f.x*sy;
center.x = eye.x + f.z*sy + f.x*cy;

It doesn't matter with which order I rotate, still the same.


texts: The steps in implementing Bézier triangle patches

texts:
What are the steps in creating a Bézier triangle patches. What steps would you do in order to create this in directx 11?

Say I just input 3 vertices and create a simple triangle. Is this enough? Or should I create a triangle with 9 vertices, all of them in different heights so it would make a bumpy triangle, then I apply berstein's formulas and make them smooth. so I get like a smooth triangle, not all bumpy.

A triangle like

My book says
Research and implement Bézier triangle patches.

Luna, Frank D. (2012-05-21). Introduction to 3D Game Programming with DirectX 11 (Kindle Location 11901). Mercury Learning and Information. Kindle Edition.

So what are the steps you would do in order to accomplish it? Please no "coulds"


texts: Unity: How can I get the width of a gameobject?

texts:
I'm trying to make sure a gameobject (2D sprite, say, panda) stays to the left of another (say, bamboo), regardless of the former's size. I thought I could take the bamboo's location, and deduct the width of the panda from it.

Something like this:

Here's my code so far:

foreach (GameObject panda in midBambooStack)
{
    Vector3 newPosition = new Vector3(midBamboo.transform.position.x - panda.transform.lossyScale.x, panda.transform.position.y, panda.transform.position.z);
    panda.transform.position = newPosition;
}

But what I end up is that the panda goes right in the middle of the bamboo, so I'm assuming the lossyScale.x bit is wrong.

Any suggestions?

EDIT: Here's my hierarchy, if it means something.


texts: Better ways of handling the server for a Multiplayer Browser Based Game

texts: I am looking to create a multiplayer browser based game, similar to tribal wars and such, and i'm trying to think of better ways of handling the server, for example when troops and buildings are completed and the landing of troop movements


texts: XNA: Placing a "field of view" rectangle on a minimap

texts:
I'm building a top-view 3ed person shooter. I have a HUD and in the HUD I have a minimap. I'm trying to draw on this minimap a rectangle which shows me my "visual field", meaning i see on the minimap which part of the map I'm currently seeing.

I've nearly achieved this, except for a scaling problem. Here's my code:

float distX = ScreenWidth - Tools.MapToCamera(Camera.pos.X, Camera.pos.Y).X;
float distY = ScreenHeight - Tools.MapToCamera(Camera.pos.X, Camera.pos.Y).Y;

Vector2 topLeft = new Vector2((calcX((Camera.pos.X - distX) / (Bg.Width / Tools.minimap.Width) + Tools.minimap.X)),
            (calcY((Camera.pos.Y - distY) / (Bg.Height / Tools.minimap.Height) + Tools.minimap.Y)));

Vector2 rightBottom = new Vector2 ((calcX((Camera.pos.X + distX) / (Bg.Width / Tools.minimap.Width) + Tools.minimap.X)),
            (calcY((Camera.pos.Y + distY) / (Bg.Height / Tools.minimap.Height) + Tools.minimap.Y)));

Tools.DrawLine(topLeft, new Vector2 (rightBottom.X, topLeft.Y), Color.WhiteSmoke);
Tools.DrawLine(topLeft, new Vector2 (topLeft.X, rightBottom.Y), Color.WhiteSmoke);
Tools.DrawLine(new Vector2 (topLeft.X, rightBottom.Y), rightBottom, Color.WhiteSmoke);
Tools.DrawLine(new Vector2 (rightBottom.X, topLeft.Y), rightBottom, Color.WhiteSmoke);

ScreenWidth/ScreenHeight are the current PreferredBackBuffer sizes.
Bg means BackGround, contains height/width, etc. of the map.
calcX(float num) : multiplies num by the current scale of the HUD.

HUD scale is measured by: hudScale = ScreenWidth / hudWidth

calcY:
float calcY(float y)
{
return y * hudScale + (ScreenHeight - (hudHeight * hudScale));
}

internal static V2 MapToCamera(float X,float Y)
{
    return new V2(X * (Tools.w / Bg.Width), Y * (Tools.h / Bg.Height));
}

public static void DrawLine(V2 start, V2 end, Color clr)
{
    sb.Draw(pointTex,start, null, clr,(float)Math.Atan2(end.X - start.X, start.Y - end.Y),
        new V2(0.5f, 1), new V2(1, (start - end).Length()), SpriteEffects.None,0);
}

pointTex = new Texture2D(gd, 1, 1); (Color set: White)

These are all the functions in use.
The end result is a rectangular frame around my position on the minimap. It follows me and i'm mostly in it's center.

The problem is, this rectangle comes out about twice larger than it should be.

Anyone care to help me with this?

  P.S: I don't use any scaling on the map or the other sprites. Scaling is done only on the HUD and it's objects. Although, I use a zoom factor for my Camera class.

Thanks in advance.


texts: What is the simplest way to render video into memory (for drawing to a texture) in .NET?

texts:
In my project I would like to be able to play back video on surfaces in the world. I intend to do this by having the video frames rendered to a block of memory, then use this  to update a texture each frame.  Everything is in place - except for the part that actually gets the video.

I have looked on Google and found that the video library world is very expansive (and geared towards video processing), and am having trouble finding a suitable one.

FFMpeg is very comprehensive, but is an entire suite and would take  a good amount of work to integrate. So far the most promising library I've found is the one based on the VLC player libraries - by virtue of it using the same resources as VLC Player it is known to be very capable; it also renders to blocks of memory, but the API (at least of the one on Codeplex) is more of a port of the C++ API rather than a managed wrapper.

The 'solution' can be any wrapper/API/library, but with characteristics that make it suitable for use in a rendering engine, namely:

Renders the video frame data to memory, so it can be picked up and
passed to a texture on the GPU easily.
Super simple - all that is needed is a way to load, jump and render a frame programatically - ideally it would use the systems codecs and not require an assortment of plugins.
Permissive license (LGPL or more free-er)
.NET bindings at least; all the better if it is natively managed

Can anyone suggest a lightweight, (.NET) library, that can take a video file, and spit out some frames into a byte[]?


texts: Can a fragment shader make per-fragment decisions on whether the fragment updates the depth buffer or not, even if the fragment is not discarded and the color is written?


texts: What language and tools are good to start with for Linux game development?

texts:
I would like to start learning about game development and I would like to do it using Linux. My main experience has been with Java and a bit of C++, but that was for applications and not games.

Now that I want to try with gaming, I'm wondering which IDE/language should I use in Linux, whether I should go with C++ and compiling files manually at the beginning, or maybe continue with Java/Eclipse, also I think I can use Eclipse with C++, I have also started reading about Python...

I was thinking in starting with the typical "Tetris" just to understand how a game works internally, and I think I can achieve that with all the previous options, but what do you recommend me or how have you started game developming under Linux?


texts: Particle systems don't start unless I look at them (Unity)

texts:
I'm currently working on an atmospheric system in Unity (day/night cycle, weather). I'm having an issue where my rain/snow particle systems won't start unless I look at them. They're way up in the sky, so the chances of a player looking at the particle system exactly in time with when the rain would start are very slim. Plus, there would be sound desync.

Yesterday I just had the particle system play on awake and realized that nothing would happen if I didn't look at them. I dismissed the thought, thinking that once I hooked them up to a script they would play when told to. Unfortunately, that's not the case.

I can provide code if need be, but I don't see how it could be necessary. If you need any extra details, I'd be glad to supply them. Thanks in advance.


texts: Unity2D: Repeating of code makes game lag (Spawnning script)

texts:
does anyone knows how to shorten down this script and that I can edit the amount of enemies I want to spawn in, so that I don't have to keep on copying and pasting the same method below again and again, my code is also making my game a bit laggy. Which isn't a good sign. This is my code:

    public bool fromTop = false;

public GameObject enemy1;
public float enemy1Time = 2f;

public GameObject enemy2;
public float enemy2Time = 2f;

public GameObject enemy3;
public float enemy3Time = 2f;

public GameObject enemy4;
public float enemy4Time = 2f;

// Variable to know how fast we should create new enemies

void Start() {
    InvokeRepeating ("Enemy1", enemy1Time, enemy1Time);
    InvokeRepeating ("Enemy2", enemy2Time, enemy2Time);
    InvokeRepeating ("Enemy3", enemy3Time, enemy3Time);
    InvokeRepeating ("Enemy4", enemy4Time, enemy4Time);
}

void Enemy1() {
    Vector2 spawnPoint = new Vector2 (transform.position.x, transform.position.y);

    if (fromTop)
    {
        float x1 = transform.position.x - GetComponent<Renderer> ().bounds.size.x / 2;
        float x2 = transform.position.x + GetComponent<Renderer> ().bounds.size.x / 2;

        // Randomly pick a x point within the spawn object
        spawnPoint.x = Random.Range (x1, x2);
    }
    else
    {
        float y1 = transform.position.y - GetComponent<Renderer> ().bounds.size.y / 2;
        float y2 = transform.position.y + GetComponent<Renderer> ().bounds.size.y / 2;

        // Randomly pick a y point within the spawn object
        spawnPoint.y = Random.Range (y1, y2);
    }
    Instantiate (enemy1, spawnPoint, Quaternion.identity);
}
void Enemy2() {
    Vector2 spawnPoint = new Vector2 (transform.position.x, transform.position.y);

    if (fromTop)
    {
        float x1 = transform.position.x - GetComponent<Renderer> ().bounds.size.x / 2;
        float x2 = transform.position.x + GetComponent<Renderer> ().bounds.size.x / 2;

        // Randomly pick a x point within the spawn object
        spawnPoint.x = Random.Range (x1, x2);
    }
    else
    {
        float y1 = transform.position.y - GetComponent<Renderer> ().bounds.size.y / 2;
        float y2 = transform.position.y + GetComponent<Renderer> ().bounds.size.y / 2;

        // Randomly pick a y point within the spawn object
        spawnPoint.y = Random.Range (y1, y2);
    }
    Instantiate (enemy2, spawnPoint, Quaternion.identity);
}
void Enemy3() {
    Vector2 spawnPoint = new Vector2 (transform.position.x, transform.position.y);

    if (fromTop)
    {
        float x1 = transform.position.x - GetComponent<Renderer> ().bounds.size.x / 2;
        float x2 = transform.position.x + GetComponent<Renderer> ().bounds.size.x / 2;

        // Randomly pick a x point within the spawn object
        spawnPoint.x = Random.Range (x1, x2);
    }
    else
    {
        float y1 = transform.position.y - GetComponent<Renderer> ().bounds.size.y / 2;
        float y2 = transform.position.y + GetComponent<Renderer> ().bounds.size.y / 2;

        // Randomly pick a y point within the spawn object
        spawnPoint.y = Random.Range (y1, y2);
    }
    Instantiate (enemy3, spawnPoint, Quaternion.identity);
}
void Enemy4() {
    Vector2 spawnPoint = new Vector2 (transform.position.x, transform.position.y);

    if (fromTop)
    {
        float x1 = transform.position.x - GetComponent<Renderer> ().bounds.size.x / 2;
        float x2 = transform.position.x + GetComponent<Renderer> ().bounds.size.x / 2;

        // Randomly pick a x point within the spawn object
        spawnPoint.x = Random.Range (x1, x2);
    }
    else
    {
        float y1 = transform.position.y - GetComponent<Renderer> ().bounds.size.y / 2;
        float y2 = transform.position.y + GetComponent<Renderer> ().bounds.size.y / 2;

        // Randomly pick a y point within the spawn object
        spawnPoint.y = Random.Range (y1, y2);
    }
    Instantiate (enemy4, spawnPoint, Quaternion.identity);
}

Please and Thank you. :)


texts: Unity 2D: Can’t resolve ArgumentOutOfRangeException: Index was out of range

texts:
I am very much a novice to coding with no background on this at all so the code you see here may be terrible.

Basically I’m making an endless runner, made up of a player character and a set of obstacle prefabs. The obstacle prefabs have a trigger on them so that when the player hits it, it spawns the next prefab. I’m using the code below, and when the player hits the first spawn trigger it will spawn a prefab, but on tripping the next trigger it gives me the ArgumentOutOfRangeException error in the console and doesn’t spawn anything.

public class ObsTrigger : MonoBehaviour
 {

 public GameObject spawnTrigger;
 [SerializeField] private List<Transform> obstacleList;

 private void OnTriggerEnter2D(Collider2D other)
 {
     if (other.CompareTag("Player"))
     {
         for (int i = 0; i < obstacleList.Count; i++)
         {
             spawnObstacle();
         }
     }
 }

 public void spawnObstacle()
 {
     {
         Transform chosenLevelPart = obstacleList[Random.Range(0, obstacleList.Count -1)];
         Instantiate(chosenLevelPart);
     }
 }

}

If anyone can point me in the right direction I would really appreciate it!


texts: More efficient using invokerepeating or update?

texts: Im fairly new to unity development and I am working on repeating an enemy. I currently have the functionality working correctly in which I use invokerepeating to spam an enemy. Now, I have an if statement that drops a different enemy if a specific Item is hit. This functionality works in both invokerepeating and update. Could someone explain to me which one is more efficient? And why?


texts: How would I go about creating a river with rushing water?  I can do the texture around it but I'm stuck on the actual water part.  This is in Unity3D.


texts:
Is it bad design to have 2 classes which need each other?

I'm writing a small game in which I have a GameEngine class which has got a few GameState objects. To access several rendering methods, these GameState objects also need to know the GameEngine class - so it's a circular dependency.

Would you call this bad design? I am just asking, because I am not quite sure and at this time I am still able to refactor these things.


texts: My SDL Game executable cannot run outside codeblocks

texts:
After compiling and running SDL programs successfully inside CodeBlocks, when I run them outside CodeBlocks (by clicking .exe file) my program does not run. Instead, it says that libstdc++6.dll is missing from computer.

I have all the SDL dlls, but why is this error happening?


texts: Plugins for creating and styling custom Editor Windows like C#/C++ Form Designer or “Web Inspector”?

texts:
Unity3d allows to construct window with custom UI. Just need to use EditorGUI/EditorGUILayout classes and their static methods.
Example of custom window:

The problem is that all the components have to be added manually via script. Then need to save, switch to Editor, wait for little compile things, and then we can see the result.

In web-development people use Web Inspector (for example, we can press F12 in chrome, Tab Elements -> Styles). We can add all needed properties to element and can see the result in real-time.

EDIT. another example (better than previous): we know C# winFormApp, C++ MFC e.t.c, which has form designer. We can choose any elements and set their properties:

It would be nice to have similar plugins for Unity

So. Does Unity3d have similar tools, utilities, plugins? Utilities to inspect code and editing styles (position, margin, padding, background, width, height, color  e.t.c.)?


texts: Is it a good idea to use high-level API's in order to develop game engines?

texts:
I have been looking around the internet finding articles that talk about what you should learn to develop a game engine. Something that I keep hearing in many articles is that you should learn low-level graphics API's such as OpenGL or D3D11 (great article for example: https://www.haroldserrano.com/blog/how-to-become-a-game-engine-developer) for graphics rendering for instance.

NOTE: I will be using graphics rendering as an example for my question since it makes the most sense to me here.

This got me thinking. Is it really necessary to re-invent the wheel by creating your own framework for just rendering graphics? Isn't it sufficient to learn a library like babylon.js for graphics rendering on the web? If the main goal of creating a game engine is to lay a software framework to build video games, then spending time on developing an entire framework for graphics shouldn't be an issue if others have solved the problem for you via their graphics libraries.


texts:
I was contemplating the design of a game (translating a boardgame to the computer, specifically, which I suppose is relevant in this case) and it occurred to me that it might make sense to build the 'game' separate from the 'display.'

It would allow me to prototype something quickly with a simple text interface, and then go pretty it up later. It would also let me port the game to other media more easily.

Is this sort of compartmentalization common in games? Should I try to break things down further? Are there complications I might be missing?


texts: Offset Animated character after applying animation

texts:
I have 2 FBXs in my project. They are identically named - top to bottom - in their respective FBX hierarchies. When I bring them both into unity, FBX A is T-Posed & FBX B has an Animation within it as it has been exported from Maya. I import both FBX A and FBX B into Unity and change the Animation Type to Humanoid, change the Avatar Definition to Create From This Model. I then want to apply the animation from FBX B to FBX A by placing the FBX A in the scene, then dragging FBX A onto the Timeline and creating an Animation Track I then go into the project and drag the Animation from FBX B to the Animation Track of FBX A.
When this is done I set the Animation to Remove Start Offset.
FBX A now has the same animation as FBX B - and can be seen doing the same exact motion However, FBX A is now slightly offset from FBX B when you play both the animations in the scene, you can see that FBX B is slightly offset from FBX A.
Can anyone account for this strange behaviour?


texts: Smooth Shapes in libgdx using ShapeRenderer

texts:
I am using ShapeRenderer in libgdx to draw my only character to get rid of texture in my game.
But I am not getting quality results. Circle edges are distorted. I tried with high resolution and also by reducing size of character but result was same.

I go through This answer , it is not applicable on ShapeRenderer.

Is there anyway I can apply any filter or anti-aliasing to make it look good?

Is it worth to draw using ShapeRenderer to get rid of a high resolution texture?
I am able to induce 3d like effect by drawing lots of rectangle, circle, lines, curves etc. would it optimize the speed and fps of my game?

Code:

package com.test.com;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;

public class shapeRenderer implements ApplicationListener {

public OrthographicCamera camera;
int w,h;

ShapeRenderer sr;
    @Override
public void create() {
//Device width and height
w=Gdx.graphics.getWidth();
h=Gdx.graphics.getHeight();
camera = new OrthographicCamera();
camera.setToOrtho(false, w, h);     // it is same as camera .setToOrtho(false);
camera.update();
sr= new ShapeRenderer();
Gdx.graphics.setContinuousRendering(false);
}
@Override
public void resize(int width, int height) {
// TODO Auto-generated method stub
}
@Override
public void render() {
Gdx.gl.glClearColor(107/255f, 107/255f,107/255f, 1);
//Gdx.gl.glClearColor(190/255f, 190/255f,190/255f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();

        float x1=w/3;
        float y1=h/3;
        float cc=w/2;
        sr.begin(ShapeType.Filled);
        sr.setColor(290/255f, 190/255f,190/255f, 1);
        sr.rect(x1,y1, cc,cc);
        sr.setColor(107/255f, 107/255f,207/255f, 1);
        cc=cc/2;
        sr.triangle(x1, y1, x1+cc, y1, x1, y1+cc);
        sr.setColor(290/255f, 290/255f,290/255f, 1);
        sr.circle(x1+cc,y1+cc, (cc*(2^1/2))/2);
        sr.end();
}
@Override
public void pause() {
// TODO Auto-generated method stub
}
@Override
public void resume() {
// TODO Auto-generated method stub
}
@Override
public void dispose() {
// TODO Auto-generated method stub
}
}


texts:
I am trying to generate an ellipse outside two points (two-dimensional vectors).

Is there a formular for that, or a cool way of doing that in C# XNA?

What I am trying to do is have a particle circle around one player and another.


texts:
I'm trying to implement a 3D picking function that at the moment simply calculates the ray being sent from the camera after the user clicks the mouse on the window.

It kind of works well when the camera is facing forward (orientation [0.0, 0.0, 1.0]) but when I orient the camera upside-down or looking up/down it produces really stupid results (i.e. the ray is wildly out-of-line with the cursor, or even sometimes points behind the camera somewhere).

Here is the code:

// sv (the SceneViewport) is the window/viewport I'm clicking in
// pixel (the Vector2) is the position of the cursor, relative to the viewport centre, in pixels
public Ray PixelRayCast(SceneViewport sv, Vector2 pixel) {
    Vector2 viewportSizePixels = sv.SizePixels;
    float aspectRatio = sv.AspectRatio;
    float invFov = (float) Math.Tan(GetVerticalFOV(aspectRatio) * 0.5f);
    Vector3 rayOrientation = new Vector3(
        ((2f * pixel.X) / viewportSizePixels.X) / (1f / (aspectRatio * invFov)),
        ((2f * pixel.Y) / -viewportSizePixels.Y) / (1f / invFov),
        1f
    ) * Quaternion.FromVectorTransition(Vector3.FORWARD, Orientation); // Orientation is the camera's current orientation
    Vector3 rayStart = Position; // Position is the camera's current position
    return new Ray(rayStart, rayOrientation);
}

I'm not really a great mathematician so I'm hoping someone will be able to read through my small function and spot the mathematical error I'm making.


texts: How are lights rendered as geometry in deferred shading?

texts:
So my problem is that: At the last stage of implementing this I had problem with this sentence, " the lights in the scene are rendered as geometry". What does this mean?
Why do I store depth info for the model in an earlier stage?
What is texture projection ?

I had try to read many tutorials, but every time I end up coming here because I find what I need.


texts: Custom complex body shape with cut feature

texts:
I need to create sprites (or scene2d actors or whatever) with custom shape, preferably generated from a png image (marching squares?).

I followed some Mesh tutorials but they all hardcode the triangularized-shape vertices in an array, which is completely insane.

I will later have to give my sprite a cut feature, like this game.
so I'll have to regenerate and redraw a new shape several times. Some told me to review the Drawable classes as well as Mesh, and create my own MeshDrawable that renders using meshes.

Do you have an idea of how to dynamically generate vertices and shapes instead of hardcoding coordinates?

at what level will my Mesh be responding to touch events and reacting with the user?

Any clarification will be welcome, I'm kind of lost.


texts: XNA speed up content compile with multiple content projects: what to do when two assets reference the same sader file?

texts:
Right now our content is being compiled over the course of 10 minutes. Given that we literary have no content yet, it is a huge timebomb waiting to explode once we start ading it. As we build the game from different PCs, passing the files (specifically the ever changing solution file) from one PC to another inevitably causes content recompilation.

We are trying to find ways to solve this problem. One approach is to split the content into a number of content projects and, theoretically, the build will be done on multiple threads. But the problem we run into is the fact that each model we build references a shader file, the main shader file used to draw it. In order to make sure that every asset has access to the shader file, we put it into a separate content project. Now the problem is, the full recompilation now produces no data in the debug folder and we have no idea why this happens. We tried this approach on a small solution with tow textures (one in each of the two conten projects). They built correctly and we were able to use them in game, but with skeletal models, using custom content processor and referencing a common shader file we get empty content folders in Debug.

Has anyone done something like this and maybe solved a similar issue? Is it possible to reference a common shader file from multiple content projects in theory? Any info would be appreciated.


texts:
All my tiles/sprites have 0 as their position on the Z axis, except my main cam which has -10.

For some reason I suddenly couldn't zoom in without everything disappearing, I switched to 3D view to see where I was and it seemed like I was miles away from my tiles on the z axis. I placed a sprite into my level to check and it placed itself at -57,000 on the z axis.

How do I get my scene view back to 0 or whatever it is by default?


texts: I want to make a random shape made out of points. I want the points to create a polygon shape. Is there a clever way to create a random shape like this? Im thinking going throug X points and giving them random positions but the problem is that they shoudl never intersect and the last point should connect to the first, which they always can do but the points should be somewhat evenly spread out. Im betting there are already good algorithms for this but i lack the words to know what to look for.


texts: How to render irregular sprite sheets in SDL2?

texts:
I have a sprite sheet that's 155 x 66 pixels that I use for my game's UI. I've seen many topics regarding rendering sprite sheets by using the number of pixels and dividing that by the number of sprites to figure out where the render the sprite from. The problem with this is that the buttons on the sprite sheet cannot perfectly aligned so I'm left with differently sized sprites on the sprite sheet.

How do I render an irregular sprite sheet in SDL2?


texts: Can you get polygon collider 2d shape from a sprite?

texts:
When you create an object with polygon collider 2d from inspector, unity automatically generates polygon collider that approximately fits the sprite. My question is if there is a way to do that when creating an object from a script? While searching for a solution I found that each sprite has a sprite mesh which has vertices. I tried setting those as a path for my collider, but the result is a mess: their order appears to be messed up. My current code:

         Sprite spr; // I get that in other part of the code
         GameObject go = GameObject)Instantiate(prefab,gameObject.transform);
         go.GetComponent<SpriteRenderer>().sprite = spr;
         go.GetComponent<PolygonCollider2D>().SetPath(0, spr.vertices);


texts: How would I go about creating my own SDK to allow users to develop their own addon mods?

texts:
I am looking into developing a game, but I am very interested in the more abstract concepts such as modding. I would like to know, or get linked to information detailing the prerequisites, architecture and general idea behind, how I would develop an add-on mod support with a language such as C++ or C# specifically, although any language will be fine.

The mod would work alike to Minecraft, it adds onto the current game giving more content, but doesn't change any base code.

I'd love some detailed answers and I am more than happy to clarify anything that I didn't explain well or if I didn't provide enough information.


texts: How OpenGL works with Windows GDI in order to produce output image on computer screen?

texts:
I am curious how GDI integrates with OpengGL in order to create image for computer screen.

I know that GDI provide Device Context which describes window properties and as far as I know it also offer 2D software based rendering.

Then based on Device Context, Rendering Context is created for OpenGL.

During rendering OpenGL maintain framebuffer objects which are stored in GPU memory and those buffers are then pushed to the screen somehow? However what is the role in GDI in this process? I know that GDI is responsible for transferring image to the graphics devices... So does it mean that framebuffer contents are transferred to CPU RAM and then again to GPU in order to transfer it to display?! It doesn't sound logic...

Why such a software based drawing component (GDI) is used with OpenGL which should be able to send image straight from framebuffer (GPU memory) to display? I can't understand that...

How Windows UI is rendered? Desktop, folders, Start Menu etc. it is software based or gpu based rendering?


texts:
I've been tasked with writing an essay extolling the virtues of object oriented programming and creating an accompanying game to demonstrate them.

My initial idea is to find a tutorial for a simple game written in a programming language which does not follow the OOP paradigm (or written in an OOP language but not in an OOP way) and recreate it in an OOP way using either C# or Java (haven't yet decided). This would then allow me to make concrete comparisons between the two.

The game doesn't have to be anything complex; Tetris, Pong, etc. that sort of thing. The problem I've had so far is finding a suitable tutorial, any suggestions?


texts: Problems with moving 2D circle/box collision detection

texts:
This is my first game ever and I'm a newbie in computer physics.
I've got this code for the collision detection and it works fine for BOTTOM and TOP collision.It miss the collision detection with the paddle's edge and angles so I've (roughly) tried to implement it.

Main method that is called for bouncing, it checks if it bounce with wall, or with top (+ right/left side) or with bottom (+ right/left side):

protected void handleBounces(float px, float py) {
    handleWallBounce(px, py);
    if(mBall.y < getHeight()/4){
        if (handleRedFastBounce(mRed, px, py)) return;
        if (handleRightSideBounce(mRed,px,py)) return;
        if (handleLeftSideBounce(mRed,px,py)) return;
    }
    if(mBall.y > getHeight()/4 * 3){
        if (handleBlueFastBounce(mBlue, px, py)) return;
        if (handleRightSideBounce(mBlue,px,py)) return;
        if (handleLeftSideBounce(mBlue,px,py)) return;
    }
}

This is the code for the BOTTOM bounce:

protected boolean handleRedFastBounce(Paddle paddle, float px, float py) {
    if (mBall.goingUp() == false)
        return false;

    // next position
    tx = mBall.x;
    ty = mBall.y - mBall.getRadius();

    // actual position
    ptx = px;
    pty = py - mBall.getRadius();

    dyp = ty - paddle.getBottom();
    xc = tx + (tx - ptx) * dyp / (ty - pty);

    if ((ty < paddle.getBottom() && pty > paddle.getBottom()
            && xc > paddle.getLeft() && xc < paddle.getRight()))
            {

        mBall.x = xc;
        mBall.y = paddle.getBottom() + mBall.getRadius();
        mBall.bouncePaddle(paddle);
        playSound(mPaddleSFX);
        increaseDifficulty();
        return true;
    }
    else return false;
}

As long as I understood it should be something like this:

So I tried to make the "left side" and "right side" bounce method:

protected boolean handleLeftSideBounce(Paddle paddle, float px, float py){

    // next position
    tx = mBall.x + mBall.getRadius();
    ty = mBall.y;

    // actual position
    ptx = px + mBall.getRadius();
    pty = py;

    dyp = tx - paddle.getLeft();
    yc = ty + (pty - ty) * dyp / (ptx - tx);

    if (ptx < paddle.getLeft() && tx > paddle.getLeft()){
        System.out.println("left side bounce1");
        System.out.println("yc: " + yc + "top: " + paddle.getTop() + " bottom: " + paddle.getBottom());
        if (yc > paddle.getTop() && yc < paddle.getBottom()){
            System.out.println("left side bounce2");
            mBall.y = yc;
            mBall.x = paddle.getLeft() - mBall.getRadius();
            mBall.bouncePaddle(paddle);
            playSound(mPaddleSFX);
            increaseDifficulty();
            return true;
        }
    }
    return false;
}

I think I'm quite near to the solution but I'm having big troubles with the new "yc" formula. I tried so many versions of it but since I don't know the theory behind it I can't adjust for the Y axis.
Since the Y axis is inverted I even tried this: yc = ty - (pty - ty) * dyp / (ptx - tx);

I tried Googling it but I can't seem to find a solution for it.
Also this method fails when ball touches the angle and I don't think is a nice way because it just test "one" point of the ball and probably there will be many cases in which the ball won't bounce.