texts: Let the Game (singleton) handles the Components to add to the game

texts:
I have a class 'Bullet' implementing the DrawableGameComponent. What I want is, that the Bullet add itself to the Game. My Game is a Singleton. So I thought I figured it out, but still getting errors.

The Code:

Bullet.cs

 public class Bullet : DrawableGameComponent
{
    public Texture2D Texture { get; set; }
    public Vector2 Position { get; set; }
    public Vector2 Speed { get; set; }

    public Bullet(Game game) : base(game)
    {

    }

    public void Shoot()
    {
        Position += Speed;
        Game1.getInstance().addBullet(this);

    }

    protected override void LoadContent()
    {
        Texture = Game.Content.Load<Texture2D>("Bullet");

        base.LoadContent();
    }

    public override void Update(GameTime gameTime)
    {
        Shoot();

        Position = new Vector2(Position.X, Position.Y);
        base.Update(gameTime);
    }

    public override void Initialize()
    {
        Speed = new Vector2(2, 0);
        base.Initialize();
    }

    public override void Draw(GameTime gameTime)
    {
        Game1.spriteBatch.Draw(Texture, Position, Color.White);

        base.Draw(gameTime);
    }
}

And in my Game1.cs which is a singleton, i do the following:

public void addBullet(Bullet b)
    {
        Components.Add(b);

    }

Unfortunately i'm getting this error:
Cannot add the same game component to a game component collection multiple times.

What am I doing wrong?


texts:
I am developing a simple game for Android.

It is a really simple game, with only one object - a ball.

I am using the game loop based on delta time. However I have noticed that my game runs not in the same on different devices and I have realized that this may be caused by the following code

currentPosition.x+= velocityVector.x * deltaTime

As far as all dimensions are just simple pixels, as a result it runs slower on devices that have higher screen resolution as the ball should pass more distance with the same velocity vector.

So to conclude, could you please suggest any good algorithm or approach to implement independent movement of an object ?

Thanks.


texts: PVRCT Texture Format with glTexStorage2D on Open GL 3.0 ES How?

texts:
I've looked everywhere and I can't seem to find the answer.

How can I use glTexStorage2D with PVRCT textures? I've done this:

#define GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG 0x8C02

glTexStorage2D(GL_TEXTURE_2D, 1, GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, m_uPixelsWide, m_uPixelsHigh );

Where the GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG internal format works for glTexImage2D, but when I run that Tex Storage command, my pvr textures come out black. There are no errors posted, and when I query glGetTexParameteriv, my texture is indeed set to Immutable.

Does PVRCT not work for opengl 3.0?


texts: Move Sprite in constant speed on squircle

texts:
I'm creating a game and i need to move a sprite on squircle path.

https://en.wikipedia.org/wiki/Squircle

i created the path using the  equation :

    angle -= Gdx.graphics.getDeltaTime()*speed ;
    float x = (float) (R*Math.pow(Math.abs(MathUtils.cos(angle)),1/10f)*sgn(MathUtils.cos(angle)))+a;
    float y = (float) (R*Math.pow(Math.abs(MathUtils.sin(angle)),1/10f)*sgn(MathUtils.sin(angle)))+b;
    sprite.setPosition(x,y);

the result is :

My question is how to make the sprite move in a constant speed

Edit :
i used the formula found on Wikipedia :


texts:
This is sort of a question following onto a previous question I wrote specifically targeting XNA. Understanding that it's an involved enough process that I'd want to manage memory myself, I'm now approaching from C++. But the language isn't directly relevant to the process...

For the game Ghost Trick: Phantom Detective, the developers found that the DS' 3D renderer wasn't fast enough to render the game's characters with the depth they wanted. So, since the whole game takes place from a side viewpoint, they pre-rendered the characters' many lengthy, acted-out animations, so the whole game is technically 2D. This wasn't the first time such a thing was done, but being a "drama", they tended to have longer and smoother animations than say, a top-down shooter.

What I'm targeting is something similar, but on the desktop; my game would basically consist of several static, basic sprites serving as backgrounds, and then characters that are rendered through FMV, with an Alpha color component (likely a 24fps video made through greenscreening, then converted to whatever suits the engine best). What may make my thinking different from Ghost Trick is that on a Desktop, the character sizes would be much bigger. Currently, I'm trying to think through what people may have tried for this approach previously.

The thick-skulled straightforward approach would be to convert the video files into PNG spritesheets, in some kind of format that crops down to just a box that is non-transparent in all X and Y lines. If this is all in graphics memory at once, it would kind of add up though. If RGBA is 32 bits, an 1152x800 character's 4-second idle animation at 24fps would be 345 MB, if my math is right. One could of course save more memory by reducing character detail (ie, scaling a smaller video up) or by having a lower framerate.
A hybrid approach of that might involve keeping the frames compressed in-memory, and only keeping about 5 to 10 uncompressed at a time. I feel kind of worried that this would keep the game going through a lot of CPU/GPU work while not very much is happening, though.
Since only one of these characters is going to be onscreen at a time, my primary thought was to simply treat it as a video, and find a way to play it using the FFMPEG/LibAV libraries. It's obvious the FFMPEG developers don't have issues like keeping a 2-hour movie's frames in graphics memory, so it would certainly use better memory-management techniques. But, part of what makes this difficult for me is that I'm a simplistic Visual Studio developer who's had a lot of difficulty getting those libraries working; even being able to compile the example files after finding a pre-compiled Windows DLL. I'd also have to modify their standard operation so that videos can loop themselves, or switch video file on a dime.

Since this is an area I'm mostly figuring out for myself and I haven't found many resources on the topic, I was curious if anyone else had input in which I miss something obvious, or what they feel would be the most logical approach.

If it matters, I'm planning to try this project in either SDL or SFML. I'm a pretty experienced programmer who's just been avoiding C++ a bit longer than I should have, so I'm trying to dive back in for more practice with this project.


texts: Client/Server game even in solo: any big problem?

texts:
I'm making a game which have strong basic design based on multiplayer but also should provide a really interesting and self-sufficient solo game. A bit like a real-time strategy game. The events and actions taken shouldn't be as massive and immediate as in a FPS, so you can also think the networking like for an RTS. It's a PC game, targetting Windows, MacOSX and Linux (Ubuntu & Fedora). It's programmed in C++, using a variety of open source libraries, so I have great (potential) control over the performances.

So far I always considered that just making the game work with two applications, client & server, even in solo mode was ok.

However, as I'm in the process of starting the network code I'm having doubts about if it's a good idea. I'm not a specialist so I might be missing something in my analysis.

I see these pros and cons:

Pros:

The game works only one way so if I fix a bug it should apply on all game modes, whatever the distance with the server is;
Basic networking issues would be detected early, including behaviour with the protection softwares (firewall) installed (i am not specialist so this might be wrong);

Cons:

I suppose that even if it should be really fast enough, networking client and server on the same computer would still be slower than no networking and message passing in (one) process memory.
Maybe debugging would be more difficult? I don't have experience in this case but so far I assume that debugging with Visual Studio allows me to debug multiple process so it shouldn't be really different. Also, remote debugging.

My question is: is there a big disadvantage that I missed? Or maybe there are advantages that I missed and that should encourage me to just continue with only client-server game sessions?


texts: InvalidCastException in Farseer's raycasting when trying to use the built-in explosion class?

texts:
I'm trying to create an explosion at the point that two entities collide, but whenever explosion.Activate() is called, it causes an InvalidCastException to be thrown in Raycast(), on the line that returns the callback.

return callback(fixture, point, output.Normal, fraction);

Is this a bug in Farseer, or am I doing something wrong? It doesn't appear to be a known issue.


texts: High-resolution VR with tethered smartphone display

texts:
I have an Android SmartPhone with a fairly high resolution + USB-C port, a USB-C-to-USB-A cable, and a Google Cardboard headset.

Is it possible to develop a VR app running on a PC game engine (such as Unreal) but stream the output to the Cardboard headset by using the phone as a display? (rather than running the app entirely on the phone). For instance, if I wanted to render using a beefy NVIDIA GPU and stream the graphics over USB.

What are the options here? I'm aware of this guide, which seems reasonable: https://uploadvr.com/budget-vr-101-get-pc-vr-streaming-phone/

Is this a use case supported by any Game Engines like Unreal/Unity?


texts:
I'm trying to draw a dashed or dotted line by placing individual segments(dashes) along a path and then separating them. The only algorithm I could come up with for this gave me a dash length that was variable based on the angle of the line. Like this:

private function createDashedLine(fromX:Float, fromY:Float, toX:Float, toY:Float):Sprite
{
    var line = new Sprite();
    var currentX = fromX;
    var currentY = fromY;
    var addX = (toX - fromX) * 0.0075;
    var addY = (toY - fromY) * 0.0075;
    line.graphics.lineStyle(1, 0xFFFFFF);

    var count = 0;

    // while line is not complete
    while (!lineAtDestination(fromX, fromY, toX, toY, currentX, currentY))
    {
        /// move line draw cursor to beginning of next dash
        line.graphics.moveTo(currentX, currentY);

        // if dash is even
        if (count % 2 == 0)
        {
            // draw the dash
            line.graphics.lineTo(currentX + addX, currentY + addY);
        }

        // add next dash's length to current cursor position
        currentX += addX;
        currentY += addY;

        count++;
    }
    return line;
}

This just happens to be written in Haxe, but the solution should be language neutral. What I would like is for the dash length to be the same no matter what angle the line is. As is, it's just adding 75 thousandths of the line length to the x and y, so if the line is and a 45 degree angle you get pretty much a solid line. If the line is at something shallow like 85 degrees then you get a nice looking dashed line. So, the dash length is variable, and I don't want that. How would I make a function that I can pass a "dash length" into and get that length of dash, no matter what the angle is?

If you need to completely disregard my code, be my guest. I'm sure there's a better solution.

EDIT:
To clarify, I can't use vectors (unless they're easy to implement, I'm not even sure how vec2 works) also I'd like the dash length to be based on neither line rotation NOR line length. So, no scaling the line to get the dash length.


texts:
I have created below hexagon structure in Andengine with box2D physics extension. I want to rotate whole structure with respect to center when other ball collides with the structure using physics.

I tried weld joint and revolute joint with the bodies but it is not performing proper motion as required. All bodies are attached with weld joint and vertices have revolute joint with center body which is static like,

RevoluteJointDef revoluteJointDef1 = new RevoluteJointDef();
revoluteJointDef1.initialize(centerB, movingBody[i], centerB.getWorldCenter());
revoluteJointDef1.enableMotor = true;
revoluteJointDef1.motorSpeed = 0;
revoluteJointDef1.maxMotorTorque = 1f;
this.mPhysicsWorld.createJoint(revoluteJointDef1);

I had refered these links:
box2d manual
and box2d joints tutorial

Is there any other way to perform smooth rotation of whole structure?
Thanks.


texts: HTML5 Jump and Run Game Performance issues

texts:
we're developing a HTML5/Javascript jump and run game and therefore we have developed our own gameframework.
It consists of following most important structures:

Stage/Scene/Layer: divs
ObjectEntites/Rectangle/Sprite: canvas

In the gameloop things get moved by calculating an offset value: e.g. if we place a coin and this coin moves through the screen, it gets a new offset in each gameloop-call. The dirty area of the coin is cleared in the canvas and the coin is repainted. We pay attention that we just draw at int-values (no floating point).

Unfortunately we have some performance issues now and can't figure out why our macbook pro's are running hot while playing the game.

Are the drawing operations so crucial? We have layered Canvas, so just moving stuff gets repainted and even not the whole canvas but just dirty-areas get cleared.

IStat shows following values while playing the game:
Memory module A1 and Heatsink B get up to 60° and the rpm-Value of the Fans increases up to 3000-4000.
In firefox we see these values:

And chrome shows us this, where we also see how cpu increases:

Do you have any idea how to check performance of our game, how to find bottlenecks or general tips? We have searched for canvas performance, used firebug profiler...
We'd be grateful for any advice!


texts:
Does anyone know what Nystrom meant in this excerpt from http://gameprogrammingpatterns.com/observer.html?

I created an example implementation of the observer pattern in c++ from my medal system.

I am wanting to pass my KillType enum to onNotify without muddling up the base Observer/Subject classes with that level of specifics.

My Medals class needs to know specifics about what type of kill it was so it can award the appropriate medal (ex. Headshot).

Does anyone know of a way to use templates to do this? Or what is a good way to get that level of detail from PlayerState to Medals?

The first thing I thought of was to use polymorphism and an Event class with a bunch of subclasses for each type. But that seems really class heavy to me to just pass some variables around.

Runnable Example


texts: Exporting XNA class library as a DLL file

texts:
I have downloaded an open source project that I intend to use with my current game. The download came with all the class files from the original project as well as a pre-compiled DLL file representing the project. I was able to easily link this DLL with my current project and get it working just fine, no problems there.

The problem I now have is that I want to make a couple of changes to the original libraries (extend its functionality a bit to better suit my needs) and re-export the class library as a DLL again, but I have no clue how to do this. Is there some simple way in VS where I can just take the class library and export/compile it as a DLL file again or is there more to it than that?

This seems like something that should be pretty simple but my efforts to find an answer have so far come up with nothing.

Thanks in advance.


texts: How can I make a gradual slope with Unity Terrain tool?

texts:
As the question title states, I am trying to make a gradual slope in Unity Terrain. I want it to be many 100's metres long for a golf course and it will slope in a few directions hopefully in places.

How could this be done with Unity Terrain?


texts: Designing social network structure for a mobile game

texts: We are going to design a mobile game in which players could be related with each others in a social network-like mechanism. So, how we could integrate a mobile game and a social network (SN). Should we design a SN at first and then add game features to that or vice versa? Any suggestion?


texts: In what size should i design sprites for unity iOS?

texts:
I am developing a 2D platform game in unity.I have conceptualised the game and have to design the art assets/sprites, but the problem is at what resolution or size do i design them?

If I target the sprites size to iPad pro (as its has got highest resolution of all iOS device), can the older iPhone 4S handle it?

What are the best methods of designing art assets for multiple resolution(with best performance on older devices)?


texts: Can Cloud Functions be used for a multiplayer game server?

texts:
I'm building a turn-based online multiplayer game with Unity for both desktop and mobile.

Traditionally, I would build a Java socket server, host it in Google Compute Engine or similar, and have players connect to it. Since this works with sockets I can easily notify players of relevant events, such as matchmaking, chat, enemy turn, etc.

I've been curious about Serverless Functions for a while, such as Google Cloud or Amazon Lambda.

However, at first glance it doesn't seem to me like that would work for my game: because there ins't a constant connection (with sockets), I can't notify players of relevant events in realtime - or can I?

For mobile I realize I could probably use something akin to push notifications (so the serverless code may push messages to the relevant player's phone). But that doesn't seem as simple for desktop games.

Well, what if the players poll for messages? Like every second, call a Cloud function and ask them if there's anything for them.

I'd image that would work, but that seems rather overkill - with as little as a couple thousand players, calling the same function every second for prolonged times (the game's matches are long) sounds like it would easily increase expenses.

Is there something I am missing? A coding practice that would make serverless code feasible for a cross-platform online multiplayer game? I want to make it work, but it would seem like a socket server is still my only option.


texts: How to calculate IsGrounded more effective?

texts:
if (SimpleInput.GetButtonDown(jumpButton) && IsGrounded())
    {
        rb.AddForce(0f, 8f, 0f, ForceMode.Impulse);
    }

bool IsGrounded()
    {
        return Physics.CheckCapsule(Char_Collider.bounds.center, new Vector3(Char_Collider.bounds.center.x, Char_Collider.bounds.min.y, Char_Collider.bounds.center.z), Char_Collider.radius * 0.27f, GroundLayers);
    }

I've multiplied Char_Collider.radius with 0.27f 'cause in the tutorial that guy said You need to multiply this with %90 of your character's actual size That might be the problem because i don't actually know my character's size, i've made it in blender and scaled it down at the unity.

So if you look at the inspector panel you'll see it's 0.1 0.1 0.1 but it's actually not. I tried to spawn a cube and match them together roughly, cube's size was 0.3 1.2 0.3, that's way the number is 0.27f 'cause i just simply calculated it with the 0.3.

And finally my problem is:

I get return values from IsGrounded delayed, sometimes doesn't even get a value. Like example when i jump, sometimes it returns the value of IsGrounded False when i'm just about the hit the ground, and sometimes it doesn't returns the value of IsGrounded False. Because of this i can't make jump animation properly.

This is my HandleAnimation() method (I call that from FixedUpdate()):

void HandleAnimation()
{
    if (!IsGrounded())
    {
        anim.SetBool("Jumping", true);
    }
    else
    {
        anim.SetBool("Jumping", false);
    }
}

And this is my animator:

I am also adding those because sometimes when IsGrounded() returns false, animation doesn't works.


texts:
That is, what is connected to what and how to move between lines of speech when a sub-conversation ends?

If you have any examples of a basic dialog tree in C#, please post them.


texts:
I have a game with lots of assets, such as data files, images, etc. My understanding is that Unity is optimized to know about all resources at build time. i.e. binding those assets to Scene GameObjects or prefabs. And for performance reasons, dynamically loading files from the /Resources folder is discouraged.

My question is how can I set up a "content pipeline" for converting my asset files stored outside of Unity into a format that Unity expects.

With the XNA toolset you can create a separate project and "build" the content into a bundle. Is there way to achieve similar results in Unity? Or is the best I can do creating an external tool, and simply copying files into my Unity/Textures or Unity/DataFiles folder and generate the Unity metadata files myself?

If there isn't an off-the-shelf solution, do you have any experiences or recommendations with solving this problem?


texts:
How can we combine inheritance-based polymorphism with spatial cache friendly data structures? In a simple game engine we usually have some base Entity class which is inherited from to implement the various distinct game entities. These entities are then stored by pointer in a large array of some kind, which is iterated over for updating, rendering and so on.

However this leads to bad performance because entities will be randomly scattered throughout memory. One way I thought of to fix this problem is to have a separate array for each entity type, for example:

Goblin goblins[100];
Human humans[100];
Demon demons[100];
Entity* entities[300];

My question is: Is there a more elegant solution than that? The separate arrays approach requires rewriting the core functions of the engine itself every time I want to add or remove an entity type in the game implementation. I'm looking for a general solution which doesn't care about what the subclassed entity types are as long as they inherit from a common ancestor.


texts:
Ok, I've been writing C# for a while, but I'm new to ActionScript, so this is a question about best practices.

We're developing a simple match game, where the user selects tiles and tries to match various numbers - sort of like memory - and when the match is made we want a series of animations to take place, and when they're done, remove the tile and add a new one.

So basically it's:

User clicks the MC
Animation 1 on the MC starts
Animation 1 ends
Remove the MC from the stage
Add a new MC
Start the animation on the new MC

The problem I run into is that I don't want to make the same timeline motion tween on each and every tile, when the animation is all the same. It's just the picture in the tile that's different.

The other method I've come up with is to just apply the tweens in code on the main stage. Then I attach an event handler for MOTION_FINISH, and in that handler I trigger the next animation and listen for that to finish etc. This works too, but not only do I have to do all the tweening in code, I have a seperate event handler for each stage of the animation.

So is there a more structured way of chaining these animations together?


texts: How to calculate reflection vector from point sprite sphere?

texts:
So far I achieved building a cube map following this tutorial. Then I drew three points using glDrawArrays(GL_POINTS,0,3) and calculate the normals based on a sphere.

To compute the incoming light direction and hence the reflection vector I need the surface position. My questions are

Do I need view-space or world-space coordinates for each fragment?
How to compute the surface position for each fragment?
What's the difference between computing lighting in view-space vs. world-space?

Forgot to mention that this is the way I compute the Normal for the spheres

vec3 N;
N.xy = gl_PointCoord * 2.0f - 1.0f;
float mag = dot(N.xy,N.xy);
if(mag > 1.0f) discard;
N.z = sqrt(1.0f - mag);
N = normalize(N);


texts:
I am setting up a JavaScript Server for my Game.

Am I understanding this correctly:

If I use setInterval to call a function every second, and takes 2 seconds to process. Then I am going to "stack up" requests indefinetly the Client will become more and more out of sync?

If I use setTimeout, and specify 1 second.  Then the function will run (again, lets say 2 seconds) and then start the timeout. And not stack up requests.

Edit:
I am doing Pathfinding and sending it to the Client.
Thank you for all the help people. I think using the Callback is the best option for this.


texts: How can I know when a player quits out of a turn from the Game Center UI?

texts:
In an iOS Game Center managed turn based game, if a player quits out of turn from the Game Center UI, then turnBasedMatchmakerViewController:playerQuitForMatch isn't called (as expected). However, the other players don't seem to receive any handleTurnEventForMatch: notifications either. Is this correct?

If this is the expected behaviour, how is the game to become aware that someone has quit in this way?


texts: Optimize field of vision algorithm in a grid tiled map

texts:
I am trying to implement Field of View algorithm in my game and I followed the great tutorial here : sight-and-light and here is what I got so far :

As you can see it works fine for me :)

And then I try to use this algorithm in a tiled map. It also works fine but just a little bit slow so I am now trying to find a way to optimize the algorithm.

Some information might help to optimize :

The tiled map is Orthogonal
All the tiles have the same size 32 * 32 and are square
Tiles marked 0 means empty marked as 1 means a obstacle
I have used Connected Component Labelling algorithm for a preprocess :

All the obstacles have been merged into several regions
I know all the vertices position in each regions

Something like this :

Say I have 9 connected regions ( 9 polygons ) and 40 vertices in total.

Based on the algorithm in the above link, there will be :

ray-cast : 40 * 3   ( 3 ray-cast per vertices in angle +- 0.00001)
edges : 40
edge * ray-cast intersection test : 40 * 40 * 3 == 4800

I think there should be a way to reduce the ray cast count and the edges count that I need to do the intersection calculation in a above situation but just could not figure out a good solution.

Any suggestion will be appreciated, thanks :)


texts:
I have a rather strange exception on my application using OpenTK on Linux (ArchLinux with Mono 3.2.8) with GL.UseProgram(). I wrote a class to combine multiple files to one program:

public sealed class Shader : IContent
{
    public string Name
    {
        get { return name; }
    }

    readonly string name;
    readonly ShaderElement[] elements;
    int programId;

    public Shader(string name, params ShaderElement[] elements)
    {
        this.name = name;
        this.elements = elements;
        this.programId = -1;
    }

    public void Compile()
    {
        programId = GL.CreateProgram();
        for (int i = 0; i < elements.Length; i++)
        {
            var info = new FileInfo(elements[i].File);
            if (info.Exists)
            {
                int shaderId = GL.CreateShader(elements[i].Type);
                using (var reader = info.OpenText())
                    GL.ShaderSource(shaderId, reader.ReadToEnd());
                GL.AttachShader(programId, shaderId);
            }
            else
                throw new FileNotFoundException("Shader file not found.", info.Name);
        }
        GL.LinkProgram(programId);
    }

    public void Apply()
    {
        if (programId == -1)
            throw new InvalidOperationException("Compile() has to be called before Apply()");
        GL.UseProgram(programId);
    }
    public void Unapply()
    {
        GL.UseProgram(0);
    }

    public void Dispose()
    {
        GL.DeleteProgram(programId);
    }
}

My sample shader is very short because I try to understand how OpenGL works:
Vertex:

precision highp float;

void main()
{
    gl_FrontColor = gl_Color;
    gl_Position = ftransform();
}

Fragment:

precision highp float;

void main()
{
    gl_FragColor = gl_Color * (1-clamp(gl_FragCoord.z - 0.05, 0, 1));
    gl_FragColor.w = 1;
}

A sample call for Apply():

public override void Draw(double interpolation)
{
    GL.MatrixMode(MatrixMode.Modelview);
    GL.LoadMatrix(ref translate);
    GL.MatrixMode(MatrixMode.Projection);
    GL.LoadMatrix(ref projection);
    GL.Color3(Color.Red);
    simpleShader.Apply();
    sphere.Draw();
    simpleShader.Unapply();
}

Running the application under Windows does not generate any exception.
The following is crashing running under Linux:

First call of Draw()
 -> First call of Shader.Apply()
 -> Draws geometry for first frame
 -> First call of Shader.Unapply()
Second call of Draw()
 -> Second call of Shader.Apply()
    -> GL throws InvalidOperation Error.

Any ideas why Windows behaves different to Linux and how this can be resolved?


texts: Free Look Camera Like Arma 2 while pressing ALT

texts:
I'm trying to create a simple script that give me the possibility to rotate the camera while pressing a key. So, in a pseudo-code way, how I can intercept the Input event and limit the player's movements to hold the character direction?
I should tweak the MouseLook script? Or completely create a new one?


texts: Player hitting bottom of tile when beside it?

texts:
So my player checks if it is colliding with tiles, and it works pretty good. However, when the player is against a wall, moving upwards and sideways, it detects it as hitting the bottom of the wall since the player checks for up and down collision first. How do I prevent this? Maybe there is another collision method I could use? Thanks in advance

Here's the collision code:
player.checkCollision = function (obj) {

            const top = obj.y - this.h;
            const bottom = obj.y + obj.h;

            const left = obj.x - this.w;
            const right = obj.x + obj.w;

            if (this.x > left && this.x < right) {

                if (this.y >= top && this.y - this.vel.y <= top) {

                    this.y = top;
                    this.vel.y = 0;

                    return 1;

                }
                if (this.y <= bottom && this.y - this.vel.y >= bottom) {

                    this.y = bottom;
                    this.vel.y = 0;

                    return 1;

                }

            }
            if (this.y > top && this.y < bottom) {

                if (this.x >= left && this.x - this.vel.x <= left) {

                    this.x = left;
                    this.vel.x = 0;

                    return 1;

                }
                if (this.x <= right && this.x - this.vel.x >= right) {

                    this.x = right;
                    this.vel.x = 0;

                    return 1;

                }

            }

            return 0;

        }


texts:
I've added functionality so that I can render to a framebuffer (for post-processing and stuff).  I can successfully render to my framebuffer and then render that framebuffer, but anything with a shader does not render to my framebuffer.  Rendering with the same shader worked before I added the framebuffer step.

Here's how I create my framebuffer:

// create the color texture
colorBuffer = GL.GenTexture();
GL.BindTexture(TextureTarget.Texture2D, colorBuffer);
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba8, width, height, 0, PixelFormat.Rgba, PixelType.UnsignedByte, IntPtr.Zero);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);

// create the depth texture
depthBuffer = GL.GenTexture();
GL.BindTexture(TextureTarget.Texture2D, depthBuffer);
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Depth24Stencil8, width, height, 0, PixelFormat.DepthStencil, PixelType.UnsignedInt, IntPtr.Zero);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);

// create the fbo
GL.GenFramebuffers(1, out fbo);
GL.BindFramebuffer(FramebufferTarget.Framebuffer, fbo);
GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0, TextureTarget.Texture2D, colorBuffer, 0);
GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment.DepthStencilAttachment, TextureTarget.Texture2D, depthBuffer, 0);
GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);

And this is my shader code:

// VERTEX SHADER
#version 330

uniform mat4 world;
uniform mat3 worldIT;
uniform mat4 view;
uniform mat4 projection;
uniform mat4 textureTransformation;

in vec3 rPosition;
in vec3 rNormal;
in vec2 rTexCoord;
in vec3 rColor;

out vec3 vWorldPosition;
out vec3 vNormal;
out vec2 vTexCoord;
out vec3 vColor;

void main(void)
{
    vec4 tempWorld = world * vec4(rPosition, 1.0f);
    gl_Position = projection * view * tempWorld;

    vWorldPosition = tempWorld.xyz;
    mat3 normalSpace = mat3(world);
    vNormal = normalize(normalSpace * rNormal);
    vTexCoord = (textureTransformation * vec4(rTexCoord, 0.0f, 1.0f)).xy;
    vColor = rColor;
}

// FRAGMENT SHADER
#version 330

uniform sampler2D colorMap;

in vec3 vWorldPosition;
in vec3 vNormal;
in vec2 vTexCoord;
in vec3 vColor;

out vec4 fColor;

const vec3 ambientLight = vec3(0.1f, 0.1f, 0.1f);
const vec3 lightDir = vec3(0.0f, -1.0f, 1.0f);
const vec3 lightColor = vec3(1.0f, 1.0f, 1.0f);

void main(void)
{
    vec4 texel = texture(colorMap, vTexCoord);

    vec3 n = normalize(vNormal);
    vec3 l = normalize(lightDir);
    float nDotL = max(dot(n, l), 0.0f);

    vec4 diffuse = vec4((ambientLight + nDotL * lightColor) * vColor, 1.0f) * texel;

    vec4 specular = vec4(0.0f, 0.0f, 0.0f, 0.0f);

    fColor = diffuse + specular;
}

EDIT:
It seems to be that, for some odd reason, my shader stopped outputting at all when I added the framebuffer support.


texts: How do MMO servers handle a large concentrated number of players?

texts:
I have a pretty good understanding of how to scale servers but there's one thing I can't quite be sure about is how to manage a lot of players in a concentrated area.

If I have a server which is using multiple threads and processes as long as you limit the amount of players that can join a single game instance then this can scale indefinitely by adding more servers and placing it behind a load balancer.

But MMO games don't work that way because it's broken down into zones that anyone can connect to. So if a massive amount of players all decided to connect to the same zone it would put all of the stress on 1 server.

If you tried to spread the load across multiple servers then you'd run into problems of having to share information between the servers (Such as if player X was connected to sever 1 then all of his movements would also have to be passed on to the players connected to server 2 since server 1 and 2 are managing the load for the same zone).

So I was wondering how do you go about solving this problem? Do you just keep on ramping up the specs for the server on heavily populated zones? Or is there a fast and efficient way for multiple servers to manage the load for the same zone and efficiently share data between the two servers?


texts:
I'm trying to make a third person spaceship control system in Unity. In theory, it works like this:
Let's suppose you move your mouse to the right. The targeted direction would rotate to the right compared to the current camera direction and the camera would rotate to face towards the new direction as well.

The problem lies in the calculations: how can I calculate the direction change using the current camera rotation? Also, please mind that the ship rolls with Q and E to the left and right, respectively, as to improve player control.

The system is designed this way to help controlling bigger, slower turning ships (where direct, limited mouse following is not an option because of the low turning speed). But if you have a suggestion for a better control system for such ships, I'd be glad to hear it.


texts: How to generate a random path on a 2d Grid

texts:
I want to create a random path in a 2d grid given a start point at the bottom row and an end point at the top of the row. I do not want the shortest path, or even the longest. Instead, I want a random path that can go up, down, left and right, but one that does not intersect itself.

I've been researching this question for days and cannot find anything that helps me solve the issue. I've read this questions Simplest way to generate a random path, however, the answer provided does not allow for the path to go backwards.

Some solutions I've thought of

On every row select a random point, then travel to each of these points. This does not allow for moving backwards because I would continue to move up in the rows.
Start the the beginning point, select a random point next, and so on until I reach the goal. This does not work because I can end up trapping myself and reaching a dead end.

How can I achieve this?


texts: How to avoid obvious triangle pattern when shading 2d quads?

texts:
I'm in the very early stages of writing a 2d tile-based game using Allegro. I've hacked the Allegro source to allow me to specify tint values at each corner of a bitmap, however the resulting image has very obvious patterning where the quad for the bitmap has been rendered as two triangles:

As you can see, there are clear diagonal patterns going from top-left to bottom-right of each quad.

I'm not really sure of the correct terms to be able to search for a solution...

Are there any techniques I can apply to avoid these sorts of artifacts?

Thanks!

UPDATE: To show an example, here is the lighting system with all corners red, except for the bottom-left green:

And now, here's the equivalent with all corners red apart from the bottom-right green:

You can see the patterning is very different - not simply a 90 degree rotation.

Here's some of the Allegro code I modified:
https://github.com/stu-smith/allegro5/blob/al_draw_corner_tinted_scaled_bitmap/src/win/d3d_bmp.cpp#L187


texts:
After reading up on rendering reflections, it seems that the way to do it is the render the scene from underneath the plane of reflection, and then use projective texturing to map the reflected texture to the reflective surface.  However, why can't you just use the image from rendering the scene underneath the water, and draw it upside down behind the terrain?

Here's what I mean:
http://i.stack.imgur.com/g6VbX.png

The lines at the end of the views represent the drawn image, the colored dots are supposed to represent the corresponding points on the textures, and the brown is supposed to represent the terrain.

From the diagram, it would appear that you can just take the image rendered from the camera below the reflective surface, flip it upside down, and then draw it behind the terrain on the actual rendered image.

Is this another way to do it, or am I completely missing something here?

Thanks!


texts: How do I get diagonal 3d movement when two buttons are pressed?

texts:
I have a model moving using root motion. Currently, it's moving in 4 directions; Forward, Backward, Right, and Left.

Now, I want to make the character move in 45 degrees. I made a chart to understand the axes. (link because I can't have anymore attatchments)

http:// orig15(.) deviantart(.)net /fa04/f/2016/354/8/3/unity_movement_chart_by_blueneonkid-das9e8a.png

(Remove the spaces and parenthesis (yeah, it's a bit Youtube 2009, but what can I do? I'm new here.)

The character has a running animation for every direction, including the diagonal directions. Here is my animator controller set up:

I started out with trying to move diagonally left, and tried out a few scripts.

Script #1 (The simplest):

public class Zcontroller : MonoBehaviour {

 private Animator myAnimator;

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

 // Update is called once per frame
 void Update () {
     myAnimator.SetFloat ("VSpeed", Input.GetAxis ("Vertical"));
     myAnimator.SetFloat ("HSpeed", Input.GetAxis ("Horizontal"));
     myAnimator.SetFloat ("DiagSpeed", Input.GetAxis ("Vertical") + Input.GetAxis ("Horizontal"));
  }
}

Note: Here, I tried combining the axes inputs.

Script #2:

 using UnityEngine;
 using System.Collections;

 public class Zcontroller : MonoBehaviour {

     private Animator myAnimator;

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

     // Update is called once per frame
     void Update () {
         myAnimator.SetFloat ("VSpeed", Input.GetAxis ("Vertical"));
         myAnimator.SetFloat ("HSpeed", Input.GetAxis ("Horizontal"));

         if (Input.GetAxis ("Vertical") || Input.GetAxis ("Horizontal")) {

             if ((Input.GetAxis ("Vertical") < 0f) && (Input.GetAxis ("Horizontal") > 0)) {
                 myAnimator.SetBool ("isDiagonalLeft", true);
             }

         } else {
             myAnimator.SetBool ("isDiagonalLeft", false);
         }
      }
  }

Here, I tried using a Boolean to trigger the animation

Script #3:

Results:

Script 1 did not work, and caused the character to move diagonally only when the Down Arrow key was pressed.

Script 2 also did not work, giving me the error: "Operator '||' cannot be applied to operands of type 'float' and 'float'."

Script 3 gave me some bracket errors.

What can I do to get the character to move diagonally properly?

Is there any way to combine two float values in code? If so, how?

EDIT:
I tried a solution one guy on Unity Answers suggested, which was using a 2D Freeform Directional chart.
Here's my setup for that (Link becaus I can't have any more attatchments):

http://  img04(.)deviantart(.)net/39b5/i/2016/354/9/b/zanimator_setup_2_by_blueneonkid-dasaome.png

(again, remove the spaces and parenthesis)

It still doesn't play the diagonal run animation whenever I hold two directional keys down.

I set the Diagonal Left animation to -1, 1 and the Diagonal Right animation to 1,1

(If anyone's wondering why I'm trying to achieve such an archaic way of movement, I'm trying to emulate the locomotion style of Megaman Legends 2, an Action RPG released in 2000 for the PS1.

Unlike modern Action RPGs where you can move 360 degrees, MML2 had 8 directions of movement. Kind of like Ocarina of Time.)


texts:
Currently I am writing a litte 2D engine for training purposes. Some time ago I had some thoughts about good ways to implement and handle collision. (Not about the particular algorithm, but about how to notify collision in a general engine.)

I came to the conclusion that setting a flag and then resetting it in another place isn't a great way since I don't want to touch collision at two points in m game loop in general so I decided to go with an event based collision system which is also more easy for concurrency if needed since I can change the event type to an asynchronous model.

Basically each collision would trigger an event which contains the 2 colliding GameObjects/Actors and the collision direction for each of them as information to deal with the physic calculations which will result from the collision.

This approach creates the need for a proper event - dispatch system which also would have to be implemented

Now I wanted to ask if that is a valid approach in general or if there would be a better way dealing with collisions?

Basically event based collision allows to get easy customizable onCollision function calls for different GOs/Actors, on the other hand if one consider to create async events there would be much effort to make the whole system thread-safe and I would have to deal with the event implementation.

What would be a "best practice" approach for a collision system for a game engine considering the ways the industry is dealing with it? (I can imagine that there are several approaches but which would be the most popular ones)?


texts: With LibGDX how is it okay to use Fonts statically?

texts:
I am working on a engine/framework/game in LibGDX as a baseline for future Java games (really lightweight and stuff, just gamestates, entity framwork, physics, font, etc), but I am unsure of how I should handle font.

Should I create a Font Factory to generate fonts, manage them, and allow static access to fonts? Or should I just create fonts when I need them, like in my HUD/GUI/Player/Level/etc.


texts: Jittery Rotational Movement with Arcball implementation

texts:
I have an assignment where I need to implement arcball using Opengl (~2.0). I have it more or less implemented but I have a some problems/issues/bugs and I'm not sure whats either causing them or how to solve.

Arcball rotation: Specically minor variance in mouse movement away from the axis I'm rotating on seems to "confuse" my program, causing artifacts (such as rotating briefly a completely different direction before resuming its current path).

Code:

void mouse_motion(int mx, int my)
{

    float angleRadians;
    //handles mouse motion events
    if ( arcball_on && (mx != last_mx || my != last_my) ) {
        // if left button is pressed
        lArcAngle = arcAngle;
        cout << " Last Angle: " << lArcAngle << endl;
        cur_mx = mx;
        cur_my = my;

        glm::vec3 va = get_arcball_vector(last_mx, last_my);
        glm::vec3 vb = get_arcball_vector(cur_mx, cur_my);
        angleRadians = acos(min(1.0f, glm::dot(va, vb)));
        arcAngle = ( ( angleRadians * 180 ) / 3.14159265 );
        cout << " Angle in degrees: " << arcAngle << endl;
        //cout << " ArcAngle after Mult: " << arcAngle << endl;
        arcAngle += lArcAngle;
        cout << " ArcAngle after accumulation: " << arcAngle << endl;
        axis_in_world_coord = glm::cross(va, vb);

        last_mx = cur_mx;
        last_my = cur_my;
        //glutPostRedisplay();

    }
// other code for other functionality...
}

void display()
{
    //Background color
    glClearColor(1, 1, 1, 0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    //glClear(GL_COLOR_BUFFER_BIT);
    glEnable(GL_DEPTH_TEST);

    // Matrix setup
    glMatrixMode(GL_PROJECTION);
    glViewport(0, 0, width, height);
    glLoadIdentity();
    gluPerspective(40, (float)width / (float)height, 0.1, 1000);

    // Matrix setup
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glTranslatef(0, 0, -3);

    int myFlagCtr = getFlagCtr();
    //cout << "CRX: " << crx << " CRY: " << cry << " CRZ: " << crz << endl;

    glPushMatrix();
        //glRotatef(arcAngle, axis_in_world_coord.x, axis_in_world_coord.y, axis_in_world_coord.z);
        glTranslatef(vec_blx, vec_bly, zScaling);
        glRotatef(arcAngle, axis_in_world_coord.x, axis_in_world_coord.y, axis_in_world_coord.z);

    if (myFlagCtr == 1) {
        // Set Wireframe
        glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
        // color red
        glColor3f(1.0f, 0.0f, 0.0f);
    }
    else if (myFlagCtr == 2) {
        glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
        // color red
        glColor3f(1.0f, 0.0f, 0.0f);
        glEnable(GL_POLYGON_OFFSET_LINE);
        glPolygonOffset(-1.0, -1.0);
        //draw object
        blDrawMouseMesh();
        glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
        // color red
        glColor3f(0.0f, 1.0f, 0.0f);
    }
    else if (myFlagCtr == 0 || myFlagCtr == -1) {
        // Bring back to Default
        glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
        glColor3f(0.53f, 0.12f, 0.47f);
    }
        blDrawMouseMesh();
    glPopMatrix();
    glutSwapBuffers();
}

As you can see between the two mouse vectors I get the angle between them, and the orthonogol vector which is the axis I am rotating around. But this only seems to work in a rather "dirty" and not particularly smooth way.

Edit: I now think the problem is the accumulation of degrees, when I switch axis's it remembers the angle from before, so it will "rotate" by the same amount previously plus the new angle, I'm not sure how to solve given the loading of the identity matrix causing non-accumulated values to reset.


texts: Matrix rotation of a rectangle to "face" a given point in 2d

texts:
Suppose you have a rectangle centered at point (0, 0) and now I want to rotate it such that it is facing the point (100, 100), how would I do this purely with matrix math?

To give some more specifics I am using javascript and canvas and I may have something like this:

var position = {x : 0, y: 0 };
var destination = { x : 100, y: 100 };
var transform = Matrix.identity();

this.update = function(state) {

  // update transform to rotate to face destination

};

this.draw = function(ctx) {
  ctx.save();
  ctx.transform(transform); // a helper that just calls setTransform()
  ctx.beginPath();
  ctx.rect(-5, -5, 10, 10);
  ctx.fillStyle = 'Blue';
  ctx.fill();
  ctx.lineWidth = 2;
  ctx.stroke();
  ctx.restore();
}

Feel free to assume any matrix function you need is available.


texts:
I've been using spritekit for a while for a few small games. One thing I've noticed is that spritekit is the first game framework I've used that allows me to apply move actions to physics bodies. (without anything screwing up at least.)

Are there any cross platform game frameworks I can use that allow move actions on physics bodies? Not impulses. I've used cocos2d in the past and when I tried ccmoveby on physics bodies the simulation would get totally confused. I rather not use cocos2d anyway.

I'm asking because I want to make cross platform games and spritekit is iOS only.


texts: Are spritesheets worth it? Is a zip a good alternative?

texts:
I was wondering if spritesheets are worth it.
I am making a game with pixi.js and was thinking about optimization, beginning with asset loading. I currently have an arraya of all files and use PIXI.loader, but I know this is not good because it will make a web request for all files which takes long, so I should figure out a way to load them in one web request. The first thing I thought of was a spritesheet but then I thought "what if I just zipped everything and loaded it with something like JSZip?" I knew it was possible already (from this project that loads pixi textures from a zip) and listed what I think are potentials good and bad things:
Zip good points:

Compression meaning faster loading of assets
Compression meaning smaller build size when making a build with electron

Zip bad points:

Requires loading a separate library meaning increased loading time and using more RAM
Requires decompressing in-memory meaning increased loading time

Spritesheet good points:

Doesn't has the headers of all individual image files
Is much used so it is a proven technique

Spritesheet bad points:

No compression (or at least not comparable to zipping)
More than one network call due to phone limitations preventing sometimes files over 2024x2024px making it necessary to split spritesheets
Empty holes as all images are not the same size and there is almost always a bit of space left in the spritesheet, meaning useless pixels that are still transfered over the network

I am not a very experienced developper, so I have a few questions:

Did I miss a point above?
Are spritesheets generally worth it?
Which technique of both is more worth it? I could do both but I want to focus on one first and leave the other in a nice to have list.


texts: Understanding SpriteBatch.Draw overload XNA

texts:
I'm talking about the
public void Draw (Texture2D texture, Vector2 position, Nullable sourceRectangle, Color color, float rotation, Vector2 origin, float scale, SpriteEffects effects, float layerDepth) method.

My Sprite has Scaling, Position and Rotation.  I want it to rotate from the center, towards the mouse.

This is the method I've tried using so far:

public void RotateTo(Vector2 point)
{
    var angle = AngleBetween(Position, point);
    Rotation = MathHelper.ToRadians((float)angle);
}
public static double AngleBetween(Vector2 first, Vector2 second)
{
    double sin = first.X * second.Y - second.X * first.Y;
    double cos = first.X * second.X + first.Y * second.Y;
    return Math.Atan2(sin, cos) * (180 / Math.PI);
}

But as you can imagine, this didn't work well. First of all, the origin of the sprite wasn't the center. I've tried changing the origin parameter in the Draw method to sprite.Texture.Bounds.Center.ToVector() (ToVector is an extention method) but that also didn't work. The sprite was rotating in a weird way, not focusing around the mouse, because it seemed that the sprite was rotating around a different center point, not the mouse itself.

I didn't manage to find in depth explanations about SpriteBatch.Draw, so I hoped someone here would have the knowledge and experience to help me.

Thanks for reading, and thanks in advance for the help!


texts:
I've been recently doing test builds of my game. In Unity, I worked on baking the lighting to ensure everything looked fine. However, upon building, the game level becomes far darker and much of the lighting and baking is ineffective.

Here is how the scene looks in the editor:

And here is how it looks in the built game:

It's much darker than intended.

Here are my lighting settings which I've baked in Unity's Editor. These settings and lightmap parameters were designed to, at least in the editor, provide decent quality while making light bake times relatively quick. However, I've noticed that newer Unity's Lighting settings are way different now, so perhaps something is amiss here?

I've been at my wits end trying to figure this out for the past while, but I can't figure out why this is happening or how to fix it. Any ideas?


texts: DataPath error when loading images on Android

texts:
So yesterday i was trying to load some textures asynchronously and managed to make this
 private IEnumerator GetTextureFromPath(string _dirname)
    {
        var fileNames = Directory.GetFiles(Application.persistentDataPath + "/" + _dirname + "/"  ,"*.jpg");
        Debug.Log("data Path" + Application.persistentDataPath);
        source = new Texture2D[fileNames.Length];
        Array.Sort(fileNames, (s1, s2) => Path.GetFileName(s1).CompareTo(Path.GetFileName(s2)));
        int index = 0;
        Debug.Log(fileNames);
        foreach (var fileName in fileNames)
        {
            UnityWebRequest webRequest = UnityWebRequestTexture.GetTexture(fileName);
            while (!webRequest.isDone)
            {
                yield return webRequest.SendWebRequest();
            }
            if (webRequest.isNetworkError || webRequest.isHttpError)
            {
                Debug.Log(webRequest.error);
            }
            else
            {
                source[index] = ((DownloadHandlerTexture)webRequest.downloadHandler).texture; //LoadTextureFromPath(fileName);
                source[index].name = fileName;
                index++;
                Debug.Log("Ends server comm");
            }
        }
    }

now once i use it like this i get errors on the mobile build
2021/05/27 14:44:03.305 16476 25662 Error Unity Curl error 7: Failed to connect to localhost port 80: Connection refused

which i also tried by replacing ((DownloadHandlerTexture)webRequest.downloadHandler).texture with LoadTextureFromPath(fileName) and that cannot find the path which exists in my device and in that exact path. in the filder LevelAnimals are images which i want to load
DirectoryNotFoundException: Could not find a part of the path '/file:/storage/emulated/0/Android/data/com.FocusPoint/files/LevelAnimals'.

i found out after googling a bit that i might need to use "file///" or "file//" before the path but that didnt work either.
This script works on the editor and does the job that its supposed to do but it does not load the images on the device build.
now the LoadTexture is this
 public Texture2D LoadTextureFromPath(string path)
    {
        if (string.IsNullOrEmpty(path))
        {
            Debug.LogError("Texture path is null or empty");
            return null;
        }

        if (!File.Exists(path))
        {
            Debug.LogError($"File not found: {path}");
            return null;
        }

        byte[] bytes = File.ReadAllBytes(path);
        Texture2D texture = new Texture2D(2048, 2048, TextureFormat.RGB24, false);
        texture.LoadImage(bytes);
        Debug.Log("success");
        return texture;
    }

Any help would be appreciated thank you!


texts:
I want to draw an image that I created but the image is too big. Now I want the Gui to scale the image to a reasonable size, but when I change the width and height it doesn't make the image scale down/up but only the texture.

Code where I draw the image on screen:

@Override
    public void drawScreen(int mouseX, int mouseY, float partialTicks)
    {
        this.drawDefaultBackground();
        super.drawScreen(mouseX, mouseY, partialTicks);
        this.renderHoveredToolTip(mouseX, mouseY);
        Slot slot = getSlotAtPosition(mouseX, mouseY);

        if(slot != null) {
            if(slot.getStack().getItem() instanceof MonsterCard) {
                this.mc.getTextureManager().bindTexture(new ResourceLocation(Reference.MODID + ":textures/items/" + ((MonsterCard) slot.getStack().getItem()).getName() + ".png"));
                int i = (this.width - this.xSize) / 4;
                int j = (this.height - this.ySize) / 2;
                this.drawTexturedModalRect(0, 0, 0, 0, 154, 226);
            }
        }
    }

Image I want to draw which is 154px x 226px:

Output:


texts: First Mobile Indie Game - Monetization Model. Ad based or in app purchases?

texts: We are a team of 3 (1 graphics designer, 2 developers). We're almost done with our first Android based indie game. Which monetization model will be suitable for us? We don't want to disturb users with a lot of ads (at this point we're thinking to put only banner ads) also, if we go with in app purchases, can we also keep ads as well? or is it a better practice to follow one model at a time? How much will it affect the user experience?


texts: Creating a movable camera using glm::lookAt()

texts:
I came across this tutorial on how to create a movable camera in OpenGL using glm::lookAt(glm::vec3 position, glm::vec3 target, glm::vec3 up). In the tutorial, in order to keep the camera always facing in one direction while moving, the view matrix is created as such: view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp);, where cameraPos, cameraFront, and cameraUp are all glm::vec3 type.

What I would like to ask is why does the second argument have to be cameraPos + cameraFront? If the camera position moved to the right without changing cameraFront, wouldn't cameraPos + cameraFront have an effect of rotating to the right as opposed to staying in the same direction (which I think is what should be needed)?


texts:
I'm trying to implement a parent child relationship between Sprites and draw them to the screen. I'm calculating transforms by chaining transform matrices.

I'm using code from here:

    private void Draw(Texture2D texture, Matrix transform)
    {
        Vector2 p, s;
        float r;
        DecomposeMatrix(ref transform, out p, out r, out s);
        spriteBatch.Draw(texture, p, null, Color.White, r, new Vector2(texture.Width / 2, texture.Height / 2), s, SpriteEffects.None, 0.0f);
    }

    private static Matrix GetMatrix(Vector2 position, Vector2 scale, float rotation)
    {
        return Matrix.CreateScale(scale.X, scale.Y, 1f) * Matrix.CreateRotationZ(rotation) * Matrix.CreateTranslation(position.X, position.Y, 0f);
    }

    private static void DecomposeMatrix(ref Matrix matrix, out Vector2 position, out float rotation, out Vector2 scale)
    {
        Vector3 position3, scale3;
        Quaternion rotationQ;
        matrix.Decompose(out scale3, out rotationQ, out position3);
        Vector2 direction = Vector2.Transform(Vector2.UnitX, rotationQ);
        rotation = (float)Math.Atan2(direction.Y, direction.X);
        position = new Vector2(position3.X, position3.Y);
        scale = new Vector2(scale3.X, scale3.Y);
    }

And I'm drawing things like this:

        Matrix parentT = GetMatrix(parentPosition, parentScale, parentRotation);
        Matrix childT = GetMatrix(childPosition, childScale, childRotation);
        childT = childT * parentT;
        Draw(parent, parentT);
        Draw(child, childT);

This seems to be working fine except when the parent has a different scale than [1, 1]. For example, when the scale is [2, 1] and the child is rotating - the child gets scaled along the world X axis which causes it to look deformed:

The result I actually want is:

I still want the child to be affected by the parent's scale while taking the rotation into the account. I guess I could temper with the scale and apply it manually but that doesn't feel right. How to achieve this behaviour using matrices?


texts: Cocos2d-x how to draw in specific free form area

texts:
Here https://github.com/mikeccy/cocos2dx-finger-paint/blob/master/Classes/HelloWorldScene.h and https://github.com/mikeccy/cocos2dx-finger-paint/blob/master/Classes/HelloWorldScene.cpp you can see how a Sprite is being rendering in RenderTexture. What I want to add to this to make visible only the specific part in RenderTexture (canvas). I.e. I should apply a free form mask on it to be able to draw in a specific free form area.

How to do this in cocos2d-x 3.2?


texts: Weird "jiggly"/"warping" effect on my tiles

texts:
I need help with a problem I'm having in Unity regarding a "jiggly"/"warping" effect. It is a strange effect which occurs when I move my sprite character and makes the tiles have additional pixels which aren't on the sprite and disappear when you move more.
I've also linked a video of my issue; you can see it more clearly on the tree.
To note:

My tiles are 16x16, my fox sprite is 64x64 and the enemy sprite is 48x48.
I'm using Cinemachine.


texts:
I would like to create/find an AI algorithm/process that can be parameterized such that a change in the parameters causes a change in the AI behavior. I am specifically looking to apply this to a turn based game environment where the player is able to perform several moves (or none at all) in a single turn. The player has full knowledge of the board and should be able to take the opponent's current positioning into account when deciding what moves to make in the current turn.

My question is how can I create this type of AI? An example of behavior that I would like it to show in various situations would be:

Turn X: Attack location A with 7 units and attack location C with 12 units
Turn Y: Do nothing
Turn Z: Invest in resource collection

Then a small change in a parameter may cause the AI to only send 6 units to location A instead of 7 in the same situation as Turn X.

My only thought of how to implement something like this would be to have the parameters act as probabilities of doing action T with magnitude R. However, I could imagine how this wouldn't facilitate long term thinking, and I also have no idea how that approach would take the opponent's positioning into account. I also suspect that this approach would cause the AI to overspend within a single turn, as in, it tries to attack 3 locations with a total of 30 units, but it only has 15.

I've spent the last few hours looking through Google Scholar and have found a few papers that say that they have used a parameterized AI approach, but they don't discuss any actual implementation details. If anyone could tell me what this concept is normally called (so I can Google and research it further) or has any reference links to code that uses an implementation like this then I would really appreciate you adding it as an answer.

Also, just so people don't waste their time answering something that isn't needed, I'm only interested in the design/structure of the described process, I am not looking for ways to get good values for the parameters.

Thanks everyone!


texts: What is a good practice for 2D scene graph partitioning for culling?

texts:
I need to know an efficient way to cull the scene graph objects, to render exclusively the ones in the view, and as fast as possible.

I am thinking of doing it the following way, having in each object a local boundingbox which holds the object bounds, and a global boundingbox which holds the bounds of the object and all children.

When a camera is moved, the render list is updated by traversing the global boundingboxes.
When only the object is being moved, it tries to enlarge or shrink the ancestors global boundingboxes, and in the end updating or not the renderlist.

What do you think of this approach? Do you think it will provide a fast and efficient culling?

Also, because the render list is a contiguous list, it could accelerate the rendering, right?

Any further tips for a 2D scene graphs are highly appreciated!


texts: How many texture units are available per shader stage when compared to the total number available on hardware?

texts:
The answer to the question How many textures can usually I bind at once?, given here, explains that:

OpenGL 3.x defines the minimum number for the per-stage limit to be 16...

and that there can be a higher limit.
This still leaves some ambiguity that I would like to clarify. If we calculate the total number of texture units to be, for e.g., 192 (see here for more details), then does this mean:

theoretically, that we have access to 192 texture units available for the pixel shader? OR
we have access to 192 texture units across all stages, however that still doesn't mean we have access to 192 texture units on any particular stage. OR
?

If #2 is correct, then how do we figure out how many maximum texture units are available on any given stage?


texts: Solution for GIT commits in Visual Studio while Unity is open?

texts:
Specifications

-VS 2013 Pro (Linked with Unity)

-Unity 4.6.1

-Git Version Control (Linked with Visual Studio 2013)

Summary

After much research, I haven't found any solutions to this fix.
*While visual studio 2013 and Unity 4.6.1 is open, I am unable to commit in Visual Studio in Team Explorer. I am able to SYNC and commit when VS is closed.

ERROR: An error occurred. Detailed message: Could not open 'PROJECT/Temp/UnityLockfile': The process cannot access the file because it is being used by another process.

I understand that it is being used, but is there any work around to this? I need to write custom commit messages to close open ISSUES in git, but would be efficient if done while Unity is open.

This just slows me down in terms of product management/ workflow, so if anyone has any workarounds to commit while unity is open, it would be much appreciated.

Let me  know if you have any questions, I know there are some Unity/VS/Git masters out there

FIXED SOLUTION:
Only include ProjectSettings and Assets when committing->
http://forum.unity3d.com/threads/solution-for-git-commits-in-vs-while-unity-is-open.328380/


texts: Supreme Commander 2 has something called flow field path finding. How does it work? Is there some article available I can read up on how it works?


texts: Why doesn't my texture display with this GLSL shader?

texts:
I am trying to display a DXT1 compressed texture on a quad using a VBO and shaders, but I have been unable to get it working. All I get is a black square.

I know my texture is uploaded properly because when I use immediate mode without shaders the texture displays fine but I will include that part just in case. Also, when I change the gl_FragColor to something like vec4 (0.0, 1.0, 1.0, 1.0) then I get a nice blue quad so I know that my shader is able to set the colour. It appears to be either the texture is not being bound correctly in the shader or the texture coordinates are not being picked up. However, I can't find the error! What am I doing wrong?

I am using OpenTK in C# (not xna).

Vertex Shader:

void main() {
    gl_TexCoord[0] = gl_MultiTexCoord0;
    // Set the position of the current vertex
    gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}

Fragment Shader:

uniform sampler2D diffuseTexture;
void main() {
    // Set the output color of our current pixel
    gl_FragColor = texture2D(diffuseTexture, gl_TexCoord[0].st);
    //gl_FragColor = vec4 (0.0,1.0,1.0,1.0);
}

Drawing Code:

int vb, eb;
GL.GenBuffers(1, out vb);
GL.GenBuffers(1, out eb);
//                      Position        Texture
float[] verts = {   0.1f, 0.1f, 0.0f,  0.0f, 0.0f,
                    1.9f, 0.1f, 0.0f,  1.0f, 0.0f,
                    1.9f, 1.9f, 0.0f,  1.0f, 1.0f,
                    0.1f, 1.9f, 0.0f,  0.0f, 1.0f
                };
uint[] indices = {
                   0, 1, 2,
                   0, 2, 3
                 };

//upload data to the VBO
GL.BindBuffer(BufferTarget.ArrayBuffer, vb);
GL.BindBuffer(BufferTarget.ElementArrayBuffer, eb);

GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(verts.Length * sizeof(float)), verts, BufferUsageHint.StaticDraw);
GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(indices.Length * sizeof(uint)), indices, BufferUsageHint.StaticDraw);

//Upload texture
int buffer = GL.GenTexture();
GL.BindTexture(TextureTarget.Texture2D, buffer);

GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (float)TextureWrapMode.Repeat);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (float)TextureWrapMode.Repeat);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (float)TextureMagFilter.Linear);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (float)TextureMinFilter.Linear);

GL.TexEnv(TextureEnvTarget.TextureEnv, TextureEnvParameter.TextureEnvMode, (float)TextureEnvMode.Modulate);

GL.CompressedTexImage2D(TextureTarget.Texture2D, 0, texture.format, texture.width, texture.height, 0, texture.data.Length, texture.data);

//Draw
GL.UseProgram(shaderProgram);

GL.EnableClientState(ArrayCap.VertexArray);
GL.EnableClientState(ArrayCap.TextureCoordArray);

GL.VertexPointer(3, VertexPointerType.Float, 5 * sizeof(float), 0);
GL.TexCoordPointer(2, TexCoordPointerType.Float, 5 * sizeof(float), 3);

GL.ActiveTexture(TextureUnit.Texture0);
GL.Uniform1(GL.GetUniformLocation(shaderProgram, "diffuseTexture"), 0);

GL.DrawElements(BeginMode.Triangles, indices.Length, DrawElementsType.UnsignedInt, 0);


texts:
I'm using Slick2d for a game, and while it runs fine in Eclipse, i'm trying to figure out how to make it work when exported to a runnable .jar. I have it set up to where I load every image located in the res/ directory. Here's the code

/**
 * Loads all .png images located in source folders.
 * @throws SlickException
 */
public static void init() throws SlickException {

    loadedImages = new HashMap<>();
    try
    {
        URI uri = new URI(ResourceLoader.getResource("res").toString());
        File[] files = new File(uri).listFiles(new FilenameFilter(){
            @Override
            public boolean accept(File dir, String name)
            {
                if(name.endsWith(".png"))
                    return true;
                return false;
            }

        });

        System.out.println("Naming filenames now.");

        for(File f:files)
        {
            System.out.println(f.getName());
            FileInputStream fis = new FileInputStream(f);
            Image image = new Image(fis, f.getName(), false);
            loadedImages.put(f.getName(), image);
        }
    } catch (URISyntaxException | FileNotFoundException e)
    {
        System.err.println("UNABLE TO LOAD IMAGES FROM RES FOLDER!");
        e.printStackTrace();
    }

    font = new AngelCodeFont("res/bitmapfont.fnt",Art.get("bitmapfont.png"));

}

Now the obvious problem is the line URI uri = new URI(ResourceLoader.getResource("res").toString()); If I pack the res folder into the .jar there will not be a res folder on the filesystem. How can I iterate through all the images in the compiled .jar itself, or what is a better system to automatically load all images?


texts: How to differentiate between object types and roles?

texts:
I have a base class Object, and depending on how the object must behave on the scene, I have multiple abstract "role" classes, that inherits virtually from Object:

Updatable if the object is dynamic, and must be updated every frame;
Collidable if the object can collide with others, and thus must take part on collision detection;
Drawable if the object is visible and must be drawn.

So, for instance, a particle special effect animation is both a Updatable, because it moves, and Drawable, because it is visible, but is not Collidable. A trigger may be Updatable, but is definitely Collidable, and is not Drawable because it is invisible.

If objects are never removed or created, this design is easy to manage: I have three lists on my world, one for each object type, that hold pointers for all objects of that type: i.e. the updatable_list holds a pointer to all my Updatables, etc. This is what I have so far.

Now I have to add and remove objects, and this design is biting me.

When a new object is added, I would have to use dynamic_cast to figure out its roles and add its pointer to the proper lists. But dynamic_cast is usually referred as bad design and code smell, not to mention being slow.

When an object is removed, it can potentially be part of multiple lists, so I would have to track its existence across lists, maybe by storing std::weak_ptr instead of raw pointers, and would have to check and potentially remove every time I use an object from such list. Other options would be linear search and remove from all lists upon removal, or use std::unordered_set instead of std::list to make it fast to search and remove. But I find these other options a bit fragile, because I risk having dangling pointers if I "forget" to remove the object from some list.

So, my question, is this a good design? How can it be improved? How is this problem of different object types usually handled in game engines?


texts: How can I post scores to Facebook from a LibGDX Android game?

texts:
I am using LibGDX to create an Android game. I am not making the HTML backend of the game. I just want it to be on the Android Google Play store.

Is it possible to post the scores to Facebook? And if so, how can I do it? I searched and found the solutions only for web-based games.


texts: how to calculate resulting velocity and angular velocity rocket has on center of mass

texts:
The issue i am having is that i can't seem to figure out how to apply force from a rocket to a bodies center of mass.

*Edit
This is in 2D

e.g.
Let's call the body 'ship'

the 'ship' is 1000 (relative unit) and the center of mass is normalized at [0,0] (origin)

the 'ship' has two rockets (lets say for thrust vectoring), one at [-2,-4] (left) and one at [2,-4] (right) relative to the center of mass, and that both had nozzles pointed down (90 degree angle counterclockwise from x)

if the left rocket were to fire at say 500 (relative unit), what formula could i use to find the resulting force and angular force on the center of mass?

if it helps, the language is a superset of javascript (custom preparser similar to typescript), and i'm using a custom physics engine that only accepts force on center of mass as an array e.g. [force x, force y, force angular]. I tried to recycle my collision detection algorithm but it was like jamming a square into a circle shaped hole.

I've searched since last night and can't seem to find a formula to do this (atleast not one I can understand, I can't understand complex math notations).

Any and all help is greatly appreciated.

TL;DR
I need a formula that gives the resulting force and angular force from a offset rocket on center of mass where the result looks like:

[force x , force y , force angular]

the center of mass is normalized to origin,

and takes the variables:
rocket offset ([x,y]),
rocket angle (in degrees to center of mass),
force of rocket (in relative units)


texts:
So I'm trying to implement some collision detection in XNA. I'm aware of the Bounding Spheres, but I worry with the accuracy, most items in my game are cubic in nature, so it seems very square-peg in a round hole, so it seems to me bounding boxes would be the best solution.

I looked at having libraries(JigLibX, Henge3D) to do it for me, but most have heavy physics systems attached and that's really not what I'm wanting
I've also tried to implement solutions utilizing the Vertex buffers for Bounding Boxes after XNA's importers and processors pack the .fbx model into the Content Pipeline to no avail.

So the two things I feel I'm left with are:

Using Primitives as collisions "skins" for my objects.

Same problem here as using XNA's default bounding box, after Importation, I have no clue how to get it's size or even the vertices.

Creating a Custom Content Processor to determine the vertices at Load, and then apply transformations to the Bounding Box along with the Model itself at run-time.

problem Here is that this is a very daunting task. I'm finding it hard to locate thorough documentation on XNA's default importer, so it's highly difficult to just create a custom Processor.
I wouldn't even know how to begin to write my own importer.

TL;DR- I've hit a brick wall with 3D Collision using Bounding Boxes, Halp?


texts: Unity - Mesh Deforms terribly while mixing animations

texts:
I have a simple game I'm working on to help me learn unity3d. In my Start() function, I've used the following code to set up my animations.

        walkAnimation = animation["Walk"];
        walkAnimation.layer = 1;
        walkAnimation.blendMode = AnimationBlendMode.Additive;
        walkAnimation.enabled = true;
        walkAnimation.wrapMode = WrapMode.Loop;

        walkBackwardsAnimation = animation["WalkBackwards"];
        walkBackwardsAnimation.layer = 0;
        walkBackwardsAnimation.blendMode = AnimationBlendMode.Additive;
        walkBackwardsAnimation.enabled = true;
        walkBackwardsAnimation.wrapMode = WrapMode.Loop;

        TurnLeftAnimation = animation["TurnLeft"];
        TurnLeftAnimation.layer = 1;
        TurnLeftAnimation.blendMode = AnimationBlendMode.Additive;
        TurnLeftAnimation.enabled = true;
        TurnLeftAnimation.wrapMode = WrapMode.Loop;

        TurnRightAnimation = animation["TurnRight"];
        TurnRightAnimation.layer = 1;
        TurnRightAnimation.blendMode = AnimationBlendMode.Additive;
        TurnRightAnimation.enabled = true;
        TurnRightAnimation.wrapMode = WrapMode.Loop;

Each of them are declared before start like this

public AnimationState walkAnimation;

and I call them depending on the values of the control's axis, like such;

if(Mathf.Abs(Input.GetAxis("Rotate Player")) > 0){
                if (Input.GetAxis("Rotate Player") > 0){
                    animation.CrossFade(TurnRightAnimation.name, 0.2f);
                }

The problem is, The animations don't play, and when I turn while moving my character deforms gruesomely, his arms rise above his head and into his body, other parts grow, etc

I've been battling with mixing animations for the last two weeks, but I'm determined to get it right. If you know anything about this problem please don't hesitate to tell me what it might be. I created the model myself as well, all animations are on a single mesh, and I've tried to make the different animations affect different bones.


texts: How to target specific material with Unity VideoPlayer?

texts:
I've modeled the following tv-monitor:

This monitor has two materials. The "frame" that makes up the monitor, called MonitorFrameMaterial and the black screen material, called MonitorScreenMaterial.

I've added the Video Player to the monitor and would like to play a video "on the screen material".
Here's a screenshot of the inspector:

I've already searched the web for some time to find an answer, but I can't seem to find a way to play the video on the screen. Whenever I add a video now, it actually targets the monitor-frame (probably because it's the first material?).

Is there any way to change this, and if yes, how?
Thanks!


texts: What is the difference between shader uniforms and attributes in OpenGL?

texts:
I don't fully understand the differences between uniforms and attributes. To be honest, I probably haven't even used attributes.

Can uniforms change for each vertex? I mean to calculate the vertex's position in screen space I just multiply the vertex's local position by the model matrix, then by the view matrix and then by the projection matrix.

Projection is constant throughout the whole scene, view is constant throughout one frame, but the model matrix changes with every object. Meaning the uniform I supply to the vertex shader as the model matrix changes a lot of times per frame. Is that good? I mean I don't see another way of transforming the object...


texts: Anchoring a sprite to a specific x & y on another, regardless of rotation [Gamemaker]

texts:
I have a sprite, sDetritus, with a corresponding object, oDetritus, and an sTurret and oTurret.

If I apply no rotation (i.e. changing the image_angle) to oDetritus, I can anchor the oTurret to a specific position on the ODetritus, using its sprite as a guideline. In this case, the desired x and y for the oTurret, in relation to the oDetritus's x and y origin, are x - 37 and y + 192.

I can make the oDetritus the Owner of the oTurret, and make sure that the oTurret 'sticks' with the following in its Step event:

if instance_exists(Owner) {
x = Owner.x - 37
y = Owner.y + 192
}

However, how would I adjust this to account for rotating the image_angle of the oDetritus object underneath? Obviously then the x and y values would be wrong. I have tried using lengthdir_x and lengthdir_y, but this doesn't seem to be the correct function here.


texts: Textures rotated 90 degrees when importing a .glb file

texts:
I have a simple box, textured with bricks, in Blender:

I export this scene as glTF 2.0 and import into Godot. Here's the result:

As you can see, the bricks are rotated 90 degrees for some reason. Why, and how can I make it right?


texts:
Pretty much all I'm trying to do is revolve my 2D Array by its container.
I'm using this array for a background and I seem to be having problems with it revolving.

public class TileTransformer : GridConstants
{
    public Tile[,] Tiles;
    ContentManager Content;
    public TileTransformer(ContentManager content)
    {
        Content = content;

    }
    public Tile[,] Wraping(Tile[,] tiles,Point shift)
    {
        Tiles = tiles;
        for (int x = shift.X; x < 0; x++)//Left shift
        {
            for (int X = 0; X < GridWidth; X++)
            {
                for (int Y = 0; Y < GridHeight; Y++)
                {
                    if (X + 1 >GridWidth-1)
                    {
                        Tiles[0, Y].Container =tiles[X, Y].Container;
                    }
                    else
                    {
                        Tiles[X+1, Y].Container =tiles[X, Y].Container;
                    }
                }
            }
        }
        for (int x = shift.X; x > 0; x--)//right shift
        {
            for (int X = 0; X < GridWidth; X++)
            {
                for (int Y = 0; Y< GridHeight; Y++)
                {
                    if (X-1==-1)
                    {
                        Tiles[GridWidth-1, Y].Container =tiles[0, Y].Container;
                    }
                    else
                    {
                        Tiles[X - 1, Y].Container =tiles[X, Y].Container;
                    }
                }
            }
        }
        for (int y = shift.Y; y > 0; y--)//shift up
        {
            for (int X = 0; X < GridWidth; X++)
            {
                for (int Y = 0; Y < GridHeight; Y++)
                {
                    if (Y - 1 == -1)
                    {
                        Tiles[X, GridHeight-1].Container = tiles[X, Y].Container;
                    }
                    else
                    {
                        Tiles[X, Y - 1].Container = tiles[X, Y].Container;
                    }
                }
            }
        }
        for (int y = shift.Y; y < 0; y++)//shift down
        {
            for (int X = 0; X < GridWidth; X++)
            {
                for (int Y = 0; Y < GridHeight; Y++)
                {
                    if (Y + 1 == GridHeight)
                    {
                        Tiles[X, 0].Container = tiles[X, Y].Container;
                    }
                    else
                    {
                        Tiles[X, Y + 1].Container = tiles[X, Y].Container;
                    }
                }
            }
        }
        return Tiles;
    }

Now the Problems that I'm having is either when I shift up or left it seems the whole array is cleared back to the default state. Also when I'm revolving the array it appears to stretch it upon the sides of the screen that it is shifting towards.


texts:
I need a method to scroll an image across all sides of a cube map in a way similar to scrolling a UV texture across a water's texture to give the appearance of movement by shifting the normals. I want to cause certain areas of the skybox to grow in intensity or lower to mimic a twinkle effect for the stars. I'm using a simple perlin noise map to do it, and I just need to find a way to scroll the texture on each side of the cubemap.
I've tried to shift the texture coordinates on the samplerCube in GLSl, but it seemed to move the entire cube instead of just changing the coordinates that the cube gets the texture from.
I also tried using a regular sampler2D, but that resulted in a screen of pure grey somehow.
What can I do to get this effect?


texts:
How do I get a list of all available entities in a Source engine game?

There is only one exported function in the server DLL - CreateInterface - so it's not an option. In GoldSrc games, the server DLL features all entities as exported functions.


texts: Stuck the ball in the board (pingpong game)

texts:
this game isn't completed yet, i've created the part where the ball hits the board, but there's problem in playing and that's the ball stucking in the board. For a better comprehension and understaning i've attached a image down below , plz watch it and lemme know of your take on this bug.

    public partial class PingPong : Form
{
    public PingPong()
    {
        InitializeComponent();
        timer1.Enabled = true;
        timer1.Interval = 30;
    }

    int mx = 5;
    int my = 5;
    private void timer1_Tick(object sender, EventArgs e)
    {

        if (ball.Bounds.IntersectsWith(boardCenter.Bounds))
        {
            mx = mx * -1;
            my = my * 1;
        }
        else if (ball.Location.Y >= this.ClientSize.Height - ball.Height)
        {
            mx = mx * 1;
            my = my * -1;
        }
        else if (ball.Location.Y <= 0)
        {
            mx = mx *1;
            my = my * -1;
        }

        else if (ball.Location.X >= this.ClientSize.Width - ball.Width)
        {
            mx = mx * -1;
            my = my * 1;
        }

        ball.Location = new Point(ball.Location.X + mx, ball.Location.Y + my);

    }

    private void PingPong_KeyDown(object sender, KeyEventArgs e)
    {

        if (e.KeyCode == Keys.Up)
        {
            boardCenter.Location = new Point(boardCenter.Location.X, boardCenter.Location.Y - 4);

        }
        else if (e.KeyCode == Keys.Down)
        {
            boardCenter.Location = new Point(boardCenter.Location.X, boardCenter.Location.Y + 4);
        }

    }

}


texts:
I'm trying to rotate an object (shield) around another object (player) like this question.

My use-case is this: I have players moving around a field. Their respective shield is orbiting in a constant velocity around them. If a "ball"-object (red) touches a player, he's dead. A player can use his shield to deflect a "ball". When a shield collides with the "ball", I want the player and shield be affected by the collision; thus the player should bounce back, keeping the shield at the same distance. Alternatively, on colliding with the "ball" the shield could act like a static object, either way would be okay with me.

I tried connecting the player to the shield via a b2DistanceJoint and

applying a force to the shield (orthogonal to the line between center of player and center of shield i.e. if the shield is right of the player, the force acts downwards; if the shield is below the player, the force acts to the left). This made the shield rotate, but the player's position was affected by the rotation, which resulted in wobbling. Then, I tried changing the density of the shield to turn down the effect on the player, but then the collision with the "ball" was faulty as the ball had way more mass.
"teleporting" the shield to the right position, but the collision with the "ball" was faulty afterwards (the ball "stuck" to the shield)

I know my whole setup is not a realistic physics model, so is there a way to achieve this behaviour in Box2D?

b2Body* body;
{
    b2BodyDef bodyDef;
    bodyDef.type = b2_dynamicBody;
    bodyDef.position.Set(gameToWorld * x, gameToWorld * y);

    body = world.CreateBody(&bodyDef);

    // Define another box shape for our dynamic body.
    b2CircleShape circle;
    circle.m_p.Set(0, 0);
    circle.m_radius = gameToWorld * bodyRadius;

    // Define the dynamic body fixture.
    b2FixtureDef fixtureDef;
    fixtureDef.shape = &circle;

    // Set the box density to be non-zero, so it will be dynamic.
    fixtureDef.density = 1;

    // Override the default friction.
    fixtureDef.friction = 0.0f;

    fixtureDef.restitution = 1.0f;

    // Add the shape to the body.
    body->CreateFixture(&fixtureDef);
}

b2Body* shield;
{
    b2BodyDef bodyDef;
    bodyDef.type = b2_dynamicBody;
    bodyDef.position.Set(gameToWorld * x, gameToWorld * y);

    shield = world.CreateBody(&bodyDef);

    // Define another box shape for our dynamic body.
    b2PolygonShape rect;
    // HERE:
    rect.SetAsBox(1, 1, b2Vec2(0, 0), 45);

    // Define the dynamic body fixture.
    b2FixtureDef fixtureDef;
    fixtureDef.shape = &rect;

    // Set the box density to be non-zero, so it will be dynamic.
    fixtureDef.density = 1;

    // Override the default friction.
    fixtureDef.friction = 0.0f;

    fixtureDef.restitution = 1.0f;

    // Add the shape to the body.
    shield->CreateFixture(&fixtureDef);
}

{
    b2DistanceJointDef def;
    def.bodyA = body;
    def.bodyB = shield;
    def.length = 0;

    world.CreateJoint(&def);
}


texts: Direct3D 11 : Pixel shader and Vertex shader getting set at every draw call

texts:
I'm working on my own (much tinier) version of Monogame. Right now I've been able to draw triangles to the screen with custom shaders using Direct3D 11. The problem is that I can't get it to be as perfomant as Monogame. I did some graphics debugging and noticed something :

The above picture is my implementation and the other is Monogame. For some reason the pixel shader, vertex shader and constant buffers are assigned at every draw call. I don't understand why this is happening since in my code I only ever set those parameter once an then draw a buffer containing 2 triangles 1000 times (as a performance test).


texts:
I am reading this article on how to control the framerate and physics calculations.

But in the game I am writing, I use a third party physics library and the only thing I do to update my physics is call
a single function (runSimulation()).

Since I cannot do things like "interpolation" in the above tutorial, how can I make my game runnable in different hardware/at different framerates?


texts: How can I do optimal pathfinding for a Tetris piece?

texts:
Imagine a standard Tetris board (10x20) using the standard set of 7 tetrominoes.

Given a Tetris game state and a target position, how can I find the optimal sequence of moves that will get the currently active tetromino into that position?

A really basic example:

Clearly, the optimal path is to move to the leftmost column and not rotate the piece. I'd like the algorithm to handle more complex positions too.


texts: Ignoring collisions without using physics layers

texts:
Trying to ignore collisions between certain prefabs, but in this case I don't want to use layers since these are specific object pairs that I want to not collide, and creating a layer for each prefab would complicate the layer matrix more than I want to.

What I tried so far:

public void OnCollisionEnter(Collision collision) {
    if (collision.gameObject.tag == "Bullet") {
        Physics.IgnoreCollision(collision.collider, collider);
    }
}

So I tried ignoring the collision in the OnCollisionEnter, but this only worked partially. The objects did go one through the other, but they both slowed down. My guess is that the first frame of the collision, the one that generated the call to OnCollisionEnter, was calculated regardless of the ignore command.

Any ideas how I can make all bullets not collide to one another, without putting them in a separate layer?


texts: Unity 3D Model imported with offset Mesh

texts:
So I've edited up an image to help show the problem, since showing the game itself is not an option:

When I imported my model, the model appears normally, however when I actually put it into the scene, a duplicate of the mesh appears, off to the left and partially lower (as shown with the edited image above) and normally I would ignore it, however it's causing some issues with the camera, causing it to rotate outside of the model, and I'm guessing it's because this mesh is the center of the model.

I've been using Unity on and off for a few years but in all that time, I've never had this happen. Is it from how the model is imported, or something to do with the model itself? All the models in my game are 100% custom made, there are no assets. I'm really not sure what caused this or how to fix it.

edit: The green mesh is not visible when the game runs, you only see it in the editor.

This effect cannot be recreated with any other model, which is why I had the edited screenshot but just to show you the exact same thing with the above screenshot but in Unity with 2 models. The pink one is the regular model (just picture a different pose) and the green one being the mesh.

Again, the custom made model for this game is the only model I have seen do this and because I am not allowed to upload said model or even images vaguely resembling it, that is why I used the screenshot in the first place.


texts: How to make the camera follow the mouse in first or third person camera

texts:
I currently I have a game made of a few small scripts, the PlayerController, PlayerStats, and CameraChange (each below).

My question is how do I get the camera to follow the mouse movement? I want the player to be able to switch between each camera and look around with the mouse.

Any idea as to how I'd go about doing this? My current theory is I would some how have to access the current active camera and make it follow the mouse but not sure how to do that.

PlayerController-

using UnityEngine;

public class PlayerContorller : MonoBehaviour

{

    // Update is called once per frame
    void Update ()
    {
        var x = Input.GetAxis("Horizontal") * Time.deltaTime * 150.0f;

        var z = Input.GetAxis("Vertical") * Time.deltaTime * 3.0f;

            transform.Rotate(0, x, 0);
        transform.Translate(0, 0, z);
    }
}

PlayerStats-

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

public class PlayerStats : MonoBehaviour {

    public int Health = 100;
    public int Stamina = 100;
    public int magic = 100;

    // Use this for initialization
    void Start () {

    }

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

        }
    }
}

CameraChange-

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

public class CameraChange : MonoBehaviour {

    public GameObject ThirdCam;
    public GameObject FirstCam;
    public int CamMode;

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

        if (Input.GetButtonDown("Camera"))
        {
            if (CamMode == 1)
            {
                CamMode = 0;
            }
            else
            {
                CamMode += 1;
            }
            StartCoroutine(CamChange());
        }
    }
    IEnumerator CamChange()
    {
        yield return new WaitForSeconds(0.01f);
        if(CamMode == 0)
        {
            ThirdCam.SetActive(true);
            FirstCam.SetActive(false);
        }
        if(CamMode == 1)
        {
            FirstCam.SetActive(true);
            ThirdCam.SetActive(false);
        }
    }
}


texts: Adding vectors and applying rotation matrix using quaternion

texts:
I have a problem and looking for help, see attached image. I have a number of points (x,y,z) which are treated as connected vectors (first point as first vector base, second point as first vector end AND second vector base, etc) and I need to know the minimal and maximal coordinate points of the whole connected structure. I only know that rotation matrix using quaternion should be applied in the process, but have no such experience. Any insights or links to similar example would be appreciated.

   auto rx = _coord_x.data(); auto ry = _coord_y.data(); auto rz = _coord_z.data();

// set up dimensions of coordinates

auto ncoords = number_of_vectors();

for (int32_t i = 0; i < ncoords; i++)
{
    //normalization
    float fact = 1.0f / std::sqrt(rx[i] * rx[i] + ry[i] * ry[i] + rz[i] * rz[i]);

    rx[i] *= fact; ry[i] *= fact; rz[i] = fact;

    // rotation matrix ??

  }

}


texts: Can Bullet Physics (or another 3d physics engine) use callbacks in my engine to check static geometry?

texts:
I'm wondering if it's possible to use or hack Bullet 3d Physics (or another free 3D physics engine) so that I don't need to "import" my static geometry into Bullet - instead I want to do it the other way, so Bullet uses some sort of callback system to check geometry properties of my mesh/polygons.

Sort of like that Bullet would expect a method in my static geometry classes "checkRayIntersection" or similar, and I take care of the details and optimizations myself. The meshes are immovable, so the only thing that I expect Bullet to care about is intersections and their normals, but I might be missing something..

EDIT: as an example, consider a 10 million polygon terrain mesh which is changing all the time. You probably don't want to keep parallel data structures in the render-engine and in the physics engine for this. You don't want to use an approximation for the physics either.

Bullet uses something called MotionStates to solve this problem for its output - I was hoping there was a similar design pattern for passing geometry input.