texts: Should my assets match my reference resolution?

texts:
I'm confused over supporting multiple resolutions in my 2D game.

I'm currently working with a reference resolution of 1280x720. That means that all elements are positioned in a 1280x720 coordinate system which I scale up/down to the actual resolution using glScale. My graphic assets are all pixel graphics, so it also means I need to save them relative to this reference resolution.

Now the artist sent me some files in a pretty high resolution and I scaled them all down to match the reference resolution, but I noticed that the positions of the graphics relative to each other are slightly off. Probably because there was some rounding involved in the down scaling.

Should I increase my reference resolution to match the artwork? Or should I ask the artist to scale everything down and make sure the positions aren't off as a result? Should my reference resolution be larger anyway? (2880x2304 is what I came up with to support all modern screen resolutions and aspect ratios down to 5:4, but that seems awfully large.)

How is this commonly being tackled?

Edit: Sorry, forgot to provide some relevant background: My game is a simulation game, that is essentially a UI. So there is no such thing as a world space, I'm just positioning widgets on the screen.


texts: Books on layout and space sequencing in game design

texts:
I'm currently looking into level design books. So far I've read two, The How's And Why's of Level Design and the Ultimate Level Design Guide.

While both were useful they did not discuss layout and space sequencing as much as I was looking for. I'm looking for stuff like this:

I couldn't find books that pertain to this specific subject. Do you happen to know any?


texts: How can I handle a bunch of achievements in a game?

texts:
Take for example Team Fortress 2.  There are a huge load of achievements, and I'm wondering how the manages all of them. And since there's a lot of achievements, I'd also like to know how it "knows" you've achieved one.

Basically, how can the game handle a huge achievement system?  Is there some special process? Are there hundreds and hundreds of boolean variables all over the code, waiting for certain conditions to be met, then ,Bam, achievement?

If there are several approaches, what are they?


texts:
Essentially I'm trying to make a system which you can add a job to it then finds an AI which is idle and gives it that job to do, For an example look at Prison Architects job list system (image below).

I need to be able to add a job, removed them and look at all the jobs. The next job that this returns should be the oldest one in the list.

Initially I thought of using a queue as it already provides adding and removing but as it turns out I can only see the next item in that list (well at least thats the case with the standard C# implementation of it), meaning that if there is a certain requirement which isn't met I can't skip to the next task.

Is there a version of the queue that exposes all the items within the list or some other way of doing something similar? This will be coded in C# if that makes difference to the options available.


texts: How to create an animation from several .obj files in maya?

texts:
I have several .obj files. I plan to create an animation from these .obj file. Every mesh in one .obj file is correspond to one frame. And every frame only show one .obj file (meshes in others .obj files are hidden).I use Maya.

Any body has any suggestions?


texts: NavMeshAgent - Do something once destination is reached

texts:
I have items on the ground which I can pick up. If I'm within the radius of a trigger collider around the item, I just pick it up. If i'm not, I want to set my NavMeshAgent's destination to the item and then pick it up once I've arrived. I have done this exact thing before but have since completely forgotten how to do it.

The way picking up an item occurs is by clicking on its UI nameplate, not the physical item gameObject. Therefore, I'm using the OnPointerClick function. If possible I'd like to not have to check every frame whether I have arrived at my destination or not, but I'm open to doing it that way for now.

I'm not really familiar with how the NavMeshAgent API works. I would think that if (!agent.pathPending && agent.remainingDistance <= agent.stoppingDistance) or something similar would work. I'm kind of lost though, any help is appreciated.

void Update()
{
    if (!navMeshagent.pathPending && navMeshagent.remainingDistance <= navMeshagent.stoppingDistance)
    {
        PickUpItem();
    }
}

public void OnPointerClick(PointerEventData eventData)
{
    if (itemPickupRange.playerIsInRange)
    {
        PickUpItem();
    }
    else
    {
        navMeshAgent.SetDestination(item.transform.position);
    }
}

This doesn't work. I've tried breaking up the conditions in Update and making it a nested loop, and it still doesn't work. One other thing: there's some weird behaviour with remainingDistance. Sometimes It's a number between 0 and 1 when I'm positive that the actual distance must be much larger.


texts: Changing the RotateAround center point dynamically

texts:
Black circles are static
Red - player
Blue line - path

I'm trying to achieve a constant movement of the red dot like on the image below. For now, I have something like:

void Update(){

    target = firstCircle; // here I need to perform some calculations
    this.transform.RotateAround(target.transform.position, Vector3.forward, speed * Time.deltaTime);

}

As you can see in the code, it rotates around the upper circle now. I need to switch the target variable to the secondCircle when the player comes back to it's initial position (or is near it).

I came up with something like:

if(Mathf.Abs(Mathf.DeltaAngle(360f,this.transform.rotation.eulerAngles.z)) < 5f)
    //change target

and it works but has two issues. First - the epsilon value. If I set it to 5f the above if is true like 7 times (depending on the player's speed). Of course I could make a lock to run it only once per cycle, but there's a second problem. If the object is moving too fast, the if will be false each time, cause the speed-step is always higher than the epsilon.

How is this done in 'gravity' games like AngryBirds when the bullet changes it's attraction point?


texts:
I currently have a game concept similar to the mobile app Alphabetty where you are given a grid of letters and are tasked with spelling words. When you use a letter in a word, it disappears and new letters fall in from the top to replace the used ones.

I have been playing around with ways of making the new letter spawning more "interesting" so that players can get more complex words. I tried making it so each letter spawns based on how common it is, kind of like scrabble but didn't get great results. I have also tried representing each grid tile as a Boggle die which re-rolls each time its used, which was better but far from perfect.

The main issues are:

Vowels and consonants often end up grouped together, creating unusable areas on the board. This also goes for letters of the same type (i.e. 3 s letters side by side)
With Boggle dice it's very hard to spell words like "Blizzard" as only 1 or 2 dice have rare letters such as z, v, and k etc
For the sake of a game mode, I need to be able to seed the grid with words of my choosing slowly (i.e. as new letters fall in) so that players have the ability to spell these special words if they are particularly careful

Are there any solutions, theories or discussions out there that could help?

Thanks!


texts: OpenGL convert mouse position to world coordinates without gluUnproject in Python?

texts:
EDIT: I changed the bottom left to -1,-1 and the top right to 1,1, and while I can draw objects within this range, I cannot map the mouse x,y to the world space.
I have been trying to learn OpenGL and my current goal is to move a circle on mouse drag. I have created the circle, but I cannot seem to be able to map my mouse coordinates to the world coordinates using glOrtho. I also set the initial window position to 100, 100, I don't know if that is relevant to the issue though.
For reference this is my init code:
def init():
    # select clearing color
    glClearColor(0.0, 0.0, 0.0, 0.0)

    # initialize viewing values
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0)

I know that the glOrtho takes the left, right, bottom, top, near and far values, but when I try to convert to world space coordinates from mouse position(since I only need the x and y so I can calculate distance from the circle's origin) I end up with coordinates in the range 0.0 - 1.25, which makes no sense to me at all, because it should be 0.0 - 1.0.
This is my glutMotionFunc:
def click(x, y):
    global current_circle

    nx = float(x * SCREEN_SIZE / SCREEN_SIZE)
    ny = float(y * SCREEN_SIZE / SCREEN_SIZE)

    print("Mouse click", nx, ny)

    for circle in circles:
        print("Circle center", circle.cx, circle.cy)
        if (np.square(nx - circle.cx) + np.square(ny - circle.cy)) <= np.square(circle.r * (SCREEN_SIZE / 10)):
            current_circle = circle
            current_circle.set_position(nx, ny)

            glutPostRedisplay()

Also, why is my window 300x300 when it should be 250x250? I don't set the window size anywhere but the above init function.


texts: How should rendering be structured using SDL?

texts:
This question is probably well documented but I can't find any resources.

Basically I'm not sure how to structure rendering with SDL in my code.

I made a render class which calls the api and the game loop contains this:

while(running) {
    renderer->RenderClear();
    map->DrawMap();
    player->render();
    renderer->RenderPresent();
}

Everything is rendering properly however I'm not sure how I should structure my code if there's many more things that need rendering. I want to draw a box on the screen with SDL_RenderDrawLine but the line will only draw for one frame before RenderPresent in the main loop clears it. I don't think I should have everything placed in the loop that may need rendering.

What is the proper code structure in which objects should use the render api? An array which contains everything to render in the loop? Separate instances of Render() which call their own draw and render? Something else?


texts: How does double dispatch help collision detection?

texts: There are a few specific techniques to test if one object has hit another object in a game. One of them is called "double dispatch." Can someone explain what double dispatch is, and how it can be used to test hit objects?


texts: I am currently working on a small game that will generate a world with caves and entrances to the caves, something like Terraria if you will. Today I reached some trouble on the world/cave generation code. I want to use Perlin Noise but I am not so sure how to implement it into my code. Could someone point me in the right direction for a reference or even code samples?


texts: Where is the error in my perspective projection implementation?

texts:
My question is not really a game development question, but since it's based on 3D programming, I thought it would fit best here.

I've got a line made out of Point3D objects where the value of x, y, and z are somewhere in those regions:

x: 0 - 640
y: 0 - 480
z: 0 - 4000

I'd like to project those lines into a plane with the size of 640 * 480 (the same size as the base x * y values were) using a oerspective projection. I found some information about the matrix I should use in an old computer graphics script (there are a lot of different matrixes around the net too), but could not get it to work.

Based on this tutorial, I'm using the following parameters:

float n = 1000; // near plane
float f = 4000; // far plane
float l = 0;    // left side
float r = 640;  // right side
float b = 480;  // bottom
float t = 0;    // top

float m11 = (2 * n) / (r - l);
float m22 = (2 * n) / (t - b);
float m31 = (r + l) / (r - l);
float m32 = (t + b) / (t - b);
float m33 = (-1 * (f + n)) / (f - n);
float m43 = (-2 * f * n) / (f - n);
float m34 = (-2 * f * n) / (f - n);

m = new Matrix3D(m11,   0,   0,   0,
                   0, m22,   0,   0,
                 m31, m32, m33,  -1,
                   0,   0, m43,   0);

Now all the result-points I receive from doing a m.Transform(myPoint3D) are in ranges like:

x = -1,015 to -1,694
y = 1,568 to 1,572

In my understanding those values should be in ranges from -1 to 1, and I would scale them to fit into my plane, but those results look totally chaotic... Also, the resulting z-values aren't "flat" but ranging from 2.903 to 2.996.

Any ideas where my error is?


texts:
Trying to understand some basic 3D concepts, at the moment I'm trying to figure out how textures actually work. I know that UV and UVW mapping are techniques that map 2D Textures to 3D Objects - Wikipedia told me as much. I googled for explanations but only found tutorials that assumed that I already know what it is.

From my understanding, each 3D Model is made out of Points, and several points create a face? Does each point or face have a secondary coordinate that maps to a x/y position in the 2D Texture? Or how does unwrapping manipulate the model?

Also, what does the W in UVW really do, what does it offer over UV? As I understand it, W maps to the Z coordinate, but in what situation would I have different textures for the same X/Y and different Z, wouldn't the Z part be invisible? Or am I completely misunderstanding this?


texts: Problem with "only assignment, call, etc." while i was trying to make my 2D character not jump in the air

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

public class move2d : MonoBehaviour
{
    public float moveSpeed = 5f;
    public bool isGrounded = false;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        Jump();
        Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f, 0f);
        transform.position += movement * Time.deltaTime * moveSpeed;
    }

    void Jump()
    {
        if (Input.GetButtonDown ("Jump") && isGrounded == true) {
            gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, 5f), ForceMode2D.Impulse);
        }

    }
}

and another file for stopping my character from jumping in the air

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

public class Grounded : MonoBehaviour
{
    GameObject Character1;
    // Start is called before the first frame update
    void Start()
    {
        Character1 = gameObject.transform.parent.gameObject;
    }

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

    }

    private void OnCollisionEnter2D(Collision2D collision) {
        if (collision.collider.tag == "Ground")
        {
            Character1.GetComponent<move2d>().isGrounded == true;
        }
    }

    private void OnCollisionExit2D(Collision2D collision) {
        if (collision.collider.tag == "Ground")
        {
            Character1.GetComponent<move2d>().isGrounded == false;
        }
    }
}


texts:
I have variable=count(integer) in a Character Blueprint.
I want to increment the variable when user presses the 'R' key.
What do I so in the Blueprint that variable remains the synchronized between the server & client?
For example:
In server- 'R' key pressed 3 times so count value should be 3.
In client-'R' key pressed 4 times, so then the value should be 7.


texts:
I use multiple game Engines, but havn't used Unreal engine for quite a while, Now with the recent changes in Unreal Engine there are quite some interesting features which would be interesting to use in games.

However I also recently heard that UE4 recently dropped build support for Linux.
So my main 2 questions are
1. Did UE4 truly drop Linux build support?
and if so
2. Is there a way to get Linux build support in the latest version of UE4?

I can check the first question myself but due to the large engine size and my slow network connection this would take very long, so I figured it would save a lot of time if someone who already has the newest version installed knew the answer.


texts:
I'm subdividing a sphere so when distance gets greater, the sphere is subdivided less to save memory.

The sphere changes to another sphere when the distance is 10. My problem is that only one triangle gets rendered at a time in the geometry shader. This makes the rest of the sphere the different and causes holes and cracks. like the image below

How can I render all the triangles at one time?

my geometry function code is

 [maxvertexcount(50)]
void GS(triangle VertexOut gin[3], inout TriangleStream<GeoOut> stream)
{

if(distance(gin[0]) < 10.0f)
{
VertexOut v[15];
Subdivide2(gin, v);
OutputSubdivision2(v,stream);

}
else if(distance(gin[0]) >= 10)
{
VertexOut v[6];
Subdivide(gin, v);
OutputSubdivision(v,stream);

}
}


texts:
I've been working on a simple game with semi-realistic water. I followed some tutorials to get:

a flat water surface
reflection and refraction (blended using fresnel term)
ripples using a bump/normal map

Next step, I created a mesh to form actual waves. I'm animating it, and it looks great (for my intents and purposes).

Normally, to get the reflection, I would render everything on a second camera, which is actually the normal camera, but mirrored over the water plane, like in the image below:

Then, just sample that camera's output to find the reflected color.
Obviously, this technique doesn't work if the water level isn't consistent. In other words, with an animated mesh, this looks terrible.

Can anybody suggest a different way to implement reflections? Or show a workaround method?


texts: Move collider along with model with Mecanim jump animation

texts:
I've been creating an infinite runner game in Unity3D for a while and I got stuck in this point that whenever my character jumps using Mecanim system his model (mesh) goes to air but his attached collider does not.

For jumping I don't apply any force or somethings else. (He does not even have a rigid body component). The jumping process is only done by Mecanim animation jump.

Is there any way to make that collider to move along with the model?

Please note that since I've used character controller to controlling my character, I cannot use "Apply root motion".


texts: How can I handle transferring a character from one collision surface to another?

texts:
I've been trying to modify some slope code from an example I've found but I've come across an issue the way the method is designed it attaches the current slope and then based off that slope determines if the character is on it or not.

 protected CollisionPath attachedPath;

The issue with this though is when you try and lay down several slopes to make one continuous slope it doesn't work properly as this piece of code kicks in and makes you fall off the current slope you are standing on.

if (position.X < attachedPath.MinimumX || position.X > attachedPath.MaximumX)
{
    attachedPath = null;
}

While this isn't the case when you jump from one slope to another. I've tried to adapt the code used for jumping to one slope to another to solve the issue to no avail. The method in its entirety is below.  any help with this would be really appreciated.

private void HandleSlopeCollisions( GameTime gameTime)
{
    collisionPaths = level.collisionPaths;
    float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

    if (velocity.Y >= 0)
    {
        if (attachedPath != null)
        {
            isOnGround = true;

            position.Y = attachedPath.InterpolateY(position.X);
            velocity.Y = 0;

            if (position.X < attachedPath.MinimumX || position.X > attachedPath.MaximumX)
            {
                attachedPath = null;
            }
        }
        else
        {
            Vector2 footPosition = position;
            Vector2 expectedFootPosition = footPosition + velocity * elapsed;

            CollisionPath landablePath = null;
            float landablePosition = float.MaxValue;

            foreach (CollisionPath path in collisionPaths)
            {
                if (expectedFootPosition.X >= path.MinimumX && expectedFootPosition.X <= path.MaximumX)
                {
                    float pathOldY = path.InterpolateY(footPosition.X);
                    float pathNewY = path.InterpolateY(expectedFootPosition.X);

                    if (footPosition.Y <= pathOldY && expectedFootPosition.Y >= pathNewY && pathNewY < landablePosition)
                    {
                        landablePath = path;
                        landablePosition = pathNewY;
                    }
                }
            }

            if (landablePath != null)
            {
                velocity.Y = 0;
                footPosition.Y = landablePosition;
                attachedPath = landablePath;

                position.Y = footPosition.Y;
            }
        }
    }
    else
    {
        attachedPath = null;
    }
}


texts: How to make leg bones children of torso bone in Blender?

texts:
I'm a complete Blender novice and I'm trying to create a humanoid skeleton. I'm having problems figuring out how to make my leg bones children of the torso bone. Here's how my skeleton looks like:

As you can see from the bone hierarchy, the legs are not children of the torso. This is because I extruded them from the lower part of the torso bone. Is there any way I can fix this?

Also, on another note, would this be a good skeleton for 2D animations?


texts: Need simple 3D terrain render with big texture map

texts:
I have a 1000 x 700 height map

I have a 1000 x 700 texture map

I did something very similar about 8 years ago:

Using XNA. Unfortunately, when I bring up this old project and convert it to Visual Studio 2010 it will no longer compile and just throws tons of errors.

I'm looking for something very simple. Is there a 3D terrain single texture XNA example floating around out there that I can convert? I haven't touched XNA since about 2009 or 2010 and none of my old code will run anymore (I have no idea what's going on).

I need to do a 3D terrain proof of concept where the terrain texture is stretched over the height map. Nothing fancy. Maybe XNA.

Any ideas?


texts:
I think I already got the idea of the Entity System inspired by Adam Martin (t-machine). I want to start using this for my next project.

I already know the basic of Entity, Components, and Systems. My problem is how to handle UI / HUD. For example, a quest window, skill window, character info window, etc. How do you handle UI events (eg. pressing a button)? These are stuff that doesn't need to be processed every frame. Currently, I'm using MVC to code UI but I don't think that'll be compatible for Entity System.

I've read that Entity System is embedded on a larger OOP. I don't know if UI is outside of ES or not. How do I approach this one?


texts: Random seed function for map generation?

texts:
I am looking for a function to generate a random tile-based map as the visual boundaries of the map change (by going through the map). I want the map to be infinitely large, and have maze-like structure.

However, if the world is infinite, going back to where a player has already been before raises a problem. The game must remember how everything back there actually looked like.

So, I was thinking - "How does Minecraft solve this issue?" and I thought to myself that they must be using some kind of random-number function with a seed, that can both go forward but also backwards, and in that way, re-generate old tiles exactly as they were, but in new instances.

What are your thoughts on this?


texts: What exactly is the difference between separation and obstacle avoidance

texts: I've been reading some literature that explains both separation and obstacle avoidance. On first sight, they both seem very similar in what they are supposed to do: keeping objects apart form each other. If that is the case, why would I need to have both behaviors? Is separation sort of wrapping obstacle avoidance, and adding to it?


texts: How can the player select his weapon among many?

texts:
I'm working on the prototype of my game, I want one of the options to have a very large amount of weapons. I have searched for tutorials, but I have only found weapons changes where the weapons have already been loaded in the scene from the inspector, like this https://youtu.be/Dn_BUIVdAPg where they are only activated and deactivated.
But I want a game like dofus where there are hundreds of weapons, I think I have a data file of the weapons and so, I can load the correct model of the weapon.
How can I get the model loaded?

I have read other tutorials regarding the AssetBundle, but I think that is when you need to download the models from a server for example, but I just want to load them from the same project.

sorry for the bad english


texts:
Got pitched a project where we need to make a trading card game to promote a clients project. I don't have any brilliant ideas for rules, but was pondering if any "open-source" rulesets existed, or if its possible to purchase a licence to use some ruleset somewhere.

I noticed that Shadow Era are using the exact same rules and card structure as the World of Warcraft TCG, and was wondering if that was open, or just a "ballsey move" from Shadow Era's side.

It's gonna be a duelling TCG, but we are throwing a steampunk setting in the mix, to seperate it from the fantasy brands.

It's ofcourse sad that we don't have the time to come up with our own original and thrilling card game structure, but the hours we would have to put into making such a system is simply way out of our budget.


texts: Will TCP really affects UDP if used in different context?

texts:
I have read some questions about using both TCP and UDP in multiplayer game, such as Does it make sense to use both TCP and UDP at once? and Is UDP still better than TCP for data-heavy realtime games?.

Most answers recommend against using both at the same time, and maybe use a reliable UDP library, because of the TCP induces UDP packet loss argument stated in this paper for example.

But, if I don't use them both at the same time, e.g. using TCP when the players are still in the lobby/room and then sending data like who are in the room, players data, who just joined the room, etc. where everything must be reliable but also pretty infrequent and then as soon as the game started it switches to UDP to send data like movement, position, etc. where some packet drops is okay, is it okay to do this?

What about if the server is currently handling multiple games at once, like one game is currently playing (using UDP) and another one is still in the room (using TCP)? Will there be a massive packet loss for UDP?

Also about the simultaneous TCP and UDP packet loss, is it only happening if we use them in the same port or does it still happen regardless?


texts: Different Screen Sizes and Camera in Unity

texts: Now I know that no matter what the screen size is the camera will keep its height, so no worries about that. My question is, is there a way to manipulate the camera, either its orthographic size, or its viewport rect width, height, x or y so that the camera will fit perfectly on different screen resolutions. I know this a perfect solution for supporting different screens problem but how do other games do that? I mean I took some games from google play like bunny skater, or stick hero, those games look the same on Huawei P6 which has 1280x720 resoltuion, on Prestigio Multipad 4 which has 1024x768 and on HP Slate 7 which has 1024 x 600 resultion, now my question is how do they do that? I think the closest solution to this is to manipulate viewport rect of the camera, I'm saying this because I found a script that does so but it leaves black bars on top and bottom, the game looks the same on every device though but as I said it leaves black bars on top and bottom, so is there a solution on how to do this?


texts: How should I go about abstracting away the graphics device?

texts:
I would like to be able to move my game from using a XNA graphics device to possibly an OpenGL device in the future. So I'd like to have a somewhat abstract interface to submit polygons to. Its ok if it does not fully hide the directx pipeline. I simply want something that takes in a bunch of vertices and draws them.

I was wondering if anyone has done this and/or if you guys had any advice for me.


texts:
I am trying to create an image editing application for the purpose of generating UV maps in my own format. I am currently working on scaling the image for the purpose of zooming. I can get the image to zoom correctly, but it always zooms around the center of the image. I would like to scale around the mouse instead.

My Question

How can I scale a rectangle(image) around a point(the mouse)?

My Variables

float X = imgX;
float Y = imgY;
float W = imgWidth;
float H = imgHeight;
float mX = mouseX;
float mY = mouseY;

My Code

function scale(float ratio){
        W += ratio;
        H += ratio;
        X -= ratio/2;
        Y -= ratio/2;
}

To Clarify

I am not trying to change camera or view-port. I am trying to scale an BufferedImage through the Graphics.drawImage() function. The function take the image and the x, y, width, and height of the image to be rendered.

Example
In the Windows Photo Viewer, when you zoom in using mouse scroll, the image is zoomed around the mouse.


texts: Adjust sprite bounds of the visible part of texture

texts:
Is there any way to adjust the boundaries of the visible part of the sprite? To make it easier to understand: I have a texture, such as shown at figure 1. Then I break it into pieces and fill the resulting fragments using PRKit (wood texture on figure 2 and 3). But the resulting fragments have the transparent (green color on figure 2 and 3) and when creating a sprite from the fragments they have the size of the initial texture. Is there a way to get rid of this transparency and to adjust the size of the visible part (wood texture), openGL or cocos2d-x means?

Maybe it help - draw() method from PRKit:

void PRFilledPolygon::draw() {

//CCNode::draw();

glDisableClientState(GL_COLOR_ARRAY);

// we have a pointer to vertex points so enable client state
glBindTexture(GL_TEXTURE_2D, texture->getName());

glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_ONE_MINUS_SRC_ALPHA);
glVertexPointer(2, GL_FLOAT, 0, areaTrianglePoints);
glTexCoordPointer(2, GL_FLOAT, 0, textureCoordinates);

glDrawArrays(GL_TRIANGLES, 0, areaTrianglePointCount);

glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

//Restore texture matrix and switch back to modelview matrix
glEnableClientState(GL_COLOR_ARRAY);}


texts: How do I make an equipped item affect the equipper?

texts:
I'm making a small text-based adventure in Objective-C. I have a Player class with four properties which represent the player's attributes (strength, agility, stamina, and intelligence). I also have a Weapon class. My goal is to put a weapon in the game that will increase the player's stats as long as it is equipped. How can I achieve this in an object-oriented fashion?

I could add a method to the Weapon class that will increase the player's attributes, and call the method only when a flag is set to true (which I would set to true when initiating this particular weapon, and leave false for all other weapons I create), but that seems a bit messy and not particularly object-oriented. I recently learned about the decorator design pattern. Would I be able to accomplish my goal using decorators?


texts: Zenject injection from an existing in scene prefab

texts: I am trying to use Zenject to automatically inject a reference to a component on a game object that I have in the scene, but can only seem to make the create new component on new object work. Should I be using a prefab installer and if so why can't I just drag the prefab into the prefab installer?


texts:
I've got a problem with Unity materials.
I'm a beginner- so I used Wings3d for creating 3d models.
But there's a little Problem.
Both objects on the picture below have the same material(a Standart Material with 0 smoothness, 0 metallic and only a only an Albedo picture)-but obviously the right one has no texture( and that's the problem).

First I ignored it and used a custom shader ("Custom/WorldCoord Diffuse) which I found in a package for fixing it. Poorly this shader doesn't support Normal or Height maps and strangely slows down my game extremly (my scene with only Standart shaders ~80 FPS | my scene with this strange shader~7 FPS).
I don't know how to write my own shaders and I don't know blender, and I don't have much time to fix this.


texts: What are the other three "game dynamics"?

texts:
Seth Priebatsch recently gave a tedtalk entitled “Building the game layer on top of the world.” In it, Seth described four “game dynamics,” techniques used by game designers to make games fun and addictive. The four dynamics that Priebtsch described were:

Appointment dynamic-a dynamic in which to succeed, one must return at a predefined time to take a predetermined action. (Real life example: happy hour)
Influence and status-the ability of one player to modify the behavior of another's actions through social pressure. (Example: different color credit cards as a reflection of status)
Progression dynamic-a dynamic in which success is granularly displayed and measured through the process of completing itemized tasks. (Example: linkedin profile progress bar)
Communal discovery-a dynamic wherein an entire community is rallied to work together to solve a challenge. (Example: finding interesting content on Digg.com)

Seth explained these four game dynamics in his talk and added that his company has an additional three. Does anyone know (or have any theories) about what the other three game dynamics are?


texts: Scrambling word into least recognizable form

texts:
My goal is to present the player with a scrambled word that should be reordered back into the original form:

OELHL --> HELLO

I want a scrambling algorithm that takes any given word(>3or4 letters, may contain spaces) and turns it into the least recognizable form.

While randomly moving every letter around certainly works, I noticed that not all shuffles are equal, some are more recognizable than others. I am posting this question in case someone knows of a better algorithm (maybe based on linguistics) that ~~guarantees least recognizable form.


texts: Why does Unity save textures in bitmap format for APKs and IPAs?

texts:
Why does Unity save graphic resources in Android apks and iOS ipas in a bitmap format(width*height*bpp)?

I want to save my resources in a small apk, but instead of 1mb for an image Unity stores 11mb for a single image.


texts: How to handle Japanese on Windows and Linux using SDL_ttf and C++?

texts:
In SDL_ttf, there are a few functions provided that handles non-ASCII string literals, such as:

TTF_RenderUNICODE_Solid
TTF_RenderUTF8_Solid

and etc. I'll be using only the two functions as part of my question.

Currently, I'm fussing over whether to stick to using TTF_RenderUNICODE_Solid or TTF_RenderUTF8_Solid, mainly because I wanted my program to be able to work flawlessly on both Windows and Linux. (No plans for Mac, because of lack of hardware).

I know for a fact, on Windows, they used UTF-16 for handling wide characters. It's pretty straightforward to use Japanese for SDL, by using TTF_RenderUNICODE_Solid and the use the following code, that I'm currently using, to convert from wchar_t string literals to Uint16* type that the SDL_ttf uses:

static inline Uint16* Convert(wchar_t LString[]) {
    return reinterpret_cast<Uint16*>(&(LString[0]));
}

Thus, I can easily do:

SDL_Surface* textSurface = TTF_RenderUNICODE_Solid(font, Convert(L"い"), this->color);

But, given that any string literals, L"" is a wchar_t[] type, it makes things more complicated for me if I were to port this over to Linux. The only way I know of compiling code for Linux is to use GCC, and GCC clearly defines wchar_t to be of 32 bits long.

Of course, I can just straight up use the UTF8 versions:

TTF_RenderUTF8_Solid

And just use string literals, such as u8"あ", or u8"いいえ", and they will all work in most cases. The problem here is, when I store these string literals and then inspect the variables in the debugger, I would not get the values I wanted. The stored data would suffer from integer overflow, like so:

Where at the top, I used u8"あ" and for bottom, I used L"あ". You can see how the value is no longer preserved when using UTF8 strings, but the value is preserved when using wchar_t type strings.

Thus, I really can't use TTF_RenderUTF8_Solid in SDL_ttf to help me with Japanese encoding.

May I ask what is the best way to go about this? And how I should correctly handle Japanese on both Windows and Linux platforms?

Thanks in advance.


texts:
I'm using Pygame for Python 2 and I have the following code:

self.radius = 100
self.light = pygame.Surface((2*self.radius, 2*self.radius), pygame.SRCALPHA)
self.light.fill((0, 0, 0, 0))
pygame.draw.circle(self.light, (255, 255, 255), (self.radius, self.radius), self.radius)
alphas = pygame.surfarray.pixels_alpha(self.light)
for x, col in enumerate(alphas):
    for y, pixel in enumerate(col):
        pixel = 255 - f.distance(pygame.Rect(x, y, 1, 1), pygame.Rect(self.radius, self.radius, 1, 1))

Basically this code creates a new surface, makes it transparent so that it doesn't interfere with the background, draws a circle on it, and then makes two nested for cycles, going through all of the pixels. The problem is, these fors are too slow. How can I improve their performance?


texts: How can I use an unsigned int as a GLSL attribute for OpenGL ES 2

texts:
I'm having trouble finding conclusive information on this, but it seems like I can't pass integer attributes to GLSL for OpenGL ES or that if I do they'll be converted to float. I need a value between the range [0-65535] for each vertex. If I pass it as a float and then convert it back, I'm concerned that the value will have changed (if the precision is low enough and can't suitably represent values at the higher magnitudes).

Its also confusing trying to figure out what precision for floats the OpenGL ES 2 standard requires. It seems like the minimum requirement is 16-bit (ie some implementations will use 16-bit floats for highp variables). In this case, it would seem like the floating point number wouldn't be able to store enough information for 0-65535 since that's what a 16-bit unsigned int holds.

So, formally, how can I specify a vertex attribute that will let me precisely represent the values 0-65535 in OpenGL ES 2.


texts: What is the difference between Quaternion.Euler and transform.Rotate?

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

public class RotateObjects : MonoBehaviour
{
    public GameObject[] objectsToRotate;
    public Transform to;
    public float speed = 0.1f;
    public Vector3 spinDirection;
    public bool useMouse = false;
    public bool useQuaternion = false;
    public bool nonstopSpin = false;

    float x;

    // Use this for initialization
    void Start()
    {
        if (objectsToRotate.Length > 0)
        {
            if (useQuaternion == true)
            {
                for (int i = 0; i < objectsToRotate.Length; i++)
                {
                    objectsToRotate[i].transform.rotation = Quaternion.Lerp(objectsToRotate[i].transform.rotation, to.rotation, Time.time * speed);
                }
            }
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (objectsToRotate.Length > 0)
        {
            for (int i = 0; i < objectsToRotate.Length; i++)
            {
                x += Time.deltaTime * speed;
                objectsToRotate[i].transform.rotation = Quaternion.Euler(x, 0, 0);

                if (useMouse == true)
                {
                    if (Input.GetMouseButton(0))
                    {
                        Rotate(i);
                    }
                }
                else
                {
                    Rotate(i);
                }
            }
        }
    }

    private void Rotate(int i)
    {
        if (useQuaternion == true)
        {
            objectsToRotate[i].transform.rotation = Quaternion.Lerp(objectsToRotate[i].transform.rotation, to.rotation, Time.time * speed);
        }

        if (nonstopSpin == true)
        {
            objectsToRotate[i].transform.Rotate(0, 1, 0);
        }
    }
}

In the Update for testing I'm using Quaternion.Euler to spin the object.
In the bottom I'm using transform.Rotate.

In both cases I'm getting the same results the object is spinning around it self.

Then what is the difference between them and what should I choose when I want to spin an object ? And maybe there are more way to make an object to spin around it self. But I wonder what is the difference.


texts:
I'm trying to get a card to flip when clicked but the flipping only works the first flip. While debugging, I can see that OnMouse is called every time I click.

public class CardController : MonoBehaviour
{
   bool isShowingFront = true;
   bool isFlipping = false;
   float speed = 0.005F;
   Quaternion flipRotation = new Quaternion (0, 0, 0, 0);
   // Use this for initialization
   void Start ()
   {

   }

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

      if (transform.rotation.y != flipRotation.y) {
             transform.rotation = Quaternion.Lerp (transform.rotation, flipRotation, Time.deltaTime * speed);
             isFlipping = true;
      } else {
             isFlipping = false;
      }

   }

   void OnMouseUp ()
   {
      if (isShowingFront) {

             flipRotation.y = 180;

      } else {
             flipRotation.y = 0;
      }

      isShowingFront = !isShowingFront;
      Debug.Log ("I was clicked");
   }
}


texts: I have a MeshRenderer mr public variable in script1. I dragged mesh1 from the assets in the mr place in the inspector of script1. mesh1 has a material mat1, I try to change this material to mat2 using this mr.sharedMaterial = mat2; but the material doesn't change. It only changes the material in the assets but not the one in the hierarchy, so in the runtime nothing changes. Any advice please?


texts: How do I pixelate a scene with SceneKit and Metal, in Swift?

texts:
I managed to get pixelation working by using the OpenGLES2 rendering API, and a CIFilter. But it was way too slow, so I want to use the Metal API and just have a very simple filter that pixelates everything in the scene.

Would really appreciate some help, maybe just explaining how to set up SceneKit to use a Metal shader. Is there something I can just drop in with a few lines?


texts: Implement an upper FPS limit in the gameloop

texts:
I implemented my game-loop as described in deWiTTER's article, using the last approach with an unlimited FPS and a constant game-speed.

My problem is, that the unlimited FPS cranks up my CPU usage to nearly 100%. I understand that this is desired (as the hardware does as much as it can), but for my game, it's not really necessary (it's pretty simple). So I'd like to limit the FPS to some upper bound.

Consider my game-loop:

private static final int UPDATES_PER_SECOND = 25;
private static final int WAIT_TICKS = 1000 / UPDATES_PER_SECOND;
private static final int MAX_FRAMESKIP = 5;

long next_update = System.currentTimeMillis();
int frames_skipped;
float interpolation;

// Start the loop:
while (isRunning){
    // Update game:
    frames_skipped = 0;
    while (System.currentTimeMillis() > next_update
            && frames_skipped < MAX_FRAMESKIP){
        // Update input, move objects, do collision detection...
        // Schedule next update:
        next_update += WAIT_TICKS;
        frames_skipped++;
    }
    // Calculate interpolation for smooth animation between states:
    interpolation = ((float)(System.currentTimeMillis() + WAIT_TICKS - next_update)) / ((float)WAIT_TICKS);
    // Render-events:
    repaint(interpolation);
}

How would I implement a maximum FPS?

If i implement the repaint the way I implemented the update (or use a sleep instead of "do-nothing-cycles"), then the FPS is locked, right? That is not what I want. I want the game to be able to work with lower FPS (just as it does now), but limit the FPS to a maximum of, say 250.


texts: Realtime Multiplayer - How to handle user updates coming in different times

texts:
I have a game loop that sends new positions of every player to other players.

But there is no guarantee that the users will send the server their new positions at the same time. Actually if their connection is slow or some errors happen inbetween, then the data of the clients will flow to the server in a very varying way for every other user.

My question is, how should I handle so varying data on the server, and decide who should win in a fast-paced multiplayer game. Is the key, timestamp of the requests (seems like it is widely open to cheating), or just the clients sending me directions where they go, and their actions like pressing a button etc?

I've read lots of articles on the web, but none of them seems to completely cover the subject.

PS: I just want to decide on the server side, what should be the next 'frame' in the game by applying the game scenario to the user inputs.


texts:
When searching for slerp, I get this text:

  Slerp is shorthand for spherical linear interpolation, introduced by Ken Shoemake in the context of quaternion interpolation for the purpose of animating 3D rotation.

As far as I understand it, slerp is important for rotations in 3D, since the rotation is composed of multiple angles and it's important to consider the whole structure rather than each number individually.

However, I've also heard of people choosing between lerp and slerp for a single angle for rotation in 2D (where lerp is done with a lerp_angle method takes into account rotations in both directions). I don't understand what slerp would mean in 2D or how it would be different. Is there some case in which lerp doesn't work right in 2D? Is the behavior different, how?


texts: Cycling UV-coordinates with instanced drawing c++/opengl/glsl

texts:
I'm trying to animate 2d sprites using glDrawArraysInstanced(), and I'm having trouble separating for each "cycle" ran through the pipeline.

according to one of the tutorials I'm reading, it says:

"Send the age of each particle along with the position, and in the shaders, compute the UVs"

But without clarifying exactly how to do so. This is what my vert shader looks like atm:

#version 400 core
layout ( location = 0 ) in vec3 vertex_position; //vertices, 1 box
layout ( location = 1 ) in vec2 tex_cord; //1 tex cord
layout ( location = 2 ) in vec4 color_vec4; //1 vec4 color per texture
layout ( location = 3 ) in mat4 in_mat; //4 vec4 to make 1 mat4

//flat out int InstanceID; //use but how?

out vec2 UV;
out vec4 color4;

void main()
{
    gl_Position=in_mat*vec4(vertex_position,1.0);

    color4=color_vec4;
    UV=tex_cord;
}

And my frag shader:

#version 400 core
in vec2 UV;
in vec4 color4;

uniform sampler2D png_tex;  //texture atlas

void main()
{
    gl_FragColor=texture(png_tex,UV)*color4;
}

Does anyone know how to get the vec2-uv coordinate to change/cycle, when using instanced drawing?

Solution:

adding this to my vert shader:

UV=vec2
(
(tex_cord.x/info_vec4.z)+(1.0/info_vec4.z*info_vec4.x),
(tex_cord.y/info_vec4.w)+(1.0/info_vec4.w*info_vec4.y)
);

I know this can be done cleaner, but I'm not sure exactly how atm. This works however, and its alot faster than having to pass a new png/texture per update. The explanation for it is: info_vec4 is an ivec that I pass as an attribute with information of the current primitive/triangle. It holds: x=xcord (1-5), y=ycord (only 1), z=number of x frames total, and w=number of y total. The trick was figuring out how to iron out UV.x=0, basically by adding 1*somevalue to 0.


texts: Is there an FBX file/model viewer for Mac OS X?

texts: Is there a free tool I can use to view and inspect FBX assets? I've got a bunch of FBX files and I'd like to look at the mesh and textures and preview the animations.


texts: How do I prevent repeated interactions between two game objects?

texts:
I am making a game where a player will jump into another object called land and everytime the player lands or collides with it, a score will be given, now my problems is that my method has a loophole since for every collision a score will be given therefore if a player jumps on the same land everytime score would be added up. What are the ways of assigning attributes to the object in order to prevent the loophole from happening? Can ScriptableObject be used to solve this issue?

This is my code for spawning object

foreach (var currobj in currentObject) {
         float objectYpos = -7.14f;
         Vector3 objectPos = currobj.transform.position;
         newObjPos.y = objectYpos;
         newObjPos.x = currobj.transform.position.x;

         objectPos = Vector3.Lerp(objectPos, newObjPos, 6f * Time.deltaTime);
         currobj.transform.position = objectPos;

         if (currobj.transform.position.x < playerLocation.x - objectoffsetX) {
             rmbObjects.Add(currobj);
         }
     }
     foreach (var rmv in rmbObjects) {
         currentObject.Remove(rmv);
         Destroy(rmv);
     }
 }

 private void ObjectSpawn() {
     playerLocation = playerObject.transform.position;
     spawnLocX = Random.Range(playerLocation.x + offsetSpawnX, playerLocation.x + maxdistance);
     GameObject spawned = (GameObject)Instantiate(objectList[indexLevel]);
     spawned.transform.position = new Vector2(spawnLocX, 9); //spawn object in out of view
     currentObject.Add(spawned);
 }

My code for adding score

 private void OnCollisionEnter2D(Collision2D collision)
 {

    if (collision.gameObject.tag == "land" && !onGround)
    {
        scoreManager.AddScore(2);
    }
 }


texts: How do I detect the intersection of a curve with itself?

texts: I'm developing a game in which the player can draw a line. I want to detect if that line intersects with itself. How would I do this?


texts: How to implement curved movement while tracking the appropriate angle?

texts:
I'm currently coding a 2D top-down car game which will be turn-based. And since it's turn-based, the cars won't be controlled directly (i.e. with a simple velocity vector that adjusts its angle when the player wants to turn), but instead it's movement path has to be planned beforehand, and then the car needs to follow the path when the turn ends (think Steambirds).

This question has some interesting information, but its focus is on homing-missile behaviour, which I kinda had figured out, but doesn't really apply to my case, I think, since I need to show a preview of the path when the player is planning his turn, then have the car follow that path. In that same question, there's an excellent answer by Andrew Russel which mentions Equations of Motion and Bézier's Curve. Some of his other suggestions of implementation are specific to XNA though, so they don't help much (I'm using Marmalade SDK).

If I assume Bézier's Curve as the solution of choice, I'm left with one specific problem: I'll have the car's position (the first endpoint) and the target/final position (the last endpoint), but what should I use as the control point (assuming a square/quadratic curve)?

And whether I use Bézier's Curve or another parametric equation, I'd still be left with another issue: the car can't just follow the curve, it must turn (i.e. adjust its angle) accordingly. So how can I figure out which way the car should be pointing to at any given point in the curve?


texts: Calculate random points (pixel) within a circle (image)

texts:
I have an image that contains a circles at a specific location, and of a specific diameter. What I need to do is to be able to calculate random points within the circle, and then manipulate the pixels said points correlate to. I have the following code already:

private Point CalculatePoint()
{
    var angle = _random.NextDouble() * ( Math.PI * 2 );
    var x = _originX + ( _radius * Math.Cos( angle ) );
    var y = _originY + ( _radius * Math.Sin( angle ) );
    return new Point( ( int )x, ( int )y );
}

And that works fine for finding all the points at the circumference of the circle, but I need all points from anywhere in the circle. If this doesn't make sense let me know and I will do my best to clarify.


texts: Menu selection wont stay on selected option

texts:
My Menu has a START and a QUIT option. I'm using a controller's D-PAD for selection. The game begins with START highlighted. When I push the down button on the D-PAD, it highlights the QUIT option. Problem is when I release the down button, it returns to highlighting START.

Is there a way to possibly hold the position so that if I highlight QUIT, it will stay highlighted after releasing the button?

//First starts with START highlighted:

if(menuSelect == 1 && GC.getDPADDir() == 7){ // if QUIT is highlighted, push up
        menuSelect++;
    }
    else if(GC.isButtonPressed(1)){
        // go to game
        sbg.enterState(1);
    }

if(menuSelect == 2 && GC.getDPADDir() == 1){ // if start is highlighted, push down
        menuSelect--;
    }
    else if(GC.isButtonPressed(1)){
        // quit
        System.exit(0);
    }


texts:
Instancing improves performance (significantly) when rendering multiple (hunders? thousands?) copies of the same mesh at once. But how much overhead does it have when rendering exactly one copy with one draw call? Would it be a good or a bad idea to use instancing for all geometry rendered by engine?

Edit:
Let's say we're creating an FPS game. Most of the objects have only one instance: a knife, a gun, a machine gun, a building and a radio tower. But there are also some objects with multiple instances: trees (e.g. 3 kinds of trees with hundreds of instances), grass and so on... What I mean is: instead of rendering the one-instance objects the "traditional" way and trees and grass using instancing, we render all of them using instancing. So our radio tower has only one instance (whose information we store in an instance data buffer) and we render that tower using some kind of DrawInstanced() call with instance count equal 1. Same with all other objects (of course, trees and grass have multiple instances).

So my question is: is it a bad idea to draw a single instance of an object using instancing? Does instancing have too much of an overhead (memory- and performance-wise) or is it in any way undesired for rendering single-instance objects?


texts: How to optimize primitives in SecondLife/Opensim?

texts:
SecondLife/Opensim uses Primitives to construct models. How it works in details is explained here.

Now I have many triangles which link together. Is there any way to make them into one prim, thus reducing the number of prims?


texts:
I am trying to write code with rotates an object.

I implemented it as:

Rotation about X-axis is given by the amount of change in y coordinates of a mouse and
Rotation about Y-axis is given by the amount of change in x coordinates of a mouse.

This method is simple and work fine until on the the axis coincides with Z-axis, in short a gimble lock occurs.

How can I utilize the rotation arount Z-axis to avoid gimbal lock.


texts: How can I set up a 3D camera for a top-down game like Enter the Gungeon?

texts:
DodgeRollGames, the developers of Enter the Gungeon, tweeted that the game was in fact made in 3D

They tried to explain how they set their camera in this reddit post.
Basically what they said was :

so the walls are tilted 45 degrees toward the camera, and the floors are tilted 45 degrees away from the camera, meaning that each should experience sqrt(2) distortion because of the additional length along the z-axis. However, the vertical (y-axis) floor length shouldn't be perceptually changed.
The camera is not tilted at all.
Camera: 0 degree tilt.
Walls: +45 degrees tilt.
Floor: -45 degrees tilt.

My question is : What do they mean by "However, the vertical (y-axis) floor length shouldn't be perceptually changed". If I tilt the walls and floors by 45 degrees and -45 degrees as said, the sqrt(2) distorted walls (the walls have Z depth and are perpendicular to the ground) line up nicely, but the ground gets distorted (obviously). So I distort the ground tiles by sqrt(2) but this essentially stretches the ground by 40% so every vertical movement now has to be increased by 40%.
Can somebody explain what's going on? Any help would be highly appreciated.


texts: cocos2dx- set draw() method interval time

texts: What is the default interval of draw method call in cocos2dx engine? Can we set it manually? I couldn't find much information about it online. After researching a bit I found that update() method interval step could be adjusted by setting setAnimationInterval. Can I set a specific interval for draw method too?


texts:
Collision with an enemy should pause the game for 1.5 seconds.

My failed attempt:

bool tPause;
float timer;

public ovveride Update(GameTime gameTime) {
    if(!tPause) {
        // ...
        if(enemy.rectangle.Intersects(player.rectangle)) {
            timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
            tPause = true;
            if(timer > 1500) {
                tPause=false;
                timer=0;
            }
        }
        // ...
    }
}

What am I missing? How can I do this?


texts: How to pass the correct data into a continuous world

texts:
I'm having a hard time implementing the player moving around my world of 2048x2048 tiles that is generated using a noise function. I'm in it for weeks, and I can not, I mess around with the coordinates, and there's always a bug. I was trying like this:

1 - I paint the map around the player (I'm using a tilemap) I paint a 64x64 area, with the player positioned in the center

2 - create a rectangle and center it in the player, the rectangle has an equivalent size of 32x32, and each frame creates another rectangle that is compared with the old one, so I take the area that has not yet been painted, so I can paint.

The problem is that when I reach the extremes of the map, when x = 0 or x = 2048 for example, I need that "x" equals 2048, and equals 0, respectively, as if the world had "turned" and I'm not sure how to deal with the world's data and the coordinates of the tilemap, because when I start by painting the map around the player, it will be in a position that would be 32.32, and the rectangle 16.16, I can not understand what I have to do it, I mess up everything with the coordinates, in this question, it helped me, I'm using the mod:

Make a 2d top down game with round map

it works, but what I am not able to do is pass the x and y correct, there are always bugs of this type, where I struggle with the numbers, but no use, if I fix the floor to one side the bug appears on the other:

here was to be water, and it has a land line for example.

I'm using Godot 3.

  Up 1:

I'm not sure, but it seems everything is going very well, what I was wrong was forgetting that, for example, a 64x64 array starts from 0 to 63, I was really dumb. The image below shows what it would look like in a 64x64 world:

As I solved it was just doing this "map_size - 1" and decreasing and adding values to the left or right, 0, +31, respectively, since the rectangle starts at position 16, 16.

but when I do this now, there is another problem when this happens:

which occurs because of the "map_size - 1", but without it it is still more messy.

  ** Up 2: **

I was able to fix the up 1 error, I was calling the wrong mod function, without adding the + x and + y, so it arrived at 33 and it is no more than the verification "map_size - 1", now it is working in the horizontal and vertical movements, however I'm still wrong to move diagonally.

or

  Up 3:

I think I got it, the problem if I was not mistaken was in the "stairs", so it works:

# LEFT-UP

# RIGHT-UP

# DOWN-LEFT

# DOWN-RIGHT

But I still have to hit the pieces of map that are behind, but I think it's in the "turn them off" function. I confess that I do not quite understand why this works, I would like to understand.

Note 1: Still the rare cases that the map generates wrong, but actually abusing the keys, quickly clicking for all meaningless directions, such as varying up and down, pressing low, a very strange movement, but the failure happens.


texts:
I'm using LWJGL (opeengl wrapper for Java) and Don't know how to make a renderer class for OpenGL. So In Immediate mode rendering I'd do a method like this to draw quadralaterals.

public static void drawQuad(int x, int y, int width, int height) {
    glBegin(GL_QUADS);
    glVertex2f(x, y);
    glVertex2f(x + width, y);
    glVertex2f(x + width, y + height);
    glVertex2f(x, y + height);
    glEnd();
}

Now that I want to use OpenGL 3+ , how can I organize code like this into a static rendering class I can call methods like Renderer.drawRect(x,y, width, height);? Or if I can make something like a spriteBatch class.


texts:
This is (hopefully) a simple question that should avoid me asking a more complex question. This is in Unity (2D) but hopefully this is a general physics principle I am not getting.

I am applying a torque to a 2D object. The object has a scale of 1, a RigidBody2D with a mass of 1 and no angular drag or undergoing gravity. It is a CircleCollider2D with a radius of 1. There is nothing else attached to the object.

In the following code I apply a torque of Pi for one second. In linear motion (and from my understanding of torque) I would expect the angular velocity, after one second, to be Pi (or 180deg/s). However, running this code and printing out the speed at t=1.0, the speed is 90deg/s.

void FixedUpdate()
{
    if (time < 1.0f)
    {
        rigidbody2D.AddTorque(Mathf.PI);
    }
}

This is consistent, applying a torque of 2Pi gives me a velocity of 1Pi after the time. Where is this factor of 2 coming from?


texts: Flickering or jagged movements when sprites move along a curvilinear path

texts:
I'm making a top-down zoomable 2D game. I can't achieve a perfectly smooth curvilinear movement of the sprites, not even when I have a pixel perfect reproduction. I tried different approaches and I always ended up with either flickering or jagged movements.
I'll use this sprite as an example:

Approach 1
Sprites moving freely in floats. Sampling the texture with a linear filter. MSAA enabled.
When the sprites move at a velocity that's not a multiple of 1 pixel/frame I see them flickering, especially when they have certain pixel patterns (like a thin black outline around).
For example with the above sprite I get the following effect:

That's due to different sampling and approximation of the underlying texture between different frames. For example when a black texel of the sprite lies between two pixels, then the pixel color is the linear interpolation of two near texel and it changes to grey. Then in the next frame the texel again occupies a whole pixel and its color again becomes black.

Moreover when the zoom-out kicks in and the sprite isn't reproduced 1:1 on the screen, the flickering is much worse and other artifacts come out (they are explained here).

The problems are less noticeable at 4K, but a lot more at lower resolutions.
Using a nearest filter to sample the texture makes the movement smoother (but jagged), but it only works when the zoom level is pixel-perfect. Otherwise there are still the problems shown on the gif above.

Approach 2
Rounding the sprite positions to the nearest pixel. Sampling the texture with a linear filter. MSAA enabled.
With this approach I have no flickering, because whatever is the sampling of the texture, then it remains consistent among frames:

How the sprite is sampled:

The upper and right outlines disappears from the screen, but they are absent in any frame, whatever the position. So there's no flickering.
However there is a side-effect. When the sprite moves slowly along a curvilinear path, I see a jagged movement (the gif also has a slower framerate (~30fps), but the movement is somehow jagged also at 60fps):

Moreover if it moves at a velocity that's not a multiple of 1 pixel/frame, the movement is jerky, because in some frames it moves of 3 pixels, in other frames it moves of 2 pixels and so on.
The only situation in which I really see a smooth movement is when the sprite moves vertically, horizontally or diagonally, and its velocity is a multiple of 1 pixel/frame. But when it does a curvilinear movement or also a linear movement on an arbitrary direction (different from the aforementioned ones), then I see some visual imperfections.

None of the above approaches is fully satisfactory. Do I have to live with these problems or is there any other approach I can try to achieve a better smoothness?


texts: What's the best way to make multiple objects of the same thing?

texts:
I am coding in C#.  Due to limitations of the environment I will be working in, I cannot use any framework like the XNA Framework; only what is provided by default on Windows.

I want to create multiple ledges in a platform game.  This is what I currently have in the object class:

class Object
{
    Bitmap _image;
    Usables.Collisions collideType;

    public Object(string image, bool collideX, bool collideY)
    {
        //sets image for picturebox BG
        _image = new Bitmap(Usables.baseDir + image);
        // Collision also set here
    }

    public Bitmap Image
    {
        get { return _image; }
    }
}

and I am assigning it to a pictureBox this way in the form:

public void initGame()
    {
        pb_ledge1.Image = World.Ledge.Image;
    }

And the World class is like this:

class World
{
    static Object Ledge1 = new Object("test.png", true, true);

    static public Object Ledge
    {
        get { return Ledge1; }
    }
}

Obviously in a finished product the World class would not be set like that.  The images for the different ledge types would be set dynamically.

But my main concern is if I had 8 blocks going across the screen, I would have 8 pictureBoxes, and I would assume professional game developers do not manually assign each 8 boxes individually.  Is there a way around this?


texts: Why wouldn't games be published with Map Editors included?

texts:
15 years ago, in 2002, Warcraft 3 was released. Aside from being a great RTS game, it had lived for years past its release mostly due its World Editor - a fully-functional industrial-grade Map Editor that gave players all the tools the devs had during the development process. It has lead to creation of millions of custom maps, cinematics, campaigns, and first MobAs.

Very few companies have released their own Editors with their games since then. Even Blizzard didn't do it again with the new Starcraft release (the version which was eventually released wasn't nearly as powerful as the Warcraft's one). As we see from the history, something as seemingly trivial as this may tremendously prolong the game's lifetime. So why wouldn't developers release World Editors they used alongside with their games?


texts: In a Sonic-esque platformer, how to tell if the chracter is upside-down or not?

texts:
In a Sonic-esque platform game, how do you know if the player's character is currently upside down?
Let's say the character is running to  the left:

At a certain point the character will begin to supposedly run on the ceiling. How do I keep track of this since the chracter is touching both the ceiling and the floor of the tunnel?know

I need some way to know where the character's feet are positioned, keep track of it and allow this to change when the character is moving fast across curved surfaces.


texts:
I'm trying to use a TextureAtlas for all my textures for better performance. Every time my game starts all my tiles are packed into one texture atlas. I have put following code into my DesktopLauncher class that does that:

TexturePacker.Settings settings = new TexturePacker.Settings();
settings.maxWidth = 512;
settings.maxHeight = 512;
settings.filterMin = Texture.TextureFilter.Nearest;
settings.filterMag = Texture.TextureFilter.Nearest;
TexturePacker.process(settings,"blocks","texturePacks","blockPack");
TexturePacker.process(settings,"items","texturePacks","itemPack");

The atlas is loaded with the asset manager and I'm getting the texture region with

atlas.findRegion(..);

It all works, but I have came across an issue. The texture is not filling the whole space anymore. It should fill a 32 by 32 pixel area, but it doesn't. Here is a picture of whats happening:

There are fine blue lines between the tiles and I don't know what I'm doing wrong. My background is blue, if that's helpful information.

I have tried so far:

Loading the texture region from the .png file directly -> no blue lines, so it is an issue with the texture packer
Changing the texture filters, but no one I have tried helped

Thanks in advance for any comments and answers!


texts: Unity: Unable to take screenshots in server build

texts:
I am trying to take snapshots in the server build of my Unity application.
But the output image is all grey. From this post, I read that in headless mode, calling camera.Render() is necessary for rendering. I changed my screenshot logic accordingly.
Here is my script
private IEnumerator TakeSnapshot()
{
    yield return new WaitForEndOfFrame();

    var tempTexture = RenderTexture.GetTemporary(Screen.width, Screen.height);
    camOV.targetTexture = tempTexture;
    camOV.Render();

    var tex = new Texture2D(tempTexture.width, tempTexture.height, TextureFormat.RGB24, false);

    // Read screen contents into the texture
    tex.ReadPixels(new Rect(0, 0, tempTexture.width, tempTexture.height), 0, 0);
    tex.Apply();
    RenderTexture.active = tempTexture;

    // Encode texture into PNG
    var bytes = tex.EncodeToPNG();
    snapshotBase64 = Convert.ToBase64String(bytes);
    // File.WriteAllBytes("/Users/varun/Desktop/" + Time.time + ".png", bytes);
    Destroy(tex);
}

I initalize the camera in the Start() method
    camOV = Camera.main;

This works fine inside the editor but once I create a server build for Mac and try to run it I get this error.
ReadPixels was called to read pixels from system frame buffer, while not inside drawing frame.
 #0 ???
 #1 operator delete[](void*, std::nothrow_t const&)
 #2 operator delete[](void*, std::nothrow_t const&)
 #3 operator delete[](void*, std::nothrow_t const&)
 #4 operator delete[](void*, std::nothrow_t const&)
 #5  (Mono JIT Code) (wrapper managed-to-native) UnityEngine.Texture2D:ReadPixelsImpl_Injected (UnityEngine.Texture2D,UnityEngine.Rect&,int,int,bool)

Can someone give any suggestions? Thanks!


texts: Drawing in a static location when using a camara transform

texts: I'm using a matrix transform to move a 2d camera in Monogame, and I was wondering: How, if I initiated my spritebatch with a matrix transform, can I draw something in a static (non-moving) position? For example, I want to put debugging variables in the corner of the window.


texts: How can I get involved with open source game projects?

texts: I have a limited experience in game development and would like to get involved with open source game project.  Where should I look and how should I begin?


texts: Data flow: Game design balancing data to game

texts:
I'm thinking about how to get the game design balancing data (unit values, quest conditions etc.) to a game. I wonder how you would solve/have solved it?

Conditions:

Java server
Unity mobile client (C# scripting language)
Git based repositories

Requirements:

Client needs balancing data
Server needs balancing data
Data origin must be Excel
Data has be available on mobile without doing an app update

First problem: Transform excel data in something readable and get it to the client/server.

My idea would be to transform the excel data to JSON and commit/push it.

Second problem: How do the client/server get the data?

My idea would be to have a service running which delivers the data via HTTP.

These ideas are quite primitive and that must be a problem many games had so solve. Didn't find any useful though.


texts: Is it possible to achieve the same performance of CUDA on OpenCL?

texts: I am planning on porting some of my CPU code to GPU. I want my code to run on all GPUs, so openCL seems to be the right choice. Will I be able to achieve the same performance as of CUDA in openCL?. What framework would do better if I want to support all GPUs?


texts:
There are a lot of code in open source projects, looking at all of the code is time consuming and can be confusing to a novice like me.  Are there any sections of open-source projects that should be focused on?

What should I focus on when I look at code?

I'm asking this in general because if I ask this specifically, the question will only apply in one or two projects rather than an entire group of projects ranging in different types of games and difficulty.


texts: Is reobfuscating javascript every time the page is loaded a valid option for a multiplayer game?

texts:
I am looking for ways to prevent cheating on a multiplayer browser game. I saw this answer where it was mentioned that obfuscation is not an effective technique.
My plan is not only to obfuscate the code differently every time the page is loaded but periodically change the protocol that the client uses to communicate with the server. This would mean that even if they were able to deobfuscate the client-side code, they would need to update the protocol every time I changed it or they wouldn't be able to communicate with the game servers. I know that this will be difficult to implement, but I believe that I can do it.
Would this work? I know that it's impossible to outright prevent cheating, but I believe that this would make it extremely difficult.


texts: How can I provide access to a Python command-line from in-game?

texts: Is there a way to interact with the command line from in-game? I would like to have the user be able to jump on a console or even just interact with a button and have the game run a Python script in the background, ideally passing the output back to the user in-game.


texts: Unity + Kinect - Current, and active wrapper options?

texts:
What are some current wrapper solutions for using the Kinect with Unity? The initial primesense one seems not to be in active development.

I'm aware of the Zigfu one, however are there any open-source alternatives?


texts:
I am developing a simple 2D game. In game, I've created a prefab for charcaters. and I am changing sprite of prefab runtime. This all execute fine.
Now I want to apply click event on a particular prefab clone and want to increase scale of prefab. I am attaching a c# script what I have did till now.

[System.Serializable]
public class Shopping
{
    public string CharacterName;
    public Sprite CharacterSprite;
}

public GameObject CharacterPrefab;
public Transform CharacterSpacer;

public List<Shopping> ShoppingList;

private CharacterScript NewCharacterScript;

/*********************************************Awake()******************************************/
void Awake()
{
    MakeSingleton ();
}

/******************************Create object of the script**********************************/
void MakeSingleton()
{
    instance = this;
    DontDestroyOnLoad (gameObject);
}

// Use this for initialization
void Start () {
    LoadCharacters ();
}

void LoadCharacters()
{
    foreach (var characters in ShoppingList) {
        GameObject NewCharacter = Instantiate (CharacterPrefab) as GameObject;

        NewCharacterScript = NewCharacter.GetComponent<CharacterScript> ();
        NewCharacterScript.CharacterName = characters.CharacterName;
        NewCharacterScript.Charcater.GetComponent<Image> ().sprite = characters.CharacterSprite;

        NewCharacterScript.GetComponent<Button> ().onClick.AddListener (() => CharacterClicked (NewCharacterScript.CharacterName, NewCharacterScript.Charcater));

        NewCharacter.transform.SetParent (CharacterSpacer, false);
    }
}

void CharacterClicked(string CharacterName, GameObject Char)
{
    StartCoroutine (IncreaseScale (Char));
}

IEnumerator IncreaseScale(GameObject TempCharacter)
{
    int i = 5;
    while (i > 0) {
        yield return new WaitForSeconds (0.1f);

        Vector3 TempVector = TempCharacter.GetComponent<RectTransform> ().localScale;
        TempVector.x = TempVector.x + 0.2f;
        TempVector.y = TempVector.y + 0.2f;
        TempCharacter.GetComponent<RectTransform> ().localScale = TempVector;

        i--;
    }
}

This code triggers click event and also it increases scale but of last clone, not of clicked prefab clone.
What I am missing, I can't understand. What should I correct in this.
and Yeah! I am also attaching code of a script that I've added on prefab.

public class CharacterScript : MonoBehaviour {

public string CharacterName;
public GameObject Charcater;
}


texts: How to handle gun position while running and aiming in an FPS

texts: In an FPS, when a character runs, from the view of another character, the gun moves, and similarly when the character aims down sight.  Are the views from the third person and from the first person actually showing the same gun position?  I feel like it would be tricky to that happen and have it look natural from both perspectives.


texts: how to set multiple materials using array in the submesh of an object

texts:
I'm trying to insert multiple materials into the object's submesh using the array, but I'm not getting

public GameObject[] obj;

//material mat;

public void Color(Material mat) {

    for (int x = 0; x < obj.Count; x++)
        obj[x].GetComponent<MeshRenderer>().sharedMaterials[1] = mat;

    Material[] mats = GetComponent<Renderer>().materials;
    mats[1] = mat;
    GetComponent<Renderer>().materials = mats;

    {
        print("New Material");
    }
}


texts: Should I have one asset manager and unload and load with different gamestates? Or should I have one for each gamestate?

texts:
I am working on a LibGDX game and I would like to find out the best way to manage assets. Should I have one AssetManager that is passed through to my GameState init() method to load from each level, then unload all of those resources in the dispose() method of the gamestate.

Or, should I have a separate AssetManager in each gamestate which is passed to each of the entities and components within the gamestate and clear + dispose the entire AssetManager in the dispose() method of the gamestate.


texts: Dungeon Generation with no corridors and room dependencies

texts:
I'm making a game with a procedurally generated world created at the beginning of the game, consisting of several areas represented by grids (say, 8x8, 9x6, the sizes would ideally be arbitrary). These areas are supposed to be connected to each other through a dependency list.

A connection exists when at least 3 spaces of that grid are exposed between those two areas. In the middle cell of that 3 space connection area is the doorway between areas:

I've been trying to figure out a way to connect them, but it becomes increasingly complex the more areas you need to consider at the same time.

I've tried some paper prototyping and while it's a very simple process when doing it visually, I haven't found out a good set of mathematical expressions that allows me to place rooms with the same efficiency by code.

Here's a "simple" example I'm struggling with right now:

Area 'a' needs to be connected to 'b' and 'c'
Area 'b' needs to be connected to 'a' and 'd'
Area 'c' needs to be connected to 'a' and 'd'
Area 'd' needs to be connected to 'b' and 'c'

Consider, for simplicity, we're placing the rooms by their order of appearance on the list (I've tried others). So I'm approaching this as your standard procedural Dungeon Generation algorithm.

We place 'a' anywhere on the board, since it's the first area. Next, we pick a wall at random and, since nothing is connected to that wall, we can place 'b' there:

Now we need to place 'c', but 'a' is already on the board, and has an occupied wall, so we decide to put it on another wall. But not every placement will do, because 'd' is coming up and it needs to be connected to 'b' and 'c' too:

I tried a possible limitation that 2 rooms that have the same set of dependencies cannot be on opposite walls, but even that doesn't guarantee success:

And in other cases, where the areas have different sizes, being on opposite walls can work:

Also, not considering a used wall is a flawed assumption since it rules out valid solutions:

I've tried looking up research on other Procedural Generation algorithms or similar, such as Optimal Rectangle Packing and Graph Layout algorithms, but usually those algorithms don't take into account every constraint of this problem and are hard to mix together.

I thought about a bunch of approaches, including placing an area and backtrack until a suitable placement is found, but they seem very dependent on trial and error and costly in terms of computation. But, given the extensive research on the last two problems I mentioned, it might be the only/best solution?

I just wanted to see if someone has had similar problems in the past or is willing to help me figure this out and give me a few pointers on where I should start with the algorithm. Or, failing that, I'll have to look into loosening the constraints I've set.


texts: Good practice in implementing multi sprite (as skins) in 2d unity game

texts:
so, I want to make such functionality in my 2d game with unity :

  Multi skin character, with similar control and functionality, and with
  possible different gimmicks (such as crossy road's characters, which
  some modify game environment and / or have unique death animation, yet THEY
  CAN ONLY JUMP AROUND a.k.a only cosmetic).

Here's so far what I did :

  Make each character into separate gameobjects and prefabs, and then if
  I need to find a particular script in current active char, I use
  Gameobject.Find(). The problem is, if I need to apply a script, I need to > manually attach it 1 by 1 to each char gameobjects, which I find will  create problems if the character number grows.

Is that a good practice? Or there's any more good / best practice on this problem?

P.S.

I once read Gameobject.Find() is slow, so if possible, I want to avoid that.
I use bone-based sprite animation, so, I think, changing just the Sprite in SpriteRenderer component won't work.

Thank you.


texts: How can I create Portrait game assets to have same with gap for both iPhone 7 Plus and iPhone X?

texts:
In my Unity game I made changed my Pixel Per Unit value to 243 since the height of a Portrait game for iPhone X is 2436. The game looks great and the asset sizes look just right on the iPhone X simulator. But when I change to iPhone 7 Plus I get considerable space on the sides and it gets worse when I change to the iPad. How can I make my game have the same width gaps for iPhone 7 Plus and iPhone X without making assets look stretched horizontally or vertically?

UPDATE

The images below give an idea of my game on both 1080x1920 (for iPhone 7 Plus) and 1125x2436 (for iPhone X). It's not a match3 game. All the game objects below are static and have colliders. The gaps between are quite significant for other dynamic objects to move between. Reducing the gaps significantly would alter the movement of the dynamic objects and their sizes too, making the ratio in object sizes look wrong. I haven't started worked on scores or menus yet, so I haven't added a UI canvas yet.


texts: How to move sprite as if not rotated when rotated 90 degrees?

texts:
We're making a Tetris like game and need help rotating shapes.

Moving the shape works when there is no rotation.

However, after rotation, snapping the shape to the grid fails because the vector between the shape's current position and destination is affected by the amount of rotation (e.g., rotated 90 degrees).

As a simple example, let's assume a shape consists of one square and currently sits at (8, 0).

If the user rotates the shape 90 degrees (ignore that this functionally does nothing since the shape is only one square) then wants to move the shape to (1,0), what should the vector be? And how do you generalize the vector math?

We're using Swift 3 for an iOS game.

    if isShapePosValid(shape: curShape) {
        let firstTile = curShape.getLowestTile()
        let nearestBoardTile = getNearestBoardTile(shapeTile: firstTile)!
        let newTilePos = firstTile.parent!.convert(nearestBoardTile.position, from: nearestBoardTile.parent!)
        let moveVector = CGVector(point: newTilePos - firstTile.position)
        let move = SKAction.move(by: moveVector, duration: 0.1)
        curShape.run(move) {
            self.printShapeToBoard(shape: curShape)
        }
    }

fileprivate func rotateShape(shape: BoardShapeSprite) {
    let rotate = SKAction.rotate(byAngle: CGFloat(Double.pi/2), duration: 0.1)
    shape.run(rotate)
}

fileprivate func printShapeToBoard(shape: ShapeSprite) {
    let tiles = shape.getTiles().filter{ $0.value != .Empty }

    for t in tiles {
        let boardTile = getNearestBoardTile(shapeTile: t)
        boardTile?.setValue(value: .Taken)
    }
}


texts: A* pathfinding for grid with direction-dependent nodes?

texts:
I'm trying to understand if the A* algorithm is a possible pathfinding solution for my game.

I have a simple grid of nodes that an enemy can move around on, but the nodes represent traversable terrain at different heights in my game world. So although an enemy might be able to "jump down" from Node A to Node B (where Node A is much higher than Node B), it could not do the reverse and "climb up" from Node B to Node A. In other words, whether the A* algorithm can travel from one node to another depends on the direction of travel. It may be possible in one direction but not the other.

Can A* handle a situation like this, or do I need a different pathfinding algorithm?


texts: How to add rotation to two particle collisions?

texts: I'm trying to make a particle system where when particles collide, they merge together, to get the new velocity vector the smaller particle's force is added to the larger one. However, this isn't exactly how I want it to work because when a small particle hits the edge of a large particle it shouldn't simply move in the direction it was hit. It should impart a rotational force, and that should be resisted by inertia. The further away from the center the more it should rotate the particle as opposed to pushing it. What is the physically accurate way to approach this problem?


texts:
In the import settings for my sprite image I can select a dropdown box titled "Sprite Mode" and I can change it from Single to Multiple.

Is there any way to select "Multiple" if I'm creating a Sprite within a C# script with Sprite.Create()?


texts:
In my game, you can spawn a cube by clicking. After 10 seconds I want the cube to disappear. That's what I'm trying to do in my code but it won't work:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class circleThing : MonoBehaviour
{
    public GameObject circle;
    public GameObject block;
    public float time;
    void Start() {
         Vector3 temp = Camera.main.ScreenToWorldPoint(Input.mousePosition);
         temp.z = 5f;
         transform.position = temp;
         if (Input.GetMouseButtonDown(0)) {
             StartCoroutine(timer());
             Instantiate(block, temp, Quaternion.identity);
         }
         if (time >= 10) {
             Destroy(block);
         }
    }
    void Update()
    {

    }
     IEnumerator timer(){

        while (true)
        {
            Debug.Log(time);
            yield return new WaitForSeconds(1);
            time++;
        }
    }
}

What am I doing wrong? I get the error: Destroying assets is not permitted to avoid data loss.


texts:
Does it makes sense to apply perspective projection, in a 2D game? What will be the cost for doing so, and does it overweigh the benefits gained from the 3rd dimension?

Perspective projection has features that could be used in 2D games. Two very beneficial characteristics that come to my mind are:

Using perspective projection as a substitute for parallax scrolling.
Using perspective projection to perform depth order for 2D sprites

On the other hand, perspective projection resizes objects with distance, including 2D sprites. That is why mip mapping has been developed. Mip mapping, however, does not always produce perfect results, as it relies on interpolation between two neighboring mip-mapped frames. This might not be sufficient, for a 2D game, where developers require pixel-based precision and detail.


texts: Understanding how to use Quaternion to rotate object

texts:
I m having hard time to understand Quaternions and to use them in my engine for rotating object.
I m looking for step by step explanation, actually a correction of my view of Quaternions.
Here is how I understand they work.
q = cos(40*) + sin(40)(i+j+k)
->what I understand is that i+j+k represents the axis of rotation. Basically if i = 1 that means we rotate object around X-axis.
Formula q * point * p-1, is what I dont quite understand. Lets for the sake say I understand why forumla goes like this. What I dont seems to get how would I apply this to my engine to rotate object.
What I tried is to create 3dVector with object position, example (0,0,-5). I would use quaternion that would rotate this vector around y axis, so q * ThisVector * q(conjugate),  and then result I would put in translate matrix. But no work.
I cant seem to find a way to implement them. I saw some articles on quaternion to matrices, But what do I  put in that matrix, a result from qThisVectorq(conjugate) or it is just q that is transfromed in matrix?
EDIT
What I want is to rotate object on Y-axis using quaternion. So far,because of lack of my understanding, I m failing to rotate.
I created a class 3dVector ->three dimensional vector, and instantiate a new position (0,0,-5). This position I sent as translate matrix to opengl and multiplied with glPosition.
When I tried to rotate that object using quaternion. I just took that position (0,0,-5) and used it in formula q = q * p * q(conjugate). I manually calculated that but result I get didnt make object rotate on Y-axis around itself.
Now I m not sure, but I think it actually rotated object but not around him self,he was moved to the right, so he was not in the same position anymore
EDIT_2:
I have cube that is on position [0,0,-5] and I want to rotate it around y-axis by some angle.
I tried to write code in python
poinToRotate = Quaternion(w=0,x=0,y=0,z=-5)

angle =45

sinus = math.sin(math.radians(angle));
q=Quaternion(
w=math.cos(math.radians(angle)),
x=sinus*0,
y=sinus*1,
z=sinus*)

newPoint = q.rotate(poinToRotate)

Rotation is somewhere good but it cube does not rotate around it self but around some point.
But when
   p = Quaternion(w=0,x=0,y=0,z=0)

to make it to the center, result is all zeros.


texts: How can I change isReadable of imported DDS images?

texts:
I'm importing DDS textures from editor scripts and I need to access the GetPixels() method from each imported texture to check if the image have transparent pixels.
When importing the images by just creating the file inside the Unity project Assets folder from an editor script, the asset will have its isReadable property set to false which will cause an exception when executing GetPixels() (because isReadble is false).
The isReadble property is readonly from the Texture2D class. I read somewhere that I could use its TextureImporter class to set the property to true and re import the asset through AssetDatabase.ImportAsset(). The problem is that the importer used to import DDS images seems to be an implementation of IHVImageFormatImporter and the isReadable property there is readonly too.
As far as I checked IHVImageFormatImporter can't be converted to TextureImporter. So I left the question: in this case, how can I modify isReadable for imported DDS images?
Or maybe there is another way to be able to read those images from code without throwing an exception?


texts: why doesnt this function work? glsl opengl c++

texts:
Im trying to move a transformation matrix onto the gpu, and I managed to find this code to help me on the way:

vertex.shader:

#version 410 core
layout ( location = 0 ) in vec3 vertex_position ;

mat4 rotationMatrix(vec3 axis, float angle)
{
    axis = normalize(axis);
    float s = sin(angle);
    float c = cos(angle);
    float oc = 1.0 - c;

return mat4(oc * axis.x * axis.x + c,           oc * axis.x * axis.y - axis.z * s,  oc * axis.z * axis.x + axis.y * s,  0.0,
            oc * axis.x * axis.y + axis.z * s,  oc * axis.y * axis.y + c,           oc * axis.y * axis.z - axis.x * s,  0.0,
            oc * axis.z * axis.x - axis.y * s,  oc * axis.y * axis.z + axis.x * s,  oc * axis.z * axis.z + c,           0.0,
            0.0,                                0.0,                                0.0,                                1.0);
}

void main()
{

gl_Position=rotationMatrix(vertex_position,45.0);

}

However, this gives errorc1035: assignment of incompatible types. Shouldnt this work? What am I missing


texts:
I am writing a simple 2D game (for mobile platforms) for the first time. From an abstract point of view, i have the main player controlled by the human, the enemies, elments that will interact with the main player, other living elements that will be controlled by a simple AI (both enemies and non-enemies). The human player will be totally controlled by the player, the other actors will be controlled by AI. So i have a class CActor and a class CActorLogic to start with.

I would define a CActor subclass CHero (the main player controlled with some input device). This class will probably implement some type of listener, in order to capture input events. The other players controlled by the AI will be probably a specific subclass of CActor (a subclass per-type, obviously). This seems to be reasonable. The CActor class should have a reference to a method of CActorLogic, that we will call something like CActorLogic::Advance() or similar.

Actors should have a visual representation. I would introduce a CActorRepresentation class, with a method like Render() that will draw the actor (that is, the right frame of the right animation). Where to change the animation? Well, the actor logic method Advance() should take care of checking collisions and other things.

I would like to discuss the design of a game engine (actors, entities, objects, messages, input handling, visualization of object states (that is, rendering, sound output and so on)) but not from a low level point of view, but from an high level point of view, like i have described above.

My question is: is there any book/on line resource that will help me organize things (using an object oriented approach)?

Thanks


texts: My own coroutines waiting until finished from within a coroutine in C#

texts:
I'm using Unity but creating my own process that has it's own coroutine process. So I can't use StartCoroutine() but I'm interested in how that method works since it's easier to use than me getting the IEnumerator and stepping over it inside my function that's already called as a coroutine.

How can I create some kind of StartCoroutine() type function for users to use instead of having them step over the IEnumerator manually. So for example below I step over the IEnumerator Utilities.Wait() function manually. How could I just call that and have it do that for me and wait the specific amount of time?

public IEnumerator reduceHealth(dynamic args)
    {
        int result = Health - args.reductionValue;
        Debug.Log("Before health: " + Health);
        Debug.Log("Reducing health");

        // reduce health over time
        while (Health > result)
        {
            Health -= 1;
            Debug.Log("Health = " + Health);

            // how can I simplify this for users of this library
            var co = Utilities.Wait(2000);
            while (co.MoveNext())
                yield return null;
        }

        // snap to end result
        Health = result;

        // tell everyone we've been hurt!
        //onHurt.Raise(new { value = health });
    }

public class Utilities
{

    public static IEnumerator Wait(int ms)
    {
        var watch = System.Diagnostics.Stopwatch.StartNew();

        long lastTime = watch.ElapsedMilliseconds;
        while (watch.ElapsedMilliseconds <= lastTime + ms)
        {
            yield return null;
        }

        watch.Stop();
    }
}


texts: Unassigned reference exception when proceeding from scene to scene

texts:
So, I have built a script in unity in c# called parralax. It basically parallaxes two backgrounds and looks like this:-

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

public class Parralax : MonoBehaviour {

    public float startPos;
    public GameObject cam;
    public float parallaxEffect;

    public float length;
    public GameObject player;
    public float playerStartPos;
    public float maxDisplacement;
    void Start () {
        maxDisplacement = 0f;
        playerStartPos = player.transform.position.x;
        startPos = transform.position.x;
        cam = GameObject.Find ("Main Camera");
        length = GetComponent <SpriteRenderer> ().bounds.size.x;
    }

    void Update () {

        float dist = cam.transform.position.x * parallaxEffect;
        transform.position = new Vector2 (startPos + dist, transform.position.y);

    }
}

If I put it in respective background and assign a value to it, it works fine and runs smoothly. But, if I play the game scene-wise i.e. 1st scene to 2nd scene to 3rd scene; it crashes and says:-

Unassigned reference exception:- You need to set variable cam in inspector

Even though, it runs on the same scene, it doesn't run after I play it scene- wise. Please help!


texts: Is it essential that I learn Try/Catch and Finally statements for Game Programming, or is it something I can come back to?

texts: Doesn't seem like something that would be an essential part of GAME Programming.