texts:
I have a 2D game with sprites that come from texture atlases.  I'm trying to resolve the sorting of my sprites for rendering.

I want two sprites to be ordered by their order of insertion, or z-order, when they overlap.  Otherwise I'd want to sort by their texture index to keep sprites from the same texture together.  I use the std::sort function for sorting a vector of queued sprites.

When queueing a sprite I transform its vertices to screen-space vertices on the CPU.  The resulting polygon is used in the overlap test, which is based on this post on Stack Overflow about rectangle intersection:

bool Polygon::overlaps(const Polygon &rhs) const
{
    return overlapCheck(rhs, *this) && overlapCheck(rhs, rhs);
}

bool Polygon::overlapCheck(const Polygon &rhs, const Polygon &current) const
{
    bool result = true;

    for (int i = 0; i < NUM_VERTICES; ++i)
    {
        int i2 = (i + 1) % NUM_VERTICES;
        glm::vec2 p1 = current.positions[i];
        glm::vec2 p2 = current.positions[i2];

        glm::vec2 normal(p2.y - p1.y, p1.x - p2.x);

        float minA, maxA;
        overlapCheckEdges(*this, normal, minA, maxA);

        float minB, maxB;
        overlapCheckEdges(rhs, normal, minB, maxB);

        if ((maxA < minB) || (maxB < minA))
        {
            result = false;
            break;
        }
    }

    return result;
}

void Polygon::overlapCheckEdges(const Polygon &poly, const glm::vec2 &normal, float &min, float &max)
{
    bool haveMin = false;
    bool haveMax = false;

    for (PosIterator it = poly.positions.begin();
      it != poly.positions.end(); ++it)
    {
        float projection = (normal.x * it->x) + (normal.y * it->y);

        if (!haveMin || (projection < min))
        {
            min = projection;
            haveMin = true;
        }
        if (!haveMax || (projection > max))
        {
            max = projection;
            haveMax = true;
        }
    }
}

My sprite comparison method:

bool Polygon::operator < (const Polygon &rhs) const
{
    if (overlaps(rhs))
    {
        return zOrder < rhs.zOrder;
    }
    else
    {
        return textureIndex < rhs.textureIndex;
    }
}

The problem, of course, is that something's wrong with the sorting.  I render my scene like this:

Transform t;
t.position.x = 33.0f;
t.position.y = 33.0f;

// "wall" and "slug" comes from texture atlas #2
// "altar" comes from texture atlas #1

// Queued sprites are translated to polygons based on given matrix
renderer.queueSprite("wall", projection.getMatrix() * t.getMatrix());

t.position.x = 0.0f;
t.position.y = 0.0f;

renderer.queueSprite("slug", projection.getMatrix() * t.getMatrix());

renderer.queueSprite("altar", projection.getMatrix() * t.getMatrix());

renderer.draw(); // Sprites are sorted then drawn

The sprites have sizes of 32x32 units.  This is what I expect to get:

I get this instead:

The pink slug and the white altar are in the wrong order.  Oddly enough, if I put the dark wall at (32, 32) instead of (33, 33) so that it's just touching the slug and altar, I get the right order.

I've also noticed that in the comparison method the altar is only ever compared with the wall.  In a single sort I see this sequence of comparisons:

slug, wall
slug, wall
altar, wall


texts: Use of synthetic vs. natural sounds in modern large games

texts:
Wondering generally how sounds are created for a large game such as Halo or Mario. Obviously 8-bit games probably used synthetic sounds (like regular Mario), and modern games have prerecorded voices in them. But I'm wondering sort of how much natural sounding synthetic sounds are used in a large game. In reading about documentaries and movies, a lot of the time they have microphones and go around in nature (or have a sound studio) and record "natural" sounds. Also, some of the iPhone sounds like the bell and whatnot sound like real sounds, though not sure if they were programmatically generated / synthetic.

More specifically, wondering what an example of a game is that uses synthetic sounds (that sound realistic) extensively. I would like to learn what is possible with synthetic sounds as opposed to natural sounds, to see how realistic they can be. Then from there I might be interested in looking into how those realistic synthetic sounds are made.


texts: How can I calculate the initial velocity of a cue ball after hitting it with a cue stick?

texts:
I'm currently building a billiard game, and I'm faced with the following problem:

A cue ball is hit with a stick at an angle equal to Θ. Given that the stick is hit at the exact center of the ball, and that the force behind the stick is equal to X, how do I calculate the initial velocityX and the velocityY of the cue ball?

I don't have the necessary physics education on this topic, so I'm seeking help from others using online resources like this forum, so I hope you understand my situation.


texts: Why have a publisher on Steam now, when you can self-publish and the Greenlighting process is the same?

texts:
I can't find a definitive answer to whether putting up your game on Steam via a publisher helps somehow, other than bringing some popularity due to publisher's other games/apps. It seems that Greenlight procedure doesn't change or speed up if you have a publisher, or decide to publish yourself (at least according to Steam itself, officially, but who knows what goes on behind the scenes).

The general sentiment on the internet seems to be that you should "cut out the middleman" and save your money that would otherwise go elsewhere, for almost nothing.

People are comparing the Steam publisher to other game, music and video publishers (networks), saying they exist to help distribute your product by making physical copies (optical discs, usb drives, third-party stores), but this doesn't seem to apply to Steam, as there's nothing physical involved.

There's also a matter of advertisement, community management and posting news, updates, etc to create more visibility, which you can also manage on your own, if you wish.

So besides that, are there any important benefits to having a publisher on Steam?


texts:
I'm trying to make the sprite of my button change on click, and i used this script to achieve it:
public Button botonPlayMaster; //i assign the button on the inspector
Image imagenBoton;
public Sprite botonPlay; // same with the sprites, i send them on the inspector
public Sprite botonStop;

    // Start is called before the first frame update
    void Start()
    {
        imagenBoton = botonPlayMaster.GetComponent<Image>(); // i get the component from the button

    }

public void cambiaSprite (){
        if (imagenBoton.sprite == botonPlay) {
            imagenBoton.sprite = botonStop;
        }
        else
            {
                imagenBoton.sprite = botonPlay;
            }
    }

This script is attached to a GameManager GameObject. I assign the sprites and the GameObject Button on the inspector, and then send the GameManager object to the OnClick() function on the button's inspector and select the cambiaSprite() function. But when i click, nothing happens. Any help would be appreciated. Thanks!


texts: Can I use Paragon assets store assets in other Engines besides Unreal?

texts:
Epic Games recently released a lot of assets from their game Paragon for free. I like some of them but am not particularly fond of the Unreal Engine.
Can I use those assets in another engine like Unity or something custom?


texts: I tried to create Spawner using GameObject / Prefab, and it was cloned, but can not show on the game screen?

texts:
Unity Game
I tried to create Spawner using GameObject, and it was cloned, but can not show those clone on the game screen?

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

public class GameObjectSpawner : MonoBehaviour
{
    public GameObject coin;
    float randX;
    Vector2 whereToSpawn;
    public float spawnRate = 2f;
    float nextSpawn = 0.0f;

    void Start()
    {

    }

    void Update()
    {
        if(Time.time > nextSpawn)
        {
            nextSpawn = Time.time + spawnRate;
            randX = Random.Range (-8.4f, 8.4f);
            whereToSpawn = new Vector2(randX, transform.position.y);
            Instantiate(coin, whereToSpawn, Quaternion.identity);
        }
    }
}

Please help me!
Any help would be the extreme appreciation!


texts: Arrival Steering Behavior stop before reaching evader

texts:
Im doing steering behaviors and trying to stop before reaching the evader. Instead of reaching the evader at its center, I need it to stop before. I cant seem to figure this out though. My code is below from Programming Game AI by Example by Buckland.

Vector3 Arrive(Vector3 target, deceleration decel)
{

    Vector3 totarget = evader->target - vehicle->cp;

     //calcualte the distance to the target position
    float dist = totarget.Length();

if(dist > 0.0f)
{
    //because deceleration is enumerated as an int, this value is require to provide fine tweaking of the deceleration
const float decelerationtweaker = 0.3f;

//calculate the speed require to reach the target given the desired deceleration
float speed = dist / ((float)decel * decelerationtweaker);

//make sure the velcoity does not excceed the max
speed = min(speed, 5); //maxspeed

//frome here proceed just liek seek except we dont need to nomalize the totarget vector because we have already gone to the trouble of calculating its lenght: dist
 Vector3 vecDesired = totarget * speed / dist;

 return (DesiredVelocity - vehicle->Velocity);
}

    return Vector3(0,0,0);

}


texts: As far as I know there are only 3 base graphics libraries on Windows, the GDI, OpenGL and DirectX, is that correct, so that means that Java, Actionscript and all language use one of these 3 libraries if they are to display graphics, or maybe Java has it's own graphics library/API?


texts: How do I stop "StartServer listen failed" when I start a new server after a previous server has been destroyed?

texts:
I am trying to allow my users to be able to host servers for my game. Hosting works great, until a user decides to stop their server, and then start a new one. The game does not allow this to happen, and calls a network error:

  StartServer listen failed.

How do I get around this error?

Here is my current code for disabling the current server and starting a new one:

//disconnect client/server
NetworkManager.networkManager.Disconnect ();

//set the port
NetworkManager.networkManager.networkPort = port;
//start the server
NetworkManager.networkManager.StartServer ();
//set the map
ServerInfoManager.serverInfoManager.ChangeMap (map);

Here is NetworkManager.Disconnect():

public void Disconnect () {
    if (isServer == true) {
        StopServer ();
    }

    if (isClient == true) {
        StopClient ();
    }
}

The isServer, isClient, args[], and port variables have been set before these code sections.


texts: Separating logic and data in browser game

texts:
I've been thinking this over for days and I'm still not sure what to do. I'm trying to refactor a combat system in PHP (...sorry.) Here's what exists so far:

There are two (so far) types of entities that can participate in combat. Let's just call them players and NPCs. Their data is already written pretty well.
When involved in combat, these entities are wrapped with another object in the DB called a Combatant, which gives them information about the particular fight. They can be involved in multiple combats at once.
I'm trying to write the logic engine for combat by having combatants injected into it.
I want to be able to mock everything for testing.

In order to separate logic and data, I want to have two interfaces / base classes, one being ICombatantData and the other ICombatantLogic. The two implementers of data will be one for the real objects stored in the database, and the other for my mock objects.

I'm now running into uncertainties with designing the logic side of things. I can have one implementer for each of players and NPCs, but then I have an issue. A combatant needs to be able to return the entity that it wraps. Should this getter method be part of logic or data? I feel strongly that it should be in data, because the logic part is used for executing combat, and won't be available if someone is just looking up information about an upcoming fight. But the data classes only separate mock from DB, not player from NPC. If I try having two child classes of the DB data implementer, one for each entity type, then how do I architect that while keeping my mocks in the loop? Do I need some third interface like IEntityProvider that I inject into the data classes?

Also with some of the ideas I've been considering, I feel like I'll have to put checks in place to make sure you don't mismatch things, like making the logic for an NPC accidentally wrap the data for a player. Does that make any sense? Is that a situation that would even be possible if the architecture is correct, or would the right design prohibit that completely so I don't need to check for it?

If someone could help me just layout a class diagram or something for this it would help me a lot. Thanks.

edit

Also useful to note, the mock data class doesn't really need the Entity, since I'll just be specifying all the parameters like combat stats directly instead. So maybe that will affect the correct design.


texts:
I'm trying to achieve something like netent's roulette (which is a great product in my opinion). It's going to be implemented in html5.

I wonder which path should I take to have such a great animation for spinning ball.
My problem is that the random number is generated on the server, thus using any of currently available physics engines means loose control of the ball, I mean that it will be hard to apply forces in such a manner that ball hits the right slot.
Another option is to make my own a pseudo physics. "Pseudo" because it should always keep track of destination point. It is pretty much like playing animation generated backwards.


texts: How to edit the alpha channel of an existing specular map?

texts:
I am working with a third party model and need to change the specular map. The model material is using the spec map's alpha channel information. I have opened the spec map in Photoshop and if I go to the Channels tab I can see the Alpha 1 channel with the alpha information that I need to change.

What I would like to do is make a copy of this original and drag it into the Layers tab, so that I can revert back to this if need be. I can then duplicate this again and paint over it to create the new alpha map. Once done I can then copy and paste it as the new alpha channel, keeping the original preserved in the Layers tab.

The problem is how do I get the Alpha 1 channel into the Layers tab to make the edits? I cannot click and drag it there; and if I do Select All, Copy and Paste into a new layer nothing is pasted. How can this be done?

If I'm not using the best workflow for editing an existing specular map please suggest an alternative way. I basically just want to edit the alpha channel but keep the original as well.


texts: Preventing Unity from writing to the registry?

texts:
I see that Unity automatically writes some info to registry when it launches the game. Several people have this problem too:

Preventing Unity from writing to the registry.

How to disable writing to Windows registry?

It seems several years have passed but I still can't find how to prevent Unity from writing to registry. I just want to make Unity save & load settings from file in document folder.


texts: Why are my exported illustrator graphics blurry and messy in-game when scaling?

texts:
Non-scaled image:

And this is 2x-scaled:

I use 300dpi and did tick anti-aliasing settings for export png-24 image for my game in illustrator. But it look still bizzard when scaling. Could you please tell me what's wrong here??

What is the best way to get better art in my case?

Thank you in advance!


texts:
I have a bunch of voxels, lets just say 64x64x64, that I use to create a sphere/planet. This works very well, but once I try to apply noise to create a more interesting terrain things go wrong.

3D noise works fine, but I don't always want to create terrain with caves, overhangs etc, so I figured in those cases 2D noise would be a good solution, but I can't figure out how to use it correctly.

I tried this, where pos (world position) is a float3 and x and y are the input values for the noise function:

float x = math.acos(pos.z / math.length(pos));
float y = math.atan(pos.y / pos.x);

That results in a very noticeable seam along one axis and pinching at the poles though.

Is there any way I can convert my 3D world position into 2D coordinates, so that the noise function (Perlin or Simplex) will produce a seamless result without pinching?
I don't mind in the least if this causes symmetry or repeating features.


texts: Solution for lightweight LAN peer discovering?

texts:
I built a library for purely cross-platform programming. My games made with it run fine in Android , Pc, Linux, Mac etc.

The networking capabilities are provided by ENET library, therefore all communication between my apps is not TCP or UDP compatible, but only in the custom protocol, even tough its based on the UDP ultimately.

I don't think its possible to do what i want with ENET, thats why I ask here for help!

Lets say I have the same game running in my Android phone, my laptop and my pc. They are all in the same wifi network, and therefore in a LAN, whether its Wifi hotspot(?) or the household router.

I need each of those 3 peers to discover the other two in the network. This is meant only to find the IP of alive apps in the LAN network, to be able to host multiplayer games between them.

I can only think of one effective way to do this, UDP broadcast, wait responses, but if that is the solution, i need something small, since its the only purpose of the implementation.

Other way could be to try to connect to all IPs in the LAN address subrange, but I don't think the OS would be with me on this one :p


texts: How can I represent collision for an object needing more than PolygonShape's maximum of 8 vertices?

texts:
This is a part of map (it is a cave) of my LibGDX game (using Box2D):

I would implement a PolygonShape as the black part of the map to prevent the whatever moves (for example a ball) inside the cave from leaving it.

This is an example of my PolygonShape like I would draw it (with 100 vertices):

The problem is that Box2D doesn't allow me create it with not more than 8 vertices...

How can I fix this thing?

Sorry, my English isn't very good. :)


texts: How to create a 2D overlay over a 3D game? (LWJGL/OpenGL)

texts:
GameDev!

I would like to create a 2D overlay over a 3D world, using LWJGL (Java version of OpenGL), to show information to the player, for example, a chat box, health bar, selected cannonball type, etc.

Currently the code I have is this (Taken from several sources on the internet):

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glEnable(GL_BLEND);
        GL11.glMatrixMode(GL11.GL_PROJECTION);
        GL11.glLoadIdentity();
        glOrtho(0.0f, Display.getWidth(), Display.getHeight(), 0.0f, 0.0f, 1.0f);
        GL11.glMatrixMode(GL11.GL_MODELVIEW);
        GL11.glLoadIdentity();
        glDisable(GL_DEPTH_TEST);
        glDisable(GL_CULL_FACE);
        glDisable(GL_TEXTURE_2D);
        glDisable(GL_LIGHTING);
        glDisable(GL_DEPTH_TEST);
        glDisable(GL_CULL_FACE);
        glDisable(GL_BLEND);
        glDisable(GL_TEXTURE_2D);
        glDisable(GL_LIGHTING);
            glBegin(GL_QUADS);
            glColor3f(1, 1, 1);
            glVertex2f(0, 0);
            glVertex2f(1, 1);
            glVertex2f(1, 0);
            glVertex2f(0, 1);
            glEnd();
        GL11.glMatrixMode(GL11.GL_MODELVIEW);
        GL11.glLoadIdentity();
            glPopMatrix();
        glEnable(GL_DEPTH_TEST);
        glEnable(GL_CULL_FACE);
        glEnable(GL_BLEND);
        glEnable(GL_TEXTURE_2D);
        glEnable(GL_LIGHTING);
             glEnable(GL_DEPTH_TEST);
                glEnable(GL_CULL_FACE);
                glEnable(GL_TEXTURE_2D);
                glEnable(GL_LIGHTING);
             glDisable(GL_BLEND);
                GL11.glMatrixMode(GL11.GL_PROJECTION);
                GL11.glLoadIdentity(); // Reset The Projection Matrix
                GLU.gluPerspective(45.0f, ((float) Display.getWidth() / (float) Display.getHeight()), 0.1f, 5000.0f); // Calculate The Aspect Ratio Of The Window

                GL11.glMatrixMode(GL11.GL_MODELVIEW);
                glLoadIdentity();

However this does not show a 2D scene at all!

I would appreciate it if anybody could help me.

Thanks!


texts: Unity higher Z position tiles rendered underneath

texts:
When placing tiles in an isometric tile-map in Unity, I try to place blocks on top using the "Z Position Value" However it looks like higher Z position values get rendered underneath.

In this picture, the green cubes have a z position of 0 whereas the yellow cubes have a z position of 1. I want the yellow cubes to render on top, but they are underneath. I'm using an Isometric Z as Y tile-map and have the Transparency Sort Axis set to (x=0,y=1,z=-0.26).


texts:
I am trying to use a shader to get an effect like this. Notice how

every cube has exactly the same lightning as every other no matter where it is on the screen
if you look closely the lightning is making the front face's top parts darker, and the front face's lower  parts lighter (about 20% difference at most)
also more importantly the edges of the cubes are smoothed ( filleted )  and foggy looking

I am drawing my cubes like this with the default lightning.

        cubeEffect.EnableDefaultLighting();
        for (int i = 0; i < 10; i++)
        {
            for (int j = 0; j < 25; j++)
            {
                // apply the effect and render the cube
                foreach (EffectPass pass in cubeEffect.CurrentTechnique.Passes)
                {
                    cubeEffect.World = Matrix.CreateTranslation(-15.6f + i * 3.05f, 15.5f - j * 1.168f, 0.0f);
                    pass.Apply();
                    //draw
                    RenderToDevice(GraphicsDevice);
                }
            }
        }

This is how my cubes looks like with the default lightning... i am trying to achieve an effect like the first image. I have no experience with lightning effects and how to do something like this so, i'd appreciate any help on how to get started.

I used this http://blogs.msdn.com/b/dawate/archive/2011/01/20/constructing-drawing-and-texturing-a-cube-with-vertices-in-xna-on-windows-phone-7.aspx tutorial's help to draw this


texts: Howdo I create differently sized texture atlases for different screen sizes?

texts:
I am beginning game development and using texture atlases.
I've created textures based on the resolution 1920x1080, so I created a 1024x1024 size Texture Atlas for storing multiple graphics.

If the game is played on a 800x480 size device, the atlas will be very big to load in memory. An atlas of 512x512 would be enough and on devices with 480x320 resolution the game might not even work due to the different texture size.

How can I resize the atlas to save memory? Can I use different texture atlases for different screen sizes?

I just want to know how other game devs do it?


texts:
I want to render a tile-based map and I am not sure which class structure to use to keep logic and rendering separeted.

My class structure so far on the logic side: One abstract parent class Tile with an attribute int tileType and one class extending Tile for every kind of tile. Every of the extending class defines the value, for example in the class Tree extends Tile I have tileType = 2 and in the class Wall extends Tile I have tileType = 3.

When I render a map, I go through the array of tiles and do something like this:

switch (tileType) {
...
case 2: texture = treeTexture; break;
case 3: texture = wallTexture; break;
...
}
draw(texture, x, y);

I wonder if the class structure makes sense and if this is a good solution to render tiles? Or what other solutions are there to render tiled maps while keeping logic and rendering separated?


texts: Detecting Light Intensity Around Characters

texts:
Later Edit

Since there seemed to be a bit of confusion: I am asking this for purely didactic reasons, I'm not searching for the most efficient solution. Reformulated question: I'm working under Unity, and I'd like to know if it would be possible to somehow query the material + shader of each GameObject that has a Mesh Renderer attached to itself, in order to find out how much light has fallen on the 3D model. I'm not very experienced in computer graphics, so this may seem like a stupid question. I'm thinking of something along the line of pixel by pixel comparison of a texture's brightness at any given point in time.


texts: Monogame - SpriteBatch.DrawString() won't work

texts:
Here is my Game1.Draw() method (Constants.HeroLayerDepth is equal to 1):

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.AntiqueWhite);

        //  gameEngine.DrawEverything(spriteBatch, camera);
        spriteBatch.Begin();

        spriteBatch.DrawString(defaultFont, "Test Field", new Vector2(0, 0),
            Color.Black, 0, new Vector2(0, 0), 0f, SpriteEffects.None, Constants.HeroLayerDepth);

        spriteBatch.End();

        base.Draw(gameTime);
    }

Although I am calling DrawString(), I only see this after running the code:

How can I fix this?


texts:
I am new at Android game development. I have done some apps before, but none of them are games :)

So, I wanted to do a frame-by-frame animation of PNGs. I tried with AnimationDrawable, but OutOfMemory error comes quickly (I have a lot of PNGs). So I came upon SurfaceView. But I am stuck, because I really don't find any useful tutoirals/examples.

What is the best way to make an animation like this?

Here there already is a great answer to almost the same question, but all the links there don't work anymore.

I would really like to here suggestions how to make an animation frame-by-frame with PNGs in Android and if you have any tutorials or examples, I will be really happy :)

EDIT

I thought wrong about sprites, I think... Sorry, but I am a noob at game developing :) I have 60 PNG pictures (40kb, 427*420px each - on disk) which I would like to put in a animation. Is this even possible to do it with frame by frame animation?

The most similar and famous game that is close to mine is Talking Tom (but I don't know if they have frame-by-frame or any other method for animation).


texts:
Is glDrawArraysInstanced in OpenGL parallel when drawing those instances?

I cannot figure out by referring to its reference and numerous online tutorials.

[Update] To be more clear, I mean, for example, we have 100 instances.
Are the drawing of those 100 instances parallel?
For example, we have the 100 commands "glDrawArrays(mode, first, count);"?
Is execution of those 100 commands sequential or parallel?

I think it should be sequential. GPU begins to draw the second instance, only AFTER the first instance drawing finished.

Or glDrawArraysInstanced just save the time for "giving your GPU the commands"?

[Update 2] The reason I wanted to know the answer, is that:
If it is sequential, personally I think drawing thousands of tree leaves in this way is time consuming. I may draw them in one shader program with some algorithm tweak.


texts: Multiplayer XNA without a LIVE account? (PC)

texts:
I decided it was time to stick in a bit of multiplayer into my game, but came across my first hurdle when i quickly downloaded an example from the XNA website.

It prompted me with a login to live. However i really DO NOT want my game to use live accounts.

This is PC btw.

Basically i wanted to know, is it possible to have multiplayer with XNA without logging in through a live account?

Also, is it better to stick with the built in XNA networking, or use a totally different library such as lidgren?


texts: I'm a software engineer and I'm hoping to move my career towards game development. I'm reading a book right now on 2D using C++/DirectX. When I get into 3D I know I want to do it correctly. For example, I know nothing about 3d space. So if I learn only an API I might know it but I don't know if I can develop an interractive mini 3d world with it. I wouldn't call myself successful just having a rotating crate with the latest shaders etc. My math skills are up to trig/linear algebra and still in college. I know more math is to come. Should I be reading on 3D theory books before picking up on OpenGL/Direct3D, or any other suggestions? I just know an API isn't going to teach 3D game development and don't want to be lost afterward. I'm very book-oriented so that's fine if there's suggestions there too. Thoughts are welcome. Thanks!


texts: Assertion Failed: TextureRHI - Texture Casting Errors (UE4)

texts:
I am taking a pointer to a UTexture2D asset "MyTexture2D", and casting it to an array of FColor using the following:
FTexture2DResource* Resource = (FTexture2DResource*)MyTexture2D->Resource;
uint32 Stride = 0;
void* MipData = RHILockTexture2D(Resource->GetTexture2DRHI(), 0, RLM_ReadOnly, Stride, false);
const FColor* FormatedImageData = static_cast<const FColor*>(MipData);

While this runs fine in the editor, and compiles successfully into a build (Windows10), I get the following error on running the .exe:
"Assertion Failed: TextureRHI"
Which corresponds to the line :
check(TextureRHI);
in the function FD3D12DynamicRHI::LockTexture2D_RenderThread
From what I can tell, I need to do some or part of this function on the rendering thread using ENQUEUE_RENDER_COMMAND but I don't know what such a call would look like as I've struggled to find any kind of documentation on the API.
If anyone could suggest the proper syntax for the required render call, I'd be extremely grateful.
Many thanks.


texts: How should I arrange storage for components referenced in a quad tree?

texts:
I like the Unity's entity-component-system approach, I'm working on something similar. However I'm not sure where and how I should store the components.

An easy answer would be: "store the components in the corresponding system" - this is logical (who else is interested in the component if not the handler system?), and cache-friendly (continuous memory, so iterating through the collection would/could cause less cache miss).

However there are two major problems with this approach. Actually it's only one which generates the other. The generated problem is the simpler, I start with that:

A Behaviour (aka. custom user script) component can be added to the GameObject (aka. entity). The Behaviour must be able to get other components which are added to this object (similar to Unity's MonoBehaviour). However the object is not storing any component directly, so we have to query the component from the corresponding system. In a simple world, this query can be done only once after the required component is created, because its address won't change until its actually removed. This way, the Behaviour component can query other components in its constructor/init function and everyone is happy. But what if the other component's address can change? Actually this is the root cause of this problem and it's generated by the next one:

Storing components in an array can be a good thing because it's memory(bus) friendly. However it's not ideal in some cases, eg. when I have a spatial partitioner tree (QuadTree right now). I have two choices:

1)

I can keep the "global" continuous array representation and store pointers only in the QuadTree. However, this way when I query the components which belongs to a QuadTree node and iterate on the result, cache misses are introduced (jumping back and forth in the memory).

// pseudo-code

// "global" storage
pool<RigidBody> rigidBodies;
pool<Mesh> meshes;
// etc.

QuadTreeNode
{
    // only pointers to the "global" array elements
    vector<RigidBody*> rigidBodies;
    vector<Mesh*> meshes;
}

2)

I can use node-based component array which means the iteration is more cache-friendly. But when the component has to be moved to a different QuadTree node, it must be removed from the current node and must be copied to the new one. This means the component's memory address is changed which also generates my first problem (cannot query only once, because the address can change).

// pseudo-code

// not-partitioned components
pool<Behavior>

QuadTreeNode
{
    // these are not pointers, but the actual data
    pool<RigidBody> rigidBodies;
    pool<Mesh> meshes;
}

I probably pick the 1st solution, because the cache-miss is probably less noticable than the constant remove-copy and query operations (at least for "moving" components).

However, I'm interested in any better representation/storage of the components which is both cache-friendly and operation-friendly.


texts: Moving a character based on a list of Vector 3's

texts:
I have a client server scenario. On the server there is an AI character who chooses a random point on the map and pathfinds to it, when at that point it chooses a new point and pathfinds again etc. The path to each point is an array which I send to the client, then a character on the client goes to each point in the array, making it look as though it is in sync with the server's AI character. (I realise with Unet all I really need is a network identity script and  network transform component but this is a means to an end using this method).

So when the server creates the array and sends its own AI character off on the path, this array is sent to the client, the client then puts it into a List. Then using this List the Clients character moves to each node smoothly looking just like the server. My problem is that sometimes it moves and others it sticks and I get an error

  "ArgumentOutOfRangeException: Argument is out of range. Parameter name: index"

My code is as follows:

Script that sends path and receives:

public class AccessingTargetPos : NetworkBehaviour {
public List<Vector3> receivedArrays = new List<Vector3>();

[ClientRpc]
void RpcPosFromServerToGoTo(Vector3 [] path)
{
    UnityEngine.Debug.Log ("Going to ... " + path);
    receivedArrays.AddRange (path);
}

public void PrintPath(Vector3 [] path)
{
    if (isServer)
    {
        UnityEngine.Debug.Log("Send Array ...");
        RpcPosFromServerToGoTo (path);
        UnityEngine.Debug.Log("Sent!!");

    }
}

}

And my code that moves the client character based on the List:

public class ClientAiMoveToPosArray : MonoBehaviour {

AccessingTargetPos accessingTargetPos;
public float speed = 1;
public Vector3 endPoint;
int index = 0;
// Use this for initialization
void Start ()
{
    accessingTargetPos = GameObject.Find ("A*").GetComponent<AccessingTargetPos> ();
}
// Update is called once per frame
void Update ()
{
    transform.position = Vector3.MoveTowards (transform.position, accessingTargetPos.receivedArrays [index], speed * Time.deltaTime);

    if(transform.position == accessingTargetPos.receivedArrays [index])
        {
            index++;
        }
}
}

I don't understand why I am getting this error and why at times my clients character sticks. I assume I am going wrong somewhere in my ClientAiMoveToPosArray script. Am I wrong in there somewhere?

UPDATE

The error occurs for 3 reasons:

At the beginning when the client has no point to move to i.e. I start the server then the array is generated, however the client hasn't connected yet. If the client connects when the AI is moving along a path it has to wait until a new path is generated before moving.
If the AI character on the server gets stuck in an unwalkable area.
If the client is moving exactly like the server AI character. The error is appears here because when the array is generated it has to be sent over to the client, resulting in a slight delay.


texts: Is there a need to set the parameters again when updating a texture?

texts:
Suppose that I'm developing the class COpenGLControl here in code guru to use it for showing a 2D texture in an MFC CPictureControl. and after applying some filters on the image, I will update the texture to show the filtered image on the picture control.

I have set a rule for the clients of my class as follows:

Call function setImageWidthHeightType just first time of calling OnTimer and after setting pImage
pImage is the rastetr data that will be provided by another classes that have been developed using OpenCV and GDAL libraries
for the next calls of OnTimer and when updating pImage there's no need to call this function. If you do so, your client code slows down because the function InitializeTextureObject() is called in the setImageWidthHeightType function
For second and more calls of OnTimer you should call updataTextureObject() function after setting pImage. In the first call of OnTimer and before calling setImageWidthHeightType, the function updataTextureObject() should not be called and if so, the program will encounter an unhandled exception because there you still don't have any texture object to be updated.

any way I have used the following codes for the functions that are mentioned above:

OpenGLControl.h
allocate texture name which will be an unsigned integer

GLuint texture;

OpenGLControl.cpp
Generate just one texture and bind it to the target:

void COpenGLControl::InitializeTextureObject()
{
    wglMakeCurrent(hdc, hrc);
    glEnable(target);
    glGenTextures(1,&texture);
    glBindTexture(target,texture);
    glTexParameteri(target,GL_TEXTURE_WRAP_S,GL_REPEAT);
    glTexParameteri(target,GL_TEXTURE_WRAP_T,GL_REPEAT);
    glTexParameteri(target,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
    glTexParameteri(target,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
    glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_REPLACE);
    glPixelStorei(GL_UNPACK_ALIGNMENT,1);
    glTexImage2D(target,level,internalformat,ImageWidth,ImageHeight,border,format,type,&pImage[0]);
    wglMakeCurrent(NULL, NULL);
}

the question that roses up is that
Is there a need to set the parameters again when updating texture because of using wglMakeCurrent(NULL,NULL) at the end of the function above?
In other words should I write the function updataTextureObject() as this:

void COpenGLControl::updataTextureObject()
{
    wglMakeCurrent(hdc, hrc);
    glEnable(target);
    glBindTexture(target,texture);
    glTexParameteri(target,GL_TEXTURE_WRAP_S,GL_REPEAT);
    glTexParameteri(target,GL_TEXTURE_WRAP_T,GL_REPEAT);
    glTexParameteri(target,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
    glTexParameteri(target,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
    glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_REPLACE);
    glPixelStorei(GL_UNPACK_ALIGNMENT,1);
  glTexSubImage2D(target,level,xOffset,yOffset,ImageWidth,ImageHeight,format,type,&pImage[0]);
    wglMakeCurrent(NULL, NULL);
}

Or just as this:

void COpenGLControl::updataTextureObject()
{
    wglMakeCurrent(hdc, hrc);
    glTexSubImage2D(target,level,xOffset,yOffset,ImageWidth,ImageHeight,format,type,&pImage[0]);
    wglMakeCurrent(NULL, NULL);
}

What way is the correct one?


texts: What am I missing for this flycam to work correctly?

texts:
Through reverse engineering, I've found an instruction to inject on which allows me to obtain the XYZ coordinates of the camera, as well as pitch and yaw. Thus, I have the following:

  camX (Plane) -- Value is a float ranging from negative to positive
  camY (Plane) -- Value is a float ranging from negative to positive
  camZ (Up/Down) -- Value is a float ranging from negative to positive
  camH (Horizontal/Yaw) -- Value is a float in degrees from +180 to -180
  camV (Vertical/Pitch) -- Value is a float in degrees clamped to +89 to -89

I've written a script in Lua which allows me to bind directions (forward, backward, left, right, up, and down) to keys (W, A, S, D, Q, and E); however, those simply add/subtract to/from XYZ values along with a speed modifier, meaning if I'm facing forward and moving forward, everything is fine. Turning 180 degress with the mouse, though, effectively means back is forward, left is right, etc.

What I'm looking to achieve is having those directional keys apply to wherever I'm aiming the mouse pointer. So, forward is always where I'm facing, etc.

I've been piecing together the necessity of sin/cos for calculations related to this; however, I'm apparently in over my head with understanding everything I'm reading/watching. I've found a number of calculations for this based on degrees, radians, converting degrees to radians, etc., but I'm just completely lost as nothing I've tried has panned out (even though I think I understand what I'm reading).

I've ascertained that, where applicable, respective games have sin/cos values stored somewhere in memory which I could use in lieu of calculating those values myself, but I'm honestly not sure what those values look like to seek out in the first place...or exactly what I need to do to make the calculations myself. They're probably staring me right in the face in nearby memory or on the stack as I trace through code, but I simply don't know.

Are there multiple ways to calculate the appropriate angles via sin/cos? Can I use some combination of the 5 values I listed above, along with a speed modifier and Lua's math.* methods (math.rad, math.sin, math.cos), to get this flycam to work properly?

Thank you for any guidance you can provide!


texts: Can a sprite be rendered with thickness in Unreal Engine?

texts:
Is there a convenient way to have a 2D pixel art image with clip transparency (not partial transparency) rendered with thickness in Unreal Engine? Paper2D does exactly what I want, except it's a flat plane.

I'm able to achieve the effect by making an SVG outline and using Blender to make a model and map UVs, then import that into Unreal, but it seems like a lot of steps for a somewhat simple model. I am new to both of these tools and models in general, so I may be missing something obvious.


texts: How to properly give Image source for multiple sources?

texts:
I'm writing a script to change the image on the button based on previous selection.
Another script is giving the CurrentAvatar variable once previous button is pressed.

My problem is i can't seem to load an image for the button using:

AvatarSprite = Resources.Load<Sprite>("Assets/Images/FireMonsters/Lamor_Icon");

Could someone please enlighten me on the proper code?

All from assets, or is it even possible?

Also looking to have multiple options in if statements, don't know a better method.

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

public class SelectedAvatar : MonoBehaviour {

    Button CurrentHeroSprite;
    static Sprite AvatarSprite;
    public static string CurrentAvatar;

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

    // Update is called once per frame
    void Update () {
        if (CurrentAvatar == "Lamor") {
            AvatarSprite = Resources.Load<Sprite>("Assets/Images/FireMonsters/Lamor_Icon");
            CurrentHeroSprite.image.sprite = AvatarSprite;
            Debug.Log ("loaded sprite for Lamor");
        }
        //if etc etc etc
    }
}


texts:
For some reason, my slider and audio resets back to 0 when I stop and play the game after I changed the value. Here is the code, I can't spot anything wrong with it:

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

public class MainAudio : MonoBehaviour {

public Slider slider;

void Awake()
{
    PlayerPrefs.Save ();
    GetComponent<AudioSource> ().volume = PlayerPrefs.GetFloat ("CurVol");
    if (slider)
    slider.value = GetComponent<AudioSource> ().volume;
}
public void VolumeControl(float volumeControl)
{
    GetComponent<AudioSource> ().volume = volumeControl;
    PlayerPrefs.SetFloat ("CurVol", GetComponent<AudioSource> ().volume);
    PlayerPrefs.Save ();
}
}


texts: It is feasible to complete decouple a graphics engine from game logic?

texts:
Is it possible, or even feasible, to have graphics engine completely decoupled from game logic?

Why I ask is because I want to start working on a game (I'm a complete beginner in game development, but I have 8+ years of programming under my belt), but there are more than a couple graphics engines out there to pick from. Also I do not anticipate my development speed will be very fast, so I would like to be able to swap out an old graphics engine for a new one if the old one becomes too out of date.

I want to work with OpenGL for possible cross platform compatibility, so that should at least reduce issues that may arise from supporting multiple graphics APIs.


texts: Java game engine for android and desktop

texts:
I want implement 2d game as desktop application. And after development move it to android platform.

Engine should be have input and network managers.

Help me choose.


texts:
I want to pass my array (which is inside my c# code) to my shader.

Shader "custom/shader4"
{
    Properties
    {
        _myArray("Array", Float[256]) = []
    }

    SubShader
    {
        Pass
        {
            CGPROGRAM
            public float _myArray[256];

//code...

^this is obviously not working. Is anyone here who knows how to solve this?

(also in c#:)

myMaterial.MyArray = anotherArray;

It has to be something like this- right?
Or do I need a workaround?


texts:
I have a lightning effect that travels from point A to point B, I am having trouble placing placing point B correctly.

As you can see from the object hierarchy the points (LightningStart, LightningEnd) are nested 3 levels deep. _parentReaction.affectorWidget.transform.positionis the position I would like the object to be at.

As you can see below I have tried setting the position equal to the other widgets transform, I have also tried using transform.InverseTransformDirection and transform.TransformDirection in varying combinations, I have tried many options the code below is just me going back to basics to see what I missed.

I am not sure even which object I am supposed to call TransformPoint from, the Widget with the effect )(Point A) or the Widget at Point B?

Given the above scenario how would I position LightningEnd so that is at the same position as_parentReaction.affectorWidget.transform.position?

I understand this is a very common question and I have read many previous questions related to this but two hours later, I would just like to know how its done so I can understand where I am getting this wrong.

Thank you.

Edit: _controller is the Widget Running this effect, since it spawns as a child of this I dont need to worry about its position.

    public override IEnumerator Do(Widget _controller, WidgetReaction _parentReaction)
{
    effect = _controller.GetComponent<Widget_Effect_Comp>().AddEffect(effect);

    while (true)
    {
        start = effect.effectPrefab.transform.Find("LightningStart").transform;
        end = effect.effectPrefab.transform.Find("LightningEnd").transform;

        Debug.Log("End Position : " + effect.effectPrefab.transform.Find("LightningEnd").transform.position);

        //Debug.Log("Widget World Pos : " + _controller.transform.position);
        //Debug.Log("Widget Local Pos : " + _controller.transform.localPosition);

        //Debug.Log("AffectorWidget World Pos : " + _parentReaction.affectorWidget.transform.position);
        //Debug.Log("AffectorWidget Local Pos : " + _parentReaction.affectorWidget.transform.localPosition);

        effect.effectPrefab.transform.Find("LightningEnd").transform.position = _parentReaction.affectorWidget.transform.position;

        Debug.Log("End Position : " + effect.effectPrefab.transform.Find("LightningEnd").transform.position);

     yield return new WaitForSeconds(2f);
    }

}

public class WidgetEffect : ScriptableObject
{
    public string effectName;
    public GameObject effectPrefab;
}

public WidgetEffect AddEffect(WidgetEffect _widgetEffect)
{
    if (!activeEffects.ContainsKey(_widgetEffect))
    {
        GameObject go = Instantiate(_widgetEffect.effectPrefab);
        go.transform.parent = effectContainer.transform;
        go.transform.position = Vector3.zero;
        go.transform.localPosition = Vector3.zero;
        activeEffects.Add(_widgetEffect, go);

        return _widgetEffect;
    }
    return null;
}

Edit: Removed Extended Explanation not related to initial question!
[![enter image description here]]


texts: Would a company take a game pitch seriously if they were pitched a fully finished game?

texts:
Let's say hypothetically that I had a fully realized and functioning game using a well known IP (a character from Nintendo or from another company, for instance), where the game is finished and wouldn't have any development time, would they entertain the idea to release it?

It would be made with their characters so I would have no right to it (in the case of money) but would they entertain the idea if they found it good and fresh.?

I have seen answers to this question saying a definite no for they were presented an idea of a game and not a completed product. And I know most people would want compensation for there time, but if it's already done and bug tested, play tested and polished, would they entertain the idea if they found they wouldn't have much to do on their end and I would not seek any rights to the design?


texts: How to implement 2 cameras in a unique stage using LibGDX

texts:
I am quite new to LibGDX. I am trying to make a game, where the character is an Actor, and it's controlled by a Touchpad(included in the main Stage as an Actor too).

My problem is that I am trying to put the stage's camera to be always centered on the character, but I have no idea of how to solve this, I've been searching and it seems I have to use 2 cameras, 1 to show the controllers (the touchpad), and another to show the actors and that stuff, so while the actors are moving, the touchpad will keep on the screen, but I do not really know how should I do this, my code is this:

public class GameScreen extends BaseScreen {

    Stage stage;
    Character character;//it extends from actor
    Touchpad joystick;
    int screenWidht, screenHeight;
    Skin joystickSkin;

    public GameScreen(AwesomeTanks game) {
        super(game);
        screenWidht = Gdx.graphics.getWidth();
        screenHeight = Gdx.graphics.getHeight();

        joystick = new Touchpad(0,getTouchPadStyle());
        joystick.setColor(joystick.getColor().r, joystick.getColor().g, joystick.getColor().b, 0.5f);
        joystick.setBounds(10, 10, screenHeight / 2.5f, screenHeight / 2.5f);

        character = new Character();

        stage = new Stage();
        stage.addActor(character);
        stage.addActor(joystick);

        Gdx.input.setInputProcessor(stage);
    }

    @Override
    public void hide() {
        stage.dispose();
        joystickSkin.dispose();
        character.detach();

    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(1f, 1f, 1f, 1f);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        character.moveBy(joystick.getKnobPercentX() * character.velocity * delta, joystick.getKnobPercentY() * character.velocity * delta);

        if(joystick.isTouched())
            character.setRotation((float) ((180/Math.PI)*Math.atan2(joystick.getKnobPercentY(),joystick.getKnobPercentX())));

        stage.act(Gdx.graphics.getDeltaTime());
        stage.draw();
    }
}


texts: References are missing after migrating Unreal assets

texts:
I'm currently trying to migrate some VFX assets (meshes, materials, textures, material instances, niagara emitters and niagara systems) to another project on another machine.
My folder structure looks like this: C:\Users\Documents\MyName\UnrealProjects\MyProject\Content\ThirdPersonBP\MyVFX
My current workflow is like this:

In Unreal I right click on "MyVFX" and choose to migrate it and then choose a destination folder (not another project).
Zip the migrated folder and put it on another machine.
Unzip "MyVFX" from the zip to C:\Users\Documents\OtherName\UnrealProjects\OtherProject\Content\ThirdPersonBP
Put the niagara system into the level

The problem that now occurs is that references are not set. For example, the Sample Texture node in a material does not contain a set texture or a niagara system does not have anything set in the Mesh Renderer module (neither mesh nor material).
Everything works again as intended once the references are set again manually. But, that's tedious work of course and I don't want my teammates to do that for every effect I create.


texts: XNA - How to use One Rectangle in sprites for collisions

texts:
I'm new to XNA and game development in general. If I want to make an object solid so my character cannot pass through it, I would use several Rectangles to make the collision more "realistic"

What I do is to use the method Intersects() with both;

This are two Rectangles that will be solid. (Highlighted in Red):

And I wonder if there is a way to use one rectangle to achieve something like this:


texts: Where is the Shader Designer in Visual Studio?

texts:
I have Visual Studio 2012 Ultimate and I've been trying to access the Shader Designer. I searched through MSDN's text and Channel9's videos, but they keep failing to mention how to access it.

Can someone let me know where it is?


texts: Why is server frame rate slower than client's?

texts:
I have read in my lecture notes in a game dev class that in a server-client-architecture multiplayer game, it is common practice to have the server running at a lower frame rate than the client (20 fps compared to 60 fps for example)

No reason was given in the notes so I want to ask if anyone has a solid explanation for this?

My guess is that the server "waits" a little for all clients to send some packets before making its calculation. But this seems to be a different technique (bucket synchronization) altogether


texts: Wheel rotation, to change velocity of vehicle

texts:
I update the velocity of my vehicle like so:

[v setVelocity:  ((2 * 3.14 * 100 * (wheel.getRotationValue / 360) / 30)) * gameSpeed]; // update on 60 fps this gets velocity on all frames divide by 60 for 1 frame.

This is done in my update method in my world class.

Now wheel.getRotationValue returns the rotation value which is worked out like this:

- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:[touch view]];
    location = [[CCDirector sharedDirector] convertToGL:location];

    if (CGRectContainsPoint(wheel.boundingBox, location))
    {
        CGPoint firstLocation = [touch previousLocationInView:[touch view]];
        CGPoint location = [touch locationInView:[touch view]];

        CGPoint touchingPoint = [[CCDirector sharedDirector] convertToGL:location];
        CGPoint firstTouchingPoint = [[CCDirector sharedDirector] convertToGL:firstLocation];

        CGPoint firstVector = ccpSub(firstTouchingPoint, wheel.position);
        CGFloat firstRotateAngle = -ccpToAngle(firstVector);
        CGFloat previousTouch = CC_RADIANS_TO_DEGREES(firstRotateAngle);

        CGPoint vector = ccpSub(touchingPoint, wheel.position);
        CGFloat rotateAngle = -ccpToAngle(vector);
        CGFloat currentTouch = CC_RADIANS_TO_DEGREES(rotateAngle);

        float limit = 0.5;
        rotationValue += (currentTouch - previousTouch) * limit;
    }

    touching = YES;
}

Say I steer the vehicle to the far right of the screen, and want to move it to the far left, It wont start moving to the left of the screen until the rotationValue is past 0 degrees again (the wheel is in its center posistion) and is dragged past this value.

Is there anyway to change the code I have above, so that movement on the wheel is recognised instantly and updates the velocity of v instantly too?


texts:
I want to create a top-down rpg kind of game. It doesn't have the turn-based battles, for the most part, as it's more of a puzzle type game with an overarching mystery to solve, with not much action. However, I've been playing with the idea of adding different kinds of gameplay from other genres that mixes well with this top-down perspective, such as Zelda-style melee combat, fast "kill 'em all" shoot 'em up action like Hotline Miami, and stealth like the Metal Gear series.

Lets say I have ten chapters of around two hour length each. The distribution of each gameplay element would, for example, go something like this:

Chapter 1: regular top-down
Chapter 2: regular top-down (small stealth segments)
Chapter 3: Zelda
Chapter 4: regular top-down (small rpg turn based fight)
Chapter 5: Metal Gear
Chapter 6: Hotline Miami (small stealth segments)
Chapter 7: regular top-down
Chapter 8: Zelda
Chapter 9: Hotline Miami
Chapter 10: mix of Zelda, Hotline Miami, Metal Gear and turn based rpg fight

These gameplay styles fit with the narrative, which would've previously only been cutscenes. The Zelda parts for example are flashbacks to medieval times, where it shows how the evil bad guy was born and how the first few attempts at destroying him went for an order of knights (spoilers: not too well, but they did manage to slay many of the bad guy's monster army and weaken him a bit).

Now, regardless of whether or not you think I could pull something like this off (I have my doubts as well, but that's not the point of the question), could this be a bad idea? Variety is the spice of life after all, but I feel that maybe the player could be overwhelmed or annoyed having to learn different mechanics from different genres. Could it be disruptive to the gaming experience if you suddenly play a different kind of game? Or does it not matter as long as it's integrated well with the rest of the gameplay and story?


texts:
I have a game engine using an entity-component system (ECS). I serialize the data contained in the ECS by having a system that registers serializers for different component types. I want to create networking,= using authoritative peer-to-peer, where I still have a server, but it acts only as the traffic center, and does not run the game logic. The idea is that specific entities are synchronized across client instances.

However, there is a problem with this. While I can easily serialize my data, I don't know how to synchronize it over a network, or load it from a file. The problem lies in how my system communicates; how do I tell which entity is which, on the other end? How do I let the receiving side know which entity the sent data was meant for?

My entity ids are currently generated as sequential numbers, but it feels very unreliable to use them, as there could be a time when the numbers are not synchronized. For example, one might create a decal entity sooner, or the order in which they are created could be different. This also makes seeded random GUIDs unusable.

What system could I use to identify my entities, when sending data over network or storing them in file?


texts: How to parse User-defined types from String?

texts:
I am trying to save data about various entities in each Level in my game in a JSON file and load it at Runtime(Like a Scene file in Unity). I can save simple stuff like floats and ints and parse them back to with functions like std::stof. I can even handle stuff like a Vector3(3 floats).

Say, I want to save a User-type like CollisionSystem which resolves Collision between entities with a ColliderComponent. CollisionSystem does not contain any data and only Behaviour. How can I infer the Type from just the string and create an Object of CollisionSystem?

{
    "MovementSystem" : {},
    "RenderSystem" : {},
    "CollisionSystem" : {},
    "entities" : [
        {
            "PositionComponent" : {
                "x" : 10,
                "y" : 0,
                "z" : 10
            },
            "SpriteComponent" : {
                "source" : "\"assets/textures/Goblin.png\""
            },
            "ColliderComponent" : {}
        },
        {
            "PositionComponent" : {
                "x" : 0,
                "y" : 0,
                "z" : 30
            },
            "SpriteComponent" : {
                "source" : "\"assets/textures/Hero.png\""
            },
            "ColliderComponent" : {}
        }
    ]
}

The Brute Force method I could think of is a Switch case statement in the Parser
like so:

System* GetSystem(string system_type)
{
    switch(system_type)
    {
        case "MovementSystem":
            return new MovementSystem();

        case "CollisionSystem"
            return new CollisionSystem();

        .
        .
        .

        default:
            return nullptr;
    }
}

which can be called like:

System* moveSystem = GetSystem("MovementSystem");
System* collisionSystem = GetSystem("CollisionSystem");

moveSystem->update();
collisionSystem->update();

However, I don't think it's the right way to do this. I am new to C++. So I might be missing some language features that might do this. Is there an elegant way to do this?


texts: Can I use music I made in GarageBand or FL Studio in a commercial game?

texts:
I'm a beginning developer and I'd like to make music for my game. I've searched this question on the site, and when it comes to music in games, I see many people suggesting programs like FL Studio, Reaper, GarageBand, etc.

What are the legal implications of using music made with them in a commercial game? Is it okay to use music I've created on my computer with one of these programs (I was thinking of FL Studio) in a game I plan to profit from?


texts: Why does my Unity Android export fail with "No resource identifier found"?

texts:
When I try to export my Unity game to Android, I get this error:

CommandInvokationFailure: Failed to re-package resources. See the Console for details.
AndroidManifest.xml:4: error: No resource identifier found for attribute 'isGame' in package 'android'
AndroidManifest.xml:4: error: No resource identifier found for attribute 'banner' in package 'android'

What could cause this?


texts: Which technique should I use to create procedurally generated planets

texts:
I am working on a personal project to create a game, in which you can fly in space to various planets and land on said planets.
I was originally using a script to create an IcoSphere which I stored using recursive chunks which worked as a LOD.
The results looked good from space, however, after creating a player on the planet, the triangles were still very large. The IcoSphere was only subdivided 5 or 6 times due to the lengthy processing times.
I was going to base the texturing of the magnitude of the point on the sphere taking into account various factors.
Is there a better method to generate planets without these processing times?
EDIT
I am only interested in generating the planet surface, not the positioning in the galaxy/universe
I have done research online into different techniques. I've seen people using cube spheres however that looked to have caused a lot of distortion around the corners. I've also seen Octohedrons which were subdivided but I think that'd give the same problems as my icosphere technique


texts: Black screen when try to capture Vive gameplay using VRCapture

texts:
I'm using Unity, the first recording in VR Mode was fine. Then the rest were just black screen. No errors were detected and my gameplay was just playing fine. Also the red dot recording signal on Vive HMD was not there anymore. Any advice ?

Setting :

========VRCapture Diagnosis========

Software Checksum: 37CD Version: 1.0.278.128
Processor: Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz
Display Card: GeForce GTX 950M/PCIe/SSE2
Operating System: Microsoft Windows 10 64 Bit
VR Headset: HTC Vive MV
Microphone: Microphone (2- USB Audio Device)


texts: Detecting collision of multiple moving objects

texts:
I have wrote a simple game that has a 100 balls bouncing off the borders of the canvas. Each ball is an instance of ball class function that has the following definition:

var cnv = document.getElementById("mycanvas");
var ctx = cnv.getContext("2d");
...
...

function ball() {
    // at instantiation, set the ball in a random position
    this.x = parseInt(Math.random()*cnv.width) +1;
    this.y = parseInt(Math.random()*cnv.height) +1;
    this.size = parseInt(Math.random() * 10) + 1;

    // and give the ball a random speed at a random direction
    this.x_speed = parseInt(Math.random()*10) +1;
    this.y_speed = parseInt(Math.random()*10) +1;
    if (this.x_speed>5) {
        this.x_speed *= -1;
    }
    if (this.y_speed>5) {
        this.y_speed *= -1;
    }

    // draw() and update() for the instance will be called from the main game loop
    this.draw = function() {
        ctx.beginPath();
        ctx.fillStyle = "white";
        ctx.arc(this.x,this.y,this.size,0,Math.PI*2,true);
        ctx.fill();
    };

    this.update = function() {
        this.x += this.x_speed;
        this.y += this.y_speed;

        if (this.x >= cnv.width || this.x<=0) {
            this.x_speed *= -1;
        }
        if (this.y >= cnv.height || this.y <= 0) {
            this.y_speed *= -1;
        }
    }
}

In the main game loop, I call gameUpdate() which in turn calls update() for each ball, like so:

var balls = [];   // array to hold all instances
...
...
function gameStart() {

   for(var i=0;i<100;i++) {
       balls.push( new ball() );   // create an instance and store its reference
   }
}

function gameUpdate() {
    for(var i=0; i<balls.length;i++) {
         balls[i].update();     // this ensures that each ball moves on its own

    }
}

Now my question is:
How can I manage to detect collision between all of the instances of balls ?

Here is my attempt, but I already know it is not efficient:

function detectCollision() {
    for(var i=0;i<balls.length;i++) {
        for(var j=0;j<balls.length-1;j++) {
            if (i !== j) {   // make sure we have two different balls to check with
                // assuming that collision() exists and checks x,y for each parameter and return boolean
                if (collision(balls[i],balls[j])) {
                      console.log("boom!");
                }
            }
        }
    }
}

What is a better way for checking collision of moving objects?


texts: InvalidOperationException in build only, when trying to select object in a dynamically loaded scene using Linq

texts:
Here is the relevant code:

private void Awake()
{
    StartCoroutine(LoadScenes());
}

private IEnumerator LoadScenes()
{
    this.sceneLoad1 = SceneManager.LoadSceneAsync(Scene1, LoadSceneMode.Additive);

    while (!this.sceneLoad.isDone)
    {
        Debug.Log("Loading scene 1...");
        yield return null;
    }

    this.sceneLoad2 = SceneManager.LoadSceneAsync(Scene2, LoadSceneMode.Additive);

    while (!this.sceneLoad.isDone)
    {
        Debug.Log("Loading scene 2...");
        yield return null;
    }
}

private void Start()
{
    SceneManager.GetSceneByName(Scene1)
                .GetRootGameObjects()
                .Where(root => root.GetComponent<God>() != null)
                .Select(root => root.GetComponent<God>())
                .Single()
                .SpreadGospel();
}

(Scene1 and Scene2 are const strings.)

The program works fine when running in the Unity editor. However, when I make a development build, I see the follow error message:

    InvalidOperationException: Operation is not valid due to the current state of the object
  at System.Linq.Enumerable.Single[God] (IEnumerable`1 source) [0x00057] in /Users/builduser/buildslave/mono/build/mcs/class/System.Core/System.Linq/Enumerable.cs:1968
  at MySolution.GodInitializer.SpreadGospel () [0x00001] in D:\repos\MySolution\SourceCode\SourceCode\GodInitializer.cs:100
  at MySolution.GodInitializer.Start () [0x00012] in D:\repos\MySolution\SourceCode\SourceCode\GodInitializer.cs:77

... which indicates that the scene wasn't fully loaded before I tried to access the God singleton.

What changes should I make to fix the problem?


texts: Null Reference to camera when loading new scene

texts:
I am getting the error:

  MissingReferenceException: The object of type 'Camera' has been
  destroyed but you are still trying to access it. Your script should
  either check if it is null or you should not destroy the object.

The camera in my game contains a persistent object script, which prevents the camera from being destroyed when loading a new scene.

private void Awake()
{
    DontDestroyOnLoad(transform.gameObject);
}

The scene is switched via a method in the GameManager:

public void loadScene(UnityEngine.Object arena)
{
    operation = SceneManager.LoadSceneAsync(arena.name);
    state = GameState.LOADING;
}

and finally the camera contains another script which adds a distortion effect:

void OnRenderImage(RenderTexture source, RenderTexture destination)
{
    distortCam.CopyFrom(mainCam); //Error occurs here
    distortCam.backgroundColor = Color.grey;
    // ...Some more code ...
}

The error occurs in this last method, but the camera still exists in the editor. mainCam is a Camera object that is assigned onAwake via mainCam = GetComponent<Camera>();

Also if I switch the loadScene method to:

public void loadScene(UnityEngine.Object arena)
{
    operation = SceneManager.LoadSceneAsync(arena.name, LoadSceneMode.Additive);
    state = GameState.LOADING;
}

it works perfectly, but it is inconvenient to always have to loadScenes additive.

Why is the reference to the mainCam being lost? I have tried to check if it's null and reassigning it before using it, but so far I still have the problem. Any ideas?


texts:
Context: I'm making a little "program your robot army" sort of game in Java in which the player writes Lua scripts (which are then run by LuaJ) to program their robots to do stuff. So far there are two objectives:

Keep It Simple, Stupid, and
React to the environment.

To take a simple example of what I currently have, the player should be able to tell their robot to go to a particular location with something like

robot:goTo(5, 8)

Like Colobot, the scripting engine effectively halts (blocks) at that instruction until the robot has reached its destination.

I like this -- it's meets the first requirement nicely, in that you can't do anything until goTo decides to return. It's also simple on the Java side -- I can basically do while (/* condition */) yield() and just resume the coroutine every tick (then maintaining state in local variables is trivial). But: what if that resource at (5,8) disappears, or an enemy comes near, or energy runs low? There's no opportunity to bail -- the robot has to reach (5,8) before it can do anything else.

The main other idea I can think of is to produce some sort of loop:

while not robot:near(5,8) do
    if robot:enemyNearby() then
        break -- and do some other stuff, presumably
    else
        robot:moveTo(5,8)
    end
end

where moveTo this time sets the velocity/acceleration and then immediately returns, without blocking until arrival.

I could have robot:goTo return the actual coroutine (either wrapped, so you just call it, or directly, which requires calling coroutine.resume and passing the coroutine), which might look something like this:

moveTask = robot:moveTo(5,8)
while not robot:near(5,8) do
    if robot:enemyNearby() then
        break
    else
        moveTask()
        -- or perhaps coroutine.resume(moveTask)
        -- or some other syntactic sugar
    end
end

These last two approaches look pretty similar, but reusing a coroutine as in the second example makes managing state (e.g. a path) trivial, at the cost of exposing coroutines to the player.

To reiterate, the goal is to allow for writing simple scripts, in which a set of actions are executed in series (sorta like queued actions in The Sims), while simultaneously allowing more complex scripts with actions that may be interrupted by arbitrary events (nearby enemy, target moved, stats dropping).

Any tips or ideas would be much appreciated!


texts: HTML5 Canvas 2D lighting and normal maps

texts:
How using the HTML5 Canvas can I create a 2D game with light sources and also add an extra depth using normal maps.  I have never really done lighting in 2D before and I'm not sure where to start.
Something like this:

or

(source: wholehog-games.com)


texts:
I'm so excited to learn ray tracing and did a lot of fun. But I'm stuck at rendering empty Cornell Box scene.

It has some darker color along the bright color and it's seem different with the image in the book.
Sorry if my English confuses you because I'm still learning it.
My source code about this project for someone want to check.
https://github.com/trinhlehainam/StudyRayTracing


texts: Importing Mobile Ads Unity plugin results in standard input InvalidOperationException

texts:
When I import Mobile Ads Unity plugin this error shows up. How can I fix it, and why am I getting this error?

While the “Resolving Android Dependencies” dialog and loading bar is open,  the following appears in the console:

InvalidOperationException: Standard input has not been redirected.
System.Diagnostics.Process.get_StandardInput ()
(wrapper remoting-invoke-with-check) System.Diagnostics.Process:get_StandardInput ()
GooglePlayServices.CommandLine.RunViaShell (System.String toolPath, System.String arguments, System.String workingDirectory, System.Collections.Generic.Dictionary`2 envVars, GooglePlayServices.IOHandler ioHandler, Boolean useShellExecution, Boolean stdoutRedirectionInShellMode)
GooglePlayServices.CommandLine.Run(System.String toolPath, System.String arguments, System.String workingDirectory, System.Collections.Generic.Dictionary`2 envVars, GooglePlayServices.IOHandler ioHandler)
GooglePlayServices.CommandLine+<RunAsync>c__AnonStorey1.<>m__0 ()
UnityEngine.UnhandledExceptionHandler:<RegisterUECatcher>m__0(Object, UnhandledExceptionEventArgs)


texts: Handling multiple controllers in a single player game

texts:
Currently implementing input support for a single player game and I'm unsure how best to handle the (admittedly odd) situation where the user plugs in 2 or more controllers. Should only one be active, or should they all control the character?

What I'm currently doing is the following:

If there are multiple connected when the game starts I just using the first one that's picked up.
If the user connects another controller I ignore it.
If the user disconnects a controller I pause the game and ask them to reconnect or press a key to drop back to keyboard/mouse controls.

But I'm wondering if this is reasonable. Should all controllers pass input to the character (this is going to be a nightmare for button mapping though, I'd need to implement some way of providing profiles for different controller types). If not, should I just allow the user to switch controller after disconnecting by pressing one of the buttons? Should a newly connected controller override the previous one?

There's just so many options here...


texts: How to stop a jump midair and remove y velocity in the process

texts:
What I want to do is to cut a jump midair by turning off the y velocity when the player releases the jump button (like in Hollow Knight). I managed to do that with:
rb.velocity = new Vector2(rb.velocity.x, 0f);

My problem is when I cut the jump and I am midair, if I repeat the release jump button process, the whole thing happens again, the character staggers as long as I am releasing the jump button continously.
I would like to be able to do that only once when I am off the ground. I am a noob when it comes to coding so I don't really know what to do.
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.Events;

 public class PlayerController : MonoBehaviour {

     public Animator animator;

     private Rigidbody2D rb;
     public float speed;
     private float moveInput;
     public float jumpForce;

     private bool isGrounded;
     public Transform feetPos;
     public float checkRadius;
     public LayerMask whatIsGround;

     private float jumpTimeCounter;
     public float jumpTime;
     private bool isJumping;
     private bool facingRight = true;
     public float jumpDownForceY = 0;

     void Start()
     {
         rb = GetComponent<Rigidbody2D>();

     }

     void Update()
     {

         isGrounded = Physics2D.OverlapCircle(feetPos.position, checkRadius, whatIsGround);

         if (Input.GetButtonDown("Jump") && rb.velocity.y == 0)
             rb.AddForce(Vector2.up * 700f);

         if (Mathf.Abs(moveInput) > 0 && rb.velocity.y == 0)
             animator.SetBool("Running", true);
         else
             animator.SetBool("Running", false);

         if (rb.velocity.y == 0)
         {
             animator.SetBool("Jumping", false);
             animator.SetBool("Falling", false);
         }

         if (rb.velocity.y > 0.2)
         {
             animator.SetBool("Jumping", true);
         }

         if (rb.velocity.y < 0)
         {
             animator.SetBool("Jumping", false);
             animator.SetBool("Falling", true);
         }

         if (isGrounded == true && Input.GetButtonDown("Jump"))
         {
             isJumping = true;

             jumpTimeCounter = jumpTime;
             rb.velocity = Vector2.up * jumpForce;
         }

         if (Input.GetButton("Jump") && isJumping == true)
         {

             if (jumpTimeCounter > 0){
                 rb.velocity = Vector2.up * jumpForce;
                 jumpTimeCounter -= Time.deltaTime;
             } else {
                 isJumping = false;
             }

         }

         if (Input.GetButtonUp("Jump"))
         {
             isJumping = false;
             rb.velocity = new Vector2(rb.velocity.x, 0f);

         }

     }

     void FixedUpdate()
     {
         moveInput = Input.GetAxisRaw("Horizontal");
         rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
         Flip(moveInput);

     }

     private void Flip(float moveInput)
     {
         if (moveInput > 0 && !facingRight || moveInput < 0 && facingRight)
         {
             facingRight = !facingRight;
             Vector3 theScale = transform.localScale;
             theScale.x *= -1;
             transform.localScale = theScale;
         }

     }
 }


texts:
My best goal atm is just make one 1vs1 battle with no animations more than something which makes me realize the attack is done.

I'm learning C and Xlib, and now I know how to put an image in a window in Xlib.

Yes, it's nothing, but it was my first goal, show images in a window, and then start to do things.

So now I'm starting to think how I will make the game.

Since I'm thinking how make a low quality battle 1vs1 with no more than the two sprites and a black background in a window, I'm focusing in the battle "system" to make a little base and see how things will go.

I think the way is this (Maybe you know a better one, but it's just what i was testing one day and it works):

The map has coords like X and Y, so the sprites or enemies or whatever is in the game, are occuping some X and Y.

Then to use an attack I will take the X and Y of the attacker, and move one of them depending on the direction the attacker is looking.

For example, I want attack with a melee skill. I'm looking at right, so I take my X coord and move the X one step (maybe copying it in a variable first). This will be done with something like X=X+1; or X+=1; So my Y coord still unchanged, but my X is one step to right, then it's like I moved to right, but I'm still in my position because are the coords who are moving, not me really.

Then I make a condition like if X and Y are equal to Xenemy and Yenemy then, do attack.

So the base is move my coords or someone coords and do the attack moving X and Y and testing if they are the same of the enemy.

The ranged attacks will be the same, but repeating the process depending on range until it's done or the range is out.

X++;
if (X and Y are equal to Xtarget Ytarget) then do attack;
else  X++ and try again until the range is out or attack is done;

But, my questions are:

How I should do to attack more than 1 enemy? I need test all the coords of all sprites while I do this, or there is a better way like a selectable target or something?

I should use the Window coords, and the pixmap coords (the images or sprites) and copy them to attack, or I should make a new map with different X and Y?

What I must have in mind for the future? I mean, how I should make all coordinates and be sure the method I'm using is not lacking something which I should realize?

I'm having a wrong start? I guess I'm wrong when I'm focusing on only one target.

I guess the ranged skills should have X and Y, move on the map, and affect whatever is in the X and Y. But I have no more idea than test all the possible targets every time the skill cords move.

There is a way to create a global target to test only one location and know if there is an attackable target?

BTW: I will appreciate some corrections on my english. I will remember it, so I will learn with your edits. I  guess formatting is not needed and will be useless since there is no real code, but maybe you can do or add something to explain better what I'm trying to say.

I must say sorry for my bad english, I'm spanish and the english level here is shit. I've learned more playing wow on pirate servers than at the school and now reading programming docs.

If you know some books, info or questions I can look, please share it if they will be useful for me.


texts:
In my latest game I'm making, you can slice a 2D object arbitrarily, demonstrated in this gif:

You can continuously cut it into hundreds or thousands of pieces. This doesn't create a lot of lag, because they're always in a sleeping physics state, but there's a problem when you cause them to move.

I'm not really sure how to deal with making it so there's not so much rubble from cutting something apart. I don't really want to delete them after a certain amount of time; I don't like how, if you go back to something you cut up after a while, it randomly disappeared.

How can I clean up excessive player-created rubble?


texts:
I've recently started reading about VBOs.

If, for example, I want to draw a cube using VBOs, can I use one VBO to hold the coordinates for the 8 vertices, and another one as an index array, to specify the order in which the vertices are drawn?

If it's possible I'd appreciate some help on the matter, or a link to good tutorial you may know on the subject.

Thanks.


texts: Can I give a player money for completing my game?

texts: As it says in the title, can I give a player that completes my game (which might be hard to complete) money?


texts:
How can I achieve an outline effect similar to the ones found in League of Legends or Diablo III?

Is it done using a shader? How?
I would prefer answers that are not tied up to any particular engine but one that I can adapt to whatever engine I'm working on.


texts: Can I remove the systems from a component entity system?

texts:
After reading a lot about entity-component based engines, I feel like there is no real definition for this kind of engine. Reading this question, and the linked articles, made me think a lot. I do not feel that comfortable using the system concept, so I'll write something else that is inspired by this pattern. I'd like to know if it is a good way to organize game code, and what improvements can be made.

Regarding a more strict implementation of the entity-component based engine, is my solution viable? Do I risk getting stuck, at any point, due to the lack of flexibility of this implementation, or anything else?

My engine, as for entity-component patterns, has entities and components, but no systems, since the game logic is handled by components. I also think the main difference is the fact that my engine will use inheritance and object-orientated programming concepts, in general. I don't try to minimize them.

Entity: an entity is an abstract class. It holds a position, width, height, scale and a list of linked components. Every frame, the entity will be updated (i.e. all the components linked to this entity will be updated), and rendered, if a render component is specified.
Component: like for entity, a component is an abstract class that must be extended to create new components. The behavior of an entity is created through the components collection. Components are updated when the owning entity is updated, or for only one specific component (render component), rendered.


texts: Ouya build experiencing odd graphical artifacts, screen half black

texts:
I'm witnessing very odd graphical artifacts when I run my Unity game on Ouya. After the Unity splash screen, the game loads with the screen half black.

This seemingly has started occurring out of the blue. It also doesn't occur in the editor or the standalone build, only on Ouya. I can't think of a single reason why this would be happening. If I open the Ouya menu screen and close it, the game returns to normal; somewhat, as there may be some artifacts lingering but the screen isn't half black like in the screen shot above.

I know there's not much to go off of, but any insight into why this may be happening is greatly appreciated.


texts: Way to avoid excessively bright objects with specular lighting?

texts:
I have a typical Phong shading with specular light. I have all the parameters tuned so to give appropriate highlights from a point light source. Now the problem I have is a new object that has a large flat surface which tends to face directly towards the light source (which is a bit offset from the camera). It also has a normal map which is primarily in one direction (steel panels). This results in a pure white object.

I have a lot of options to try and work around the problem, but I was wondering if this is a common issue and perhaps there is a clean workaround. The various options I see (and am trying) are:

Reduce specular map intensity. There are two problems here, first when the object is not facing the camera it looks dull, second on a low quality setting I don't use specular maps.
Clamp the range of specular light. This of course limits the highlights for the entire scene. It also limits the highlights when the object isn't facing the camera.
Put a per-object specular light limit. This at least doesn't affect the whole scene, but does dullen this object when not facing the camera.


texts: How do i implement a hit box system in a fighting game?

texts: In a fighting game a move that you execute is basically just a series of hit boxes that are enabled and disabled at certain times. I want to know how do you create this hit box system. I have no idea as to how to make a flexible system where I can enable and disable a hit box on any frame of a move and also adding additional frame data. All I can think of is having a list that is the size of the amount of frames of the move, and add all of the enables, disables, and frame data as one list item. The problem with that is that a list item can only be one object so I have to somehow make all my frame data and hit box enables & disables into one object. If I can have as many hit boxes in a move as I want then this list item object needs to have a list as well, which I don't think is a good way of doing it. So I just want to know all of the good ways of implementing a hit box system in a fighting game.


texts:
I am looking to make a program that will allow me to test units for balance when in combat. The idea is that there will be two teams of so many units of different types. I would loop through a battle system that would pick units, have them attack, etc, and then see which team won and do this many many times for an average.

The thing I am having issues with is how to design or make the classes for the units. I tried making a class for a generic unit and then classes that pulled from it for each different unit. The issue was when I called a unit from a team, tried to add one etc. I need to know what the unit type was, that was I couldn't write one function that understood all the unit classes.

I am looking to make a system for the units that allows me to have each unit have the same basic stats, health, speed, etc. But that each unit will also have their own functions for abilities that would be different then other units. It would also allow me to make a method where I can say get a unit from an arraylist and call its get speed method and it wouldn't demand I know the unit class. For instance, grunt g = new grunt() instead something where I can get the unit and just call, unit.getspeed();

Any help or ideas for how I can do this, please ask for more information if needed.


texts:
As my game is purely multiplayer, online performance is important.

Should I run two threads for each player/connection? (One for input and one for output) or should I run one thread for all player input and one thread for all player output?

What is the pros and cons, and how do I deal with high ping players in the second method?


texts:
Edit 2

In the following picture sprite1 (the red square) is hitting the platform from the left, so:

 sprite1_rightEdge>platformSprite leftEdge

would be true, so I can simply reposition sprite1 to align it with the left edge of the platform. So....

sprite1X=platformSpriteX-platformSpriteWidth

This is fine, however, lets say that sprite1 hits from the right, the problem I have here is that the first condition (above) is still true. So....

sprite1_rightEdge>platformSprite leftEdge

So my sprite1 still gets positioned at the left edge of the platform......

The same also happens in reverse....

Using velocity

I've had some success with velocity, but again I'm not clear on how this works properly.

For example, if I say something like:

if (Sprite1 moving right at time of collision)

Then I can assume it's hit the platform from the left.  This works, but what if the sprite is 'falling' from the top and lands on the platform while also moving right?  It will again get re-positioned at the left edge of the platform.

partial sucess

So far, I managed to get this working (although not fully implemented yet), by saving the old position of Sprite1, repositioning it and checking the old position, so if  the old position was to the left of the platform, then I can assume it came in from  the left.

If someone could let me know the best way to proceed it would be much appreciated.

Just to clarify what I'm asking - I have 2 objects - 1 is a platform and the other is the main character, I wish to make the player stop regardless of which side he hits the platform (from the top, bottom, left or right) - I will definitely be moving at distances of more than 1 px at a time).

I've attempted using velocity but this doesn't seem to work correctly as well as double checking x/y positions once a collision has happened but again I get some very off results.  Some pseudo code of how to detect which side a sprite has hit would be much appreciated :-)

I have researched this and have seen pretty much every Q&A on this site regarding this subject (as far as I know) but the answers are either not relevant to my particular query or I simply don't understand them.

Original question

I understand the basic principles of collision detection for squares / rectangles

i.e.,

(Pseudo code)

public boolean testCollision(){

if (bottom of sprite1<top of sprite2)
return false;

if(top of sprite1>bottom of sprite2)
return false;

if(left edge of sprite1 > right edge of sprite2)
return false;

if(right edge of sprite1 < left edge of sprite2)
return false;

return true;
}

I also know that I can stop my sprite going off the edge of the screen like so:

if(spriteX<0){spriteX=0};

However using something akin to the first method above for detecting collision between 2 specific objects, how can I make my 1st sprite actually stop so he can't pass through it?

At the moment, although I can detect when the two are touching, I'm unsure how to make it so that they can't actually pass through each other.

A push in the right direction would be a great help - thanks!


texts: How can I implement voxel-based lighting with occlusion in a Minecraft-style game?

texts:
I am using C# and XNA. My current algorithm for lighting is a recursive method. However, it is expensive, to the point where one 8x128x8 chunk calculated every 5 seconds.

Are there other lighting methods that will make variable-darkness shadows?
Or is the recursive method good, and maybe I am just doing it wrong?

It just seems like recursive stuff is fundamentally expensive (forced to go through around 25k blocks per chunk). I was thinking about using a method similar to ray tracing, but I have no idea how this would work. Another thing I tried was storing light sources in a List, and for each block getting the distance to each light source, and using that to light it to the correct level, but then lighting would go through walls.

My current recursion code is below. This is called from any place in the chunk that does not have a light level of zero, after clearing and re-adding sunlight and torchlight.

world.get___at is a function that can get blocks outside of this chunk (this is inside the chunk class). Location is my own structure that is like a Vector3, but uses integers instead of floating point values. light[,,] is the lightmap for the chunk.

    private void recursiveLight(int x, int y, int z, byte lightLevel)
    {
        Location loc = new Location(x + chunkx * 8, y, z + chunky * 8);
        if (world.getBlockAt(loc).BlockData.isSolid)
            return;
        lightLevel--;
        if (world.getLightAt(loc) >= lightLevel || lightLevel <= 0)
            return;
        if (y < 0 || y > 127 || x < -8 || x > 16 || z < -8 || z > 16)
            return;
        if (x >= 0 && x < 8 && z >= 0 && z < 8)
            light[x, y, z] = lightLevel;

        recursiveLight(x + 1, y, z, lightLevel);
        recursiveLight(x - 1, y, z, lightLevel);
        recursiveLight(x, y + 1, z, lightLevel);
        recursiveLight(x, y - 1, z, lightLevel);
        recursiveLight(x, y, z + 1, lightLevel);
        recursiveLight(x, y, z - 1, lightLevel);
    }


texts:
I am currently writing a sports strategy management game (cricket) in PHP, with a MYSQL database, and I have come across one stumbling block - how do I update games where neither player is online?

Cricket is a game played between two players, and when they (or one of them) is online then everything is fine; but what if neither player is online?  This occurs when championship games are played, and these games need to happen at certain times for game reasons.

At the moment I have a private web page that updates every 5 seconds, and each time it loads all games are updated; but then I have the problem that when my private web page stops (for example my computer crashes or my web browser plays up) the game stops updating!


texts: How to check mouse coordinates and mouse events

texts:
I'm building a simple game where if the mouse's X coordinate is greater than 200, and you click, the screen will turn red. Here's the code:

var mouseX = event.clientX;
  var mouseY = event.clientY;

function startGame(){
 if(mouseX > 200){
  document.body.style.backgroundColor = "red";
 }
}
document.addEventListener("onmousedown", startGame);

Am I using an incorect way of finding coordinates or am i using an incorrect way of finding mouse down or what? I can't use Jquery btw.


texts:
I have developed an iPhone app. When I have installed it in the device, it worked fine, ie it showed, the logo screen, the title screen and goes to game screen and now I have exited pressing the home button. The problems starts when I relaunch the app, it straightly goes to the game screen, by skipping the splash screens.

While I was working on it the app crashed and when I launched again it showed the logo screen and title screen. But when I relaunched it, the splash screens where skipped.

Could you tell me the possible errors that might have occurred?


texts: How can I efficiently create/store/implement animations as I add to my game?

texts:
My game's characters are made up of different parts (head/body/legs/etc), and whatever items they have equipped. As I'm creating the animation system for my game, I want to try to anticipate a large number of combinations for different pieces for each character. Originally, I had planned on having a frame-by frame animation for each piece for each animation, and then layer them to combine them into a character, but this seems like it would be a lot of work for my artist, and that the memory/disk size would start to add up as well since we would need a sprite for every frame, of every customization of every piece, in every animation, for every character.

What efficient ways are there to create/implement these animations as we add more and more configurations to our game?

Edit: I'll also point out that my artist is using flash to make the graphics and animations, but the game is in Java (libgdx, but I can also hard code OpenGL if I need to).


texts: What is a good algorithm for a stock market simulation?

texts:
I am making a text game about investing in the stock market, however I need a better algorithm, as the current simulation just goes up and down randomly. How can I make it so that its a more realistic simulation in python.

I've looked at the answer to the question
"How would I implement a realistic stock market?", but I want the stock price to be influenced by the users actions, and based on non random actions that they have done. For example, if they buy a massive quantity of an item in the game, the value will go up


texts: Allowing a secondary market for online content

texts:
Many games with an online component, allow players to buy various kinds of content. As far as I know, none of them allow a secondary market where players resell purchased content to other players. Presumably this is because the developers think disallowing the secondary market will get them more sales.

However, there seems to be a widely held school of thought regarding Magic: the Gathering (the nonelectronic card game) that the existence of a secondary market actually increases revenue by encouraging people to buy more cards in the hope of being able to resell them. Whether that theory is true or false, the mere fact that many people believe it, should encourage at least some video game developers to try allowing a secondary market.

Given the existence of a reasonably widely held theory that this is a good idea, why is it that no video game developers whatsoever allow a secondary market?


texts: What shape should you use for player collision?

texts:
I'm working on a simple Box2D platformer, and I was wondering, what is the best shape to use for the player's box? I'm currently using a circle with a radius of 10, but that doesn't work well, as when the player collides with a corner, they can get stuck on it, or won't be able to move forwards properly and it feels really awkward. What should I use instead?

I've heard ovals work well for this kind of thing, but there's no easy way to create an oval in B2D without creating 3 circles on top of each other. I've also seen rectangles used, but aren't those less accurate?