texts: How to set multiple animations in cocos2d-x

texts:
I'm currently starting with cocos2d-x to build games for blackberry/android/iOS.

I have the png and plist for the animations of a character created with texturepacker. I load them with CCSpriteBatchNode and CCSpriteFrameCache then I use a function created by me that loads all frames into an array of frames, then create a CCAnimation object and store the CCAnimate object created with the animation (code is more clear) the thing is that I have a function that detect touches and it is supposed to cycle through all animations, but it always crashes.

here is some code (this goes in the init()):

_batchNode = CCSpriteBatchNode::create("Character/girl.png");
_cache = CCSpriteFrameCache::sharedSpriteFrameCache();

_cache->addSpriteFramesWithFile("Personajes/girl.plist");

_character = CCSprite::createWithSpriteFrameName("girlneutral1.png");
_character->setPosition(ccp(winSize.width * 0.1, winSize.height * 0.5));
_batchNode->addChild(_character, 1);
this->addChild(_batchNode);
createAnimation(0, "girlpush", 8, 0.15f);
createAnimation(1, "girlneutral", 4, 0.3f);
createAnimation(2, "girlcrash", 12, 0.3f);
createAnimation(3, "girljump", 12, 0.2f);
createAnimation(4, "girltrick", 12, 0.3f);

_character->runAction(CCRepeatForever::create( _charanimation[3]));

this->setTouchEnabled(true);

the function that loads the animations (_charanimation[] is just an array of CCAnimate):

void HelloWorld::createAnimation(int a, CCString animation_name, int frames, float delay)
{
    CCArray* animframes = CCArray::createWithCapacity(frames);
    char str[100] = {0};
    for(int i = 1; i <= frames; i++)
    {
        sprintf(str, "%s%d.png", animation_name.getCString(), i);
        CCSpriteFrame* frame = _cache->spriteFrameByName( str );
        animframes->addObject(frame);
    }
    _charanimation[a] = CCAnimate::create(CCAnimation::createWithSpriteFrames(animframes, delay));
    //_charanimation[a]->getAnimation()->setLoops(-1);
}

and I get the animation to work (the one I set with runAction()) but if I try to change the animation, for example, when I touch the screen:

void HelloWorld::ccTouchesBegan(cocos2d::CCSet* touches, cocos2d::CCEvent* event)
{
    action++;
    action%=5;
    _character->stopAllActions();
    _character->runAction( CCRepeatForever::create(_charanimation[action]));
    char str[100];
    sprintf(str, "Animation: %d", action);
    pLabel->setString(str);

}

it crashes... I don't know if I am doing it wrong, if anyone could help, I will appreciate.

If I change the animation in runAction() it shows the animation correctly, but I can't change ingame with touches.

by the way, this is the error I get in console:

cocos2d-x debug info Assert failed: reference count should greater than 0
In function retain -- ..\..\cocoa\CCObject.cpp:92 m_uReference > 0 -- assertion failed


texts: How Lots of ComputeBuffers at Once Affect Performance Unity

texts:
How will lots ComputeBuffer instances affect performance? And why?
I know that I should call ComputeBuffer.Release() on every ComputeBuffer I create, but will it affect performance if I were to have lots of open ComputeBuffers at once? and by "lots" I mean hundreds to thousands.
It of course goes without saying that all of those ComputeBuffers will be released at some point, possibly at the same time.


texts: I want to know how would I tell if a quad touches another quad in my game built in Slick2D. I have a class that I named "Bounds" which has 4 "Point" objects which just store an X and a Y value and a "Bounds" object stores 4 "Point"s. Simply it has 4 2D vectors, one stores the top left, another stores the top right, another stores the bottom right and the other stores the bottom left. I need to be able to check if two quads based of those 4 coordinates are inside each other. Does anyone have an idea of what I should do?


texts:
Again some problems with my RTS base:

I have worked on the script that should select the unit, if its clicked.
In this case, I check if the raycast hit's the object and checks, if it has a selectable child, which is basically a projector for a circle on the ground. This should be toggled on.

You can see, how the clored ray intersects with the unit but it doesn't show the expected debug message.

Here's my full code that handles the mouse interactions:

using UnityEngine;
using System.Collections;

public class Mouse : MonoBehaviour {

    RaycastHit hit;

    public static GameObject CurrentUnit;

    private static Vector3 mouseDownPoint;

    void Awake()
    {
        mouseDownPoint = Vector3.zero;
    }

    public GameObject Target;

    private float raycastLength = 1000; // Mathf.Infinity;
    void Update () {

        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if(Physics.Raycast(ray, out hit, raycastLength)) {
            if (Input.GetMouseButton(1))
            {
                mouseDownPoint = hit.point;
            }
            if (hit.collider.name == "Terrain")
            {
                if (Input.GetMouseButton(1)) // wenn rechtslick -> ziel instanziieren
                {
                    GameObject TargetObj = Instantiate(Target, hit.point, Quaternion.identity) as GameObject;
                    TargetObj.name = "Target Instance";
                }
                else if (Input.GetMouseButtonUp(0) && CheckLeftClick(mouseDownPoint))

                    DeselectIfSelected();
                //Terrain click end
            }
            else {
                if (Input.GetMouseButtonUp(0) && CheckLeftClick(mouseDownPoint))
                {
                    //does the ray hit a unit with selection child?
                    if (hit.collider.transform.FindChild("Selection"))
                    {
                        //unit found
                        Debug.Log("Unit found");

                        if (CurrentUnit != hit.collider.gameObject)
                        {
                            //enable the selection child
                            GameObject SelectedObj = hit.collider.transform.FindChild("Selection").gameObject;
                            SelectedObj.SetActive(true);
                            if (CurrentUnit != null)
                                CurrentUnit.transform.FindChild("Selection").gameObject.SetActive(false);
                            //replace selection
                            CurrentUnit = hit.collider.gameObject;

                        }
                    } else
                    {
                        //if not a unit
                        DeselectIfSelected();
                    }
                }
            }
            } else {
                if(Input.GetMouseButtonUp(0) && CheckLeftClick(mouseDownPoint))
                {
                    DeselectIfSelected();
                }
            }

        Debug.DrawRay(ray.origin, ray.direction * raycastLength, Color.yellow); // ray to position

    }

    #region Helper

    //check, if mouse is clicked

    public bool CheckLeftClick(Vector3 hitPoint)
    {
        float clickZone = 0.8f;
        if (
         (mouseDownPoint.x < hitPoint.x + clickZone && mouseDownPoint.x > hitPoint.x - clickZone) &&
         (mouseDownPoint.y < hitPoint.y + clickZone && mouseDownPoint.y > hitPoint.y - clickZone) &&
         (mouseDownPoint.z < hitPoint.z + clickZone && mouseDownPoint.z > hitPoint.z - clickZone))
            return true;
            else return false;
    }

    public static void DeselectIfSelected()
    {
        if (CurrentUnit != null) {
            CurrentUnit.transform.FindChild("Selection").gameObject.SetActive(false);
            CurrentUnit = null;
        }
    }
    #endregion

}

I'd be very happy, if someone could help with that problem


texts: How do I follow this glsl1.2 + lights + shadows tutorial?

texts:
I am following this great tutorial but I have many questions.

Let's see if I understand the basic idea.

1. I must create the same number of FBOs that lights (maximum 8).
2. I must create the same number of depth textures (shadow maps) that FBOs.
3. For every FBO I must perform offscreen render (render to texture, drawing the scene from the point of view of each of the lights, maximum 8 times).

Is this correct or can I use just a texture with multiple FBOs, or fbo with various textures or how?

Assuming you use the idea above, how should the final render of the scene?

glUseProgram(programa);
  glUniformli(shadowM0,4);
  glActivateTexture(GL_TEXTURE4);
  glBindTexture(GL_TEXTURE_2D,depthT0);
  //Draw Escene?

  glUniformli(shadowM1,5);
  glActivateTexture(GL_TEXTURE5);
  glBindTexture(GL_TEXTURE_2D,depthT1);
  //Draw Escene?

  glUniformli(shadowM2,6);
  glActivateTexture(GL_TEXTURE6);
  glBindTexture(GL_TEXTURE_2D,depthT2);
  //Draw Escene?

  ...
glUseProgram(0);

Is this okay? I think not, because it uses a lot of resources and the scene would have to be drawn up to 7 times. (One per light source and shadow mapping).

Well but then how should the render scene with multiple light sources and shadows?


texts: Why is my texture array getting only the last link index?

texts:
Here's my code:

[SerializeField] GameObject[] uitex = new GameObject[3];

void GetTextureFromServer()
{
    string dealer_img = "";

    for (int i = 0; i < PlayInfo.Instance.gametablelist.Count; i++)
    {
        dealer_img += PlayInfo.Instance.gametablelist[i].dlrimage;
        dealer_img += ",";
    }
    Debug.Log("HERE ARE THE LINKS : " + dealer_img);

    string[] links = dealer_img.Split(',');

    for (int j = 0; j < links.Length - 1; j++)
    {
        Debug.Log("HERE ARE THE NEW LINKS : " + links[j]);

        new BestHTTP.HTTPRequest(new System.Uri("*************************amazonaws.com/resources/" + "dealer/pic/" + links[j]),
        (BestHTTP.HTTPRequest req, BestHTTP.HTTPResponse res)
        =>
        {
            for (int k = 0; k < uitex.Length; k++) {
                var tex = new Texture2D(20, 20);
                tex.LoadImage(res.Data);
                uitex[k].GetComponent<UITexture>().mainTexture = tex;
            }
        }).Send();
    }
}

The problem with this code is that it's only getting the last index of my links. What could be the problem on my iteration?

Here's an approach that works that shows what the expected behavior is:

 for (int i = 0; i < tzPlayInfo.Instance.bc_gametablelist.Count; i++)
{
    dealer_img += tzPlayInfo.Instance.bc_gametablelist[i].dlrimage;
    dealer_img += ",";
}
string[] newLinks = dealer_img.Split(',');

new BestHTTP.HTTPRequest(new System.Uri("**************************.amazonaws.com/resources/"
    + "dealer/pic/" + newLinks[0]),
    (BestHTTP.HTTPRequest req, BestHTTP.HTTPResponse res)
    =>
    {
        var tex = new Texture2D(20, 20);
        tex.LoadImage(res.Data);
        uitex[0].GetComponent<UITexture>().mainTexture = tex;
    }).Send();

new BestHTTP.HTTPRequest(new System.Uri("**************************.amazonaws.com/resources/"
    + "dealer/pic/" + newLinks[1]),
    (BestHTTP.HTTPRequest req, BestHTTP.HTTPResponse res)
    =>
    {
        var tex = new Texture2D(20, 20);
        tex.LoadImage(res.Data);
        uitex[1].GetComponent<UITexture>().mainTexture = tex;
    }).Send();

new BestHTTP.HTTPRequest(new System.Uri("**************************.amazonaws.com/resources/"
    + "dealer/pic/" + newLinks[2]),
    (BestHTTP.HTTPRequest req, BestHTTP.HTTPResponse res)
    =>
    {
        var tex = new Texture2D(20, 20);
        tex.LoadImage(res.Data);
        uitex[2].GetComponent<UITexture>().mainTexture = tex;
    }).Send();

new BestHTTP.HTTPRequest(new System.Uri("**************************.amazonaws.com/resources/"
    + "dealer/pic/" + newLinks[3]),
    (BestHTTP.HTTPRequest req, BestHTTP.HTTPResponse res)
    =>
    {
        var tex = new Texture2D(20, 20);
        tex.LoadImage(res.Data);
        uitex[3].GetComponent<UITexture>().mainTexture = tex;
    }).Send();

It's working perfectly, but now the problem is that it is not very clean code.


texts: Mixamo Rig Hierarchy Reference (In Text List/Tree format)? (modelling in Maya for use in Unity and Mixamo)

texts:
I'm trying to find a quick reference to match Mixamos rigging hierarchy. I'm confused over which bones are 'root' and how many bones in the spine/pelvis/chest etc. I want my characters I make in Maya to be fully supported by Mixamo library of animations as well as my own keyframe style animations I intend to make in Maya.
I'm really struggling to make a fully human IK rig for my characters. I found this on Unity Documentation: https://docs.unity3d.com/2017.3/Documentation/Manual/Preparingacharacterfromscratch.html
It states:
Possible structures for the hierarchy might be:-

HIPS - spine - chest - shoulders - arm - forearm - hand
HIPS - spine - chest - neck - head
HIPS - UpLeg - Leg - foot - toe - toe_end

But in other examples and guides I read and watched (including the official Maya documentation) the HIPS are not the root.
This is how I understood the hierarchy to be:

BACK_ROOT - pelvis - hip - knee - ankle - foot - toes
BACK_ROOT - lower_back - upper_back - lower_neck - upper_neck - head
upper_back - arm_root - shoulder - elbow - wrist

I am quite sure I have it wrong but have tried many variations of parenting the bones together, and indeed have tried different amounts of bones as some tutorials differ.
I've had multiple problems with my rig mainly from the fact I can't get the  Human IK to work fully in Maya (adding IKHandle to leg or arm can work, but the root just moves the character and there is no way for me to make him crouch automatically as I move the body downwards).
Now I'm lost and not sure even how many bones I need and where.
I already posted a question here and Maya Forums about the similar issue. I got this response on Maya Forums (https://forums.autodesk.com/t5/maya-animation-and-rigging/ik-handle-for-back-bones-allowing-me-to-move-body-downwards-and/m-p/10321981) but I didnt understand what he meant and when i tried adding what he suggested it failed with orange in the HIK view and said it was not alighed to X-axis
(It was aligned but the elbows where bent out just slightly as per the maya docs tutorial and others I had seen)
I done another attempt and the arms look aligned to me:

If someone knows of a text guide showing in exactly what a good hierarchy of joints looks like, please be kind enough to post it. I try searching the web but all i can see is tutorial videos and text I have already seen.


texts: One Dimensional Perlin noise vs Multi-Dimensional

texts:
I am reading through a book called "The Nature of Coding" and I am working on porting the examples from Processing.js to Regular old Java. The example I am on uses the following method call in processing...

noise(x)

I noticed this class provided by Perlin himself, however, it is three dimensional. Can I just do something like this to make it one dimensional (seems too easy)...

static public double noise(double x) {
    return noise(x, 0, 0);
}

Or is there some other changes I have to make?


texts: How to communicate success/failure within an abstract hint system without using sound or words

texts:
I am designing a hint system for a "game".
The game is an interactive art simulation for multi-touch and although it is rather intuitive to figure out the basics of how to run that simulation there are some more complicated things to it that I would like to help the user discover.
My design rules are that it needs to be abstract and mostly transparent. There can be no sounds or words to this hint system. I am hesitant to use symbols as well.
I realize this makes it quite difficult to effectively communicate with the user but that is sort of the point. It is supposed to be a bit of a puzzle so it is rewarding to solve and in this case it is completely fine if the user does not.
These hints will show up when the user is close to figuring out a new aspect of the simulation. The goal of it is to communicate what the missing piece is for them to get there.
For example on one of the hints I need to get the user to hold a new finger down for more than 1 second under certain conditions.
In order to communicate this I want to show some sort of indicator. When the user puts their finger on the indicator it reacts communicating that that was a good choice but there is still more to do. If the user lifts their finger before 1 second I want to show some sort of "failure animation" however if the user lifts their finger longer than 1 second I want to show some sort of "success animation". The user would also notice that the behavior of the simulation changed.
I have chosen a ring/circle as the core shape for the indicator. This makes sense because generally a hint appears somewhere they are not touching and they begin being "in progress" once their finger is on the indicator. I am good with shaders so I will make it look better later.
So far the hint has been reading but I am concerned about how clear it is whether they failed or were successful at executing whatever the hint was hinting about. I have thought about having the indicator turn "green" for good or "red" for bad but the problem here is that color scheme isn't universal. AND most critically it begs the question of what a "neutral" color is/should be for the indicator before the user has started on the hint and while they are doing it and the indicator is following their finger. Teal was my gut instinct but that color is already pretty close to green.
I am worried about the use of just color and specifically the colors red/green so I am looking for other ideas on how I might be able to get this indicator to communicate success or failure following the rules at the top.
Are there other ways I could communicate success/failure?
In addition does anyone know of any other games/projects that use a non-verbal/written hint system communicating more abstractly/with colors? Would be good to have some reference.
Any related articles are great too.
Here is sort of a state diagram of the indicator if that helps. I have included a simple/mockup of the indicator with very simple shapes but obviously to give you an idea it will look better. In the holding example the hint would start by being in the state "hint start" somewhere on screen and when the user touches it would transition to "hint in progress". If the user releases before 1 second it would then go to "failure" and turn red but if the user releases after 1 second it would go to "green" for success.


texts: Why code reflection became a must in game engines?

texts:
I'm currently doing some research on programming languages(compile time reflection area, if you ask) and I found that on the game engine area the reflection feature becomes a must, an engine either uses a language which has reflection feature itself(for example uses C#), or implements it for non-reflection languages(for example both UE and CryEngine implement reflection mechanisms for C++).

I'm not a game developer, so I have no experiences on game developing and not familiar with engines, so can anyone tell me in what case the reflection becomes a must? And what's more, does reflection used only in development phase or also used in released production?


texts: Cocos2d-x : Socket.io-client-cpp crashes after creating scene

texts:
I'm using https://github.com/socketio/socket.io-client-cpp with cocos, because the built-in socket.io doesn't support callback (http://discuss.cocos2d-x.org/t/doesnt-work-with-socketio-2-0-1-and-failed-calling-back-with-old-version/37225/3)

Everything is fine, until i want to push new scene after receiving server signal
Here is my code

SocIO::SocIO() {

    // client object
    _client = new sio::client();
    _client->connect("ws://localhost:3000");
       ....
       _client->socket()->on("joinedRoom", bind(&SocIO::joinedRoom, this, placeholders::_1));
}

void SocIO::joinedRoom(sio::event &a)
{
    Scene* newScene = PlaygroundScene::createScene(1); // crash on this line
}

I don't know what happened here, didn't get this error with built-in socket.io.
Is it because of threading?


texts:
I've been working on a top-down, and the player already has animations for moving left and right.  However, if I move a certain distance and stop, it will stop on the walking animation, which isn't logical as opposed to a standing animation while the player is idle.

I've been using this input handler class:

public class InputHandler implements KeyListener
{
public boolean up = false;
public boolean down = false;
public boolean left = false;
public boolean right = false;

public InputHandler(Game game)
{
    game.addKeyListener(this);
}

public void toggle(KeyEvent ke, boolean Pressed)
{
    int KeyCode = ke.getKeyCode();

    if(KeyCode == ke.VK_UP) up = Pressed;
    if(KeyCode == ke.VK_DOWN) down = Pressed;
    if(KeyCode == ke.VK_LEFT) left = Pressed;
    if(KeyCode == ke.VK_RIGHT) right = Pressed;
}

public void keyPressed(KeyEvent e)
{
    toggle(e, true);
}

public void keyReleased(KeyEvent e)
{
    toggle(e, false);
}

public void keyTyped(KeyEvent e)
{

}
}

and it is coupled with the tick() method from my main class:

private void tick()
{
    if(input.right)
    {
        xScroll++;

        if(xScroll / 16 % 2 == 0)
        {
            dirFacing = 2;
        }
        if(xScroll / 16 % 2 != 0)
        {
            dirFacing = 4;
        }
    }

    if(input.left)
    {
        xScroll--;

        if(xScroll / 16 % 2 == 0)
        {
            dirFacing = 1;
        }
        if(xScroll / 16 % 2 != 0)
        {
            dirFacing = 3;
        }
    }

    if(input.down)
    {
        yScroll++;
    }

    if(input.up)
    {
        yScroll--;
    }
}

Again, the above yScroll will be added later, I really just need to solve the standing animation first.


texts:
I have a Collada file with a rigged mesh.  I've read the node tags in the library_visual_scenes tag and extracted the matrix for each node and stored everything in a hierarchical bone structure.  My Matrix container is "row major", so I'd store the first float of a matrix tag in the 1st row, 1st column, the second in the 1st row, 2nd column, etc.  From what I gather this is the Bind Pose Matrix.  After that I went through the  tag and extracted the float array in the source tag of the skin tag of the controller for the mesh.  I stored each matrix from this float array in their corresponding Bone as the Inverse Bind Matrix.  I also extracted the bind-shape-matrix and stored it.

Now I'd like to draw the skeleton with OpenGL to see if everything is working correctly before I go about skinning.  I iterate once over my bones and multiply a bone's Bind Pose Matrix by it's parents and store that.  After that I iterate again over the bones and multiply the result of the previous matrix multiplication by the Inverse Bind Matrix and then by the Bind Shape Matrix.  The results look something like this:

[0.2,    9.2,  5.8,   1.2 ]
[4.6,   -3.3, -0.2,  -0.1 ]
[-1.8,   0.2, -4.2,  -3.9 ]
[0,      0,     0,     1   ]

I've had to go to various sources to get the little understanding of Collada I have and books about 3d transform matricies can get pretty intense. I've hit a brick wall and if you could please read through this and see if there is something I'm doing wrong, and how I'd go about getting an X,Y,Z to draw a point for each of these joints once I've calculated the final transform, I'd really appreciate it.


texts:
I have a moving platform which is being moved like this:
Vector2 currentPosition = rigidBody2d.position;
Vector2 movement = Vector2.MoveTowards(currentPosition, target, speed * Time.deltaTime);
rigidBody2d.MovePosition(movement);
velocity = (movement - currentPosition) / Time.deltaTime;

And I want to have the moving platform ease in and out of target speed when moving. Basically accelerate from starting position up to speed defined in speed parameter and then decelerate when near target position.
Someone told me to try using SmoothDamp instead of MoveTowards but I am a little perplexed with the behavior.
I've tried using it as follows:
Vector2 movement = Vector2.SmoothDamp(currentPosition, target, ref velocity, 0.1f, speed);

but no matter how much I modify the smoothTime the platform never goes near the set speed (5). It is mostly below 1 or around 1-1.1
What am I doing wrong here? How can I implement easing for my moving platform while still having it reach the set speed?


texts: Flash Professional vs FlashBuilder 4.6 for mobile app development

texts:
From the marketing materials I see online, it seems to me that FlashBuilder 4.6 is a subset of the functionality available in Flash Professional.  If I understand correctly, mobile app development target iOS and Android started as a plugin for Flash Pro and has since been made a separate product.

But can Flash Pro still do all the multi-platform targeting that FlashBuilder 4.6 can do?  What other considerations are there between the two applications that are critical to understand for mobile app development?

Thanks!


texts:
I've been working with the Farseer Physics Engine (which since posting has become Velcro Physics) to try and build a simple 2D, sidescrolling game. Creating basic rectangle blocks worked easily enough, but I discovered when I tried to create some very simple triangle slopes that my existing 'character' avatar would not collide with them. This baffled me for a while until I began using the debug view to discover that while the body of the triangle appeared where I had placed them, the fixture which determined collisions was offset, as shown below (The debugging view is itself offset from the actual sprites because I'm clearly not smart enough to figure out the proper projection matrix):.
It turns out that whatever coordinates I give for the center of the triangle, the fixture appears at (2x, 2y). For example, in the attached image, there is a triangle sloping up to the left at (-4, -1) in the game's coordinate system. The fixture (light green triangle bordered in magenta) is at (-8, -2).
I know this has to be a simple mistake I'm making, but damned if I can figure it out. Here's how I create a new slope in the level:
public override void AddToWorld(FarseerPhysics.Dynamics.World world, Vector2 position)
        {
            body = BodyFactory.CreateBody(world, position);
            body.BodyType = FarseerPhysics.Dynamics.BodyType.Static;

            Vertices vertices = new Vertices();
            if (type == SlopeType.LEFT)
            {
                vertices.Add(new Vector2(position.X - 0.5f, position.Y - 0.5f));
            }
            else
            {
                vertices.Add(new Vector2(position.X + 0.5f, position.Y - 0.5f));
            }
            vertices.Add(new Vector2(Position.X + 0.5f, position.Y + 0.5f));
            vertices.Add(new Vector2(position.X - 0.5f, position.Y + 0.5f));

            FixtureFactory.AttachPolygon(vertices, 1f, body, this);

        }

The position parameter is given to be the center, thus the 0.5 offsets to create the triangle's edges.
Any insight would be greatly appreciated; this engine seems powerful but the documentation is definitely lacking.


texts: Cross platform development tool/platform for the modern indie game developer?

texts:
I'm a Flash developer, but I think it's time to think of other avenues. Ideally I want to be able to write once but be able to deploy to as many different platforms as possible, so iOS AND Android....Web AND Mobile. Are Html5 game development platforms good enough to create games that run on the web and mobile? or should I go with say Corona for iOS and Android, and use Html5 just for web?

I'm a professional developer so paying out for a decent game dev platform is not an issue, I just want to make sure I'm using the best tools for the job over the next few years.

Only interested in developing 2D games. Might well need physics. Corona definately seems a good option for mobile, but if it's possible to create everything in Html5 even if it's more work I'm wondering if it's worth the time learning that.


texts: Unity's Quaternion.Lerp slows down when target is directly behind turret

texts:
Software: Unity v5.2.1f1 Personal

I am trying to achieve the effect of a turret in Unity. For this I have a turret consisting of 3 parts as well as a target. The problem is that whenever the target my turret is targeting has a z of < 0, the lerp speed is extremely slow. However, the further away the target is from x=0 (both positive and negative), the faster it will move. This effect only occurs when my target has a transform.position.z of < 0. When z > 0 the transform.position.x has no effect on the lerp speed. My setup is as follows:

The 3 turret parts are the base, turret and barrel.

The base is nothing more than a block for the turret to rest on.
The turret is a block holding the barrel in place with base as his parent. The turret rotates around its y-axis to always face the target. The barrel has turret as his parent. The barrel rotates around its x-axis to always face the target. See the picture below for the end result.

Base: Blue; Turret: Red; Barrel: Green;

The turret has the following code:

public class turretRotation : MonoBehaviour {

    public Transform target;

    void Update()
    {
        Vector3 relativePosition = target.position - transform.position;
        relativePosition.y = 0;
        Quaternion rotation = Quaternion.LookRotation(relativePosition, new Vector3(0, 1, 0));
        transform.localRotation = Quaternion.Lerp(transform.localRotation, rotation, Time.deltaTime);
    }
}

The barrel has the following code:

public class barrelRotation : MonoBehaviour {

    public Transform target;
    public float speed = 1;
    Vector3 relPos;
    Quaternion rot;

    void Update () {
        // Position of target relative to my position
        relPos = (target.position - transform.position).normalized;

        rot = Quaternion.LookRotation(relPos, new Vector3(0,1,0));

        // Lerping localRotatiot > rot with speed: Time.deltaTime * speed (set to 1 by default)
        transform.localRotation = Quaternion.Lerp(transform.localRotation, rot, Time.deltaTime *  speed);

        // Resetting y- and z-EulerAngles to 0; This way only the x-EulerAngle will be affected.
        // The y rotation is inherited from the parent (turret_turret)
        transform.localEulerAngles = new Vector3(transform.localEulerAngles.x, 0, 0);
    }
}

In this picture the Lerp is working as intended; Note target.transform.z > 0

In this picture the target has a z = -5 and x = 0; pay particular attention to the Lerp speed

It eventually gets there, but it takes a very long time. For some reason, the further away the target is from x=0, the faster the Lerp speed. Note: Still slower than intended

In this picture the target has a z = -5 and x = -10

So for some reason when target.transform.z has a negative value, the higher the distance from target.transform.x to x=0 the higher the Lerp speed.

I've done a fair bit of searching and came across a post on answers.unity.com describing a similair problem; Unfortunately, no reply.
http://answers.unity3d.com/questions/1084067/lerp-problem-when-target-is-behind.html

So my question is: "Why is this happening and more importantly, how can I fix this?"

Any help would be much appreciated!


texts: How can I stop explodable objects from creating new ones during cleanup?

texts:
I have a problem with the handling of explosions in my game.

Currently, I have an entity create an explosion when it is destroyed (in the destructor). The issue with this is that when I change states, all my game objects are deleted. This causes explodable objects to create explosions when my EntityManager is already deleted.

I'm still pretty new to game development and I believe my design is very poor. How can I solve this problem?


texts: controll mouse cursor movement speed in unity

texts: Im searching for a way to lower my mouse movement cursor speed and not to let the user move it fast but i dont know how. i searched in internet but could not find something Usefull. thank you for helping.


texts: Retrieving an array of images from Firebase Storage

texts:
As title says I'm trying to get all images on firebase storage and save them to an array which later on i will be using to load them into the scene. i can manage downloading on image so far but I'm unsure of how to make them into an array.
This is the code I'm using now to download one image by name and assigning it into a texture variable
        storage = FirebaseStorage.DefaultInstance;
        storageRef = storage.GetReferenceFromUrl(_url);

        storageRef.Child(_resourceName).GetBytesAsync(1024* 1024).ContinueWithOnMainThread(task =>
        {
            if (task.IsCompleted)
            {
                Texture2D texture = new Texture2D(1, 1);
                byte[] fileContent = task.Result;

                texture.LoadImage(fileContent);
                Debug.Log(texture.name.ToString());
                selectedText = texture;
            }
            if (task.IsFaulted)
            {
                Debug.Log("faulted DOWNLOAD");
            }

        });

now through that i want to replace my current function which loads all images through the inspector.
 if (LevelSystemManager.Instance.CurrentLevel < source.Length)
        {
            selectedText = source[LevelSystemManager.Instance.CurrentLevel];
        }

Source being the array i use from the inspector to load those images into the game scene which then are selected into the selectedTex Texture2D and loaded based on the level, so 0 element in array == level0 , 1 == level 1 etc. etc.
So i was wondering if i have a couple of folders inside firebase with 10 to 20 images each how can i make that source array pull from that folder? And as a result remove the need to have them in the game and of course not setting them through the inspector.


texts: How to convert or import files from Illustrator in Tiled for game development?

texts:
I have created all my images for a game in Illustrator, now I want to convert them in Tiled Sheets for developing my game in libGDX.
So could I import or convert these .ai files from Illustrator in Tiled?


texts: Why does this impulse not affect the body?

texts:
I'm just getting started with Box2d and I'm trying to apply an impulse to a circle but nothing really happens.

First I define ball:

BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2);
ball = world.createBody(bodyDef);
CircleShape dynamicCircle = new CircleShape();
dynamicCircle.setRadius(50f);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = dynamicCircle;
fixtureDef.density = 0.5f;
fixtureDef.friction = 0.4f;
fixtureDef.restitution = 0.6f;
ball.createFixture(fixtureDef);
dynamicCircle.dispose();

then I call this line from inside my inputprocessor

public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    Gdx.app.log("input", "touchDown");
    ball.applyLinearImpulse(new Vector2(0f, 5000f), ball.getPosition(), true);
    return true;
}

Here's the render method:

public void render() {
    Gdx.gl.glClearColor(1, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    debugRenderer.render(world, camera.combined);
    world.step(1 / 60f, 6, 2);
}

I tried logging this and can confirm the touchDown event is triggered, but the impulse never applies.

Am I forgetting some call to make this work? What might be going wrong?


texts: Subtracting magnitude from 2D circle contact

texts:
I'm trying to create an agar.io clone. In agar.io, each player can have multiple cells that "chase" the mouse pointer. The cells can also have multiple masses and the velocity is tied to the mass. The bigger the cell, the slower it moves. The first picture in this question is a good representation of how this plays out

The cells can't overlap (mostly), so I've already implemented

check to see if they are touching
calculate how much they overlap -> distance between circle centers, minus both circle's radius
calculate a push vector -> subtract the two centers, normalize the resulting vector, and multiply by overlap value

The above code mostly works, but in the regular game if you have a smaller/faster blob moving behind a larger/slower blob, the faster blob will start to slide around the larger blob. I'm not sure how to implement that.

I think you should be able to calculate the normal to the point where the circles touch, and remove the magnitude of the "chase the mouse" velocity  in the direction of the normal? I'm not sure how to do that. Math is not my strong suit.

I took the idea for the circle collision from this link and I think my question of how to remove the velocity from the circle normal is in this link which talks about how to calculate the reflection off of a circle, but I haven't been able to translate that to code.

I'm using C++, not that that matters.

There's also the open source agar.io clones, Ogar and Agar.io-clone, but I haven't found much digging through the code with how they handle that.


texts: How to avoid collision detection to enter infinite loop in this case?

texts:
I am writing a collision detection system which uses the logic mentioned by Trevor here

But I have anticipated a problem which I have shown as a diagram

How do we handle this problem?


texts: How to use an overlapping shader so that it uses layers sort from sprite renderer and its transparent

texts:
Im using the shader from
question
, but once I put it in the game, and my character gets close to it, it will be hidden by the shadow of the tree, which is transparent.
Any way to make the shader transparent and/or maybe use the sprite renderer sort layer system
I have been trying to use stencil configurable shader with no luck
Thank you for your help
Not sure what combination of these should work:

The character is using a normal sprite renderer.


texts: How do I calculate a point between two points with a given distance percentage?

texts:
I've made a simple drawing:

The distance between these two points is calculated with a simple formula:

Which gives: 5,38

I need to calculate the green point's coordinates, which is set at 80% distance from the B point towards the A point.

I could make a direction vector between A and B, and then, add (dir * 5.38 * 0.8) to the B point itself, but it gives me strange results.

Is there a simpler (and more efficient!) way to achieve that?


texts: How can I make my button do something when clicked?

texts:
I'm trying to create a game with libGDX in Android Studio, and I am struggling with my code to add a command to the program to do something when I press the button.

I have added an ImageButton, but now I struggle to get it to do something when I click on it.

Here's my code:

 bplay.addListener( new ClickListener(){
        public void clicked(InputEvent event, float x, float y){
            batch.begin();
            batch.draw( splash, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() );
            batch.end();
        }
    });


texts: How to clear out a drawn texture from the screen in libGDX

texts:
I am trying to clear out the drawn texture from the screen.

Lets take a classic game example - in many games when the character goes through the coins the coins clears out from the screen and displays a sweet animation like fade in and fade out the points collected from that coin(+10) and show the coin exploding animation on that position.

I want to do something similar to that.
I am using SpriteBatch to draw the texture region like below.

Setting texture Region:

(...)
 public Texture texture;
    public TextureRegion coin;
    texture = new Texture(Gdx.files.internal("data/texture.png"));
    texture.setFilter(TextureFilter.Nearest, TextureFilter.Nearest);
    coin = new TextureRegion(texture, 0, 336, 65, 73);
 (...)

   Drawing the texture into screen :

 public SpriteBatch batcher;
 batcher = new SpriteBatch();
 batcher.setProjectionMatrix(cam.combined);
  batcher.begin();
    batcher.enableBlending();
    batcher.draw(coin, x, y, 65,73);
    (...)
    (...)
  batcher.end();

The game character is also drawn using the same logic shown above.
Now when the game character will collide with the coin that I have drawn,the coin must be cleared(vanished) and some animation or big font like +50 must fadein and fadeout in that position.I tried but didn't find anything that would do this.
So how to do that ?


texts:
I understand how to generate geometry using marching cubes at an isosurface, but I haven't been able to find a clear explanation on how to calculate the vertex normals for a mesh produced using marching cubes.

Right now, for each triangle generated during the lookup phase, I can calculate a face (not vertex) normal simply by taking the cross product of two of the vectors in the triangle ie:

Triangle = [p1, p2, p3];
normal[face] = (p2 - p1).cross(p3 - p1).normalized();

But how do I compute the vertex normals at p1 p2 and p3 to allow for smooth shading? The only way I can think of is to sample the density function to produce an estimate of its gradient -- but is there a faster way?


texts: 2D terrain with midpoint displacement and collision

texts:
I followed this theory Here to implement a simple scrolling 2D terrain for my running game. I am used to dealing with collision via a tile system but am looking for a good theory on how to perform terrain collision (keeping the player on-top the land) with a midpoint displacement 2D terrain

I am not worried about the physics aspect but how to determine if a character intersects an array of points generated by the theory above. Example if I have an array of points

Points[]

these points are used to draw lines to make a terrain. Now in my mind I would first find the player center. Take the center X and see which two points it is between. So if X is 4.6 lets say it is between points that lay on X=3 and X=6.

Player X = 4.6
Point1 X = 3, Y = 3
Point2 X = 6, Y = 5

So now knowing this I somehow need to calculate  what Y would be giving that X = 4.6. And once I have Y ensure that the Player Y > CalculatedY. If it is not push the player up to what Y the player should be.

So I guess what I a saying is

X = 3, Y = 3
X = 6, Y = 5
X = 4.6, Solve for Y


texts: How to handle re-rendering a scene in my custom game engine?

texts:
I have a very simple game engine. A GameObjectManager stores a collection of all the GameObjects. When I want to render, I just call GameObjectManager.render() from the rendering context.

This works well for rendering most objects, but now I am looking to add a water shader to the scene where it takes in reflection and refraction textures. The reflection and refraction textures will be computed each frame by re-rendering the scene from a new perspective. Unfortunately, my design choice of having a single GameObjectManager to store all GameObjects just won't work for this - it wouldn't make sense to store a GameObject for the water in the GameObjectManager.

What is a good game engine design pattern to handle re-rendering the scene for an effect such as a reflection?


texts: On Click Add Listener not working on Game Object

texts:
I have this code attached to a 3D cylinder game object. I plan to use it as an arrow and rotate it when clicked and dragged. I had no idea what do as I am a beginner so I started with adding an onClick listener to a Button component on the Cylinder, and wrote this script which I added as component to the cylinder.. But the Rotate() function isn't called when I click on it, as there is no message in the Log.. This is the code:

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

public class MoveAim : MonoBehaviour {

    public bool isAiming;
    private Button button;

    void Start () {
        isAiming = true;
        button = GetComponent <Button>();
        button.onClick.AddListener (Rotate);
        Debug.Log ("Start!");
    }

    void FixedUpdate () {
    }
    void Rotate() {
        Debug.Log ("Click recorded");
    }

}

Any idea what to do? And how should I implement the rotation of the cylinder? Help would be appreciated!

Thanks!


texts: Maintaining relative location of objects across different screen resolutions

texts:
I'm developing a very simple interactive HTML5 game, in which I need to show a room having multiple objects like a cupboard, table, fan etc.

How can I display all of the objects together, so that they remain at same place, on all screen resolutions?


texts: Strange 3D game engine camera with X,Y,Zoom instead of X,Y,Z

texts:
I'm using a 3D game engine, that uses a 4x4 matrix to modify the camera projection, in this format:

 r r r  x
 r r r  y
 r r r  z
 - - -  zoom

Strangely though, the camera does not respond to the Z translation parameter, and so you're forced to use X, Y, Zoom to move the camera around. Technically this is plausible for isometric-style games such as Age Of Empires III. But this is a 3D engine, and so why would they have designed the camera to ignore Z and respond only to zoom? Am I missing something here? I've tried every method of setting the camera and it really seems to ignore Z.

So currently I have to resort to moving the main object in the scene graph instead of moving the camera in relation to the objects.

My question: Do you have any idea why the engine would use such a scheme? Is it common? Why? Or does it seem like I'm missing something and the SetProjection(Matrix) function is broken and somehow ignores the Z translation in the matrix? (unlikely, but possible) Anyhow, what are the workarounds? Is moving objects around the only way?

Edit: I'm sorry I cannot reveal much about the engine because we're in a binding contract. It's a locally developed engine (Australia) written in managed C# used for data visualizations.

Edit: The default mode of the engine is orthographic, although I've switched it into perspective mode. Its probably more effective to use X, Y, Zoom in orthographic mode, but I need to use perspective mode to render everyday objects as well.


texts: Unity Rigidbody2d jittering movement in the y-axis

texts:
As said, rigidbody moves fine, even smoothly in the x axis.

Problem comes in on the y axis. Whenever the character goes up or down, it noticeably shakes.

Additional Info:

Unity 5.6
Using linear interpolation
Mass is 5
Linear Drag is 20
Gravity is 0
Angular Drag is 0
Locked rotation on the z-axis
Dynamic Rigidbody
No parent Object, not even a child

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

public class PlayerMovement : MonoBehaviour {

Rigidbody2D rbody;
//Animator anim;
public float speed = 0;
/*SpriteRenderer sr;
Vector2 movementVector;
void Start () {
    rbody = GetComponent<Rigidbody2D> ();
    anim = GetComponent<Animator> ();
    sr = GetComponent<SpriteRenderer>();
}*/

void Update(){
    //sr.sortingOrder = ((int)Camera.main.WorldToScreenPoint (sr.bounds.min).y) * -1;
    movementVector = new Vector2 ((Input.GetAxisRaw("Horizontal"))*3, Input.GetAxisRaw("Vertical"));
    /*if (movementVector != Vector2.zero) {
        anim.SetBool ("isWalking", true);
        anim.SetFloat ("inputX", movementVector.x);
        anim.SetFloat ("inputY", movementVector.y);
    } else
        anim.SetBool ("isWalking", false);
}*/

void FixedUpdate(){
    rbody.AddForce (movementVector * speed);
}

}

I also noticed that changing the mass and linear drag affected the movement speed on the y axis but not on the x axis, and movement on the y axis is noticeably faster than on the x axis, which is why I multiplied the horizontal input by 3.


texts:
I'm trying to implement a Material system in a small engine for training and I've got  questions about materials.

Currently I've got that:

Material: A Material with array of Technique
Technique: Stock an array of Pass
Pass: Content RenderState (blend to apply, draw mode, face culling, …), Shader/Program and an array of Parameter
Geometry: Buffers, Indices, Vertices, ….
Parameter: A parameter is use to stock and share values with program (color, texture,…)

Now I'm not sure about that:

A Material is something shared by Meshes or each Mesh have his own Material?
In my scene, I've got 5 trees: two red trees and 3 blue shiny red trees (same Geometry). Each tree have is own Material or each tree have a reference to the same Material?
The Material own by a Mesh is a copy of a Material or a reference to the original Material?
In my Material I have texture offset and scale, it's useful for drawing a part of the Texture only, but how can I manage offset and scale if my Material is shared and each owner didn't use the same values? (In the case where all my objects are in the same texture atlas)
If each mesh have his own Material instance (a copy of an original Material) how can I know if each Mesh have the same Material? (An ID per Material may be?)

Thanks a lot!


texts: What steps can developers take to improve the graphics of their games?

texts:
My understanding is that the differences in graphic quality between games for systems like Xbox One and PS4 and Pixar-style movies stems from that the former are rendered in real-time.

But even with real-time rendering, it looks like some game makers can get rather nice looking results. An example below is about the new Gears of War game:

Above image is from this YouTube video posted by GameSpot. So admittedly it could be from a video (e.g. a promo) that has been rendered more than the actual game.

Anyway so what I wanted to ask is, are games solely dependent on the real time rendering on the target system, or are there some steps developers can take (besides the obvious: start with as good graphics as possible) to improve the graphics in their game?

Edit: here I am referring strictly to in-game graphics.


texts: Enemy moving towards Player in a 2D setting?

texts:
i want to apologize if this seems so basic, but I'm having trouble having an Enemy move in my Player's Direction in a 2D Top-Down game.

I already saw a lot of other answers but they all use the .LookAt() and .Forward but i'm not using rotations so i cannot just move them in the direction they are looking at, i just need to move them along X and Y, and i managed to do a pretty horrible workaround :

//I tried getting the difference between player and enemy positions, but this is relative, and slows down the closer it gets to the player.

Vector2 distance = new Vector2(player.position.x - enemy.position.x, player.position.y - enemy.position.y);

enemy.AddForce(distance * walkspeed);

So, how could i make the Enemy move in the direction the Player is, but with a constant speed?


texts: Should I use textures not sized to a power of 2?

texts:
In the early days of OpenGL and DirectX, texture sizes were required to be powers of two.  This meant interpolation of float values could be done very quickly, using shifting and such.

Since OpenGL 2.0 (and preceding that, via an extension) non-power-of-two texture dimensions have been supported.

Do power-of-two textures have performance advantages on modern integrated and discrete GPUs? What advantages do non-power-of-two textures have?

Does a significant desktop population have cards supporting non-power-of-two textures?


texts: Is it bad-practice using left-handed coordinate system in OpenGL eye-space?

texts: In the engine I am currently programming I want to use a left-handed coordinate system for eye-space instead of the glFrustum standard right-handed one. Is that in anyway considered bad practice?


texts:
I had noticed the AndEngine a few days ago, and I tried to create basic game with a few Sprites.Sure, the engine makes the development process much more easier.However I found the sprite lacking a major functionally:

Whenever there is a need to refer to the position of an Sprite the engine manipulates the position based on the top-left corner of sprite,this is not the best thing because there is a need to subtract/add the width/height to its position in order to refer to its center.However when we refer to he scale of the Sprite it scaled according to its center point (which is great)

I find it very confusing to refer to its position each time differently.I solved that by extending the Sprite class and implementing my methods of setCenter and getCenter, I guess that not the best way to do so.

Do you have any suggestion?


texts: Handling multiple agents in astar pathing

texts:
When working with grid based path finding in how do you normally handle different agent types? In the game I am working on I have a regular agent, and one that occupies 2 cells on the grid, and one that can fly. The idea I have now is to use a separate AStar map to store the grid for each type. The height is max 4 units so I can use AStar for flying as well.

This keeps it possible to add new actor types as well but is it waste of memory? Also how to deal with avoiding nodes occupied by other agents? The game is turn based so I don’t want to do any object avoiding type thing. Is there a simple way to mark a node in the AStar as temporarily unwalkable?

I am using the Godot Engine and would like to use the in built astar implementation but I can create my own if really needed.


texts:
I am working on a tower defense game in Flash. Right now most towers find the the nearest enemy in range (enemies are in an array), get the enemies coordinates, and fire a bullet. When it hits the coordinates [bullet.hitTestPoint(x, y)] it damages the enemy.

I want to design a tower that will shoot a bullet at the first enemy just like above, however, the bullet needs to go its max range and damage all enemies it hits along the way. I am having some trouble determining what enemies it is hitting.

The best way I have come up with so far is when the bullet reaches its max range, I draw a line from that point back to my tower. Then I loop through the enemy array and use [enemies[i].hitTestObject(bulletLine)]. If that returns true, it damages that enemy.

This seems to work okay, but I would like something more realtime and sometimes it seems like this is hitting enemies it shouldn't hit.


texts:
I'm creating a networked game and I have a huge problem understanding how to keep everything in sync. Right now I have a server and a client and the client can log in and move a character around using the keyboard arrows.

When a arrow key is hit I send data to the server, that then sends that data out to all the clients and then it moves the appropriate character in a specific direction.

However if I keep on hitting arrow keys eventually the result on two different clients will look different and they fall out of sync. So what is the best way to stop this from happening?

I've read that 1 method is to send data back and forth to figure out the latency between each client and then to include that into the movement, is that really the best method around at dealing with this? In which case would anyone be kind enough to explain in more detail how that works exactly?

Thanks


texts:
There's this one precious little if in my code that is not doing what I want him to do.

Language is written in C# and doing it in Unity

Basically, I put a date on the Inputfield, which is linked to: BonoFinish, as soon as BonoFinish reaches DateTime.Now, it should appear a new gameobject, problem is... it does crap. What am I missing? Here's the code:

if (BonoFinish ==  DateTime.Now)
    {

        PagPrincipal.SetActive (false);

        print (DateTime.Now);

        Bonos.SetActive (true);

        Debug.Log ("funciona");

        Invoke ("apagaBonos", 30f);
    }

Also, Bonofinish is written like this:
 BonoFinish = DateTime.ParseExact (HoraBono.text, "dd-MM-yyyy HH:mm", null);


texts:
I have some problems using an int 3x3 matrix as the convolution filter to do edge detection. (I know int matrices are not very meaningful since there is only float on the gpu)

Here is the code:

   float2 stepSizeX = (1.0/512.0,  0.0);
   float2 stepSizeY = (0.0, 1.0/512.0);

   for(int y = -1; y <= 1; y++)
   {
      for(int x = -1; x <= 1; x++)
      {
        float4 c = tex2D(origSampler, TexCoord + stepSizeX * x + stepSizeY * y);
        endColorX.rgb += c.rgb * theMatrix[x+1][y+1];
      }
   }

The matrix is set to:

-1 -2 -1
0 0 0
1 2 1

..in the application, but it seems the values in the HLSL shader are different, though I can't figure out how and why?


texts: Animation won't play unless movement key is held down

texts:
In Game Maker I am creating a 2D RPG and combat is a part of it. I have some animations that will play when the left or right mouse button is pressed (Depending on if you want ranged or melee attacks) but when a movement key (for example, D) is not pressed the animation won't play. Only when that key is pressed will the animation play, which is annoying as it ruins the fluid nature of the game. I'll post the code for pressing D and pressing RMB down (not A orLMB` because the code is identical, just reversed).

RMB:

if mouse_check_button(mb_right)
{
  if cusdirection = 0
  {
    if inair = true
    {
      //Do Nothing
    }
    else
    {
      hspeed = 0
      sprite_index = spr_qa_atk_bow_right
    }
  }
}

D:

if keyboard_check(ord("D"))
{
  hspeed = -5
  cusdirection = 0
  if inair = false
  {
    sprite_index = spr_qa_walk_right
  }
  else
  {
    sprite_index = spr_qa_inair_right
  }
}


texts: Is it possible to export animations from Blender to Unity prefab without re-exporting entire character?

texts:
I have a fully rigged and animated character that I recently exported from Blender as an FBX to Unity. I need to make more animations for the character now but I am very tired of exporting the entire character every time I make a change. I do not need to update texture coordinates or vertex weights (probably). Is there a way to record a new animation in Blender and attach it to the existing Unity character?

Or alternatively, is there now a viable way to produce quality animations for characters inside of Unity? My character needs to move fingers and toes but does not have facial animations.


texts: What if I extend a uclass without UClass() in Unreal Engine?

texts:
What happens if I extend a uclass (or UObject) without the UClass() macro?

Will it still be a UClass() and managed by the garbage collector?

I'm just curious.

Update

I managed to extend ULineBatchComponent without UCLASS nor GENERATED_UCLASS_BODY(), it compiled, did not complain, and I could instantiate it.


texts: What are the advantages and disadvantages of exporting spritesheets instead of models from Spriter into Unity?

texts:
I'm working on a simple 2D platformer in Unity and have been using the Spriter2Unity tool to import my Spriter animations directly into Unity.
I have noticed that this creates large hierarchies of gameobjects within the imported prefabs, basically 1 per image piece.

Since the animations are fairly simple, I am thinking it would be cleaner to import each of them as a spritesheet and hook them up with a spriterenderer on the player object rather than using the importer tool.

Would this actually result in any performance benefit at runtime or are the impacts of animating a lot of game objects at once negligible?


texts: Calculate average velocity of the object before the game start

texts:
I have a game object (player), and with device screen width and average FPS, I'm able to calculate exact velocity for the player to reach whole screen from left to right in a specified time (fx. for 1 second). Objective of this is to move player on different devices still same (reach for 1 second their screen width).

I can calculate this in runtime. But is it somehow possible to calculate it before, for example in surfaceCreated? Because in my game, I need that velocity to be constant from start (I can't change it in runtime). Is possible to approximately calculate it?


texts: Looking for literature about graphics pipeline optimization

texts:
I am looking for some books, articles or tutorials about graphics architecture and graphics pipeline optimizations. It shouldn't be too old (2008 or newer) - the newer, the better.

I have found something in [Optimising the Graphics Pipeline, NVIDIA, Koji Ashida] - too old, [Real-time rendering, Akenine Moller], [OpenGL Bindless Extensions, NVIDIA, Jeff Bolz], [Efficient multifragment effects on graphics processing units, Louis Frederic Bavoil] and some internet discussions. But there is not too much information and I want to read more.

It should contain something about application, driver, memory and shader units communication and data transfers. About vertices and attributes. Also pre and post T&L cache (if they still exist in nowadays architectures) etc. I don't need anything about textures, frame buffers and rasterization.

It can also be about OpenGL (not about DirecX) and optimizing extensions (not old extensions like VBOs, but newer like vertex_buffer_unified_memory).


texts: Phaser 3 - Show items from object layer - image not loading

texts:
Trying to create a collectible objects from object layer I've created with Tiled, however, don't know the proper way to map the objects and my image file which contains several images.
What would be the proper way of showing the image from the object layer created by Tiled?
So far I have come up with this routine which finds the Sprite but it seems the image itself is not loaded as seen in the image below.
   private pickupsGroup!: Physics.Arcade.StaticGroup

   ...
   this.pickupsGroup = this.physics.add.staticGroup();
   const pickupsGameObjects = this.map.createFromObjects('Pickups', { });
    pickupsGameObjects.forEach((object) => {
      const sprite = object as Phaser.GameObjects.Sprite;
      sprite.setDepth(9);
      this.pickupsGroup.add(sprite);
    });

   ...

Tiled. (propsA.png consists of several images, bottom right corner.)

The pot object can be found in the map file outdoors1.json
...
 {
         "draworder":"topdown",
         "id":13,
         "name":"Pickups",
         "objects":[
                {
                 "gid":4775,
                 "height":32,
                 "id":8,
                 "name":"pot",
                 "rotation":0,
                 "type":"pickup",
                 "visible":true,
                 "width":32,
                 "x":396.666666666667,
                 "y":564
                }],
         "opacity":1,
         "type":"objectgroup",
         "visible":true,
         "x":0,
         "y":0
        },
...


texts: Orthogonal projection matrix affecting z-buffer on one device

texts:
I am experimenting using Matrix.orthoM for a isometric projection, rather than Matrix.frustumM.

On one device, the z buffering does not appear to be working correctly and I get a cut away effect seen below on the wheels in particular. Both devices work fine with frustum projection.

Sorry not much to go on, just hoping someone will just be able to take one look and recognise the problem.

Sony Xperia Z:

LG P920:

Sony Xperia Z:

LG P920:


texts: SDL2 - Updating part of a texture is slower than updating all of it

texts:
I'm programing a kind of cellular automaton in which each pixel is an automaton.
I'm using a SDL2 streaming texture with the SDL_LockTexture() and SDL_UnlockTexture() methods to "open" the whole texture and draw the full 426x240 array of pixels. Like this:
  // inside update() method
  world_texture_.lock((void**)&world_pixels_, &texture_pitch_);

  for (int i = rows_ - 1; i >= 0; --i) {
    for (int j = 0; j < cols_; ++j) {
      const auto current_index {getIndex(i, j)};
      checkAutomatons(current_index); // this checks stuff and changes world_pixels_ accordingly
    }
  }

  world_texture_.unlock();

Lately I figured out that I don't need to update the whole texture, as the vast majority of pixels weren't changing from frame to frame. So I made a method to create an SDL_Rect around the area that needs to be updated, drastically decreasing the number of pixels to check. Like this:
 // inside update() method
 world_texture_.lock(&bounding_box_, (void**)&world_pixels_, &texture_pitch_);

 for (int i = bounding_box_.y + bounding_box_.h - 1; i >= bounding_box_.y; --i) {
   for (int j = bounding_box_.x; j < bounding_box_.x + bounding_box_.w; ++j) {
     const auto current_index {getIndex(i, j)};
     checkAutomatons(current_index);
   }
 }

 world_texture_.unlock();

But to my surprise, this "precision" way is doing slower than checking every pixel and updating the whole texture. Profiling gives me an average of 0.001537s for the whole texture and 0.003079s for the "precision" way. You may think that my algorithm to determine the area to be updated makes it go slower, but the algorithm is running in both versions, but only the "precision" one is using the rectangle generated.
Why could this be? Reading the SDL2 docs it seems the correct way to change a texture that is being updated often. Maybe is because the range of the for loops changes at every update() call and some register or other low-level thing gets changed/updated?


texts: How to Render two or more images on video frame in same draw call using metal

texts:
I'm new bee to graphics programming and i have an existing code base which basically takes frame from video and passes it to metal shader where effects (like colour changes) happens.

Whats currently happening ?

I can use the existing method to send image as texture and it gets blended with the original frame and new frame is created .

what I want to achieve ?

I want to place multiple images on the original image in the same drawing call what would be the best way to achieve it? Should I change the existing render pipeline or shader can handle it.


texts: Humanoid Retargetting: Number of frames in LateUpdate is not the same as frames in animation

texts:
I need to play an animation in such a way that each frame is for sure being played and not skipped.
Why? I want to transfer an animation from 1 model to another. One model is Humanoid, the other one is Generic. This way, I can "save out" the Humanoid retargetting and process it in an external animation editor later.
To transfer the animations, I need to make sure that I don't miss any frame while copying the pose to the other model.
To do that, I use a very slow animator speed like this:
_animator.speed = 0.01f;

The Unity editor says this about the animation:

To make sure that each frame is really shown / played, I have implemented my own counter.
My counter however returns 43 frames and not 51 frames as the Inspector.
No matter how often I repeat this process, it always return 43 frames.
What am I missing?
Thank you!
private void LateUpdate()
{

    float f = _animator.GetCurrentAnimatorClipInfo(0)[0].clip.length * (_animator.GetCurrentAnimatorStateInfo(0).normalizedTime % 1) * _animator.GetCurrentAnimatorClipInfo(0)[0].clip.frameRate;
    int iCurrentFrameIDInAnimationFile = (int)f;

    bool bIsNewFrame = (iCurrentFrameIDInAnimationFile != _iLastFrameIDInAnimationFile);

    if (!bIsNewFrame)
    {
        return;
    }
    else if (bIsNewFrame)
    {
        _iFrameCount += 1;
    }

    _iLastFrameIDInAnimationFile = iCurrentFrameIDInAnimationFile;

    if (_animator.GetCurrentAnimatorStateInfo(0).normalizedTime > 1 && !_animator.IsInTransition(0))
    {
        //animation has finished playing
        Debug.Log("Frames: " + _iFrameCount); //this returns 43 frames. Why???
    }


texts: Approaches on 2D top-down track racing visualisation

texts:
I'm considering writing a very simple management style game with the theme being motorsport racing.
I've got a good idea how to do the 'management side', but the issue I'm having is how to visually render cars and move on a track (something a bit like):

The key points (keeping it simple):

the user won't control the vehicle directly, they are the 'manager' (think football manager) - they can decide on a strategy but cannot control the vehicle
the car should stay on track (visually) - they may 'crash' (along with other events) though
the speed it goes around the track is determined by vehicle performance
a car will be aware of other near-by cars around the track - for example, if they're about to be overtaken, they may actually do a slower lap as they are defending - they may collide, along with other events

My initial thoughts are there are two key design elements here, the track and the car.
The track:

a track is composed of many segments
each segment is stored in an array
a segment (I'm not entirely sure here) but one thing it might contain is a 2D array:

(From [this](https://gamedev.stackexchange.com/questions/149966/approaches-on-2d-top-view-racing-game-track-design) answer gave an approach of using multi-dimensional arrays)
_ _ _ _ _ _ _ _ _ _
| d d x x x d d d |
| d d r r r d d d |
| d d r r r d d d |
| d d r r r d d d |
| d d r r r d d d |
| d d r r r d d d |
| d d r r r d d d |
| d d e e e d d d |
| _ _ _ _ _ _ _ _ |

_ _ _ _ _ _ _ _ _ _
| d d x x x d d d |
| d d r r r d d d |
| d d d r r r d d |
| d d d d r r r e |
| d d d d r r r e |
| d d d d d d r e |
| d d d d d d d d |
| d d d d d d d d |
| _ _ _ _ _ _ _ _ |

Above is a straight and a 90 degree corner - x exit, e entry, r racetrack and d dirt. Maybe I could create a bunch of these and create a track.
Or maybe a simpler version where I define just an entry and exit:
_ _ _ _ _
| d e d |
| d r d |
| d e d |
| _ _ _ |

_ _ _ _ _
| d x d |
| d r e |
| d d d |
| _ _ _ |

The simplified version where I define an entry e and exit x. I can add additional points r and then construct a curve/straight-line based on the x, e and r coordinates?
My idea is that the vehicle will then move across each segment and I can calculate the time it takes to complete that segment. I can then add up all segments which will give me the lap time. With this approach, I can also check the previous/current/next segment to determine if there are other vehicles it needs to defend/attack against.
The car:

store all vehicles in an array
each vehicle will always be in a segment
speed it completes the segment is determined by its performance (and segment characteristics)
vehicle can 'see' if there are other vehicles in previous/current/next segment and decide whether to overtake/defend.

I think I could make this work, but I'd be really interested to know if there are better/simpler approach - bearing in mind it's mostly a visualization and the speed and events are determined by my program.


texts: Sponza scene with more physically motivated materials fit for physically based renderers

texts:
I've tried it with the default values and a lighting model copied straight from here, but the results were ludicrous. Basically since everything is way too shiny (high specular material values), most of the screen is very white unless I set the light intensity to a very small value or manually change roughness of the materials to very high values, in which case everything looks like someone spent years polishing the stuff.

Is there a version of the scene around with more physically motivated materials? Or am I just using them/interpreting them wrong?

The reason I even ask is because the scene seems to be very popular as testmaterial for global illumination algorithms, where physically based lighting seems to be commonplace.


texts:
Can someone explain the following code? I need to learn what each part means so I can turn it into enemy movement in a space shoot-em-up

Vec2d playerPos;
Vec2d direction; // always normalized
float velocity;

I get the above is naming two 2d Vector objects, and creating a variable called velocity. I'm not sure what the normalized comment is about, though.

update()
{
   direction = normalize(playerPos - enemyPos);
   playerPos = playerPos + direction * velocity;
}


texts: Why does component.GetComponent() return "null", when a rigid body is NOT attached?

texts:
In the following code, when T is Rigidbody, calling componentToLookIn.GetComponent<T>() returns "null" when there is no rigidbody attached, instead of simply null:

public static class ComponentExtensions
{
    public static bool TryFindComponent<T>(this Component componentToLookIn, out T componentToLookFor)
    {
        componentToLookFor = componentToLookIn.GetComponent<T>();
        return componentToLookFor != null;
    }
}

Here is the debug window:

As a result, componentToLookFor != null ends up being true, which is obviously not what I want.

When I invoke componentToLookIn.GetComponent<T>() where T is NOT Rigidbody, null is returned as expected when there is no component of type T found.

What is so special about components of the Rigidbody type that GetComponent<Rigidbody>() behaves differently?

EDIT:

For contrast, here is the debug window when GetComponent<BoxCollider>() is invoked on a game object that does not have any component of the type BoxCollider:

As you can see, the value of childComponent is simply null, not "null". componentToLookFor != null therefore returns false.


texts:
I am developing a top down game and I'm having trouble with a delay in switching from one character walk direction to another, particularly if the previous direction key is still being pressed by the user.

Take the following user interaction:

User presses up arrow;
User presses right arrow (up arrow is still pressed);
User releases up arrow (right arrow is still pressed).

The problem I am experiencing is that there is a delay in the character switching from the "walk up" movement to the "walk right" movement.

requestId: 0,
settimeoutID: 0,
counter: 0,

move: function(keyCode) {
  var _this = this;
  // Frame per seconds
  var fps = 60;

  if (this.requestId === 0) {
    (function animationLoop() {
      // Control the timing of an animation with requestAnimationFrame
      _this.settimeoutID = setTimeout(function() {
        _this.render();
        _this.requestId = requestAnimationFrame(animationLoop, _this.move);
      }, 1000 / fps);
    })();
  }
},

changeAnim: function() {
  if (this.counter % 10 === 0) {
    if (this.currentFrame > 1) {
      this.currentFrame = 0;
    } else {
      this.currentFrame++;
    }
  }
},

render: function() {
  // Add some drawing
  this.counter++;

  if (keyCode === config.PLAYER_DOWN) {
    this.action = 'Front';
    this.newPos.y += 1;
  } else if (keyCode === config.PLAYER_UP) {
    this.action = 'Back';
    this.newPos.y -= 1;
  }

  if (keyCode === config.PLAYER_RIGHT) {
    this.action = 'Right';
    this.newPos.x += 1;
  } else if (keyCode === config.PLAYER_LEFT) {
    this.action = 'Left';
    this.newPos.x -= 1;
  }
  this.changeAnim();
  // Draw player logic
  this.drawPlayer.reDraw(this.playerSprite[1].Walk[this.action][this.currentFrame], this.newPos);
},

onKeyUp: function() {
  // Cancel the animation request
  if (this.requestId) {
    clearTimeout(this.settimeoutID);
    cancelAnimationFrame(this.requestId);
  }
  // Allow a new request to be called
  this.requestId    = 0;
  this.counter      = 0;
  this.currentFrame = 0;
  this.drawPlayer.reDraw(this.playerSprite[1].Walk[this.action][this.currentFrame], this.newPos);
}

Note: The function move gets called every time a new key is being pressed.


texts: Taking advantage of multithreading between game loop and openGL

texts:
Talking in context of a game based on openGL renderer :

Let's assume there are two threads :

Updates the game logic and physics etc. for the in game objects
Makes openGL draw calls for each game object based on data in the game objects (that thread 1 keeps updating)

Unless you have two copies of each game object in the current state of the game you'll have to pause Thread 1 while Thread 2 makes the draw calls otherwise the game objects will get updated in the middle of a draw call for that object, which is undesirable!

But stopping thread 1 to safely make draw calls from thread 2 kills the whole purpose of multithreading/concurrency

Is there a better approach for this other than using hundreds or thousands or sync objects/fences so that the multicore architecture can be exploited for performance?

I know I can still use multithreading for loading texture and compiling shaders for the objects which are yet to be the part of the current game state but how do I do it for the active/visible objects without causing conflict with draw and update?

What if I use separate sync lock in each of the game object? This way any thread would only block on one object (ideal case) rather than for the whole update/draw cycle!
But how costly is taking locks on each object (game may have a thousand objects)?


texts: How long does it take for OpenGL to actually update the screen?

texts:
I have a simple OpenGL test app in C which draws different things in response to key input. (Mesa 8.0.4, tried with Mesa-EGL and with GLFW, Ubuntu 12.04LTS on a PC with NVIDIA GTX650). The draws are quite simple/fast (rotating triangle type of stuff). My test code does not limit the framerate deliberately in any way, it just looks like this:

while (true)
{
    draw();
    swap_buffers();
}

I have timed this very carefully, and I find that the time from one eglSwapBuffers() (or glfwSwapBuffers, same thing) call to the next is ~16.6 milliseconds. The time from after a call to eglSwapBuffers() to just before the next call is only a little bit less than that, even though what is drawn is very simple. The time that the swap buffers call takes is well under 1ms.

However, the time from the app changing what it's drawing in response to the key press to the change actually showing up on screen is >150ms (approx 8-9 frames worth). This is measured with a camera recording of the screen and keyboard at 60fps.

Therefore, the questions:

Where are draws buffered between a call to swap buffers and actually showing up on screen? Why the delay? It sure looks like the app is drawing many frames ahead of the screen at all times.
What can an OpenGL application do to cause an immediate draw to screen? (ie: no buffering, just block until draw is complete; I don't need high throughput, I do need low latency)
What can an application do to make the above immediate draw happen as fast as possible?
How can an application know what is actually on screen right now? (Or, how long/how many frames the current buffering delay is?)


texts: Can a behavior tree represent the same logic as a finite state machine?

texts:
So I was just learning about Behaviour trees and I thought they're really cool. So I decided to use them in my games. But what I don't quite understand is:

Short: Can everything done in an FSM, be done in a BT?

Long: So one of the games I'm involved in has some RE (classical resident evil) mechanics. In RE, interaction with triggers could change. For ex see this video, take 2:40 as an example (it's the tiger statue puzzle from RE1) - basically, if you interact with it the first time, it says "It's a tiger statue, it appears to have holes in its eyes". If then you use the Blue gem on it, it rotates to the left (or right) revealing an item behind it, if you pickup the item you go back to the initial state. Use the red gem and it would rotate the other direction revealing another item, pickup it and you're back again. This is obviously an FSM. Here's how it looks:

So how can this tiger statue puzzle FSM be done in a BT? (if at all) - Is this more suited for an FSM? or a BT would be nice to use here as well?

Thanks for all tips/any help.

EDIT: Gamedev.net crosslink.


texts: Does scaling affect performance in OpenGL?

texts:
I've never been able to understand the best practice in this context. I usually want to ship my game with as minimum size as possible. So whereever possible, I try to use scaling of my graphics. Let's suppose I have to draw a 1000 X 300 px wall of yellow color in my game. So I usually just use a 3 X 3 px yellow image and stretch it in game (using nearest neighbor filter). Is this the right approach?

Let us consider another situation. Let's suppose I wish to render rain in my game. Basically 2 X 30 px blue white gradient streaks . Let us suppose at any time 200 drops max are going to be rendered . Now if I just ship a 2 X 6 px streak with the game and scale it at runtime , will it affect performance?

In short, how does scaling affect performance in OpenGL?


texts: Having trouble with constructors and the deque class

texts:
I've recently been trying to make a better version of my previous remake of the classic snake game by implementing data encapsulation and abstraction. I also decided to replace my horrible choice of a linked list for holding the snake's tail co-ordinates with the more sensible choice of a deque. Since I am a beginner and I have honestly no clue what is going on (I'd be worried if I did know what I was doing), I would appreciate some assistance with helping me understand what is wrong with my usage of the deque and how I can fix it.

From what I can gather I believe it has something to do with improper usage of constructors, yet I still have not fully grasped the concept of constructors to be able to properly debug it.

SnakePart.h

#ifndef SNAKEPART_H_
#define SNAKEPART_H_

#include <deque>

class SnakePart {
public:
    void advance(int x, int y, bool loose_tail = true);
};

extern std::deque<SnakePart> parts;

#endif /* SNAKEPART_H_ */

SnakePart.cpp

#include "SnakePart.h"

void SnakePart::advance(int x, int y, bool loose_tail) {
        std::deque<SnakePart> parts;
        parts.emplace_front(x, y);

        if(loose_tail)
            parts.pop_back();
}


texts: Whats a good way to make realistic brick walls?

texts:
This is a screencap from Blackops III:

I tried this using 5 maps including displace and normal, but it still looks too flat. I was wondering what a good method or workflow is to make walls actually look like theyre popping out, like what the steps are. For example, do people displace in their modeling software and import the mesh? I just want to hear the steps you guys of the community would take to produce this effect. Thanks.

My wall:


texts: How can I keep the same speed to be static speed and how to move the objects all at the same time?

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

public class MoveObjects : MonoBehaviour
{
    public GameObject[] objectsToMove;
    public float stepsPerSecond = 1f;
    public float speed = 3f;

    private Vector3 trackStart;
    private Vector3 trackEnd;
    private float phase = 0f;

    // Use this for initialization
    public void Init()
    {
        objectsToMove = GameObject.FindGameObjectsWithTag("Stair");
        // Infer the start & end positions of the track
        // from the position of the first & last steps
        trackStart = objectsToMove[0].transform.position;
        int count = objectsToMove.Length;
        var span = objectsToMove[count - 1].transform.position - trackStart;
        // The track ends one more step distance after the last step.
        // (So the last step has some distance to travel before it wraps)
        trackEnd = trackStart + (count + 1) * span / count;
    }

    // Update is called once per frame
    void Update()
    {
        if (objectsToMove != null && objectsToMove.Length > 0)
        {
            MoveRealistic();
            //MoveRegular();
        }
    }

    private void MoveRealistic()
    {
        float n = (float)objectsToMove.Length;

        foreach (GameObject step in objectsToMove)
        {
            float step_x = step.transform.position.x;
            float max_x = (n - 1f) * 24f; // The javascript has this "24", which is based on the width of the step + the outline.
            step_x = Mathf.Repeat(step_x + speed * Time.time, max_x);

            float r = 5f;
            float x_for_atan = step_x * r / max_x - r / 2f;
            if (step_x < 3f * 24f)
            {
                x_for_atan = -r / 2f + .5f;
            }
            if (step_x >= max_x - 3f * 24f)
            {
                x_for_atan = r / 2f - .5f;
            }

            float step_y = 180f + 120f * (float)Math.Atan(x_for_atan);

            step.transform.position = new Vector3(step_x, -step_y, 0);
            // negative y because the javascript uses top, which starts at 0
            // at the top, and positive goes down. Unity goes the other direction.
        }
    }

    private void MoveRegular()
    {
        float divisor = 1f / objectsToMove.Length;

        // Compute the current phase of the escalator,
        // from 0 (1st step at track start) to 1 (1st step at track end)
        phase = Mathf.Repeat(phase + stepsPerSecond * divisor * Time.deltaTime, 1f);

        // Place each step a proportional distance along the track.
        for (int i = 0; i < objectsToMove.Length; i++)
        {
            float t = Mathf.Repeat(phase + i * divisor, 1f);
            objectsToMove[i].transform.position = Vector3.Lerp(trackStart, trackEnd, t);
        }
    }
}

Whne I'm using the MoveRealistic I'm using a break point on the line:

step_x = Mathf.Repeat(step_x + speed * Time.time, max_x);

I see that speed value is 3 and max_x value is 216.
The only value that change is the step_x what make the speed to change to very very high. And I want a static speed(3).

Another problem is that each time one object(step) is moving when he finished moving the next one move. But I want to create a escalator stairs effect using this method and the objects should move all the same time like it is in this jsfiddle: And this is where I have take the code from and converted it to unity csharp:

jsfiddle

Last problem is that the objects the step's(stairs) moving in other position/s and not on their original position/s.

This is the steps/stairs original position. And where they should move.

And this is where they are moving when using the MoveRealistic method:

When using the MoveRegular method they are moving fine but I want to be able to use also the MoveRealistic method like in the jsfiddle.


texts: Trying to create a '2D 8 Ball Pool' game - Trajectory Prediction

texts:
I am trying to create a game similar to (Pocket Run Pool) https://www.youtube.com/watch?v=ewlAE6NQnsI&t=215s a 2D pool game that is much simpler than a 3D one I need help with creating code for trajectory prediction something similar to this https://docs.unity3d.com/Manual/physics-multi-scene.html
How do I go about doing this?


texts: How do I simplify a 2D game grid for level management while keeping its by-pixel features?

texts:
(I cross-posted this from StackOverflow as this seems to be a more appropriate f̶o̶r̶u̶m̶ community. I've looked around a little here and I did not find an answer, so I hope this is not a recurring question.)

This is a question dealing with 2D world design.

I am playing around by creating a 2D bird's eye view shooter game, and I am looking to make the game sleek and advanced. I hope to be able to write physics so projectiles have momentum and knock-down properties.

I am immediately running into the problem of world design.

I need a way to have level files that store everything there is about a game. This is easiest by just having a grid of objects. But there are thin-walls and other objects that don't seem to fit into a traditional cell of a grid. I want to be able to fit all these together so I can streamline level design; so I don't have to put in the exact pixel-specific start and end of a wall.

There doesn't seem to be an obvious translation from level file to game without forcing myself into a pacman-life scenario, meaning a scenario where the game feels boxy and discrete. There is a contrast between the smoothly (relatively) moving characters and finite jumps in a grid.

I would appreciate an answer that would describe implementation options or point me to resources that do. I would also appreciate references to sites that teach game design.

The language I am using is Java (although I would love to use C or C++, but I can never find convenient resources in those languages).

Thank you for any answers. Please leave any questions in the space below; I will be able to answer them later tonight (28th Nov).

Answering Questions:

I will definitely consider using a game engine; I wanted to write a lot of it myself, but I am rethinking gradually.

Perhaps there is no answer to this question that I will "like", and the process is just inherently a bit tedious.

I meant to find a way to easily specify things like "wall goes here" without saying "add wall at 293, 195 with width 123 and height 5". This of course, is easy by dividing the game world into a grid. But dividing a gameworld into a grid is not ideal, because it has to deal with things like objects taking up more than one grid, objects being irregularly shaped and taking up only part of the grid, etc..

I've had more time to think about this, and I think that there is no way to "gridify" my world without losing some major functionality, and so I think I will have to create a world editor, where I can more easily create levels.

I still foresee problems though, specifically with AI. I need to have pathfinding capabilities, and so the algorithms naturally have some sort of search-space reduction, which is essentially making a grid. I will have to read more about this.

Until then I would still appreciate answers and suggestions on this design choice. I hope this clarifies my question - if it does not, please direct a question and I can try to answer it.

(Storing object locations is the only practical way to do any of this, I now realize).


texts:
I want to animate a character who could be doing any number of things.

Say for example, I want the character to get into bed, under the covers. Do I animate the character and the sheets moving together? Separately? If separately do I need to call both animations simultaneously to ensure it fits together properly?

Or, if two characters are going to hug. Do I animate them hugging or just animate them separately hugging and try to align them in-game?


texts: Random lines away from images in java2d opengl game

texts:
Working on a java game that uses some pngs images for icons/textures. A few images ( fewer than 5, out of dozens ) are showing some odd parallel "artifact" lines. They move with the image, are certainly not in the PNG itself.

I can't figure out what's causing it. Using slick2d, lwjgl. I've tried slcik2d and opengl methods of clamping textures but that didn't help.

This black line is showing off the right-hand side of an icon (maybe 50% of the actual image width away). It should not be there.


texts: Move camera from wherever camera is to pinned point

texts:
So, I need to switch/ move/ animate camera from point X (not point A,as I don't know where the camera is at that momemnt) to point B (place where you want your camera to move).

This is for cinematics...like when you press a button in game which does something (opens doors maybe) but you can't see where nor what did you activate, so you show the player with the camera where and what happened.

I tried to animate camera to position, camera just goes crazy.
Then I tried to make an empty object placed at the position where the camera should be and move camera with code to that objects
position.
I tried enabling Camera 2 and disabeling Camera 1 but it just doesn't work.

Enable/ Disable Code:

public var door: DoorAnim;

public var triggered : boolean = false;

function OnTriggerEnter() { triggered= true; }
function OnTriggerExit()  { triggered= false;}

function Update(){
    if (triggered && Input.GetKeyDown(KeyCode.JoystickButton1)){
            Debug.Log("Door 1 built");
            camera1 = GameObject.Find("Camera1");
            camera1.enable = false;
            camera2 = GameObject.Find("Camera2");
            camera2.enable = true;
            door= GameObject.Find("door1");
            door.animation.Play();

    }


texts: LibGdx - Move sprite in the direction of other sprite

texts:
I'm kind new to LibGdx and I'm still learning. I'm working on a small game project to learn this nice framework. However, I'm having some issues with my game. My game is a top down shooter. There is a human character(space marine) that has to shoot an alien, which will be always moving in his direction until it  dies. My code doesn't have any bullets yet.I was able to make the shooter rotate in the direction of the cursor, as well, the alien rotate in the direction of the shooter, but I can't make the alien move in his direction. I'm pretty sure that my method that does that is completely wrong. I've tried a lot to fix it , but I can't get it fixed ! I appreciate your attention guys !
You can find the full code of the main class here:
 https://github.com/Igor-Lopes/LibGdx/blob/master/Splash.java#L125

public void moveAlien() {
    float mX = 0;
    float mY = 0;
    int velocity = 50;
    vAlien = new Vector2(-1 * (float) Math.sin(Alienbody.getAngle()) * velocity,
            (float) Math.cos(Alienbody.getAngle() * velocity));

    mX = (float) Math.cos(Math.toRadians(spacemarine.getRotation()));
    mY = (float) Math.sin(Math.toRadians(spacemarine.getRotation()));

    vAlien.x = mX;
    vAlien.y = mY;
    if (vAlien.len() > 0) {
        vAlien = vAlien.nor();
    }
    vAlien.x = vAlien.x * velocity;
    vAlien.y = vAlien.y * velocity;
    vAlien.x += vAlien.x * Gdx.graphics.getDeltaTime();
    vAlien.y += vAlien.x * Gdx.graphics.getDeltaTime();
}

public float rotateMarine() {
    float angle = 0;
    float mouseX = 0;
    float mouseY = 0;
    mouseX = Gdx.input.getX();
    mouseY = 677 - Gdx.input.getY();
    angle = (float) Math.toDegrees(Math.atan2(mouseX - spacemarine.getX(),
            mouseY - spacemarine.getY()));
    if (angle < 0)
        angle += 360;
    spacemarine.setRotation(angle * -1);
    return angle;
}

public float rotateAlien(Sprite s, float posX, float posY) {
    float angle = 0;
    float mouseX = 0;
    float mouseY = 0;
    mouseX = posX;
    mouseY = posY;
    angle = (float) Math.toDegrees(Math.atan2(mouseX - s.getX(), mouseY - s.getY()));
    if (angle < 0)
        angle += 360;
    s.setRotation(angle * -1);
    return angle;
}

@Override
public void render(float delta) {
    float angle;
    moveAlien();
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    world.step(Gdx.graphics.getDeltaTime(), 6, 2);
    angle = rotateMarine();
    rotateAlien(alien, spacemarine.getX(),
            spacemarine.getY());
    if (Gdx.input.isKeyPressed(Input.Keys.W) == true
            && spacemarine.getY() < 560) {
        Marinebody.setTransform(spacemarine.getX(), spacemarine.getY() + 4,
                angle);
    }
    if (Gdx.input.isKeyPressed(Input.Keys.S) == true
            && spacemarine.getY() > 0) {
        Marinebody.setTransform(spacemarine.getX(), spacemarine.getY() - 4,
                angle);
    }
    if (Gdx.input.isKeyPressed(Input.Keys.D) == true
            && spacemarine.getX() < 920) {
        Marinebody.setTransform(spacemarine.getX() + 4, spacemarine.getY(),
                angle);
    }
    if (Gdx.input.isKeyPressed(Input.Keys.A) == true
            & spacemarine.getX() > 8) {
        Marinebody.setTransform(spacemarine.getX() - 4, spacemarine.getY(),
                angle);
    }
    alien.setPosition(Alienbody.getPosition().x, Alienbody.getPosition().y);
    spacemarine.setPosition(Marinebody.getPosition().x, Marinebody.getPosition().y);
    batch.begin();
    spacemarine.draw(batch);
    alien.draw(batch);
    batch.end();
    // stage.act();
    // stage.draw();
}


texts:
Is it possible to animate a sprite shape?  I don't see the Sprite Shape Profile in the animator properties, so I was just wondering if there's another way to do that.
To clarify:
Our game is 2D animated by hand, and one level has conveyor belts that span the level.  We can animate it normally, but that will end up taking more video memory than if we were able to animate the conveyors as tiled sprite shapes.  It may not end up being worth the effort to save the memory, but I figured it was worth a shot.  Because the sprites span the level, they end up taking up lots of space in a sprite atlas.


texts: Is there any game engine using a functional programming language?

texts:
Is there any game engine using a functional programming language similar to Scheme, Common Lisp, Clojure or JavaScript?

I've tried Unity3D but their "JavaScript" is not actually JavaScript, is strongly typed and is not functional.


texts: Is it possible to reuse the same window in multiple games?

texts:
In particular, I'm thinking about C# and XNA, and obviously on Windows. Let's say I have the main game which is a normal XNA game, but at some point I would like to momentarily switch to a mini-game that was also implemented in XNA but is completely independent of my game.

Is there any way I can switch to and back between the two games, while reusing the same windows handle? And preferably keeping the old state in memory, although I could also implement this persistence writing to a file.

And when going back to the initial game, is there any way I could access the value returned by the mini-game's main method? For instance, 1 or 0 depending on whether the player cleared the mini-game or not.

Andrew Russell wrote:

  You should build your mini game and your main game into separate classes within the same program. Each of those classes should have Update, Draw, Initialize, etc methods. You should then have some kind of master controller to call those methods to have only one game active at a time (this could also simply be in your main game class).

Thanks for the answer. Your suggestion is what I'd do in a normal game situation - one where I'd be the one creating all of the mini games and their content.

But this is not a game, but rather a game maker tool for creating graphic adventures, and it is the end user that might feel the need to plug in external mini-games in response to certain game events.

The older internal engine that I'm trying to replace was done in Flash, and solved this problem simply by loading an SWF inside of the main SWF. It worked okay for most cases. I'm trying to do something similar but with XNA now.

But following your train or thought, perhaps I could create a separate assembly containing a base class or common interface for all mini games, and compile it as a dll. Then the user would reference that library, implement the interface and compile into his own library which could be loaded by the engine at runtime and executed as a separate state inside the main game. Am I missing some hidden implications?


texts: Predicting physics/trajectory for pool/billiards games

texts:
I'm thinking of making a quick proof of concept of a billiard-style game mechanic, where the player has perfect information of what is about to happen.
Here's a good example:

I'm only mildly familiar with physics in both Unity and Flixel-Box2D, and I can't really off the top of my head imagine how to do this.

Should I even use physics at all, or should I just use basic math?