texts: How might I script the creation of CLR objects?

texts:
I am looking for a method to script the creation of entities (arrays of components) for delivery through my entity factory, i.e scripted creation of .net objects.

I have looked into Lua but it seems dynamically creating CLR objects is a somewhat impractical.

Is there another method I could use to achieve this?
Is there a general pattern / approach to take towards scriptiing out functionality in this context?

My factory provides an abstracted EntityComponent[] per request, so the scripting platform would need to be aware of and be able to construct the component types defined within the c# namespace.

I want to be able to define the components of an entity and the components relevant properties in some declarative form within a script. To give some background information, I was let onto this when I found deserializing entity definitions from XML was going to be very awkward. Reflection within C# is an option but if it is not my only option I would very much seek to avoid it.

EDIT:
Turns out I was very wrong about Lua! It is unbelievably easy to achieve what I was describing once you get the LuaInterface DLL up and running, importing types from your C# application into Lua is simple and effective.


texts: How to export FBX models to use in SharpDX?

texts:
I am trying to export a model from 3ds Max 2014 as a fbx file and use it in my SharpDX driven project.
In the SharpDX example solution, there is a project named ModelRendering.Desktop. I just modified it to load my exported testmodel.

This is the result when running the program:

As you see, I modeled a cube in 3ds Max. But the sample application shows me something different. When I try to export some more complex models, their renderings are totally broken.

I use the default export settings ("Autodesc Media & Entertainment"). Do I need to hit a special export option or do I need to use some external converter? What is the common way to use fbx models from 3ds Max in SharpDX?


texts:
When working with OpenGL, you often recieve integer id:s to keep track of OpenGL objects.

For example, representing a simple mesh, you may have a number of references to objects like so:

GLuint arrayBuffer;
GLuint elementArrayBuffer;
GLuint texture;

Having many meshes, the id:s add up quickly. Therefore my problem is, where it is most logical and efficient to store them?

Alternative 1

My first thaught was to hand out the id:s to corresponding game entities. Something along the lines:

class Entity {
public:
    GLuint arrayBuffer;
    GLuint elementArrayBuffer;
    GLuint texture;
    // Other methods...
}

Then having a render class:

// Create the buffers and textures and pass id:s to entity.
renderer.init(entity);
// Render with corresponding buffer/texture id:s stored in entity
renderer.render(projection, view, entity);

Where it then is easy enough, in the implementation of the render method, just picking id:s and render with them.

Some disadvantages is that this is a leaky abstraction, where OpenGL concepts are "leaked" to game entities. Which does not feel quite right. An advantage might be that the method supposedly is efficient. You do not have to find id:s, you know them for each rendering pass.

Alternative 2

Another alternative would be to store the id:s internally in the renderer. For example, an internal data struct:

struct RenderData {
    GLuint arrayBuffer;
    GLuint elementArrayBuffer;
    GLuint texture;
}

Then having an unordered map with references to each entity and corresponding RenderData:

std::unordered_map<unsigned int, RenderData> render_data;

Then in the rendering method, the correct render data is fetched from the map only by a unique id that is stored in each entity.

Advantages of this approach, is that it is less "leaky", where only the entity id is passed to the renderer, to know what data to use. Disadvantages may be slightly less efficiency, because of lookups in the unordered map?

I would greatly appreciate inputs on this, what approach to prefer, or if there are any other approaches out there?


texts:
I am trying to come up with a system to measure or estimate the skill of a player at a single player game (so no head-to-head rating system help here). Specifically, it is a pinball game, but I do believe it is similar to most point-based single player games.

I have thought of 3 approaches:

total points scored with a threshold for each skill level
average points scored over all time
average points scored over last X games

All of them use points, which I think is probably the right metric: anything a player does in pinball grant points, with the most difficult objectives worth more points. Points also take into account all of the rare combination of objectives (like score multiplier + multiball) that would be hard to track manually.

However, I am not sure which approach to use and I bet other games have implemented similar skill-measuring system that I can use as a guide, so I'd appreciate any and all help on this.


texts: How to draw the simplest grid map OpenGL 1.0

texts:
I want to draw a simple black & white grid map, like that:

I have been searching for a way to generate tile, a tile map and tho and I want to draw this map and thats all. I mean that I want to draw it only once so it should be easy.
I use OpenGL 1.0. How can I draw that and how should I draw - should I draw an Image and place it  like a map, should I draw a tile and multiple it ?


texts: "Create Test Script in current folder" button is grayed out in Unity

texts:
I thoroughly read the Unity Test Runner documentation.

It is said in the documentation that the button may be disabled only if the creation of the script will lead to an error.

  This option is disabled if adding a test script would result in a compilation error.

But I do not understand this. How could a creation of the script possibly lead to an error?

I will be grateful for any help provided.

I found here a little bit more info, but it did not help me out.


texts:
I want to generate a background, which is used in the game, on every instance of the game based on certain conditions. To do so, I'm using a sf::RenderTexture and a sf::Texture like this:

sf::RenderTexture image;
std::vector<sf::Texture> textures;
sf::Texture texture;
// instantiating the vector of textures and the image not shown here
for (int i = 0; i < certainSize; ++i)
{
    if(certainContition)
    {
        texture.setTexture("file");
        texture.setPosition(pos1, pos2);
    } else
    {
        ...
    }
image.draw(texture);
}

The point here is that I draw single textures on a sf::RenderTexture, but because textures always are on the graphic cards memory, I can't exceed a certain map size which I have to.
I also considered using an sf::Image, but I can't find a way to draw an image (i.e. a texture) to it.
The third way I found was using an sf::VertexArray, but this seems to be a bit too low-level for my rather simple purposes.
So is there a common way to dynamically generate a background image based on other existing images?


texts: Learning OpenGL GLSL - VAO buffer problems?

texts:
I've just started digging through OpenGL and GLSL, and now stumbled on something I can't get my head around this one!? I've stepped back to loading a simple cube and using a simple shader on it, but the result is triangles drawn incorrectly and/or missing. The code I had working perfectly on meshes, but was attempting to move to using VAOs so none of the code for storing the vertices and indices has changed.

What I have for creating the VAO and buffers is this

//Create the Vertex array object
glGenVertexArrays(1, &vaoID);

// Finally create our vertex buffer objects
glGenBuffers(VBO_COUNT, mVBONames);

glBindVertexArray(vaoID);

    // Save vertex attributes into GPU
    glBindBuffer(GL_ARRAY_BUFFER, mVBONames[VERTEX_VBO]);

    // Copy data into the buffer object
    glBufferData(GL_ARRAY_BUFFER, lPolygonVertexCount*VERTEX_STRIDE*sizeof(GLfloat), lVertices, GL_STATIC_DRAW);

    glEnableVertexAttribArray(pos);
    glVertexAttribPointer(pos, 3, GL_FLOAT, GL_FALSE, VERTEX_STRIDE*sizeof(GLfloat),0);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mVBONames[INDEX_VBO]);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, lPolygonCount*sizeof(unsigned int), lIndices, GL_STATIC_DRAW);

glBindVertexArray(0);

And the code for drawing the mesh.

glBindVertexArray(vaoID);
glUseProgram(shader->programID);

GLsizei lOffset = mSubMeshes[pMaterialIndex]->IndexOffset*sizeof(unsigned int);
const GLsizei lElementCount = mSubMeshes[pMaterialIndex]->TriangleCount*TRIAGNLE_VERTEX_COUNT;
glDrawElements(GL_TRIANGLES, lElementCount, GL_UNSIGNED_SHORT, reinterpret_cast<const GLvoid*>(lOffset));

// All the points are indeed in the correct place!?
//glPointSize(10.0f);
//glDrawElements(GL_POINTS, lElementCount, GL_UNSIGNED_SHORT, 0);

glUseProgram(0);
glBindVertexArray(0);

Eyes have become bleary looking at this today so any thoughts or a fresh set of eyes  would be greatly appreciated.


texts: FMB alteration based on derivative and noise value

texts:
I'm still working on my procedural terrain generation and kind of sniffing ideas from Sean Murray (No Mans Sky programmer). So I watched this GDC17 presentation, but some things just don't make sense to me:

Altering amplitude based on currentGain AND noise value? This just makes all heights (large noise val like 1) do no alteration and the small ones to make the amplitude really tiny. How does that represent Altitude Erosion?

The audio also doesn't help much, has he isn't going into code detail.

Any ideas to makes sense out of this?


texts: Unity3D Android - Move your character to a specific x position

texts:
I want to move my character (which is a cube for now) to a specific x location (on top of a flying floor/ground thingy) but I've been having some troubles with it. I've been using this script:

var jumpSpeed: float = 3.5;
var distToGround: float;

function Start(){
    // get the distance to ground
    distToGround = collider.bounds.extents.y;
}

function IsGrounded(): boolean {
    return Physics.Raycast(transform.position, -Vector3.up, distToGround + 0.1);
}

function Update () {
    // Move the object to the right relative to the camera 1 unit/second.
    transform.Translate(Vector3.forward * Time.deltaTime);

    if (Input.anyKeyDown && IsGrounded()){
        rigidbody.velocity.x = jumpSpeed;
    }
}

And this is the result (which is not what I want):

https://www.youtube.com/watch?v=Fj8B6eI4dbE

Does anyone have any idea how to do this? I'm using UnityScript (Javascript).


texts: Loading a vertex shader compiled by Visual Studio 2012

texts:
I've got an extremely simple vertex shader that Visual Studio 2012 compiles into a .cso file. Now I want to load this file and create a vertex shader on the graphics device using the ID3D11Device::CreateVertexShader function.

So far I have the following code:

ifstream vs_stream;
size_t vs_size;
char* vs_data;

vs_stream.open(vsCompiledPath, ifstream::in | ifstream::binary);
if(vs_stream.good())
{
    vs_stream.seekg(0, ios::end);
    vs_size = size_t(vs_stream.tellg());
    vs_data = new char[vs_size];
    vs_stream.seekg(0, ios::beg);
    vs_stream.read(&vs_data[0], vs_size);
    vs_stream.close();

    result = device->CreateVertexShader(&vs_data, vs_size, 0, &m_vertexShader);
    if(FAILED(result))
    {
        return false;
    }
}
else
{
    return false;
}

I seem to be able to load the file fine, I get sane values in vs_size and vs_data however CreateVertexShader returns E_INVALIDARG and sets m_vertexShader to null.

How can I fix this error?

note that I can't use anything in the d3dx* headers since they are not supported in the Windows 8 App store


texts:
I am writing a 2D game where my game world has x axis running left to right, y axis running top to bottom, and z axis out of the screen:

Whilst my game world is top-down, the game is rendered on a slight tilt:

I'm working on projecting from world space to screen space, and vice-versa. I have the former working as follows:

var viewport = new Viewport(0, 0, this.ScreenWidth, this.ScreenHeight);
var screenPoint = viewport.Project(worldPoint.NegateY(), this.ProjectionMatrix, this.ViewMatrix, this.WorldMatrix);

The NegateY() extension method does exactly what it sounds like, since XNA's y axis runs bottom to top instead of top to bottom. The screenshot above shows this all working. Basically, I have a bunch of points in 3D space that I then render in screen space. I can modify camera properties in real time and see it animate to the new position. Obviously my actual game will use sprites rather than points and the camera position will be fixed, but I'm just trying to get all the math in place before getting to that.

Now, I am trying to convert back the other way. That is, given an x and y point in screen space above, determine the corresponding point in world space. So if I point the cursor at, say, the bottom-left of the green trapezoid, I want to get a world space reading of (0, 480). The z coordinate is irrelevant. Or, rather, the z coordinate will always be zero when mapping back to world space. Essentially, I want to implement this method signature:

public Vector2 ScreenPointToWorld(Vector2 point)

I've tried several things to get this working but am just having no luck. My latest thinking is that I need to call Viewport.Unproject twice with differing near/far z values, calculate the resultant Ray, normalize it, then calculate the intersection of the Ray with a Plane that basically represents ground-level of my world. However, I got stuck on the last step and wasn't sure whether I was over-complicating things.

Can anyone point me in the right direction on how to achieve this?


texts:
I am working on a simulation project that requires me to have entities walking around in a 3D world. I have all that working, matrix transformations, etc. I'm at the point where I need what is essentially a view frustum, so I can give each entity a visible area. However, when looking over the calculations required to do it, it seems like a perspective frustum is only required to be able to project it onto a 2D screen. Is there another, easier to code solution, that would function better, such as an orthogonal perspective? Could I just define a shape mathematically and test wether the coordinates of the objects are inside or out? I am not really a 3D coder (and I am doing this all from scratch, not using an engine or anything), so I would like the simplest solution possible for my needs.

Thank you!


texts:
So basically I'm using this:

 public bool IntersectPixels(Rectangle rectangleA, Color[] dataA,Rectangle rectangleB, Color[] dataB)
    {
        int top = Math.Max(rectangleA.Top, rectangleB.Top);
        int bottom = Math.Min(rectangleA.Bottom, rectangleB.Bottom);
        int left = Math.Max(rectangleA.Left, rectangleB.Left);
        int right = Math.Min(rectangleA.Right, rectangleB.Right);
        for (int y = top; y < bottom; y++)
        {
            for (int x = left; x < right; x++)
            {
                Color colorA = dataA[(x - rectangleA.Left) + (y - rectangleA.Top) * rectangleA.Width];
                Color colorB = dataB[(x - rectangleB.Left) + (y - rectangleB.Top) * rectangleB.Width];
                if (colorA.A != 0 && colorB.A != 0)
                {
                    return true;
                }
            }
        }
        return false;
    }

In order to detect collision, but I'm unable to figure out how to use it with animated sprites.

This is my animation update method:

public void AnimUpdate(GameTime gameTime)
    {
        if (!animPaused)
        {
            animTimer += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
            if (animTimer > animInterval)
            {
                currentFrame++;
                animTimer = 0f;
            }
            if (currentFrame > endFrame || endFrame <= currentFrame || currentFrame < startFrame)
            {
                currentFrame = startFrame;
            }
            objRect = new Rectangle(currentFrame * TextureWidth, frameRow * TextureHeight, TextureWidth, TextureHeight);
            origin = new Vector2(objRect.Width / 2, objRect.Height / 2);
        }
    }

Which works with multiple rows and columns.

and how I call the intersect:

    public bool IntersectPixels(Obj me, Vector2 pos, Obj o)
{
Rectangle collisionRect = new Rectangle(me.objRect.X, me.objRect.Y, me.objRect.Width, me.objRect.Height);
                    collisionRect.X += (int)pos.X;
                    collisionRect.Y += (int)pos.Y;
if (IntersectPixels(collisionRect, me.TextureData, o.objRect, o.TextureData))
{
    return true;
}
return false;

}

Now my guess is that I have to update the textureData everytime the frame changes, no?
If so then I already tried it and miserably failed doing so

Any hints, advices?

If you need to see any more of my code just let me know and I'll update the question.

Updated almost functional collisionRect:

collisionRect = new Rectangle((int)me.Position.X, (int)me.Position.Y, me.Texture.Width / (int)((me.frameCount - 1) * me.TextureWidth), me.Texture.Height);

What it does now is "move" the block up 50%, shouldn't be too hard to figure out.

Update:

Alright, so here's a functional collision rectangle(besides the height issue)

collisionRect = new Rectangle((int)me.Position.X, (int)me.Position.Y, me.TextureWidth / (int)me.frameCount - 1, me.TextureHeight);

Now the problem is that it's still not getting the correct color values of the animated sprite.

So it detects properly but the color values are always:

R:0 G:0 B:0 A:0

↑↑↑ disregard that, it's not true after all.

For some reason now the collision area height is only 1 pixel..


texts:
I'm working on a flash game that saves your progress locally. These saves can easily be hacked. My solution is to add an md5 hash of all the variables saved into the save file itself. When loading the save, the game would check if the hash is valid.
Is this a good solution? Are there better solutions?


texts: What is instancing, and how can I update my graphics code to do it?

texts:
This question directly follows on from this one:

How can I implement a renderer that can draw many kinds of primitives?

I have a small amount of drawing code structured in the following way:

A mesh object can be instantiated with different configurations of vertices and indices in order to form any desired shape. A reference to this mesh is then passed to every gameObject class, this class holds spacial information and a draw method that combines this data with that of the mesh to draw that object with the proper transforms.

The mesh is simply responsible for holding pointers to the appropriate buffers.

I was under the impression (wrongly I think) that because I actually only have one object of each type that I'm drawing multiple times, that this WAS instancing. I know this isn't the case.

What EXACTLY is the difference between what I'm doing and hardware instancing and what changes do I need to make to achieve it?


texts: How to balance spawn system with multiple objects?

texts:
I'm trying to make a top-down endless runner.

I have divided my screen into 3 columns. Right now I have some objects spawned from the bottom of the screen that go up towards the top. I have 3 different types and each of them has a random speed between 4 and 8 and can be spawned at intervals that vary from 0.2f to 2f.

I've noticed though that it may happen that these objects are spawned in a way that it is impossible for the player to dodge them (all the 3 columns are occupied by these obstacles on the same line).

Is there a way to check if this scenario is going to happen in the next wave and to, for instance, destroy one obstacle out of those. How could this be done?


texts: How does Speed in Animator Window in Unity work?

texts: If speed 1 is considered normal playback, is it by a second? So animation play once in a second? If I have my animator speed set as 100, would it make the speed become 0.06 then ?


texts: What is the difference between a Sprite and a Texture?

texts:
I have an assignment due for University, and my task is to discuss textures used within video games, and how they have evolved.

My main question is, what is the fundamental difference between using a sprite, or using other texture methods?

Having done a little research myself, I seem to be inclined that Sprites store images in a single file, and can be used for animations etc.. and were commonly used with older video games, generally using sprites as all of their game visuals. Now, with modern games, sprites I believe tend to be less used as technology advances and other textures are available such as bump mapping. Although sprites are still used today to accommodate features such as a health bar or long distance textures.

But what are the main advantages of using textures, over sprites?


texts: How to implement line of sight restriction in actionscript?

texts:
I have a problem with a game i am programming. I am making some sort of security game and i would like to have some visual line of sight. The problem is that i can't restrict my line of sight so my cops can't see through the walls. Below you find the design, in which they can look through windows, but not walls. Further below you find an illustration of what my problem is exactly.

this is what it looks like now. As you can see, the cops can see through walls.

This is the map i would want to use to restrict the line of sight.

So the way i am programming the line of sight now is just by calculating some points and drawing the sight accordingly, as shown below. Note that i also check for a hittest using bitmapdata to check whether or not my player has been spotted by any of the cops.

private function setSight(e:Event=null):Boolean
{
    g = copCanvas.graphics;
    g.clear();

    for each(var cop:Cop in copCanvas.getChildren())
    {
        var _angle:Number = cop.angle;
        var _radians:Number = (_angle * Math.PI) / 180;
        var _radius:Number = 50;

        var _x1:Number = cop.x + (cop.width/2);
        var _y1:Number = cop.y + (cop.height/2);
        var _baseX:Number = _x1 + (Math.cos(_radians) * _radius);
        var _baseY:Number = _y1 - (Math.sin(_radians) * _radius);

        var _x2:Number = _baseX + (25 * Math.sin(_radians));
        var _y2:Number = _baseY + (25 * Math.cos(_radians));
        var _x3:Number = _baseX - (25 * Math.sin(_radians));
        var _y3:Number = _baseY - (25 * Math.cos(_radians));

        g.beginFill(0xff0000, 0.3);
        g.moveTo(_x1, _y1);
        g.lineTo(_x2, _y2);
        g.lineTo(_x3, _y3);
        g.endFill();
    }

    var _cops:BitmapData = new BitmapData(width, height, true, 0);
    _cops.draw(copCanvas);

    var _bmpd:BitmapData = new BitmapData(10, 10, true, 0);
    _bmpd.draw(me);

    if(_cops.hitTest(new Point(0, 0), 10, _bmpd, new Point(me.x, me.y), 255))
    {
        gameover.alpha = 1;
        setTimeout(function():void{ gameover.alpha = 0; }, 5000);
        stop();

        return true;
    }

    return false;
}

So now my question is: Is there someone who knows how to restrict the view so that the cops can't look through the walls? Thanks a lot in advance.

ps: i have already looked at this tutorial by emanuele feronato, but i can't use the code to restric the visual line of sight.


texts: Gamemaker: Making a bullet Spawn at the enemy it was called from

texts:
I'm making a gamemaker game with gml. In this game I have multiple enemies (same object) on screen at the same time. I want them to all spawn a bullet at their location. But instead each enemy spawns a bullet at one single enemy. They all shoot but the bullets appear in the wrong location. I want the bullet to spawn at the location of the instance is was called for. How do I do this?

Thank you for reading my question.

Code:
obj_carrier is the enemy I want to spawn from.
obj_carrier_bullet is the bullet I want to spawn at location of the carrier
There are multiple carriers around the stage.
In the step event of the carrier following an if statement:

   instance_create(obj_carrier.x, obj_carrier.y, obj_carrier_bullet)


texts:
I got some scaled cubes (1, 2.5, 1) in a 3D Space with a grounded floor with position (0, 0, 0) and scale (100, 0, 100) like in the picture. But why are the cubes scaled out from the center. I want to level them on top of the ground.

This is my matrix manipulation code:

Matrix4f.scale(scale, mMatrix, mMatrix);
Matrix4f.translate(position, mMatrix, mMatrix);

So how is OpenGL scaling my cube, How can I level it?


texts:
I have developed an iOS game and currently the game is in beta phase. I have integrated Google Analytics (GA) to understand the users' behavior. I am distributing the game to my beta testers using TestFlight.

Recently, I found that number of sessions shown by TestFlight data is not matching with that of GA's data.

I have following questions:

Is GA's data is more reliable than the TestFlight's data?
Is GA suitable analytics solution for mobile games? If not, what are the reasons for that? Is Firebase analytics more reliable compared to GA?
I am looking for an analytics solution which can help to analyze behavior of each user (per user tracking instead of aggregated data). Can Firebase analytics provide this feature?

I would appreciate any suggestions and thoughts on this topic. Thank you.


texts: When is it best to load screens in mobile games?

texts: In the develpment of a mobile game, is it a good to load all the screens at the start of the game, or destroy and create new ones during the game? I am doing the second thing, because I suppose that the first one consumes a lot of memory, what's recommended?


texts: Syncing Sprites themselves over a Network

texts:
Ok, just found out I can't use [SyncVar] for a sprite gameobject. Furthermore that, [SyncVar] works only on simple values. My question is How would I go about syncing a Sprite over a network?

To explain the context for where I need it, I have a code for players to select an Avatar to play with. Player 'A' and 'B' are able to change their avatars in their own respective device. But the changes made by player 'A' are not reflected in 'B' and vice versa.

So the question is How do I sync a Sprite GameObject?

Note: I am using unity 5.4 and unity's default multiplayer system.


texts: javascript efficient collision detection

texts:
I have a processing game where I am having serious lag problems with collision detection. I am using the most effective code I can think of however after about 9 levels in The game gets unbearably laggy. I would show you the code but site wont handle my less thans.

If you want to check the program out you can find it here:
https://www.khanacademy.org/computer-programming/tanks-v1245/6637554186715136
under the tankMelee function ~line 160


texts: How do I make sure my tic-tac-toe AI always plays to a draw?

texts: I'm working on a little project. The aim is to play Tic-Tac-Toe against an AI, but I require that the game always results in a draw against the AI opponent. How can I implement the AI to ensure that?


texts:
I'm using SDL2 with .NET bindings. Keyboard handling is encapsulated in static class, and keyboard handling code part looks like this:

// class members
private static int _numkeys;
private static IntPtr _keysBuffer;
private static byte[] _keysCurr = new byte[(int)SDL_Scancode.SDL_NUM_SCANCODES];
private static byte[] _keysPrev = new byte[(int)SDL_Scancode.SDL_NUM_SCANCODES];

// called once, to get buffer pointer
_keysBuffer = SDL_GetKeyboardState(out _numkeys);

// update keyboard state each frame
var tmp = _keysPrev;
_keysPrev = _keysCurr;
_keysCurr = tmp;
// copy new state
Marshal.Copy(_keysBuffer, _keysCurr, 0, _numkeys);

all is workig as expected mostly, however once in while one of the following behavior occurs:

Physical key is pressed, but no key press is detected. Keypress is detected after key repeat interval.
Physical key is pressed, but no key press is detected. Lasts for infinite amount of time.

For example, I press Right (D), the movement to right starts, shortly after I press Fire (SPACE), movement is stopped, no firing occurs, then after key repeat interval firing starts, but movement to Right is stopped despite key is also still pressed.

Unfortunatelly I have both 1) not discovered 100% reproducible pattern for the bug yet (seems like it happens on burst sequental presses), 2) have no ideas what is the cause.

For now I just want, a fresh view on my code (is it solid?) and maybe some ideas on what to check. Thanks!


texts: Unity's particles look dull (mobile/additive)

texts:
I've created a couple VFX for a project and exported them as a unitypackage. Now, I want to showcase each effect and created a new project for that. However, the particles all look very dull and it seems like they're not using the additive shader of the particle correctly. I've tried to mess around in the project quality settings, but nothing has changed. They're both using the default URP. I've also checked the camera settings for both projects, but I think that's the wrong place either way, because they look wrong in the scene view, as well. I'm not sure where else to look?

The right particle system is displaying the effect correctly (bright with transparency) while the left one is the same system after importing to another project. I want the left system to look like the one on the right.

Edit: Even when just display 2 particles being spawned on top of each other in prefab view, the current project is much duller. It doesn't look like additive blend at all.


texts:
I am developing a game in XNA and am trying to create an effective AI for the enemy and friendly spaceships but am having a hard time keeping the game effective without disadvantaging one side or the other (deliberately). My current setup is as follows:

Ship targets enemy based on proximity.
Ship changes direction and moves toward target, firing when in range. Ship fires single repeater weapon in the forward direction.
Ship will not change direction when closer than certain distance from enemy.
If you are directly following and shooting at a ship, the ship does not attempt to evade fire. (consequence of #3)
All ships have similar firepower.

I am trying to improve this system and am willing to rewrite if necessary. Most of the ships end up flying around each other, shooting but never hitting. I have thought of several ideas to improve it:

Once health drops significantly, ship will boost away from firing ship.
Some ships are randomly chosen to be equipped with torpedoes (maybe add aft firing?).
Make ships more wary of attacking cruisers (they tend to die quickly when attacking).

Does anyone have any other suggestions as to improve the AI of the ships? Does anyone have a completely different system of doing this?


texts: Calculate the best route for racing games

texts:
I'm trying to structure a system for rating player's performance in my arcade-style racing game. So I'm thinking about calculating the best route possible, and trying to guide the player towards the best way of driving.
Is there any work into such problem? Links to papers/implementations would be awesome.


texts: XNA Framework and looking around relative to the world instead of camera?

texts:
So I've been toying around with creating a game in the XNA framework. A great place to start is simply being able to move and walk around.

I kinda have looking around...

I start off with the camera position/direction as follows:

cameraDirection = Matrix.CreateLookAt(new Vector3(0, 0, 1.5f), new Vector3(0, 1, -1), Vector3.Up);

I also have a small cube rendered in a static location, on which I plan to walk around. I'm manipulating the cameraDirection from a controller as follows:

GamePadState one = GamePad.GetState(PlayerIndex.One);
if (one.Buttons.Back == ButtonState.Pressed)
    this.Exit();
if (one.ThumbSticks.Right.Length() > .1f) {//Deadzone, must push stick at least 10%
    cameraDirection *= Matrix.CreateRotationY((float)(gameTime.ElapsedGameTime.TotalMilliseconds * (.002 * one.ThumbSticks.Right.X)));
    cameraDirection *= Matrix.CreateRotationX((float)(gameTime.ElapsedGameTime.TotalMilliseconds * (-.002 * one.ThumbSticks.Right.Y)));
}

And at first this appeared to work. Then I realized that the X and Y axes are relative to the camera's current orientation. If I turn left and right while looking straight forward, that appears to work. If I look straight down and then turn left and right, I'm rotating along a different axis. I want to look around in relation to the world's axes instead of the camera's... How can I do this?


texts: Problem calculating normals for heightmaps

texts:
So far I have been using normal avering to calculate the normals for my vertices in my heightmap, with good graphical result (see picture), however it is terribly slow. With a incresing image size the calculation time increases exponationally.

So I wanted to try implementing this algorithm insteed, but it isn't going very well. I have tried to trow around the variables a bit and tried diffrent combinations but nothing seems to work. Something that seems to be recurring is this shadow line pattern i get everywhere (the picture is a bit dark but i hope you can see the pattern).

My best guess to why this isnt working is because the algorithm isnt taking 2 of the neighboring vertices in to account in the calculation (See picture, blue is vertice we are trying to calculate normal for, green is the ones used in algorithm, red isnt used)

However, this algorithm seem to pop up in alot of places so that makes me think it has to be rigth. So im not sure if im doing it wrong somehow or if the algorithm is wrong. I was hoping some of you guys had runed in to the same problem and could give me some tips to what might cause this problem.

This is my translation of the algorithm im using

int cols = hmInfo.terrainWidth;
int rows = hmInfo.terrainHeight;

#define height(x, y)  hmInfo.heightMap[(y*cols) + x].y
XMVECTOR normal;
for(DWORD y = 0; y < rows; ++y)
{
    for(DWORD x = 0; x < cols; ++x)
    {

        float sx =  height( x < cols-1 ? x+1 : x, y) - height(x ? x-1 : x, y);
        if (x == 0 || x == cols-1)
              sx *= 2;

        float sy =height( x , y < rows-1 ? y+1 : y)- height(x, y ?  y-1 : y);
        if (y == 0 || y == rows -1)
            sy *= 2;

        normal=  XMVectorSet(-sx , 2.0f,  sy , 0.0f);
        normal = XMVector3Normalize(normal);

        tempSubset.vertices[y*cols+x].normal = XMFLOAT3(XMVectorGetX(normal),XMVectorGetY(normal), XMVectorGetZ(normal));

    }
}

PS. Seeing how it works with normal averaging im fairly sure that all other parts of the program is working fine DS.


texts: Why can't I add a float4 read from a Texture2D.Sample in the Vertex Shader?

texts:
These lines work (compile fine):

float4 offset = HeightMap.Sample(HeightSampler, input.Texcoord);
input.Position.xyzw += float4(0, 1, 0, 0);

These do not (any use of offset together with input/output Position causes the error):

float4 offset = HeightMap.Sample(HeightSampler, input.Texcoord);
input.Position.xyzw += offset;

No matter what I try to do to use the offset values to change the positions it breaks:

float4 offset = HeightMap.Sample(HeightSampler, input.Texcoord);
matrix<float, 4, 4> offs = {
    1, 0, 0, 0,
    0, 1, 0, 0,
    0, 0, 1, 0,
    offset.x, offset.y, offset.z, 1
};

output.Position = input.Position;
output.Position = mul(output.Position, offs);

Debug output:

(32,9): error X4532: cannot map expression to vs_5_0 instruction set
(62,19): There was an error compiling expression
(49): Error compiling effect hr=S_OK (0x00000000)

Anyone have an idea why?


texts: How to execute code every x seconds in unity?

texts:
So I have a flashlight battery script I created and I need to know how do you make the battery variable go down every few seconds(whatever time you set.) I tried InvokeRepeating but it was an absolute disaster (The battery variable just went down really fast and ignored my script). Anyways this is the code I have:

void Update ()
{
    if (light == false) {
        battery+=0;
    }
    if (light == true) {
        battery--;//This is what I want to have every few seconds
    }

    if (battery == 0) {
        myLight.enabled = false;
        light =false;
        battery++;
        InvokeRepeating("invoke", 1, 0.01F);
    }
}

void invoke(){
    light = false;
    myLight.enabled = false;
}


texts:
We are developing a 2D game for Android on Unity. It's our first project, we don't have a lot of knowledge on Unity. We have 2 scenes, in first scene there is only a "Play" button. When that button clicked, other level loads.

void Update () {
    startButton.onClick.AddListener(() =>
    {
       Application.LoadLevel(1);
    });
}

Problem is; when we click on Play button, it takes at least 10 seconds to load other level. There isn't much objects on other level so it shouldn't take that much time to load. Sometimes it takes 20 seconds and sometimes game freezes and level won't load. How can we reduce that loading time?


texts: How can someone make 3D tiles not looking like perfect cubes?

texts:
Here are the graphics an artist did for me:

While the texture is nice when seen as image file, I think the tile is somewhat flat.

The problem is:

If he bevel the cube, then there will be tiling problems (not to mention seams between cubes). How can he make tile looks less flat?

If he make the 3D model to act like 2D isometric Tiles (which have very irregular outline) there will be so much polygons that will be a nightmare for him to model dozen of Tiles.

Of course keep in mind that for occluding reasons (each cube project 6 planes that are used to occlude hidden geometry) the overall shape should be actually bigger than a cube volume, but not smaller (anyway I can loose the height requirement, cubes can be made of any height).


texts:
In Vavio, how do you make an enemy aim at the player then shoot a bullet? Here's the code I tried:

LevelSpawnData/spawnData-L0.json

{
"spawns": [
    {
      "time": 3.2,
      "leave": 12.8,
      "pattern": "Test/aim.lua",
      "movement": "Test/move.lua",
      "model": "circle",
      "material": "red",
      "x": 0.5
    }
  ]
}

Patterns/BulletSpawning/Test/aim.lua

bullet = pattern.NewBullet()
bullet.speed = 3
bullet.angle = ??? -- Want to set this to angle towards player
pattern.SpawnBullet(bullet)


texts: How to get a translation vector in a certain direction? SAT

texts:
I'm using the seperating axis thereom for discrete collision detection. I have code to find the minnimum translation vector (or distance) to seperate two shapes but how can I adjust it to get a vector in a certain direction that seperates the shapes? For example: If a box A is overaping box B 10 pixels horizontaly and 40 pixels vertically the MTV would calculate to move the box horizontally 10 px or so but I want to seperate the boxes vertically (move 40px up). How can I adjust my code to calculate a MTV in a direction of my choosing?

    const Vector2 ShapeImpl::CalcDisplacement(const AxesVec &axes, const Shape &a, const Shape &b) const
{
    Vector2 displacement;
    Precision_t Overlap = std::numeric_limits<Precision_t>::infinity();
    Axis smallest;

    for (auto && axis : axes)
    {
        const Projection pA = b.Project(axis);
        const Projection pB = a.Project(axis);

        // No Collision
        if (!pA.IsOverlap(pB))
            return Vector2(0, 0);

        else
        {
            const Precision_t o = pA.GetOverlap(pB);

            if (std::abs(o) < std::abs(Overlap))
            {
                Overlap = o;
                smallest = axis;
            }
        }

}

    displacement = smallest * Overlap;

    return displacement;
}


texts: Unproject mouse position to tile -- extremely jumpy position?

texts:
I'm trying to unproject the mouse position to get the position on the X-Z plane of a ray cast from the mouse. The camera is fully controllable by the user. Right now, the algorithm I'm using is...

    private bool getHoveredCorner(ArcBallCamera camera, System.Windows.Point m, out int tx, out int ty)
    {
        tx = -1; ty = -1;
        Ray ray = camera.unproject((float) m.X, (float) m.Y);
        Vector3 p = ray.Position + (-ray.Position.Y / ray.Direction.Y) * ray.Direction;
        float u = p.X / totalWidth;
        float v = p.Z / totalHeight;
        if(u < 0 || u > 1 || v < 0 || v > 1) return false;
        tx = (int) Math.Round(u * tileWidth);
        ty = (int) Math.Round(v * tileHeight);
        return tx >= 0 && tx <= tileWidth && ty >= 0 && ty <= tileHeight;
    }

And camera.unproject is...

    public Ray unproject(float x, float y)
    {
        Matrix m = viewProj;
        Vector3 p1 = Vector3.Unproject(new Vector3(x, y, 0), 0, 0, width, height, nearPlane, farPlane, m);
        Vector3 p2 = Vector3.Unproject(new Vector3(x, y, 1), 0, 0, width, height, nearPlane, farPlane, m);
        Vector3 dir = p2 - p1;
        dir.Normalize();
        return new Ray(p1, dir);
    }

The problem is that the projected position is "jumpy". As I make small adjustments to the mouse position, the projected point moves in strange ways. For example, if I move the mouse one pixel up, it will sometimes move the projected position down, but when I move it a second pixel, the project position will jump back to the mouse's location. The projected location is always close to where it should be, but it does not smoothly follow a moving mouse. The problem intensifies as I zoom the camera out. I'm not sure what's causing the problem, but I'm thinking it might be numerical instability?

EDIT 1: Video showing the problem

EDIT 2: A little snooping around in .NET Reflector on SlimDX.dll:

public static Vector3 Unproject(Vector3 vector, float x, float y, float width, float height, float minZ, float maxZ, Matrix worldViewProjection)
{
    Vector3 coordinate = new Vector3();
    Matrix result = new Matrix();
    Matrix.Invert(ref worldViewProjection, out result);
    coordinate.X = (float) ((((vector.X - x) / ((double) width)) * 2.0) - 1.0);
    coordinate.Y = (float) -((((vector.Y - y) / ((double) height)) * 2.0) - 1.0);
    coordinate.Z = (vector.Z - minZ) / (maxZ - minZ);
    TransformCoordinate(ref coordinate, ref result, out coordinate);
    return coordinate;
}

// ...

public static void TransformCoordinate(ref Vector3 coordinate, ref Matrix transformation, out Vector3 result)
{
    Vector3 vector;
    Vector4 vector2 = new Vector4 {
        X = (((coordinate.Y * transformation.M21) + (coordinate.X * transformation.M11)) + (coordinate.Z * transformation.M31)) + transformation.M41,
        Y = (((coordinate.Y * transformation.M22) + (coordinate.X * transformation.M12)) + (coordinate.Z * transformation.M32)) + transformation.M42,
        Z = (((coordinate.Y * transformation.M23) + (coordinate.X * transformation.M13)) + (coordinate.Z * transformation.M33)) + transformation.M43
    };
    float num = (float) (1.0 / ((((transformation.M24 * coordinate.Y) + (transformation.M14 * coordinate.X)) + (coordinate.Z * transformation.M34)) + transformation.M44));
    vector2.W = num;
    vector.X = vector2.X * num;
    vector.Y = vector2.Y * num;
    vector.Z = vector2.Z * num;
    result = vector;
}

...which seems to be a pretty standard method of unprojecting a point from a projection matrix, however this serves to introduce another point of possible instability. Still, I'd like to stick with the SlimDX Unproject routine rather than writing my own unless it's really necessary.


texts: How can I use Cocoa beans in Minecraft Forge custom crafting recipes?

texts:
I'm creating a Minecraft mod with Forge, and I need to create a custom crafting recipe that uses cocoa beans. However, when I try to create the recipe, it does not work (as in, I cannot craft items with the specified pattern).

When src/main/resources/assets/mymod/recipes/myrecipe.json looks like this, it works fine:

{
    "type": "minecraft:crafting_shaped",

    "pattern": [
        " X ",
        " X ",
        " X "
    ],

    "key": {
        "X": {
            "item": "minecraft:iron_ingot"
        }
    },

    "result": {
        "item": "minecraft:gold_ingot",
        "count": 1
    }
}

but when it looks like this, I can't craft items with the recipe:

{
    "type": "minecraft:crafting_shaped",

    "pattern": [
        " X ",
        " X ",
        " X "
    ],

    "key": {
        "X": {
            "item": "minecraft:cocoa_beans"
        }
    },

    "result": {
        "item": "minecraft:gold_ingot",
        "count": 1
    }
}

According to https://minecraft.gamepedia.com/Cocoa_Beans#ID, the name ID for cocoa beans is minecraft:cocoa_beans, which is exactly what I entered. However, the crafting recipe does not seem to be loaded into the game.

Why isn't the second crafting recipe working and how can I fix it?

I'm using Forge version 1.12.2-14.23.5.2768 and Eclipse version 2018-09 (4.9.0), and I'm running Minecraft directly from Eclipse.


texts: Finding a suitable axis-angle to avoid gimbal lock

texts:
In OpenGL the camera faces the -z axis with the +y axis pointing up. I am using quaternions to represent the orientation of my objects (which works well) and am trying to do the same for the camera. I want the camera's initial orientation rotation to face the +x axis with the up vector being +z. I was attempting to initialize the camera's quaternion rotation by multiplying two 90 degree rotation quaternions in an effort to achieve this, but I believe I am experiencing gimbal lock because I cannot orient the camera properly (the first rotation works fine, the second one produces undesired results). I haven't been able to wrap my head around an axis-angle representation that will orient the camera the way I want.

In summary:

I'm searching for an axis angle (or anything that can be converted to a quaternion really) that will provide the following rotation:

inital camera orientation: facing -z axis, +y pointing up

desired orientation: facing +x axis, +z pointing up

Note: I am already aware of gluLookAt, this problem was my attempt at understanding more about how everything works.


texts: How were cartridge-based games programmed?

texts:
I'm thinking of like the SNES, N64, Atari... even the DS today, I suppose.

SNES games did not usually take up more than 4 MB of space, and N64 games were usually 32 to 64 MB worth of data.

These days, you can barely compile a "hello world!" program without the resulting compilation generating 1.21 gigabytes!! of data. (Joking aside, files today do take up tons and tons of space compared to some of the technology back then.)

So... how did they do it?

What did they program these games in? ASM? The entire thing in ASM?!
How were graphics created? What technology did they have to create sprite sheets and, in some cases (like the N64), 3D models?
How did they fit so many levels, characters, quests and items on these cartridges? I mean, Super Mario World on the SNES clocks in around 1 MB, and it has 96 exits! Ocarina of Time, Banjo-Kazooie, DK64 and a few other games take up less than 64 MB and had huge worlds, tons of content and 3D models!

Sorry if my questions seem a little out-there, I'm just amazed that a lot of great titles out there managed to fit in such a small storage space.

It's fascinating to me because even tiniest and most trivial of files and games manage to take up at least a few MB, so imagining that huge levels like those in GoldenEye 007 managed to take almost no data at all is mind-blowing.


texts:
I'm currently building a fragment shader which is using several textures to render the final pixel color.

The textures are not really textures, they are in fact "input data" to be used in the formula to generate the final color.

The problem I've got is that the texture are getting bi-linear-filtered, and therefore the input data as well. This results in many unwanted side-effects, especially when final rendered texture is "zoomed" compared to original resolution.

Removing the side effect is a complex task, and only result in "average" rendering. I was thinking : well, all my problems seems to come from the "default" bi-linear filtering on these input data. I can't move to GL_NEAREST either, since it would create "blocky" rendering. So i guess the better way to proceed is to be fully in charge of the interpolation.

For this to work, i would need the input data at their "natural" resolution (so that means 4 samples), and a relative position between the sampled points.
Is that possible, and if yes, how ?

[EDIT] Since i started this question, i found this internet entry, which seems to (mostly) answer my needs.
http://www.gamerendering.com/2008/10/05/bilinear-interpolation/

One aspect of the solution worry me though : the dimensions of the texture must be provided in an argument. It seems there is no way to "find this information transparently". Adding an argument into the rendering pipeline is unwelcomed though, since it's not under my responsibility, and translates into adding complexity for others.


texts: Style/technique to focus on for creating visual art assets efficiently

texts:
I'm mostly a programmer, but I'd like to be able to do competent work on other parts of games I make when working on solo projects.

What I'm specifically asking here is what sort of techniques or styles for visual asset creation should I study and use to be able to work with the most efficiency? Basically, what would end up being the least work as a whole, taking into account possible changes late on in the development, reuse of assets created for other projects, etc.

What I mean by "technique or style" here is things like vector art, digital painting, pixel art, poly modeling, sculpting, etc.

I'm mostly interested in comparisons of the various techniques as a whole. It's hard to get a good big picture view of the situation not having a lot of experience with doing real work with each technique. Also, obviously if you're making a 3D game you'll need to make 3D assets, but for now, let's talk about techniques for creating assets for a 2D game, where the assets could be either 2D or 3D.


texts: A python script controlling a Unity game

texts:
I wish to build a simple game in Unity such that the objects in the game can be controlled via a Python script (or a code in any other programming language). Is this possible? If yes then how? If no then are there any other alternatives to achieve similar results?

To make it more clear, say that I have 10 objects in my current scene. What I wish to do is to address each object individually via Python. One way of doing this is setting up keyboard bindings to select a particular object and then using keyboard and mouse events to control this object. But, is there a more cleaner (a native) way of doing the same?


texts: Move a 2D point to a target (first accelerate towards the target, then decelerate)

texts:
I have a point entity that I would like to move to a target point (in 2D).

I think I would like it to accelerate away from its current position (the point could already have a velocity), to some maximum velocity, and decelerate as it approaches the target, eventually coming to a stop on the target.

I think both the acceleration and deceleration should have constant magnitudes, but given that the entity can have a velocity, which may not be in the same direction as the target, the direction of the acceleration/deceleration could be different every frame.

I am not coding in any particular language or framework yet, and just want to know if this is easy/possible. Am I describing something that is quite common (like a targeted missile that stops at the target/an AI controlled space ship in a game)? If it is hard, is there another way I can achieve the same kind of motion?


texts: How do I fix "failed to set new screen configuration" when moving to fullscreen in Ubuntu?

texts:
So I used SFML to create a small C++ game for a class in a windows environment, using Visual Studio 2015. As a personal project, I tried to port the game over to a Linux environment, seeing as how SFML is advertised as multi-platform. However, upon doing so, I was met with some problems. I'm using Ubuntu 16.04 LTS, and nothing seems to be working correctly!

I tried making a test window that's 640x480, and then tried to make it fullscreen. The screen appears to be making the transition to fullscreen, but when I look at the terminal, every time I switch to fullscreen, it prints "failed to set new screen configuration". I checked the valid fullscreen resolutions on my monitor and 640x480 was one of them.

I'm about ready to give up on SFML and moving to SDL. Everything worked like a charm on a Windows environment, but migrating to Ubuntu has just been nothing but trouble. How do I fix my fullscreen?

Here is my fullscreen code:

if(keyReleased)
{
    keyReleased = false;

    if(style == FULLSCREEN)
    {
        this->create(sf::VideoMode(640,480,32), "WINDOW", sf::Style::Default);
        style = WINDOWED;
    }
    else
    {
        this->create(sf::VideoMode(640,480,32), "WINDOW", sf::Style::Fullscreen);
        style = FULLSCREEN;
    }
}


texts:
What is a good technique to enable an object to move between to points in a nice curved motion?

The end position could also be in motion, such as the trajectory of a homing missile.


texts:
What other options/alternatives are there to "edge split" for smooth shading low poly game models.

As I understand it, edge split does what it say's, its splits the mesh therefore increasing the vert count.  I have considered manually marking the edges as sharp however I would imagine this leaves artifacts on the model(in-game) ?

Cheers.


texts:
I'm working on a small C++ component based game engine, as such...

Object Foo might extend GameObject and x number of component interfaces, like Renderable and/or Physical. So let's assume that Foo looks like this:

class Foo : public GameObject, public Renderable { ... }

...and Renderable looks like this:

class Renderable
{
    virtual void render(void) = 0;
}

So, my engine is divided into sub-systems like the Renderer and AssetManager, etc. and all of those GameObjects are stored in some kind of container, for simplicity sake lets say it's an array.

My question is simple, it's the Renderer's job to hit up all of the game objects that are Renderable and do some work on them, how then can I test or know which objects are Renderable in this component-based approach?

Or furthermore, should I be testing each object in the first place or is there a better way for the Renderer to do it's job (perhaps the Renderable interface should attach each GameObject to a list maintained by the Renderer upon creation)?

Thanks, -Cody


texts:
I have two cubes, one parent and one child. I want to use the parent's cube mesh as a mask for the child cube. I want to make visible only the part of the child cube that it is inside the parent cube.

I can easily achieve this effect with 2D sprites using the Sprite Mask, but I can't find a way to do it for 3D areas or 3D objects.

What I have:

What I want:


texts: How fill gutter using ID3DXTextureGutterHelper interface?

texts:
Using UVAtlas (Direct3D 9) Packed charts are separated by a
  user-specified gutter width. The gutter width is the amount of
  separation between charts, and allows for bilinear interpolation and
  mip-mapping to avoid rendering artifacts at chart boundaries. D3DX
  provides an interface for automatically filling in these gutters - see
  ID3DXTextureGutterHelper for more information.

How I can do that? I call ApplyGuttersTex, after calling ResampleTex but nothing changed.


texts:
I want to import some 3d models to my javaFX application.

In javaFX I can create rectangles, traingles, circles, pentagons.
Those figures can be filled with color or filled with image.
They are called nodes. Nodes can be added to group and be visible ( nodes also can be rotated, scaled and translated ).

I want to import 3d model and it to be as a node, so I could add model to a group and rotate, scale and translate.

How can I achieve this?


texts: How to stack units in a tile based game?

texts: I'm trying to make it so that no more than 5 units can be stacked on a tile. I have a Tile class that creates each tile's preferences. Should I store the units in an array or arraylist in this class?


texts:
I'm interested in path finding between multiple maps - could be indoor/outdoor maps, different levels in a building etc but the main restraint is that there are one (or more) ingress/egress points between the different maps.  I've looked and couldn't find any good solutions, yet I'm aware of several games which use similar systems.

I've found this paper - Hierarchical Shortest Path Finding Applied to Route-Planning for Wheelchair Users which seems to address a similar issue, but it is purely theoretical.

Anyone done similar with some experience they could share, or some tips?


texts: Game runs at different speeds in Chrome versus Firefox

texts:
I am using Box2D for physics on the server side.
Player position is updated on the server, so there is nothing the client can do except give input.

But running game in Chrome only, the player moves faster as compared to running in Firefox only.

If running in both browsers (one player in each browser), then the game in both browsers runs at the speed at which it runs in Chrome.

Using this update loop:

function update() {

    for(let p of players){

        if(p.dead) continue ;

        p.keyEvents();

        aabb.lowerBound.Set( p.body.GetPosition().x-p.s_w/(2*scale),p.body.GetPosition().y-p.s_h/(2*scale) );//top left
        aabb.upperBound.Set( p.body.GetPosition().x+p.s_w/(2*scale),p.body.GetPosition().y+p.s_h/(2*scale) );//bottom right
        world.QueryAABB( ReportFixture , aabb , p.id );
        p.socket.emit('players',foundPlayers);

        foundBodies.players=[];

    }

    world.Step(
       1 / 60   //frame-rate
        ,  8       //velocity iterations
        ,  3       //position iterations
    );

    if(deletePlayerIds.length>0){
        deletePlayer();
    }

    world.ClearForces();
}

setInterval(update, 1000/60);//to call update loop

I have read that for Box2D there is no need to apply a delta.

What could be the reason for different speeds, and how it can be resolved?


texts: What exactly is the "blend factor" t in Color.Lerp?

texts:
I had a bit of a look around and couldn't see anywhere this was addressed, my apologies if it has been.

In Color.Lerp, I understand that the 3rd parameter t is not in fact the time that it takes to change between the colors but is rather the "blend factor". If the first color is at 0 and the second is at 1, then a blend factor of e.g. 0.2 would indicate it is closer to the first than the second.

My confusion is this - how exactly is it determined how long it takes the lerp to occur? I assume it's something to do with the frames per second? e.g. if the blend factor is 0.001 and frames per second are 50, with lerp in the update function then it should take 0.001 * 50 = 0.05 of a second for the change to occur?


texts: Center attribute of BoxCollider2D not working?

texts:
I've been trying to make a laser beam for my 2D shmup. I've set up a LineRenderer, along with a box collider 2D, and I've noticed that the center of the collider is positioned at one end of the line.

My settings are

Line

2 Elements

(1)0x 0y 0z
(2)0x 0y 10z

Not using World Space
Rotated 90 on the Z axis (to face the 2D camera)

I thought the Center attribute would align the box collider, but changing the X value seems to do nothing. Is it possible to align the box collider such that it is around the beam, and not sticking outside of it?

Image reference:


texts: Why does this simple if-statement that checks my main characters state never get called (Java/LibGDX)?

texts:
Been working on this for a while - basically I want my player to perform a front flip when he jumps (screen tap -> player jumps). I wrote the animation class Animator (extends Player implements ApplicationListener and my plan is to initialise it in Player (main character class) whenever his state becomes JUMPING. I did a few tests using System.print and found that when the screen is tapped (i.e. whenever touchDown() is called) the Player's state IS modified (using stateModifier("jumping").

However, the code inside if(state == playerState.JUMPING) in update() for some reason is never called. I know this is the case because the System.print I wrote never gets outputted. I'll throw my code in here since you will probably need to see the big picture:

public class Player extends GameObject implements InputProcessor {
private Animator jumpAnimation; // the class where the animation takes place
private playerState state; // enum of player states
private float gravity;
private boolean allowJump;
private float accelerationJump;
private Texture img;
private Sprite sprite;

public Player(float xPos, float yPos) {
    super(xPos, yPos);
    img = new Texture(Gdx.files.internal("JUMP1.png"));
    sprite = new Sprite(img);
    setxPos(xPos);
    setyPos(yPos);
    setxSpeed(4.6f);
    setySpeed(0);
    sprite.setX(getxPos());
    sprite.setY(getyPos());
    setType("player");
    gravity = 0.34f;
    accelerationX = 0.02f;
    accelerationJump = 14f;
    allowJump = true;
    Gdx.input.setInputProcessor(this);
    state = playerState.NORMAL;
}

// change the player state
public void stateModifier(String modify) {
    if (modify.equalsIgnoreCase("jetpack")) {
        state = playerState.JETPACK_MODE;
    } else if(modify.equalsIgnoreCase("normal")) {
        state = playerState.NORMAL;
    } else if(modify.equalsIgnoreCase("jumping")) {
        state = playerState.JUMPING;
        System.out.println(state);
}
}

public void update() {

    // Player's speed in the y plane is affected by gravity
    setySpeed(getySpeed() - gravity);
    // Player constantly moving
    moveBy(getxSpeed(), getySpeed());
    // Don't allow Player to fall below the ground due to gravity
    if (belowGround()) {
        moveTo(getxPos(), groundY);
    }
    // If Player is on the ground then he can jump, so set allowJump to true
    if (onGround()) {
        allowJump = true;
        setySpeed(0);
    }
    // if the player is in a jumping state, run the jump animation
    if (state == playerState.JUMPING) {
        // this print statement should get called when a player jumps but never does
        System.out.println("should animate right now");
        jumpAnimation = new Animator(getxPos(), getyPos());
    }
}

public void jump() {
    setySpeed(getySpeed() + accelerationJump);
}

@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    // if the player is in a normal state (i.e. not jumping) and he is allowed to jump
    if (state == playerState.NORMAL && allowJump) {
        // set player state to playerState.JUMPING
        stateModifier("jumping");
        jump();
                    // set player state to playerState.NORMAL after the jump
        stateModifier("normal");
        allowJump = false;
    }
    return true;
}

}

Any help is highly appreciated, thank you very much.

tl;dr when screen is tapped, touchDown() is called, which changes the Player's state to JUMPING. however when i write an if statement in update() to check for this, it never gets executed. why is this the case?


texts:
I am curious as to what algorithm/logic game AI/NPCs would use when discovering information about their environment.

There are two scenarios that I could envision.

The NPCs are all knowing in regards to elements in the environment, but choose to ignore them unless certain conditions are met (e.g. the guard will not "find" his fallen comrade's body unless he is x feet from the body)
The NPCs really do discover the environment by scanning it or something... (maybe similar to path finding?)

Maybe these are both used in conjunction...

Could anyone point me in the right direction towards any preferred methods?

I tried googling for this information, but could not find anything that seemed relevant.


texts: How can I make a "wet surface"/"shallow puddle" shader in Unity?

texts: In my game I need to create dynamic water puddles but I cannot find a tutorial that shows how I can make such an effect (an example of which is shown below). How can I do it?


texts:
In one of my projects I have a game area in the shape of a circle. Inside this circle another small circle is moving around. What I want to do is keep the small circle from moving outside the bigger one. Below you can see that in frame 2 the small circle is partly outside, I need a way to move it back to just before it is about to move outside. How can this be done?

Also, I need the collision point along the arc of the big circle so that I can update the small circle's velocity. How would one go about calculating this point?

What I would like to do is before moving the small circle, I predict its next position and if it is outside I find the time of collision between t=0 and t=1 (t=1 full time step). If I have the collision time t then I just move the small circle during t instead of a full time step. But again, the problem is I don't know how to detect at that time the collision occurs when it comes to two circles and one being inside the other.

EDIT:

Example of collision point (green) I want to find. Maybe the picture is a bit off but you get the idea.


texts: Running a WindowsGL MonoGame release on end Machine

texts:
Can anyone tell me what is required of a PC to run a released MonoGame.
I mean what software the PC needs to have installed to run the games.
I have some problems running my released games on other PC's than my developer machine. They simply stops responding when I try to run them.


texts:
I saw this question and was hopeful to find the answer to my question, but no such luck:
How do I make someone walk in Skyrim?

I want to, using papyrus ONLY, make Actors that I spawn to travel/patrol to a PatrolIdleMarker, preferably one that I create in the Papyrus script and set the coordinates for.

Example:
I want a bandit to appear at a random location but specific distance from the Player. Then I want the bandit to start moving towards the player, attacking the player. The script below works just fine for this:

ScriptName SomeQuestName extends Quest

ActorBase property LvlBanditMelee1H auto

Int[] BanditStatus
Actor[] Bandits

Event OnInit()
        Int MaxBandits = 11
        Bandits = new Actor[11]
        BanditStatus = new Int[11]
        int i=0
        while(i

Event OnUpdate()
        Float SpawnDistance = 15000.0
        Float ClearDeadDistance = 10000.0
        Float ClearAllDistance = 20000.0
        Int SpawnCounter = 0
        Int MaxBandits = 10
        if (PlayerRef.Z < 20000 && PlayerRef.GetWorldSpace() == Tamriel && (MQ101DragonAttack.IsCompleted() || MQ101DragonAttack.GetStage() > 195))
            int i = 0
            int j = 0
            while(i
                        if(VerboseDebug==1)
                            Debug.Notification("Bandit #" + i + " has wrong BanditStatus.")
                        EndIf
                    Else
                        Distance = PlayerRef.GetDistance(Bandits[i])
                        if((Bandits[i].IsDead() && Distance > ClearDeadDistance ) || Distance > ClearAllDistance )
                            If(BanditStatus[i]==2)
                                Bandits[i].Delete()
                                Bandits[i] = None
                                BanditStatus[i]=0
                            EndIf
                            if(BanditStatus[i]==1)
                                Bandits[i].Disable(true)
                                BanditStatus[i]=2
                            EndIf
                        EndIf
                    EndIf
                EndIf
                i+=1
            EndWhile

    RegisterForSingleUpdate(30.0)

EndEvent

But lets say I wanted the Bandit to just patrol passed the player, replacing the bandit with say an Imperial guard?

ActorBase property LvlGuardImperial auto

Removing one row to stop spawned actor to start attacking the player from a distance:
Bandits[i].StartCombat(PlayerRef)

And instead adding
Bandits[i].EnableAI()
won't work - the imperial guard will stand in one spot, only moving if combat starts close by or if the player comes into proximity and the guard is hostile to the player. If they are friendly the guard will simply stand/talk but not patrol or walk...

I need the codelines for adding creating a PatrolIdleMarker, LinkedReference or something else that I can set X,Y,Z to related to the Player, so that the spawned Actors will patrol passed the point where the player was when they spawned.

I have even tried to make them patrol to PatrolIdleMarkers already defined in vanilla Skyrim (Stable outside Solitude, Barracks in Falkreath etc), but the Actors will just not start patrolling/walking...

It also seems no forums are active anymore when it comes to Skyrim... I am so glad there will be a new release of Skyrim this fall (Skyrim Remastered) and hopefully some old modders will attend the forums again...


texts: Which data structure to use to render a large isometric game world?

texts: I'm starting development of a 2d isometric (tiled, roguelike) game and I'm brainstorming which kind of data structure I would use to store runtime data like tiles and entities, but I don't want to use a 2D array (as the world will be huge). How could I handle the rendering in such a case?


texts: Player jittering against wall when held down button

texts:
So, I'm making a top down RPG.

Everything's going excellent, but this problem is quite annoying. Now, when the character moves against the wall, the player jitters back and forth. I'm guessing it's because the player is trying to move into the wall, and then the wall collision is pushing it back, which makes an annoying back and forth movement. My question is obviously, how do I stop this from happening?

Thanks!

PS: I'm using transform.translate to move the player, and I'm using C#.

EDIT: I'm also using a 2D Rigidbody, and 2Dbox colliders on both.


texts:
Context

So in my current project (written in Java using LWJGL / OpenGL, so GLSL for shaders) I added lighting quite a few months ago, which was already an interesting challenge, having never done something like that before. Now I did my research, and in the past few days I found absolutely nothing particularly helpful about this subject (which was really surprising, I thought this to be a much more common problem), which is why I am asking here. Anyway, after a lot of searching around and asking for help, this is what the current lighting system looks like:

Desired effect

The current lighting is somewhat neat but not good enough, as I would like it to have an additional parameter for something like light width (currently there are already color, intensity, angle, smoothness and linear + quadratic attenuation parameters).

What I would like to achieve is an effect along the lines of this (paint.net mockup, but should make it clearer):

It sounds like such a simple thing to do and yet I can't get my head around how to do it (I thought about somehow having two different light positions and tracing lines between that or rotating the current fragment point in the fragment shader, but both seem incredibly slow and I don't even know where to start with them).

Edit

Here as requested the part of the fragment shader that's responsible for lighting:

for (int i = 0; i < numLights && i < MAX_LIGHTS; i++)
{
    if (lightColor[i].a > 0.0 && myDepth >= minAffectedDepth[i] && myDepth <= maxAffectedDepth[i])
    {
        if (isSpotLight[i])
        {
            lightDistance = lightPosition[i] - myPos;
            distance = length(lightDistance);
            spotEffect = dot(normalize(spotDirection[i]), normalize(-lightDistance));

            if (spotEffect > spotCosCutOff[i])
            {
                spotEffect -= spotCosCutOff[i];
                spotEffect /= (1.0 - spotCosCutOff[i]);

                spotEffect = pow(spotEffect, spotExponent[i]);
                attenuation = spotEffect / (1.0 + linearAttenuation[i] * distance + quadraticAttenuation[i] * distance * distance);

                color += attenuation * lightColor[i] * ownColor * lightColor[i].a;
            }
        }
        else
        {
            color += ownColor * lightColor[i] * lightColor[i].a;
        }
    }
}

TLDR;
I want to add "volumetric" lighting to my 2D project with GLSL, so a width parameter to the lighting system, which currently consists of punctual light sources (and for some reason, light sources in real life usually aren't perfectly punctual ;)).


texts: GLSL - Rewriting shaders from #330 to #130

texts:
I recently created a game (LD21) that uses a geometry shader to convert points into textured triangles/culling. Since I was under the impression that the support for #330 was widespread I only wrote #330 shaders, but it seems that a lot of not so old hardware only support #130 (according to GLView)
Now, since I'm only familiar with the #330 core functionality I am having trouble rewriting my shaders to #130. The fragment shader was quite trivial to rewrite, but I've only managed to get my vertex and geometry shader down to #150.
So, is it possible to rewrite the shaders, or would it require a lot of changes in my rendering engine?
Geometry shader
#version 150
layout(points) in;
layout(triangle_strip, max_vertices = 4) out;
uniform mat4 oMatrix;
in VertexData
{
    vec4 position;
    vec4 texcoord;
    vec4 size;
} vert;

out vec2 gTexCoord;

void main()
{
    if(vert.position.x>-4f && vert.position.x<4f && vert.position.y>-2f && vert.position.y<2f)
    {
        gTexCoord=vec2(vert.texcoord.z,vert.texcoord.y);
        gl_Position = vert.position + vec4(vert.size.x,vert.size.y,0,0);
        EmitVertex();

        gTexCoord=vec2(vert.texcoord.x,vert.texcoord.y);
        gl_Position = vert.position + vec4(0.0,vert.size.y,0,0);
        EmitVertex();

        gTexCoord=vec2(vert.texcoord.z,vert.texcoord.w);
        gl_Position = vert.position + vec4(vert.size.x,0.0,0,0);
        EmitVertex();

        gTexCoord=vec2(vert.texcoord.x,vert.texcoord.w);
        gl_Position = vert.position;
        EmitVertex();

        EndPrimitive();
    }
}

Vertex shader
#version 150
#extension GL_ARB_explicit_attrib_location : enable

layout (location = 0) in vec2 position;
layout (location = 1) in vec4 textureCoord;
layout (location = 2) in vec2 size;
uniform mat4 oMatrix;
uniform vec2 offset;
out VertexData
{
    vec4 position;
    vec4 texcoord;
    vec4 size;
} outData;

void main()
{
    outData.position = oMatrix * vec4(position.x+offset.x,position.y+offset.y,0,1);
    outData.texcoord = textureCoord;
    outData.size = oMatrix * vec4(size.x,size.y,0,0);
}


texts: How would you go about applying curvature to the rendering of a flat surface?

texts:
I want to draw a 2D planet surface. I have a set of tiles, which by themselves are flat if you draw them. Now I want to apply something to the drawing process, which makes it look curved the more you go to the edges of the screen (kind of like this). Does anyone have an idea how you could do that?

If its relevant, Im using the LibGDX framework for Java.


texts: Method subscribed to an event is called twice for every time the event is raised

texts:
I am trying to make an inventory system in Unity with ScriptableObjects and a text driver that displays the contents of an inventory. So far the code looks like this:
-An InventoryObject is defined as having a "Container" List of ItemObjects (simple scriptable objects, they just have a little information on the object as its sprite, its name, and whether or not it is stackable) and some methods to properly add or remove items (taking item stacking into account) from that list. https://pastebin.com/t4P3aGmi
-A PlayerInventory is a script that will be carried by the player's character. It contains a method for adding items collided with to its assigned InventoryObject instance. It also contains an OnItemPickedUp event that takes its InventoryObject instance as a parameter and passes it to listeners like UpdateDisplay. OnItemPickedUp is raised whenever a collision with a compatible item happens. https://pastebin.com/RsV7XYPp
-An UpdateDisplay script that listens to the OnItemPickedUp event and subscribes the
ProcessInventoryToSingleString(InventoryObject _inventory) method, that subsequently calls several methods to transform the contents of the InventoryObject's Container list into a single, formatted string. https://pastebin.com/N0nsvcWH
-The items are represented by giving a GameObject with a collider2D, aSpriteRenderer and script that contains the particular ItemObject's data and sets its SpriteRenderer's sprite to the ItemObject's.
The problem I'm having is that the method subscribed to the event is being called more than once for each time the event is raised. as shown by the debug logs. Sometimes it's called twice, sometimes even four. This results in my UI display showing more items than there are.
https://files.catbox.moe/afa467.mp4
https://files.catbox.moe/6oxh9b.mp4
Here are pictures of the console debug logs:

I appreciate any help.
EDIT: These errors also appear. I'd like to believe that they're unrelated.


texts: How to design context menus based on whatever the object is?

texts:
I'm looking for a solution for a "Right Click Options" behaviour.

Basically any and every item in a game, when right clicked, can display a set of options based on whatever the object is.

Right click examples for different scenarios:

Inventory: Helmet shows options (Equip, Use, Drop, Description)

Bank: Helmet shows options (Take 1, Take X, Take All, Description)

Floor: Helmet shows options (Take, Walk Here, Description)

Obviously each option somehow points to a certain method that does what is says. This is part of the issue I'm trying to figure out. With so many potention options for a single item, how would I have my classes designed in such a way as to not be extremely messy?

I've thought about inheritance but that could be really long winded and the chain could be huge.
I've thought about using interfaces, but this would probably restrict me a little as I wouldn't be able to load item data from an Xml file and place it into a generic "Item" class.

I'm basing my desired end result on a game called Runescape. Every object can be right clicked in the game and depending on what it is, and where it is (inventory, floor, bank etc.) displays a different set of options available to the player to interact with.

How would I go about achieving this? What approach should I take to first of all, decide which options SHOULD be displayed and once clicked, how to call the corresponding method.

I am using C# and Unity3D, but any examples provided do not have to be related to either of them as I'm after a pattern as opposed to actual code.

Any help is much appreciated and if I have not been clear in my question or desired results, please post a comment and I'll tend to it ASAP.

Here is what I have tried so far:

I've actually managed to implement a generic "Item" class that holds all of the values for different types of items (extra attack, extra defence, cost etc...). These variables get populated by data from an Xml file.
I have thought about placing every single possible interaction method inside of the Item class but I think this is unbelievably messy and poor form. I've probably taken the wrong approach for implementing this kind of system by only using the one class and not sub-classing to different items, but its the only way I can load the data from an Xml and store it in the class.
The reason I've chose to load all my items from an Xml file is due to this game having the possibility for 40,000+ items. If my math is correct, a class for each item is a lot of classes.


texts:
I'm trying to build an RPG worldbuilder. I have seperate classes for images. Like this.

Object1::Object1(int x, int y, CSDL_Setup *sdl_set, int *p_CamX, int *p_CamY)
{
    X_pos = x;
    Y_pos = y;

    MouseX = 0;
    MouseY = 0;

    CamX = p_CamX;
    CamY = p_CamY;

    Object = new CSprite(sdl_set->GetRenderer(),"data/Trees/Tree3.png", X_pos, Y_pos, 100, 200, CamX, CamY);

}

I've created a vector of objects of the class Object1 and pushing it back when I create a new image. I draw them here.

void DrawObjects()
{
    for(std::vector<Object1*>::iterator i = Object.begin(); i != Object.end(); ++i)
    {
        (*i)->Draw();
    }
}

Now the rendering is done by the order the objects are created. I want to do the rendering based on y values of each object. I did a lot of research but couldn't find any example code. I also have other classes for other images. So I tried something on my own to sort y values and detect which y value corresponds to which object. But I'm stuck here.

int a;
void DoChanges()
{
    if(ChangeMade)
    {
        a = 0;

        for(std::vector<Object1*>::iterator i = Object1.begin(); i != Object1.end(); ++i)
        {
            ObjectArray[a] = (*i)->GetY();
            a++;
        }
        for(std::vector<Object2*>::iterator i = Object2.begin(); i != Object2.end(); ++i)
        {
            ObjectArray[a] = (*i)->GetY();
            a++;
        }
        ...

        SIZE = Object1.size() + Object2.size() + Object3.size() + ...;

        sort(ObjectArray, ObjectArray + SIZE);

        for(size_t i = 0; i < SIZE; i++)
        {
            for(size_t j = 0; j < SIZE; j++)
            {
                if(tree1[j]->GetY() == ObjectArray[i])
                {
                }
                else if(tree2[j]->GetY() == ObjectArray[i])
                {
                }
                ...
            }
        }

        ChangeMade = false;
    }

Is there a way to create an array of pointers to store the addresses of objects to different classes by their y values and use this array to do the rendering? Or do you have any suggestions on how to handle creating objects to the sprite class and rendering or any useful links?

Thanks.


texts: I can edit colliders by holding down the shift key. But when i add a second collider, the shift key always selects the first one. And there is no "Edit Collider" button in the editor (Win/4.5.4f1). I'm testing it with two EdgeColliders2D.


texts:
Im trying to understand the SRP batcher. I have a scene with 300 fairly low-poly models.
These are my rendering stats with SRP Batcher:

And this is without SRP Batcher:

Some observations (This is all with dynamic batching enabled, models share a GPU instanced material):

With SRP Batcher the Tris and Verts seem to lower almost impossibly low, sitting at the low thousands, while without the SRP Batcher they are almost 5 million.
With SRP Batcher the draw calls are at almost 3000, with none being batched. On the other hand, without SRP Batcher the draw calls are at 103, with almost 2500 being batched.

I cannot really make sense of this. I see no noticable effect on the FPS. I have no idea which is actually better for performance. The stats above make no real sense to me, seems strange that enabling SRP batcher removes all batched calls... Can someone help me understand which is better and when to use what?
Everything is tested on latest unity and URP versions.


texts:
I am using the following code to move a CCSprite left and right.

-(id)init{
    CCMenuItemImage * moveLeftButton = [CCMenuItemImage itemFromNormalImage:@"Move Left Button.png" selectedImage:@"Move Left Button.png" target:self selector:@selector(moveLeftVoid:)];
}
-(void)moveLeftVoid{
    id moveLeft = [CCMoveBy actionWithDuration:.3 position:ccp(-10, 0)];
                [_mainSprite runAction:moveLeft];
}

This does work, but only as a single tap. What I want for the CCSprite to move continously in that direction when the CCMenuItem is held down. Then when it's released the character stops moving. If you need to see more code, please just ask. :) Thanks


texts: Design Question, Thoughts on Path Finding for a Galaxy Map

texts: I am thinking through solutions for a galaxy map.  We have different solar systems that need to be connected.  I do think a-star (A*) is possibly a good solution but was curious if it was really the only solution.  The galaxy map should remain static for the entire game.  I've also included an image similar to how the galaxy map would be setup.


texts: Java 2D Game Development - Best Performance With Rendering

texts:
I have seen two different rendering methods. One of them is rendering multiple bufferedImages like g.drawImage(image1 to imagexxx, x, y). Like in my game I have to render, on each tick, 880 buffered images. This is very bad. I have a good computer but my max fps is 140. There should be another way to get better performance.

The second way is drawing one single bufferedImage and setting its pixels to RGB from the other bufferedImages.

What is the best way? Is there another way to get better performance?


texts:
Hey. I'm trying to create an enemy that travels at a speed s on screen but I'm having trouble with trying to make the speed vary in a smooth motion. Basically, I can get the enemy to move at a constant rate but at random intervals, I'd like it to speed up then slow back down to it's original speed, or slow down then speed up to it's original speed. I imagine I'd have to use a graph function of sorts, but I'm not great at maths so are there any suggestions on how this can be achieved?
Feel free to let me know if my question is unclear.Thanks!


texts: Unity C# - Rotate smoothly an object towards the direction given by input

texts:
I am trying to rotate an object towards the direction given by de direction of the input. For example, if I am pressing 'up' of the directional pad, the player should rotate pointing that direction.

I've tried using Euler angles, and when I press the direction, I call a coroutine that sums the eulerAngle.y of the object till it gets the angle of the direction, but it doesn't work. I don't know if there is another approach to use.

Here is the code for the coroutine. It starts if a certain key is pressed and if a flag is not activated:

 IEnumerator rotateTowards(float angle)
 {
    rotating = true;
    Debug.Log("Rotating the mono...");
    Debug.Log("Your angle: " +transform.eulerAngles.y);
    float turningTime = 0.8f;
    //float thisAngle = this.transform.eulerAngles.y;
    Vector3 thisAngle = this.transform.eulerAngles;

    if(thisAngle.y < angle)
    {
        while(thisAngle.y < angle)
        {
            thisAngle.y += turningTime * Time.deltaTime;
            this.transform.eulerAngles = thisAngle;
        }
    }

    if(thisAngle.y > angle)
    {
        while(thisAngle.y > angle)
        {
            thisAngle.y -= turningTime * Time.deltaTime;
            this.transform.eulerAngles = thisAngle;
        }
    }

    this.transform.eulerAngles = thisAngle;
    rotating = false;
    yield return null;
 }

Thanks in advance.


texts: How do I offset a TouchPanel input in Monogame

texts:
I am creating my first 2D game in monogame.  I have used RenderTarget2D to maintain a 4:3 aspect ratio.  If it is played in a window of any other ratio it will offset the RenderTarget2D position to create a Letterbox black bar effect.  I accomplish this with:

        Rectangle RenderArea;
        // Calculate target and current aspect ratios
        float outputratio = (float)Window.ClientBounds.Width / (float)Window.ClientBounds.Height;
        float targetratio = (float)Screen.Width / (float)Screen.Height;

        // Calculate rectangle on screen we will be drawing to
        if (outputratio <= targetratio)
        {
            // output is taller than it is wider, bars on top/bottom
            int currentheight = (int)((Window.ClientBounds.Width / targetratio) + 0.5);
            int barheight = (Window.ClientBounds.Height - currentheight) / 2;
            RenderArea = new Rectangle(0, barheight, Window.ClientBounds.Width, currentheight);
        }
        else
        {
            // output is wider than it is tall, bars left/right
            int currentwidth = (int)((Window.ClientBounds.Height * targetratio) + 0.5);
            int barWidth = (Window.ClientBounds.Width - currentwidth) / 2;
            RenderArea = new Rectangle(barWidth, 0, currentwidth, Window.ClientBounds.Height);
        }

(Screen being my RenderTarget2D)

I then draw my RenderTarget2D to this area on the screen.  This works great.  The only issue I have is how to get touch and mouse inputs offset to this location on the screen without having to offset my TouchPosition.Position.X and Y manually every time I check their position.

I have already set my TouchPanel virtual size with:

        TouchPanel.DisplayWidth = Screen.Width;
        TouchPanel.DisplayHeight = Screen.Height;

but I don't know of a way to offset the returned TouchLocation X and Y by my RenderArea X and Y.

Is there any way to accomplish this without manually offsetting every position check?


texts:
I'm having an issue with calculating the predicted linear angle a projectile needs to move in to intersect a moving enemy ship for my 2D game.

I've tried following the document here, but what I've have come up with is simply awful.

protected Vector2 GetPredictedPosition(float angleToEnemy, ShipCompartment origin, ShipCompartment target)
{
    // Below obviously won't compile (document wants a Vector, not sure how to get that from a single float?)
    Vector2 velocity = target.Thrust - 25f; // Closing velocity (25 is example projectile velocity)
    Vector2 distance = target.Position - origin.Position; // Range to close
    double time = distance.Length() / velocity.Length(); // Time

    // Garbage code, doesn't compile, this method is incorrect
    return target.Position + (target.Thrust * time);
}

I would be grateful if the community can help point out how this is done correctly.

EDIT

Here is my (working) method following the advice given:

protected Vector2 GetPredictedPosition(ShipCompartment origin, ShipCompartment target, Ship enemyShip, Ship firingShip)
{
    Vector2 targetVelocity = enemyShip.Direction * enemyShip.Thrust;
    Vector2 projectileVelocity = firingShip.Direction * 25f;

    Vector2 velocity = targetVelocity - projectileVelocity; // Closing velocity
    Vector2 distance = target.Position - origin.Position; // Range to close
    double time = distance.Length() / velocity.Length(); // Time

    return target.Position + new Vector2(Convert.ToSingle(targetVelocity.X * time), Convert.ToSingle(targetVelocity.Y * time));
}


texts: How can I improve make it shorter the gate control script and how to make the doors stop at original position?

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

public class GateControl : MonoBehaviour
{
    public float openSpeed = 1f;

    private GameObject[] doors;
    private bool entered = false;
    private bool exited = false;
    private Vector3[] doorsOriginPos;

    private void Start()
    {
        doors = GameObject.FindGameObjectsWithTag("Door");

        doorsOriginPos = new Vector3[2];
        for (int i = 0; i < doors.Length; i++)
        {
            doorsOriginPos[i] = doors[i].transform.position;
        }
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Collider")
        {
            entered = true;
            exited = false;
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.tag == "Collider")
        {
            exited = true;
            entered = false;
        }
    }

    private void Update()
    {
        if (entered == true)
        {
            doors[0].transform.position += Vector3.up * openSpeed * Time.deltaTime;
            doors[1].transform.position += Vector3.down * openSpeed * Time.deltaTime;
        }

        if (exited == true)
        {
            for (int i = 0; i < doors.Length; i++)
            {
                if (doors[i].transform.position != doorsOriginPos[i])
                {
                    doors[1].transform.position += Vector3.up * openSpeed * Time.deltaTime;
                    doors[0].transform.position += Vector3.down * openSpeed * Time.deltaTime;
                }
            }
        }
    }
}

Seems too much code or too long and can be simpler.

And the part:

if (doors[i].transform.position != doorsOriginPos[i])

Never true. I want that when the doors are getting close they will stop at the original position and won't continue move up/down nonstop.


texts: Conditionally use java or android classes

texts: I'm using bezier curves in my libgdx project. I was testing the desktop version using java.awt.geom with GeneralPath but when I went to test on android, it raised an error saying that I can't import java.awt. Android have corresponding classes for GeneralPath, Point2D etc so my question is how can I use those classes in their respectives environments?


texts: Change game from portrait to landscape dynamically

texts:
I have multiple classes that implement Screen.

I want to, say, have the Main Menu screen portrait, then the Play Screen landscape. Is there anyway of changing the orientation dynamically?

I thought I could just start another Activity and have the Play Screen extend Game. And the new Activity would intialize the Play Screen. But it appears that you can't call startActivity or the like, obviously, as LibGDX is platform independent.

I use Gdx.graphics.getWidth() and Gdx.graphics.getHeight() to align Sprites and Actors so it looks "right" on different devices.

I've also tried swapping the Gdx.graphics.getWidth() and Gdx.graphics.getHeight(), respectively, but can't seem to get the position of sprites and actors correct.


texts: How do I go about hiring Level Designers from the Modding community?

texts:
The company I'm working for is growing fast and there's been talk of trying to hire level designers from the modding community. My question is simply, where would be good places to look for this, and how would we go about vetting who to hire?

Does anyone have any experience of this?


texts: How to handle dimension changes on tileset? (Tiled)

texts:
I am using Tiled map editor.

My question is:
What should I do if I would like to change the dimensions of the graphic file for the tileset? The IDs will shift if I will not adapt the graphic accordingly.

My idea is to write a simple script that can swap/shift the IDs in the map.
Is there a better way? Or is there a script already that I can use?


texts: How can I Increase pixel In rendering my shader?

texts:
This is my flow map shader , it works correctly but I have problem In Rendering.
how can I Increase pixels per unit In my shader?

Shader "Custom/Flow Map"
{
    Properties
    {
        _MainTex ("Sprite Texture", 2D) = "white" {}
        _Color ("Tint", Color) = (1,1,1,1)
        _FlowMap ("Flow Map", 2D) = "white" {}
        _FlowSpeed ("Flow Speed", float) = 0.05

        [MaterialToggle] PixelSnap ("Pixel snap", Float) = 0
    }

    SubShader
    {
        Tags
        {
            "Queue"="Transparent"
            "IgnoreProjector"="True"
            "RenderType"="Transparent"
            "PreviewType"="Plane"
            "CanUseSpriteAtlas"="True"
        }

        Cull Off
        Lighting Off
        ZWrite Off
        Blend One OneMinusSrcAlpha

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma multi_compile _ PIXELSNAP_ON
            #include "UnityCG.cginc"

            struct appdata_t
            {
                float4 vertex   : POSITION;
                float4 color    : COLOR;
                float2 texcoord : TEXCOORD0;
            };

            struct v2f
            {
                float4 vertex   : SV_POSITION;
                fixed4 color    : COLOR;
                half2 texcoord  : TEXCOORD0;
            };

            fixed4 _Color;

            v2f vert(appdata_t IN)
            {
                v2f OUT;

                OUT.vertex = mul(UNITY_MATRIX_MVP, IN.vertex);
                OUT.texcoord = IN.texcoord;
                OUT.color = IN.color * _Color;
                #ifdef PIXELSNAP_ON
                OUT.vertex = UnityPixelSnap (OUT.vertex);
                #endif

                return OUT;
            }

            sampler2D _MainTex;
            sampler2D _FlowMap;
            float _FlowSpeed;

            fixed4 frag(v2f IN) : SV_Target
            {
                float3 flowDir = tex2D(_FlowMap, IN.texcoord) * 2.0f - 1.0f;
                flowDir *= _FlowSpeed;

                float phase0 = frac(_Time[1] * 0.5f + 0.5f);
                float phase1 = frac(_Time[1] * 0.5f + 1.0f);

                half3 tex0 = tex2D(_MainTex, IN.texcoord + flowDir.xy * phase0);
                half3 tex1 = tex2D(_MainTex, IN.texcoord + flowDir.xy * phase1);

                float flowLerp = abs((0.5f - phase0) / 0.5f);
                half3 finalColor = lerp(tex0, tex1, flowLerp);

                fixed4 c = float4(finalColor, 1.0f) * IN.color;
                c.rgb *= c.a;
                return c;
            }
            ENDCG
        }
    }
}


texts: Differences between Overlap and Intersection testing?

texts:
I have heard of techniques such as overlap testing and intersection testing for collision detection and collision resolution.

I looked up on the two techniques, but I don't see what differences they have. On every frame, the overlap testing will check to see if it overlaps another object by looking if any vertices is inside another object's bounding volume. The intersection testing on the other hand casts a line from its centre point to check for intersection. But since it's only a line, it may not be as accurate. So it has to cast many lines continuously from all over its edges in its moving direction and, hence, is more costly. Is this true and is the only difference between the two techniques?

Otherwise, what are the differences between the two techniques? Also, are there any differences in terms of collision resolution between the 2 techniques/


texts: vuforia unity how to detect that we have " lost track of" an object

texts: I'm working on a vuforia project and would like to be aware when vuforia can no longer detect the object in unity. Is there an easy way to write a script that is executed opon loosing track of an object for a given time?


texts: Visual studio alternatives for unity as intellisense not working

texts: I am new to unity and unity tools for game dev are unavailable in vs community,i also tried vs code.So what are some alternatives for vs for unity scripts for a beginner?