texts: Hide building roof & Hide faces/vertices depending on world location

texts:
I'm currently developing a small game for my own enjoyment and I've ran into a problem. As you probably know many third person games (such as Runescape and XCOM, for example) hide the roofs when you enter a building so that you can still see your character. I'm using lwjgl and my current solution is to use clipping planes to simply stop rendering everything above a certain height when the player is inside of a building, but this gives bad results because if there are other buildings or tall entities nearby they are also not rendered above that plane.

I've thought of some solutions - one of them being to simply hide certain faces/vertices when I'm in certain areas. This could also be applied to other things than just buildings as well. Is this the right way to approach this problem? Or is there a better way to handle this?

PS. I'm not very experienced with openGL (especially shaders), so if the solution requires shader work I might need more detailed descriptions.


texts:
I want to be able to create addons for any game, the example I will use is League of Legends. With addons I mean, for example when my level integer changes I want to play a sound in the background.

The programming language I want to use is C#.

What I want to know is how I'm able to read my level integer inside C#, from there on I should be able to do anything I want.

What I've found out is, with a program like Cheat Engine you can look for memory values and adresses inside your RAM. And I think there is a way to assign a variable in C# to the value of a memory adress. But how can I find the value of my level in the first place? The memory adress might change each time I start the game or even level up. I think it has something to do with pointers, but where do I find the pointer?

But the biggest problem is that I can't even find some values I look for iside the memory. Maybe it encrypts the values? How can I find out what it does and where it puts it? An example is Flash games. If you look for the variable money that has a value of 100 you need to multiply it by 8 and look for 800 iside the memory of that process.

How do I find the correct memory adress each time?
How do I find out the way it might save a variable?

I'll give any extra information about the problem if you want.


texts:
I want to be able to have physics objects semi-buried in leaves, dirt, or whatever and be able to have the player click on the area a couple times to uncover them, and he can't pick it up until he has uncovered it.  (He picks it up also by LMB.)
How can I achieve this?  I am using blueprints.  Can anyone show me how?


texts: d3d11 renderqueue multi pass rendering design best practice

texts:
The goal: issue least calls to d3d11 ImmediateContext and render advanced effects like toon / outline / anything that requires rendering the same vertex buffers with at least two different vertex shader and pixel shader programs efficiently by sorting opaque drawcalls front to back and transparent drawcalls back to front.

What I did: Abstract calls to d3d11 immediate context by a DrawCall struct that acts as a gpu command recorder. A call to DrawCall.SetIndexBuffer will create a c# Action that will issue a call on the ImmediateContext upon invoke call. The DrawCall internal gpu command list is sorted the following way: set shaders, set constantbuffers, set blendstate, set stencilstate, set vertexbuffers.... I am using sharpdx and c#.

My problem: I use a 64bit sortkey for my gpu commands. When rendering complex effects like outline or anything that requires state changes to outputmerger the whole idea with sorting doesn't seem right... example: I render opaque objects first and then transparent objects... I want to render an object opaque with a diffuse shader and it should have a red transparent outline. For this effect I have to modify stencil and blend states in between drawindexed calls. According to my sortkey those gpu commands are on different draw loops opaque<>transparent but the stencilstate requires both drawindexed calls to be one after another.

Should I implement a chained gpu command for multipass rendering or are there better ways to handle such effects?


texts:
Can you change Unity's default script template for a single project?

Here it's explained how to do that globally and it's fine, I wonder if you can do it on a per-project basis.

I mean, I'd bet you can't or I would have been able to find it, but maybe I missed something, or there's a plugin, who knows...


texts:
I am designing a new game and I am trying out the entity-component design where entities are comprised of groups of components holding a bunch of attributes. I also have a stack of 'game states' and 'game systems'. On creation, a new state grabs a bunch of (singleton) system s from a provider of systems. The systems are created at the beginning and maintain a list of entities that are relevant to it by inspecting what components are on the entity. At the moment I have the game logic within a bunch of 'systems', the state simply maintains a list of systems to update/draw.

I realize that the state should really be holding all information relevant to the state. For instance the state should be holding the information on who's turn it is e.t.c. I have it so the system stores all information on the state at the moment and accesses it via the observer pattern. This is turn leads to all sorts of problems as it pretty much couples the system s to the state + it makes the code pretty messy and inefficient.

For instance I have a movement system that is interested in entites with the 'movable' component. The system needs to read from the state who can move at this point. How far they are allowed to move and also controller input to actually do the move. For each of these things I must access the observer methods to modify the state from the system.

The game is turn based at the moment and one of the states is a movement state, it has two systems registered to it, a movement system and a camera system which it updates in turn.

At the moment the movement system gets from the state an entityId representing the 'selected' entity and checks input to see if the player is moving it. If moved the 'location' component is updated on the entity and the system stores the location onto the state via the observer. The camera system then looks up this location on the state and updates the entity with the 'camera' component with this location.

The solution I have at the moment does not seem elegant at all and it is extremely long winded to implement even simple functionality. I am thinking I am doing something fundamentally wrong with the design. I have a few questions that come to mind:

Should the state hold the list of entities and do the logic?

The systems should maybe only be pure logic calls at this point that hold no variables.
How would I handle entities in this situation? I can envisage a state holding loads of entities only to be used for specific segments of the logic.

Should the components hold the logic?
Should I just make the systems into 'micro-states'? Which is to make them separate instances and have them hold local variables needed for the state.


texts: Unity DontDestroyOnLoad not always working after Android build

texts:
I've been using this small script as a component to any object I want to not be destroyed at scene loading.
public class DontDestroy : MonoBehaviour
{
    void Start()
    {
        DontDestroyOnLoad(gameObject);
    }
}

It has been working fine. It works for my GameOver canvas which I've been using for a long time whilst making the game.
Today I added the same script to a new AndroidControls Canvas I made. In the Editor it worked fine. Then I built it for Android to run on my physical phone (Galaxy S10). It gave me a Null exception.
It turned out to be caused by the AndroidControls Canvas being destroyed between scene loading (even though as I say, I tested in Editor for a few runs and it didnt get destroyed). And it gets a little weirder because after the attempted build to APK, and fail on physical device, it then failed to work in the editor. It continues to not work in each test after this in Editor, however if I remove the component and add it again, the entire process then repeats.
Please help as I don't have a clue how to start fixing this. The only thing I can imagine it being wrong is it started as soon as I used this script on two canvas's simultaneously. (I highly doubt I am correct but it's the only thing I could notice at all that might be causing this).
This picture actually shows my DontDestroy component is attached to Canvas_AndroidControls, but in the Hierarchy you can already see that it is not in the DontDestroyOnLoad section (excuse the pink overlay for play-mode):

Maybe relevant, here are some of my specs:
Win 10
Unity 2020.3.5f1 (Just downloaded NDK/SDK for Android today via Unity Modules)
Android 11 (Samsung Galaxy S10)


texts: MonoGame - Left/Right Sided Collision Not Working

texts:
I'm working on a platformer as part of my course, the problem I have come across is Left/Right sided collision is not working very well. I already have bottom & top collision working. Here is an example of the problem in action:

As you can see pretty much all the time I'm slowing down, I know this issue but haven't found a work around code solution yet. The main problem I'm having as you can see is my player being able to slide almost into the middle of the block if he's coming down and moves into the block.

The slow down problem is due to my left/right collision code, I just haven't found a viable solution yet for sided collision.

Collision Code:

        foreach (SkyTile block in PlatformBlocks)
        {

            IntersectRectangle = block.GetRect();
            GetRect().Intersects(ref IntersectRectangle, out IntersectResult);
            if (GetRect().Intersects(block.GetRect()))
            {
                if (IntersectResult && (IntersectRectangle.Bottom > GetRect().Bottom))
                {
                    isPlatformColliding = true;
                }

                if (IntersectResult && (IntersectRectangle.Top < GetRect().Top))
                {
                    isPlatformBottomColliding = true;
                }

                if (IntersectResult && (IntersectRectangle.Left > GetRect().Left))
                {
                    isPlatformLeftColliding = true;
                }

                if (IntersectResult && (IntersectRectangle.Right < GetRect().Right))
                {
                    isPlatformRightColliding = true;
                }
                break;
            }
        }

        if (isPlatformColliding)
        {
            velocity.Y = 0;
        }

        if (isPlatformBottomColliding && !isPlatformColliding)
        {
            velocity.Y = 20;
        }

        if (isPlatformLeftColliding)
        {
            velocity.X = 0;
        }

        if (isPlatformRightColliding)
        {
            velocity.X = -0;
        }


texts: Transform bone absolute position to relative position

texts:
I'm working on adding IK to my engine and right now I'm implementing the FABRIK algorithm to give full support to more than three bones.
The algorithm works by giving the joints positions, the start position (first joint), the target, and a threshold. I have already wrote the code and, as far as I can tell, it is correct.
When I use the algorithm I feed the world positions of each bones in the current frame and the target to reach and then the algorithm returns the position each bone should be in.
The issue is that the positions returned are also in WS and my animation library, Cal3D's setTranslation function, requires the relative translation of the bone (if I'm not wrong, this is the position relative to the father bone).
Does anybody know how I should transform the WS my bone is supposed to be at to the relative position I must give to the setTranslation method? Is that possible?


texts:
I am learning to use FBOs and one of the things that I need to do when rendering something onto user defined FBO, I have to setup the projection, modelview and viewport for it. Once I am done rendering to the FBO, I need to restore these matrices. I found:

glPushAttrib(GL_VIEWPORT_BIT);
glPopAttrib();

to restore the viewport to its old state. Is there a way to restore the projection and modelview matrix to whatever it was earlier ?

Tech: C++/OpenGL

Thanks!


texts: Entity component system, Communication between components

texts:
I am trying to implement ECS for my simple 2D game. I would like to ask a question about how components should communicate between themselves and with entity.

I tried to implement few components, like SpriteComponent, MoveComponent, CollisionComponent, etc.. What is the appropriate way of communication between these components? E.g. my Sprite & Physics components need to know about current position, which is affected by Move component. I gave every single of my components handle that refers to the entity, which they can send to engine and call different functions, like updatePosition(EntityHandle handle, float x, float y). Is this the right approach?


texts: How can I add a transparent overlay to a UI in libGDX?

texts:
I am attempting to use the following code

        shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
        shapeRenderer.setColor(3,3,3,.3f);
        shapeRenderer.rect(0,0,gameWidth,gameHeight);
        shapeRenderer.end();

So that when the menu is accessed, a transparent background appears. The problem I am facing is that when I try to do this the objects rendered by the SpriteBatch seem to misbehave. Upon further research i found that attempting to nest that code within SpriteBatch.begin() and SpriteBatch.end() is the cause of that. However, If I try to place the code after the SpriteBatch.end(), because the SpriteBatch has ended the objects rendered by it do not appear behind the transparent rectangle.
(I tried assigning SpriteBatch and Shaperender a different camera, however, that didn't fix the problem.) How can I fix this or find another way to implement the transparent background for the menu.


texts: Where to store constantly changing game data such as duels data?

texts:
I'm making a discord bot which allows players to collect and duel cards. All the cards, players and other data is stored in MongoDB but where should I store duels data? Duels data will keep changing as player's make moves thus mongoDB might affect performance significantly.

Another issue is time mangement, a turn lasts for 60 seconds and duel lasts for 600 seconds, I can't update timer in mongoDB every 1 second to reflect how much time is left. I was previously using redis for these purposes but redis has really basic structure which causes code to become really messy thus making it extremely difficult to add new features.

What are your suggestions? How should I go about storing duel data?

Here's the data that I want to store:

duelID (String)
player1ID (String)
player2ID (String)
betAmount (Integer)
currentTurn (String)
currentPhase (String)
player1Health (Integer)
player2Health (Integer)
playedCharacterCard (Boolean)
player1Hand (Array<Objects>)
player2Hand (Array<Objects>)
player1Spots (Array<Objects>)
player2Spots (Array<Objects>)


texts: Rectangle collision doesn't work on WP 8

texts:
Collision detection is not working correctly when my 64x64 pixel block touches a bigger block. The big(rect2big) block measures 128x128 pixel. The falling block should change it's color to black when it touches another block, but that's not working if it touches the big block. The falling block changes it's color far too late when it touches the big block. You can see that in this video: http://www.vidup.de/v/QFeTK/

What is wrong? Why is collision detection not working correctly when the falling block touches the big block?

public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    Texture2D rect, rectbig;
    Rectangle rect1, rect2, rect2big;
    bool rectcollision = false;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
        TargetElapsedTime = TimeSpan.FromTicks(333333);
        InactiveSleepTime = TimeSpan.FromSeconds(1);
        this.graphics.PreferredBackBufferWidth = 480;
        this.graphics.PreferredBackBufferHeight = 800;
        graphics.IsFullScreen = true;
    }

    protected override void Initialize()
    {
        base.Initialize();
    }

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
        rect = Content.Load<Texture2D>("block64");
        rectbig = Content.Load<Texture2D>("block128");
        rect1 = new Rectangle(200, 0, rect.Width, rect.Height);
        rect2 = new Rectangle(200, 200, rect.Width, rect.Height);
        rect2big = new Rectangle(200, 400, rectbig.Width, rectbig.Height);
    }

    protected override void Update(GameTime gameTime)
    {
        rect1 = new Rectangle(rect1.X, (int)(rect1.Y+1.0f), rect.Width, rect.Height);

        if (rect1.Intersects(rect2) || rect1.Intersects(rect2big))
        {
            rectcollision = true;
        }
        else
            rectcollision = false;

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);
        spriteBatch.Begin();
        spriteBatch.Draw(rect, rect2, null, Color.White, 0, new Vector2(rect.Width / 2, rect.Height / 2), SpriteEffects.None, 1);
        spriteBatch.Draw(rectbig, rect2big, null, Color.White, 0, new Vector2(rectbig.Width / 2, rectbig.Height / 2), SpriteEffects.None, 1);
        if (rectcollision == true)
          spriteBatch.Draw(rect, rect1, null, Color.Black, 0, new Vector2(rect.Width / 2, rect.Height / 2), SpriteEffects.None, 1);
        else
            spriteBatch.Draw(rect, rect1, null, Color.White, 0, new Vector2(rect.Width / 2, rect.Height / 2), SpriteEffects.None, 1);
        spriteBatch.End();
        base.Draw(gameTime);
    }
}


texts: How do AI agents access information about their environment?

texts:
This might be kind of a trivial question, but I am having trouble understanding this. Would very much appreciate your help.

In game development using object oriented design, I want to understand how AI-agents access the information they need from the game world in order to perform their actions.

As we all know, in games very often AI agents need to 'perceive their environment' and act according to what is happening around them. For example, an agent might be programmed to chase the player if he/she gets close enough, avoid obstacles while moving (using the Obstacle Avoidance steering behavior), etc.

My problem is I'm not sure how to do that. How can an AI agent access the information it needs about the game world?

One possible approach is that the agents simply request the information they need directly from the game world.

There's a class called GameWorld. It handles important game logic (game loop, collision detection, etc), and also holds references to all of the entities in the game.

I could make this class a Singleton. When an agent needs information from the game world, it simply gets it directly from the GameWorld instance.

For example, an agent might be programmed to Seek the player when he/she is close. In order to do this the agent has to get the player's position. So it can simply request it directly: GameWorld.instance().getPlayerPosition().

An agent could also just get the list of all the entities in the game, and analyze it for it's needs (to figure out what entities are close by , or anything else): GameWorld.instance().getEntityList()

This is the simplest approach: agents contact the GameWorld class directly and get the information they need. However, this is the only approach I know. is there a better one?

How would an experienced game developer design this? Is the "get a list of all the entities and look for whatever you need" approach naive? What approaches and mechanisms are there to allow AI agents to access the information they need in order to perform their actions?


texts: What does a linear transformation preserve?

texts: They say an affine transformation preserves points, lines, parallel lines etc. I can see this if I think in terms of translation [Is there any other affine transformation you can give as an example, btw] But, what does a linear transformation preserve? By its definition, it seems like they preserve vector space structure. Geometrically what does that correspond to? For example, some of them preserve angles and distance but not all of them. Some preserve linear independence but I am guessing not all of them. What geometric property all of these linear transformations preserve?


texts: Unity 3d - Touchscript Asset: Get object when "touched"

texts:
I have a question regarding the exact method for getting the game object that I'm touching. I thought it would be getting the name of the PressGesture once the touch starts...but it returns me a Swipe Controller object name, so that is not the correct. I have read, though not extensively, the TouchScript documentation, but I haven't found a method that gets information from the point you are touching/clicking

This is the code that tries to solve that issue (of course, the wrong way):

private void pressedHandler(object sender, EventArgs e)
{
    PressGesture gesture = sender as PressGesture;
    TouchHit hit;
    gesture.GetTargetHitResult (out hit);
    startPos = hit.Point;

    if(gesture.gameObject == this.swipePositions[0])
    {
        Debug.Log ("Pressed on: " + gesture.gameObject.name + " at: " + startPos);
    }
    else
    {
        Debug.Log("Not even from the start...");
        Debug.Log("This name is: " +gesture.gameObject.name);
        Debug.Log("The name should be: " +this.swipePositions[0].name);
    }
}


texts: Is there a name for this technique to put the tiles on the corner of a level?

texts:
A very common approach in development of old games is to put the tile set on the corner of a level, to use it as a reference. For example:

On this level, the developers put a set of tiles in the upper left corner.

But is there a name for this technique? I'm writing a manual about that and I would like to name it.


texts: Application using JOGL stays in Limbo when closing

texts:
I'm writing a game using Java and OpenGL using the JOGL bindings. I noticed that my game doesn't terminate properly when closing the window even though I've set the closing operation of the JFrame to EXIT_ON_CLOSE. I couldn't track down where the problem was so I've made a small reproduction case. Note that on some computers the program terminates normally when closing the window but on other computers (notably my own) something in the JVM keeps lingering, this causes the JFrame to never be disposed and the application to never exit. I haven't found something in common between the computers that had difficulty terminating. All computers had Windows 7, Java 7 and the same version of JOGL and some terminated normally while others had this problem.

The test case is as follows:

public class App extends JFrame implements GLEventListener
{
    private GLCanvas canvas;

    @Override
    public void display(GLAutoDrawable drawable)
    {
        GL3 gl = drawable.getGL().getGL3();

        gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
        gl.glClear(GL3.GL_COLOR_BUFFER_BIT);

        gl.glFlush();
    }

    // The overrides for dispose (the OpenGL one), init and reshape are empty

    public App(String title, boolean full_screen, int width, int height)
    {
        //snipped setting the width and height of the JFRAME

        GLProfile profile = GLProfile.get(GLProfile.GL3);
        GLCapabilities capabilities = new GLCapabilities(profile);

        canvas = new GLCanvas(capabilities);
        canvas.addGLEventListener(this);
        canvas.setSize(getWidth(), getHeight());

        add(canvas);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //!!!

        setVisible(true);
    }

    @Override
    public void dispose()
    {
        System.out.println("HELP"); //
    }

    public static void main( String[] args )
    {
        new App("gltut 01", false, 1280, 720);
    }
}

As you can see this doesn't do much more than adding a GLCanvas to the frame and registering the main class as the GLEventListener.

So what keeps lingering? I'm not sure. I've made some screenshots.

The application running normally.

The application after the JFrame is closed, note that the JVM still hasn't exited or printed a return code.

The application after it was force closed.

Note the return code -1, so it wasnt just the JVM standing by or something the application really hadn't exited yet.

So what is keeping the application in Limbo? Might it be the circular reference between the GLCanvas and the JFrame? I thought the GC could figure that out. If so how should I deal with that when I want to exit? Is there any other clean-up required when using JOGL? I've tried searching but it doesn't seem to be necessary.

Edit, to clarify: there are 2 dispose functions dispose(GLAutoDrawable arg) which is a member of GLEventListener and dispose() which is a member of JFrame. The first one is called correctly (but I wouldn't know what to there, destroying the GLAutoDrawable or the GLCanvas gives an infinite exception loop) the second one is never called.

Edit 2, October 30th
I've tried the following suggestions as per the comments:

Setting the default close operation to DISPOSE_ON_CLOSE doesn't have any effect
Adding an adapter for the windowClosing works and it is properly called but calling System.exit(0); there doesn't stop the program, something is left behind.
Adding a shutdown hook works and shutdown hooks are correctly processed however even adding exit there doesn't help.


texts: Seperating Axis Theorom For Collision Detection issues

texts:
I have been attempting to use the SAT test to determine whether two of my convex meshes are colliding, however I've encountered are rather strange issue. The algorithm does determine whether the objects are colliding but sometimes it seems to almost ignore orientation of one of the objects.

I am for the record, performing collisions on the polygon itself however it appears as if i am performing collision detection of the bounding box of the object. Strangely if i change the orientation of the platform that the cube is sitting on, the cube will collide with the surface of the platform in a similar way, with it appearing to collide the cube's bounding box with the platform's surface.

Even more strangely if i force the cube to collide with the platform then it functions correctly:

Here's the code I've implemented, i'm aware there's a couple inefficiencies in the code but i'm just trying to get it running properly first:

public CollisionData convexCollisions(Mesh a, Mesh b){
    CollisionData data = new CollisionData();
    data.penetration_depth=Double.MAX_VALUE;
    double s1_min, s2_min, s1_max, s2_max;

    //TEST OBJECTS AGAINST THE POTENTIAL AXIS FROM MESH A

    //rotation matrix for the normals
    double[][] rot_mat=Matrix.rotationYawPitchRoll(a.rotation.x, a.rotation.y, a.rotation.z);

    for(int i=0; i<a.faces.size(); i++){

        //the normals are stored in model space so i have to convert them to world space by rotating them according to the meshes orientation
        Vector3 normal = Matrix.vectorMatrixMultiply(a.faces.get(i).normal, rot_mat).normalize();

        double[] a_test=SATtest(normal, a.vertices);
        s1_min=a_test[0];
        s1_max=a_test[1];
        double[] b_test=SATtest(normal, b.vertices);
        s2_min=b_test[0];
        s2_max=b_test[1];

        double overlap=getOverlap(s1_min, s1_max, s2_min, s2_max);

        //if the overlap is negative, there is no collision so early out
        if(overlap<0){
            return null;
        }else {
            if(overlap<data.penetration_depth) {
                data.penetration_depth=overlap;
                data.normal=normal;
            }
        }
    }

    //TEST OBJECTS AGAINST POTENTIAL AXIS FROM MESH B

    rot_mat=Matrix.rotationYawPitchRoll(b.rotation.x, b.rotation.y, b.rotation.z);

    for(int i=0; i<b.faces.size(); i++){
        Vector3 normal = Matrix.vectorMatrixMultiply(b.faces.get(i).normal, rot_mat).normalize();

        //double s1_min, s2_min, s1_max, s2_max;
        double[] a_test=SATtest(normal, a.vertices);
        s1_min=a_test[0];
        s1_max=a_test[1];
        double[] b_test=SATtest(normal, b.vertices);
        s2_min=b_test[0];
        s2_max=b_test[1];

        double overlap=getOverlap(s1_min, s1_max, s2_min, s2_max);

        //if the overlap is negative, there is no collision so early out
        if(overlap<0){
            return null;
        }else {
            if(overlap<data.penetration_depth) {
                data.penetration_depth=overlap;
                data.normal=normal;
            }
        }
    }
    return data;
}

public double[] SATtest(Vector3 axis, Vertex[] points){
    double minAlong = Double.MAX_VALUE;
    double maxAlong = Double.MIN_VALUE;

    for(int i=0; i<points.length; i++){
        double dotAlongAxis = points[i].world_coordinates.dot(axis);
        minAlong=(dotAlongAxis<minAlong)?dotAlongAxis:minAlong;
        maxAlong=(dotAlongAxis>maxAlong)?dotAlongAxis:maxAlong;
    }

    return new double[]{minAlong, maxAlong};
}

public double getOverlap(double s1_min, double s1_max, double s2_min, double s2_max){
    return Math.min(s1_max, s2_max)-Math.max(s1_min, s2_min);
}

So it is safe to say that i am thoroughly confused, if anyone has any suggestions on what the issue could be i'd appreciate it.


texts: client-side array in the OpenGL 3.3. core

texts:
It is possible the topic (not using VBO)?

in the OpenGL 3.0 compatible profile I can to draw this way:

GLint position_index = attrib_location_get("VertexPosition");
gl::EnableVertexAttribArray(position_index);
gl::VertexAttribPointer(position_index, 3, gl::FLOAT, false, 0, pos_Data);
gl::DrawArrays(gl::TRIANGLES, 0, count_of_vertices);

Bat in the OpenGL 3.3 core profile it displays a blank screen. It is right?


texts: How do I run an APK in a device from the Unity IDE without rebuilding the binary?

texts:
I know that the button Build creates the APK in my disk.

And the button Build and Run creates it and sends it to a real device if connected via USB.

Question:

Is there any way to "Run" from the Unity IDE an APK in a physical device without having to re-build it (provided you properly built it a few minutes ago, for example?)


texts: Client AI calculations vs. Server AI calculations

texts:
I have been thinking about a game which would have an AI, and the AI would ideally do extensive calculations thinking many turns in advance.
I am curious if there is some way to put most of the burden of the AI calculations on the client while still preventing cheating. Obviously some processing has to be done on the server, but is there a way to find some happy middle?


texts: How to set a directory to download assetbundles from?

texts: Hi I'm using unity and I've created an AssetBundle file containing two different sprites. I set it's path to my desktop and I can load my assets. But how to download the AssetBundle from a directory on the web. How can I set a directory for everyone to be able to download the AssetBundle?


texts: Unable to hide / destroy AdMob Ads in Unity

texts:
I am currently working on a small game project and I want to monetize my game with AdMob ads. So I watched this YouTube Tutorial.

It works fine, but the problem is ad appears in all the scenes. So I don't want that. I want the ads on certain scenes.

For example, look at the image below.

I want the ad on Instruction scene. So when the player clicks on Back To Main Menu button ad should disappear.

I tried

bannerView.Hide ();
bannerView.Destroy();

but Unity gives some errors, it says:

error CS0103: The name bannerView does not exist in the current context

Here is the script:

using UnityEngine;
using System.Collections;

// AdMob
using GoogleMobileAds.Api;

public class Instruction_Level_Manager_Script : MonoBehaviour
{
  // Audio
  public AudioClip My_Audio_Clip ;
  private AudioSource My_Audio ;

  // Use this for initialization
  void Start ()
  {
    My_Audio = GetComponent<AudioSource>();

    // AdMob Ad
    RequestBanner ();
  }

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

  // Back to Main Menu
  public void Back_To_Main_Menu(string Main_Menu)
  {
    //Playing Audio
    My_Audio.PlayOneShot(My_Audio_Clip);

    //Destroy when leaving the level
    bannerView.Hide ();
    bannerView.Destroy();

    Application.LoadLevel (Main_Menu);
  }

  // AdMob Advertisement
  private void RequestBanner()
  {
    #if UNITY_ANDROID
    string adUnitId = "ca-app-pub-xxxxxxxx/xxxxxxxx";
    #elif UNITY_IPHONE
    string adUnitId = "INSERT_IOS_BANNER_AD_UNIT_ID_HERE";
    #else
    string adUnitId = "unexpected_platform";
    #endif

    // Create a 320x50 banner at the top of the screen.
    BannerView bannerView = new BannerView(adUnitId, AdSize.Banner, AdPosition.Top);
    // Create an empty ad request.
    AdRequest request = new AdRequest.Builder().Build();
    // Load the banner with the request.
    bannerView.LoadAd(request);
  }
}

So what is wrong with this script? I Googled it, but couldn't find satisfying solution. If this method is not possible, how can I destroy the ad?

I am using Unity 5.


texts: Does the linear attenuation component in lighting models have a physical counterpart?

texts:
In OpenGL (and other systems) the distance attenuation factor for point lights is something like 1/(c+kd+sd^2), where d is the distance from the light and c, k and s are constants.

I understand the sd^2 component which models the well known physically accurate "inverse square law" attenuation expected in reality.

I guess the constant c, usually one, is there to deal with very small values of d (and divide-by-zero defense perhaps?).

What role does the linear kd component have in the model, (by default k is zero in OpenGL). When would you use other values for k? I know that this is called the "linear attenuation" component, but what behavior does it simulate in the lighting model? It doesn't seem appear in any physical model of light that I'm aware of.

[EDIT]

It has been pointed out by David Gouveia that the linear factor might be used to help make the scene 'look' closer to what the developer/artist intended, or to better control the rate at which the light falls off.
In which case my question becomes "does the linear attenuation factor have a physics counterpart or is it just used as a fudge factor to help control the quality of light in the scene?"


texts:
I am researching Interaction Latency - the delay between pressing a key and seeing the result on screen.

I have my Unity3D application deployed remotely to an EC2 instance on AWS. I have another application, on the client, sending keyboard and mouse events to the server Unity3D application.

My goal is to measure the time between pressing a key or moving the mouse on the client and having the corresponding image displayed (on the client!). A GUID is sent from the client to the server and when the image comes back, it has the GUID that supposedly matches the command which generated the command which calls ReadPixels (yes, I know RenderTarget is faster, but I do not have the Pro license, yet).

My system works well, but I am concerned that the frame that the client receives (and which I measure against), is not the result of key that was pressed. The reason for this is because Unity3D renders, regardless of whether or not it received a command from the client application.

I'd like to only render if a key press is received from the client.

How can I do this? Any suggestions on how to measure the delay between the client key press and the updated image on the client is also welcome.


texts: How do you make the first person object the main camera?

texts: How can a first person object character be made to be the primary viewing camera in unityscript? Do I remove the main camera? or just turn one or the other on/off?


texts: How to make a property visible in the inspector window if another property is true

texts: How can I make one condition visible in the inspector window if another is true and hidden if false? For example, if isLightON  = true then isLightBright should be visible else if isLightON  = false then isLightBright should be hidden. I know this is suppose to be done using editor coding but not sure exactly how it is to be done.


texts:
I made a new project with the Android module installed, which works fine as I can build and run it on my phone when connected to my computer via USB, and yet can't get Unity Remote to work. Edit/Project Settings/Editor/Device won't display my phone's name.
I tried several internet solutions I found (such as closing and opening again both Unity and Unity Remote or enabling PTP transfer) and none worked.
Any ideas on what could be going on?


texts: How do I convert positions between local coordinate systems?

texts:
Say I have worlds and levels. Each world contains multiple levels. Levels have their own coordinate system, centered around their pivot point (assume its centre, for example). These level coordinates are expressed in floats.

Each level have has int64 coordinate.

Now I have game objects which should seamlessly travel between levels in the world. How can I transition between coordinates inside these levels?


texts: How to launch Libgdx cross-platform (Android, HTML, Desktop) multiplayer client with socket?

texts:
So i'm struggling with making my cross-platform client side to work, specifically on HTML part.
I have java server that is responsible for all the controls and events, and I control it via netty-socketio. Client is Libgdx, and desktop version works flawlessly when using io.socket.client.IO class and Gson for json serialization. The implementation of game is clunky, but everything works and multiple clients can join, move and play.

Everything went south when i tried to launch html client. Nothing seems to be working and i have ran out of ideas of what to do. This is the errors i get

[ERROR] Line 4: The import org.json cannot be resolved
[ERROR] Line 5: The import org.json cannot be resolved
[ERROR] Line 11: JSONObject cannot be resolved to a type
[ERROR] Line 12: JSONException cannot be resolved to a type

together with

[ERROR] Line 15: No source code is available for type io.socket.client.Socket; did you forget to inherit a required module?
[ERROR] Line 17: No source code is available for type com.google.gson.Gson; did you forget to inherit a required module?
[ERROR] Line 20: No source code is available for type com.google.gson.GsonBuilder; did you forget to inherit a required module?
[ERROR] Line 45: No source code is available for type io.socket.client.IO; did you forget to inherit a required module?
[ERROR] Line 47: No source code is available for type java.net.URISyntaxException; did you forget to inherit a required module?

Quick googling says, that i cannot use io.socket.client and gson in GWT.
So i'm here, trying to find some guidance, because everything I run into seems to be old and outdated. I hope someone can help me:

Is it possible to run single libgdx code for all platforms and communicate with server via socket (or anything at this point)
What libraries/repositories should I use to achieve this.
How exactly do i configure my html part to work correctly (I failed to find a single decent tutorial when using libgdx socket with html)


texts: Strange artefacts on objects behind glass in Unity 5

texts:
I think the image speaks for itself. Basically all those little dots shouldn't be there, and they go away as soon as I hide or move the glass. Any ideas on how to fix it?

This is the glass materials settings:


texts: How do I keep 1v1 player positions consistent over UDP on Kryonet?

texts:
I have a server which is simple:

When two connections comes in, it opens a game room, pass their connections to it and runs a thread with a gameloop. (Everything is running on Kryonet)

So... I made the movement, it works on TCP and UDP, but it has to be done via UDP, cause it will be a real-time game, there is no place for a lag. After switching updating positions to UDP, as we all know, some of the packets are lost. Sometimes the server is loosing some packets and it doesn't send them to the second client - that's why the opponent seems to move by 2x, not by x (it happens only sometimes).

My question is: How this kind of things should be implemented? How everything should be handled, I mean - sending states (walking, running), positions etc that there is no visible lagg? Should I send the packets more often? I heard once, that the server should also save player's positions and send it back to him and his opponent (to avoid cheating and laggs). I know how to implement these things, but I don't know how should it look like in a real-time fighting game.

If there is any experienced programmer, that could give me an advice, I would be grateful.


texts: I have a plate object which is generated somehow (I don't care how), now I want to put another object within this object on random position. Lets say that I want to put random trees on this plate. How can I achieve this in Unity. I had read for bounds but I don't know how to use it to generate position for the tree.


texts: What are the possible techniques to optimize the lighting pass in a deferred shading renderer?

texts:
I am toying around with "modern" OpenGL (this is my first attempt, I am new to this) and I have been developping my own deferred shading renderer as an exercise.

I am using an FBO with the following attachments:

DS : Depth/Stencil (GL_DEPTH32F_STENCIL8)
RT0: Position (GL_RGB16F)
RT1: Normal (GL_RGB16F)
RT2: Albedo (GL_RGB16F)
RT3: Postprocessing buffer 0
RT4: Postprocessing buffer 1

Depth + RT0, 1, 2 are filled first in one single geometry pass.

Then for each light source (point lights only for now, spheres are used as light volumes):

Stencil pass to limit light calculation to where it actually has an effect
Light pass: light contribution is accumulated in RT3

From this point on, I am only rendering a quad the size of the screen and fragment shaders are used to compute the next image.

Albedo (RT2) and Light (RT3) are blended into RT4: I now have my lit image.

I can enable more postprocessng shaders (FXAA, Depth of field, ...), in which case RT3 and RT4 are used for ping-ponging.

The thing is, even with no postprocessing, not that many lights (around 10) and a very simple scene (roughly 5k vertices), my frame rate drops like significantly as soon as I increase resolution or add more lights.

It looks like my light pass is responsible for most of this but how can I track down what exactly is slowing everything down? Are there any tricks to optimize it? Is there anything I am missing?

Thanks!

Light Fragment Shader for reference:

uniform sampler2D position;
uniform sampler2D normal;
uniform float screenw;
uniform float screenh;

uniform vec3 light_pos;
uniform vec3 camera_pos;
uniform vec4 diffuse;
uniform vec4 ambient;
uniform vec4 specular;
uniform float outer_radius;
uniform float inner_radius;

float specular_hardness = 100.0;

vec4 calc_point_light(vec3 p, vec3 n)
{
    vec3 light_dir = light_pos - p;
    float d_to_light = length(light_dir);

    light_dir = normalize(light_dir);

    vec3 eye_dir = normalize(camera_pos - p);
    vec3 half_vec = normalize(light_dir + eye_dir);

    float attenuation = (outer_radius - d_to_light) / (outer_radius - inner_radius);
    attenuation = max(min(attenuation, 1.0), 0.0);

    vec3 c = ambient.rgb * ambient.a;
    c += diffuse.rgb * max(dot(n, light_dir), 0.0) * diffuse.a;
    c += specular.rgb * pow(max(dot(n, half_vec), 0), specular_hardness) *
        specular.a;

    return vec4(clamp(c, 0.0, 1.0) * attenuation, 1.0);
}

void main(void)
{
    vec2 texcoord = gl_FragCoord.xy / vec2(screenw, screenh);
    vec3 p = texture2D(position, texcoord).xyz;
    vec3 n = texture2D(normal, texcoord).xyz;

    gl_FragColor = calc_point_light(p, n);
}


texts: In a collision detection loop, when do I apply the velocity?

texts:
I'm writing a really basic collision detection system (AABB vs AABB, AABB vs Circle, Circle vs Circle), and I've just got to the point of writing the actual loop which iterates the objects and checks for collisions.

My question is when do I apply the velocity to each object? Do I move all objects by vel * dt before I even start colliding? Do I apply the velocity as I iterate? If so, do I apply it to both objects I'm testing, or just the first, and then apply the velocity to the second when I check collisions against that one?

Also presumably I should do the whole collision check recursively (as the act of responding to one collision might cause another), but that obviously effects how and when the velocity is applied.

My suspicion is that I should move all the objects by their velocity before I begin, and then recursively detect and respond to collisions until nothing is colliding (or until some loop limit).


texts: How to force libGDX to set display mode?

texts:
The following code represents my attempt to switch display modes. I've had to include the redundant setWindowedMode because without it, libGDX would not force the change required to reflect the changes made by System.setProperty... and the border would not disappear/reappear from the window.

public static void setGraphicsMode() {
    switch (getString(OptionConstant.DISPLAY_MODE)) {
        case "windowed borderless":
            System.setProperty("org.lwjgl.opengl.Window.undecorated", "true");
            break;
        case "windowed":
            System.setProperty("org.lwjgl.opengl.Window.undecorated", "false");
            break;
        default:
            break;
    }

    Gdx.graphics.setWindowedMode(getInt(OptionConstant.RESOLUTION_X) + 1,
                                 getInt(OptionConstant.RESOLUTION_Y));

    Gdx.graphics.setWindowedMode(getInt(OptionConstant.RESOLUTION_X),
                                 getInt(OptionConstant.RESOLUTION_Y));

    switch (getString(OptionConstant.DISPLAY_MODE)) {
        case "fullscreen":
            Graphics.DisplayMode displayMode = Gdx.graphics.getDisplayMode();
            Gdx.graphics.setFullscreenMode(displayMode);
            break;
        default:
            break;
    }
}

How can I accomplish this without the the redundant call?


texts: Security concerns related to HTML 5 games

texts:
I would like to know if people could modify an HTML 5 game's code to harm either the server or other players whom visit the page.

More specifically, whether someone could modify a simple game that doesn't have things like high-scores, global stats, log-in, etc. to harm other users and/or the server the game is hosted on.

Is this only a concern for games that retrieve data to be stored on the server itself?


texts: Do i need to integrate leader-board and achievement in my game and then publish in alpha testing for google play?

texts:
I'm confused about whether I need to publish my .apk file on Google Play Console with or without achievements and leaderboard.

If I publish the game without achievements and leaderboards, then, how can I integrate the google play service at a later date?
The first thing I saw was that I should go for alpha publish. Is that necessary?
If I do publish the alpha version for the game without including achievements and leaderboard, how can I add these later? In this video, first the game is published without the achievements/leaderboard, and later he integrates them. So how does it show results since we didn't include these buttons for leaderboard and achievements?


texts:
I am developing a small game where latency matters and I have been reading this article https://samrueby.com/2015/01/26/why-is-https-faster-than-http/ and it claims that Https is faster than Http. I know that in HTTP connection is opened to transfer a single file/text/image and closes whereas in websocket connection stays open once handshake is done. I wanna know if data transfer speed can have some boost with secure connection in case of websocket.

Thank you.


texts: How do you program the right analog stick of a controller in JInput?

texts:
I have the Left Analog Stick programmed and accepting input (moving a character around). (getCompassDir() returns the values of the cardinal directions and NONE means the stick isn't touched):

// Left Analog Stick
public int getLeftAnalogStickDir() {
    // return the (x,y) analog stick compass direction
    if ((xAxisIdx == -1) || (yAxisIdx == -1)) {
        System.out.println("(x,y) axis data unavailable");
        return NONE;
    } else
        return getCompassDir(xAxisIdx, yAxisIdx);
}

This works perfectly. Now when trying to program the Right Analog Stick of the controller, I use the same code as above, but instead, I replaced xAxisIdx and yAxisIdx with zAxisIdx and rzAxisIdx (the x, y value of the right stick). The problem is that its not reading the input like the left Analog Stick.

Does anyone know why the right analog stick isnt working? I followed the tutorial from this book:

Pro Java 6 3D Game Development: Java 3D, JOGL, JInput and JOAL APIs


texts: Object array in unity not instantiating properly

texts:
I'm trying to instantiate my CarMovement class with my population class for a Genetic Algorithm, but when i run the project, the car prefab doesnt spawn.

Everything is wired up in the inspector correctly. Anyone know whats going on?

Here's the population class:

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

public class Population : MonoBehaviour {

    public int populationSize = 10;
    private CarMovement[] cars;

    // Use this for initialization
    void Start () {
        cars =  new CarMovement[populationSize];
        for (int i = 0; i < populationSize; i++) {
            cars [i] = new CarMovement ();
            cars [i].score = 1+i;
            Debug.Log (cars [i].score);
        }
        //cars[0].Start();
    }

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

Here's the CarMovement/Individual class:

public class CarMovement : MonoBehaviour {

    public float speed = 2f;
    public Rigidbody2D rb2d;
    public Vector2 spawnPosition = new Vector2((1.0f)*0.1f,3.83f);
    public int score;
    public GameObject carPrefab;

    // Use this for initialization
    public void Start () {
        rb2d = GetComponent<Rigidbody2D> ();
        GameObject.Instantiate (carPrefab,spawnPosition,Quaternion.identity);
        Debug.Log ("YAAAA");

    }

    // Update is called once per frame
    public void Update() {
        rb2d.transform.Translate (speed * Time.deltaTime, 0, 0);

    }
}


texts: How to calculate final force vector for the SKSpriteNode

texts:
I am creating space game which has an effect similar to black hole's gravitational effect. Wherever the spaceship is going, the black hole will attract it, summing up all the vectors together.

I know SKFieldNode has a method customFieldWithEvaluationBlock: that allows to calculate everything myself, but might it be another way to do that?

I have tried almost every type in SKFieldNode, but nothing helped.

There are some side effects that don't suit me (i.e. If I use an electric or magnetic field, the object repels from the black hole)
Moreover, moving with SKAction (i.e. for the spaceship) doesn't allow me to sum all movement vectors together (I cant do
- (void)moveTo:duration: actions simultaneously, even with grouping the actions)

What can you advice me? !


texts: Solution for Shipping Optimized and Minified GLSL?

texts:
I've tried to find a reputable optimizing compiler for GLSL that takes source shaders, performs what optimizations it can statically assume, and outputs a minified GLSL file with optimizations, stripped local variable names, and unnecessary content like comments/extra whitespace.

The goal is to transpile GLSL into a portable, obfuscated source file that has been optimized enough so that local device compilers can optimize the shaders at game startup while still maintaining simple and readable GLSL for development.

I'm searching for a solution in my development pipeline in lieu of HLSL's precompiled intermediate representation or Vulkan's SPIR-V intermediate representation. Am I wrong in my assumptions about shipping shaders for OpenGL, is there a best practice for optimizing and shipping shaders with a release build?


texts:
I've read all around the net, watched videos, tried things and in the end I can't make a decent platform collision detection.
I've followed this tutorial.
It didn't work out at 100%. My object stops above ground and can't hit the ground. Anyway, I think the guy got fed up with me asking questions. And his way seems too complicated. In short it's about constant calculations how far are you from a wall/ground and how much steps can you make("step" is also defined), how much DID you make, etc. Too complicated if you ask me. So let's forget about that.
I began anew on my own. Here's what I got:
private void ApplyCollision()
    {
        if (PlayerIsOnPlatform())
        {
            this.Position -= new Vector2(0, 5);  // Holds Player on platform.
        }
    }

private bool PlayerIsOnPlatform()
    {
        int playerBottom = this.Bounds.Bottom;
        int platformTop = Platform.CurrentPlatform.Bounds.Top;
        bool playerIntersectsPlatform =
            this.Bounds.Intersects(Platform.CurrentPlatform.Bounds);

        if ((playerBottom >= platformTop) && (playerIntersectsPlatform))
        {
            return true;
        }
        return false;
    }

And gravity and friction:
private void Friction()
    {
        Movement -= Movement * new Vector2(.1f, .1f);
    }

private void Gravity()
    {
        Movement += Vector2.UnitY * .5f;
    }

Like this, the player bounces a bit and stays about a pixel above ground. And the gravity is always trying to pin the object down even when I somehow manage to land on the platform.
=======
EDIT:
The player stops at the platform top correctly. But now I have another problem:
private void ApplyCollision()
    {
        // Object is above
        if (playerBottom > platformTop && playerBottom < platformBottom && playerIntersectsPlatform)
        {
            this.Position = new Vector2(currentPlayerPosX, platformTop - playerHeight);
        }
        // Object below
        else if (playerTop < platformBottom && playerTop > platformTop && playerIntersectsPlatform)
        {
            this.Position = new Vector2(currentPlayerPosX, platformBottom);
        }
        // Object to the left !! Conflicts with Vertical detection
        if (playerLeft < platformLeft && playerRight > platformLeft && playerIntersectsPlatform &&
            this.Bounds.Center.X <= platformLeft) // Not perfect
        {
            this.Position = new Vector2(platformLeft - playerWidth, currentPlayerPosY);
        }
        // Object to the right !! Conflicts with Vertical detection
        else if (playerRight > platformRight && playerLeft < platformRight && playerIntersectsPlatform)
        {
            this.Position = new Vector2(platformRight, currentPlayerPosY);
        }
    }

This methods works. It's shorter, better and doesn't need my initial boolean methods I had for top, bottom, sides check. But the Left and Right checks still need work. When the player is near the Platform border, he gets pushed/teleported off the edge. The Left check actually allows half of the Player to go off the edge without falling instantly - thanks to this.Bounds.Center.X <= platformLeft. Not perfect.
Here's a picture to illustrate the problem:

I know why this is happening. It's due to the conditions in the if statements. I guess this calls for collision depth calculation. I find Jon's implementation kinda confusing. And I wonder if that's the only solution. I tried adding another condition. Pseudocode for left check: if 1/4 of Player.Width <= platformLeft >THEN> this.Position = new Vector2(platformLeft - playerWidth, currentPlayerPosY); But due to the friction and speed I have, it doesn't work.


texts: How can I save an XML file with Unity on the Android platform?

texts:
I am writing a game that has a save function which looks like this

    public void Save()
    {

        System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(this.GetType());
        System.IO.StreamWriter file = new System.IO.StreamWriter(("Assets/Resources/Save");
         ser.Serialize(file, this);
        file.Close();
    }
}

This will work fine in the editor and on Windows machines, but when we build to Android the saving no longer works. Why is that?


texts: What are the disadvantages and/or limitations of navigation meshes?

texts:
I have a lot of materials on navigation meshes, what they are, their advantages over graphs made up of waypoints, etc. However, I haven't seen much information regarding the limitations and the disadvantages of using navigation meshes, other than the obvious time they take to be created manually (which is relatively solved by Recast).

Surely this isn't a completely "magical" technique that presents itself without any drawbacks? Could someone please explain what the limitations and disadvantages of using a navigation mesh over, let's say, a graph made up of waypoints? Or point me in the right direction?


texts: Rotating an object around it's centre in OpenGL

texts:
I'm writing small 3d viewer of models from .obj file.
I have a car and I want to rotate car's wheels. I found a lot of good examples but I still have a problem: wheel rotates around point at the it's border, not around center. You can see it on the gif.
Below part of code without code for material and lighting. I find coordinates of wheel's center.

GL.PushMatrix();

// Rotate the car
GL.Translate(x, y, z); //x=0, y=0, z=0
GL.Rotate(ori, 0, 1, 0); // ori=90

// ...
// Material and lighting code
// ...

foreach (var group in file.G)
{
    GL.PushMatrix();
    if (group.name == "wheel_rf")
    {
        float xTmp, yTmp, zTmp;
        xTmp = yTmp = zTmp = 0;
        int count = 0;
        foreach (var f in group.F)
        {
            foreach (var v in f.V)
            {
                yTmp += v.Y;
                zTmp += v.Z;
                xTmp += v.X;
                count++;
            }
        }
        yTmp /= count;
        zTmp /= count;
        xTmp /= count;
        GL.Translate(xTmp, yTmp, zTmp);
        GL.Rotate(this.wheelAngle, 1, 0, 0);
        GL.Translate(-xTmp, -yTmp, -zTmp);
    }

    // draw faces for each group
    GL.Begin(file.PrimitiveType);
    foreach (var face in group.F)
    {
        GL.TexCoord2(face.VT[0]);
        GL.Normal3(face.VN[0]);
        GL.Vertex3(face.V[0]);

        GL.TexCoord2(face.VT[1]);
        GL.Normal3(face.VN[1]);
        GL.Vertex3(face.V[1]);

        GL.TexCoord2(face.VT[2]);
        GL.Normal3(face.VN[2]);
        GL.Vertex3(face.V[2]);
    }
    GL.End();
    GL.PopMatrix();
}
GL.PopMatrix();

Note! In first time I rotate all car on 90 degrees otherwise I would have seen the car back. I can't find reason of problem. Maybe trouble in the car model, but whole car is drawn fine.


texts: Why I get inconsistent occlusion query results?

texts:
My system: Catalyst 15.12, mesa 11.2.1, Archlinux, kernel 4.5.1

Depending on camera position I get inconsistent occlusion query results. Following scene contains wall, objects behind wall and objects on sides. Objects behind wall are always invisible(correct). Objects on sides should be always visible but sometimes marked as invisible. Why? On screenshots green means visible, red boundary means occluded:

This is the code that I use:

void gems_render_objects(Scene *scene) {
    int i = 0, j = 0, res;
    AssetInstance *inst;

    if(!s_queryIds) {
        s_queryIds = (GLuint*)malloc(sizeof(GLuint)*(scene->numInstances));
        glGenQueries(scene->numInstances, s_queryIds);
    }

    //draw everything
    for(i = 0; i < scene->numInstances; i++) {
        glc_draw_inst(scene, scene->instances+i, &s_curProgramId, &s_curVaoId);
    }

    //query everything
    glDepthMask(GL_FALSE);
    glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
    for(i = 0; i < scene->numInstances; i++) {
        inst = scene->instances+i;

        glBeginQuery(GL_SAMPLES_PASSED, s_queryIds[i]);
        glc_draw_inst(scene, inst->bbInst, &s_curProgramId, &s_curVaoId);
        glEndQuery(GL_SAMPLES_PASSED);
    }
    glDepthMask(GL_TRUE);
    glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);

    //draw bounding boxes of invisible
    glDepthMask(GL_FALSE);
    glDisable(GL_DEPTH_TEST);
    for(i = 0; i < scene->numInstances; i++) {
        inst = scene->instances+i;

        res = 0;
        glGetQueryObjectiv(s_queryIds[i], GL_QUERY_RESULT, &res);

        if(res == 0) {
            GLenum prevDrawType = inst->bbInst->asset->drawType;
            inst->bbInst->asset->drawType = GL_LINE_STRIP;
            glc_draw_inst(scene, inst->bbInst, &s_curProgramId, &s_curVaoId);
            inst->bbInst->asset->drawType = prevDrawType;
        }
    }
    glEnable(GL_DEPTH_TEST);
    glDepthMask(GL_TRUE);
}


texts: Problem with making camera follow player in Javascript

texts:
So I'm testing a few things in Javascript and something I was testing was making the camera follow the player. When I move the player, instead of the dots going away from the player, they follow the player and it looks very strange.

Here is the code: https://codepen.io/anon/pen/wLgEPO?editors=0010

Move the player using the arrow keys.

Thanks.


texts: Should the render system know the entity manager?

texts:
In an entity-component based game architecture, I think the entity manager is a "high-level" system, and the render system a "low-level" system.

When I edit the position component of the entity, should the render system be aware of the entity manager, and get the position over it, or should there be no low-level system communicate with a high-level system?

I think that this should not be the case. Instead, if an entity is moved, the scene manager (also "high-level") should call a "move" function of the render system, and the render system updates the position. That means that every entity interaction has to be a function in my render system.

I'm afraid that I get cyclic dependencies in the first case. Is this the right way to go?


texts: How to allow character to keep moving after it hits a wall

texts:
I am developing an iPhone game. There is a fountain that the user should not be able to walk through. Now, this question is about checking circle-point collision or anything like that. I am checking collision with CGRectIntersectsRect(character1.frame, fountain.frame).

But, here is the problem: If I prevent the person from moving; he will never be able to move. So, I tried combatting this with following:

    if (character.center.y > fountain.center.y && CGRectIntersectsRect(character1.frame, fountain.frame) && g == false) {
        g = true;
        character1.center = CGPointMake(character1.center.x, character1.center.y-0.1);
    }
    if (character.center.x > fountain.center.x && CGRectIntersectsRect(character1.frame, fountain.frame)) {
        character1.center = CGPointMake(character1.center.x-0.1, character1.center.y);
    }
    if (character.center.y < fountain.center.y && CGRectIntersectsRect(character1.frame, fountain.frame)) {
        character1.center = CGPointMake(character1.center.x, character1.center.y+0.1);
    }
    if (character.center.x < fountain.center.x && CGRectIntersectsRect(character1.frame, fountain.frame)) {
        character1.center = CGPointMake(character1.center.x+0.1, character1.center.y);
    }

This should check what side the character1 is intersecting the fountain and then make it so it is not intersecting the fountain by incrementing or decrementing the x or y coordinates of the characters it. But, this still gives weird results. It will move it diagonally across the fountain if keep holding down on the the top side of the fountain and also, it will keep moving it left other wise on the top of the fountain.


texts: Textures blink where there would be black

texts: I am texturing my level, but every single texture "blinks" where there would be black, (as seen in photo) I dont know how to fix this, they worked fine earlier.


texts:
I'm implementing a simple 2D maze-like game. I'd also like to implement a map editor to easily create the game maps/levels for me and allow users/players to create it's own levels as well. The thing I'm just thinking about now is how to save the game entities/object in files on the hd. I'm thinking about the JSON data format, for e.g. having the list of the game objects like that:
[
   {
      "object_id":1,
      "pos_x":200,
      "pos_y":100,
      "obj_type":"brick"
   },
   {
      "object_id":2,
      "pos_x":100,
      "pos_y":300,
      "obj_type":"enemy",
   }
]

My question is is it a good idea to use the JSON to store the game level info in a game-map file?
My environment: Win 10, Microsoft Visual Studio Community 2019


texts: How to import a texture to be used as occlusion map?

texts:
The same way normal maps need to be imported as "Normal map" in the import settings, how should I setup an Ambient Occlusion texture to correctly work?

I've been searching around in the manual and the web but still not sure if AO maps should be imported as Lightmaps.


texts: How do I edit a Unity InputField by clicking on Android UI Button?

texts:
I have been stuck on this problem for a long time and not sure what I need to do. Would appreciate any help.

I am building an Android app using Unity. In my app I have an InputField, a TMP_InputField to be precise, in my Unity scene as a Prefab. I want to edit this input field by clicking on a button in my Android UI (not part of Unity scene). I don't want the input field to be editable by clicking on the input field itself.

In order to achieve this, I enabled the Hide Soft keyboard option in the editor so that user can't edit the field by clicking on the field. But I am not able to figure out how to edit the input field.

First problem is how to pop up the keyboard when I click on the Android button. I tried this.

TouchScreenKeyboard.Open("");

This pops up the keyboard but the input field doesn't show the caret and doesn't accept input.

I also tried,

EventSystem.current.SetSelectedGameObject(inputField.gameObject, null);
inputField.OnPointerClick(null);

and

inputField.Select();
inputField.ActivateInputField();

But no success. I tried to play with the focused, interactable, activated properties but nothing works.

This should be easy but I am unable to get it to work. Would really appreciate any help. Thanks!


texts: How can we match polygon data structure with a background image

texts:
I am referring to this fireball game.

The ball will collide with background, which is in polygon form.

I was wondering, how I can match my polygon data structure with the background image. Say, I had requested artist to draw me a polygon background. Then, how I can generate a polygon data structure to describe the polygon background image?


texts: Composite 3-D and 2-D using Anamorphic Projection?

texts:
I'm working on a game which takes place on a two dimensional grid similar to the fluid background grid in Geometry Wars. It is implemented as a procedurally drawn spring system which may have force applied to the intersection points resulting in a primitive fluid dynamic simulation.

Let's say I want to elevate the grid into three-space. One way would be to upgrade the whole world to 3-d. Then I could render the grid to a texture and map it onto a plane which could be placed in three dimensions. What I am more interested in, however, is how I might 'fake' it by simulating perspective using 2-D. For example, its easy to vary the horizontal grid spacing based on the cell's row in the grid. By squeezing it at the top I can create a visually convincing vanishing point, but the physics and interaction with the grid is not right.

I'd like to be able to layer the 2-D grid over a separate 3-D layer such that they appear to be one. Have y'all seen the impressive demonstrations of anamorphic projection recently featured on YouTube?

Intrigued, I found another tutorial video which shows how to draw anamorphically using pencil and paper.

Anyone have an idea of how to approach the problem of creating an anamorphic projection space in 2-D that would line up with a given perspective projection as that of a typical 3-D Camera?

I envision that this would manifest as an array of weightings applied to each point in the 2-dimensional grid which I could use to modulate the physics forces that drive the grid, creating a more realistic spring system than is possible with a simple faked perspective.


texts:
In Box2d, can I make a static object to be permeable by dynamic objects? Can I simulate something like water in a way that it lets rigid bodies to dive into it but at the same time pushes them off over time?

Here's an illustration I've made:

Three circles in steady state rest inside my "game world" with some gravity.
I push the top circle down, two circles on bottom start sinking into walls since wall objects are permeable.
Walls slowly push circles back into the world once the top circle stopped affecting them.


texts: Why do my pyramids fade black and then back to colour again

texts:
I have the following vertecies and norms
GLfloat verts[36] = {

-0.5, 0, 0.5,
 0, 0, -0.5,
0.5, 0, 0.5,

0, 0, -0.5,
0.5, 0, 0.5,
0, 1, 0,

-0.5, 0, 0.5,
0, 0, -0.5,
0, 1, 0,

0.5, 0, 0.5,
-0.5, 0, 0.5,
0, 1, 0

};

GLfloat norms[36] = {

0, -1, 0,
0, -1, 0,
0, -1, 0,

-1, 0.25, 0.5,
-1, 0.25, 0.5,
-1, 0.25, 0.5,

1, 0.25, -0.5,
1, 0.25, -0.5,
1, 0.25, -0.5,

0, -0.5, -1,
0, -0.5, -1,
0, -0.5, -1
};

I am writing my fists Open GL game, But I need to know for sure if my Normals are correct as the colours aren't rendering correctly. my Pyramids are coloured then fade to black every half rotation then back again.

My app so far is based on the boiler plate code provided by apple. heres my modified setUp Method
 [EAGLContext setCurrentContext:self.context];

[self loadShaders];

self.effect = [[GLKBaseEffect alloc] init];
self.effect.light0.enabled = GL_TRUE;
self.effect.light0.diffuseColor = GLKVector4Make(1.0f, 0.4f, 0.4f, 1.0f);

glEnable(GL_DEPTH_TEST);

glGenVertexArraysOES(1, &_vertexArray); //create vertex array
glBindVertexArrayOES(_vertexArray);

glGenBuffers(1, &_vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, _vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(verts) + sizeof(norms), NULL, GL_STATIC_DRAW); //create vertex buffer big enough for both verts and norms and pass NULL as data..
uint8_t *ptr = (uint8_t *)glMapBufferOES(GL_ARRAY_BUFFER, GL_WRITE_ONLY_OES); //map buffer to pass data to it
memcpy(ptr, verts, sizeof(verts)); //copy verts
memcpy(ptr+sizeof(verts), norms, sizeof(norms)); //copy norms to position after verts
glUnmapBufferOES(GL_ARRAY_BUFFER);
glEnableVertexAttribArray(GLKVertexAttribPosition);
glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0)); //tell GL where verts are in buffer
glEnableVertexAttribArray(GLKVertexAttribNormal);
glVertexAttribPointer(GLKVertexAttribNormal, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(sizeof(verts))); //tell GL where norms are in buffer
glBindVertexArrayOES(0);

And the update method.
- (void)update
{

float aspect = fabsf(self.view.bounds.size.width / self.view.bounds.size.height);
GLKMatrix4 projectionMatrix = GLKMatrix4MakePerspective(GLKMathDegreesToRadians(65.0f), aspect, 0.1f, 100.0f);

self.effect.transform.projectionMatrix = projectionMatrix;

GLKMatrix4 baseModelViewMatrix = GLKMatrix4MakeTranslation(0.0f, 0.0f, -4.0f);
baseModelViewMatrix = GLKMatrix4Rotate(baseModelViewMatrix, _rotation, 0.0f, 1.0f, 0.0f);

// Compute the model view matrix for the object rendered with GLKit
GLKMatrix4 modelViewMatrix = GLKMatrix4MakeTranslation(0.0f, 0.0f, -1.5f);
modelViewMatrix = GLKMatrix4Rotate(modelViewMatrix, _rotation, 1.0f, 1.0f, 1.0f);
modelViewMatrix = GLKMatrix4Multiply(baseModelViewMatrix, modelViewMatrix);

self.effect.transform.modelviewMatrix = modelViewMatrix;

// Compute the model view matrix for the object rendered with ES2
modelViewMatrix = GLKMatrix4MakeTranslation(0.0f, 0.0f, 1.5f);
modelViewMatrix = GLKMatrix4Rotate(modelViewMatrix, _rotation, 1.0f, 1.0f, 1.0f);
modelViewMatrix = GLKMatrix4Multiply(baseModelViewMatrix, modelViewMatrix);

_normalMatrix = GLKMatrix3InvertAndTranspose(GLKMatrix4GetMatrix3(modelViewMatrix), NULL);

_modelViewProjectionMatrix = GLKMatrix4Multiply(projectionMatrix, modelViewMatrix);

_rotation += self.timeSinceLastUpdate * 0.5f;
}

But providing I understand this correct one pyramid is using the GLKit base effect shaders and the other the shaders which are included in the project. So for both of them to have the same error, I thought it would be the Norms?


texts: Efficient way to implement animation from spritesheet?

texts:
I'm actually trying to port a GBA game to SDL for educationnal purpose.
The game has many sprites and tiles. Since the GBA screen size is 240x160px, I decided to scale it 2x. At first, it went okay creating spritesheet for animations, because typical animations had something around 2-8 frames.

However, I faced yesterday a problem that I had not seen coming. I got a 89-frame animation. Including the scale, each frame is around 480x320px. With 89 frames, it creates a huge image.

When I load it into a SDL_Texture with IMG_LoadTexture, the size of the test program goes from ~9MB to 56MB. I find this huge considering the image weights at most 4MB (without compression, PNG-32 bits I believe). No matter what compression I do, it still takes ~50MB.

Here's the code that loads the image:

m_frameDestRect = { 0, 0, 480, 320 };
m_frameSrcRect = { 0, 0, 480, 320 };
m_pTexSprite = IMG_LoadTexture(pRenderer, "image.png");

I keep the SDL_Texture in a SDL_Texture* property of my class. It also never change.

Here's the code that "draws" the texture:

SDL_RenderCopy(m_pRenderer, m_pTexSprite, &m_frameSrcRect, &m_frameDestRect);

Here's the code that "update" the frame:

uint32_t frameX = (m_frame + 1) % 5;
uint32_t col = (m_frame + 1) / 5;

m_frameSrcRect = { frameX * 480, col * 320, 480, 320 };

I could live with that, but then I saw that I got an animation that has 489 frames...

Since I am no expert in video games programming, nor in imaging, I came here to ask this very question.

1. Is the RAM consumption of SDL_Texture (and whatever loaded behind) normal ?
2. Animation wise, are there other ways to implement them?

I find it totally impressive all these sprites (got tons of them, in gif formats) actually loaded quite smoothly on the GBA, considering the number of frames.

Any advice / solutions / answers is more than welcomed.

Thanks


texts: Is it a bad idea to store functions inside components in ECS?

texts:
Say I have three entities: Player, Spikes, and Zombie. All of them are just rectangles  and they can collide with each other. All of them have the BoxCollision component.
So, the BoxCollison system would look something like this:
function detectCollisions () {
  // for each entity with box collision
    // check if they collide
      // then do something
}

The issue is, the sole purpose of the BoxCollision component is to detect collision, and that's it. Where should I put the game rules, such as "if the Player collided with Spikes, diminish its health" or "if the Zombie collided with Spikes, instantly kill the Zombie"?
I came up with the idea that each Entity should have its onCollision function.
Programming languages such as Javascript and F# have high-order functions, so I can easily pass functions around. So when assembling my Player entity, I could do something like:
function onPlayerCollision (player) {
  return function (entity) {
    if (entity.tag === 'Zombie') {
      player.getComponent('Health').hp -= 1
    } else if (entity.tag === 'Spikes') {
      player.getComponent('Health').hp -= 5
    }
  }
}

const player = new Entity()
player.addComponent('Health', { hp: 100 })
player.addComponent('BoxCollision', { onCollision: onPlayerCollision(player) }
// notice I store a reference to a function here, so now the BoxCollision component will execute this passing the entity the player has collided with

function detectCollisions () {
  // for each entity with box collision
    // check if they collide
      onCollision(entity)

onPlayerCollision is a curried/closure function that receives a player, and then returns a new function that wants another Entity.
Are there any flaws with this? Is it okay for components to store references to functions? What are other ways of avoiding game rules in components? Events?
Thanks!


texts: Unexpected scaling of UI elements after build [Unity Web]

texts:
I have an unusual scaling of UI Elements after my build in unity for WebGL

Game in Unity Engine:

Game in Itch.io:

Has anyone seen this kind of behaviour? any suggestions on what I should look into?
Happy to provide more info on the matter.

Thanks!


texts: How to set material to gameobject dynamically using c# script in unity?

texts:
I want to set material to a gameobject in unity using c# script.

I am using this code to set the material of mesh renderer attached to the gameobject -

MeshRenderer mesh = gameObject.GetComponent<MeshRenderer>();
        mesh.materials[0] = materialsCopy[0];

here materialsCopy is an array of type Materials which I've made public and I am attaching the Materials by drag & drop to the materialsCopy but when I run the game I get a white colored mesh instead of the set material of the 0 index materialsCopy. The 0 indexed materialsCopy has albedo set to an image. I want this image to get attached to the gameobject. How should I proceed ?

In addition to this I am also getting a warning - Tiled GPU perf. warning: RenderTexture color surface  (0x0) was not cleared/discarded, doing


texts: Handling multiple lights of different types in GLSL

texts:
I want to be able to support multiple lights of different types (point, spot & directional). Note that I also want to be able to render transparent/translucent objects, which rules out deferred rendering.

This means that I will need a fixed upper limit on the number of lights. All of the implementations I have seen use a uniform array, for example:

struct PointLight
{
    vec3 color;
    float intensity;
    float radius;
};

uniform PointLight pointLights[8];

How can I best extend this to multiple types of lights? Two possible options are:

Create multiple uniform arrays, one for each type of light.
Define a struct that can be used for all three types of light and then have some way of differentiating the types of lights in the array (e.g. using start index and count uniforms or adding some kind of type flag to the struct).

Both have disadvantages. Both waste memory (although the first more so than the second) and the second either requires additional uniforms or flag checking.

What is the usual method for handling multiple lights of various types?


texts: How can I implement explosion effects in a 3D game?

texts: I was wondering how I could implement explosion effects in a 3D game. I'm specifically interested in graphical techniques for creating the effects, not the related logic or systems.


texts: Snake game collision with wall and reset

texts:
So I have a collision with itself and collision with the apple. I just cant figure out how to get it to collide with the wall. What my teacher helped me with was it made it teleport to the other side like the portals in packman. the other thing i need help with is it restarting when it collides. I have it to where it resets its size but that's it.

<canvas id="gc" width="400" height="400"></canvas>


texts: How to set the position of objects in pixels on the scene editor

texts:
I created a camera of the size of 480x854 as the project is meant for Android but whenever I try to position objects on the scene editor, their positions dont seem to be in pixels. It is like -10 y on the top and 10 y on the bottom of the camera. So what I want is to see and position the objects on the scene editor in pixels.

Thanks in advance.


texts: How to rotate a moving canvas in Android

texts:
I am developing an Android game. In this game some trains are moving on tracks. I am able to move trains horizontally and vertically using two train images for horizontal train and vertical train separately.

Now I want to move a train that is coming on horizontal track to vertical, I want to visualize it as it is now taking turn and moving on vertical track.

How can I do this, do I need to use so many images for each turning pixel, or is there any other way to turn the train?

Please suggest.


texts:
I am approaching OpenGL and general gaming-development. I want to start by coding a simple 2D game in Java (lwjgl) but, since I can create models with Blender, I don't want to use 2D sprites, but a semi-flat environment. My target is to remake a classic game but with some cool stuff like particle emitters, bump mapping, lighting and so on... The basic idea is to make something that looks like Super Mario Bros Wii (or Kirby's Adventures Wii, or Super Smash Bros. etc...).

Do you think I have to use JavaMonkeyEngine?
Some hints,code snippets, tutorials, links?
Do I have to handle a "z-fixed" camera or set-up OpenGL to render in 2D mode?
What about the HUD?
Sorry if my question is too generic, but I would like to have a clear idea of what I have to do before starting writing code. As always, thanks for your help!


texts: How to "repeat" a sprite in the gameworld in a random fashion?

texts: I have a platform flash game which includes a level with just two backgrounds which are flipped side by side so that a looping background effect is created. In this I have to include Obstacles. Basically, when I designed the level, that was neat and good. But now I want to make the obstacles come randomly . Another factor is that since the player character in the platformer always keeps on running, if two obstacles come almost close together, it results in an impossible condition to win the game. So i need to avoid that too, without losing the factor of making the player think that the game is random.


texts:
I am developing a game in Unity3d.

In this game, 2 teams will fight without any human interaction. The fight results must be always the same, if the same teams are the same. This way, I must reproduce the same fight in many devices, getting the same results in each device.

The map where the fight happens is a 3d environment, so, my soldiers can move in any direction. And the soldiers cannot walk in the same space of another soldier, so I need an agent avoidance algorithm.

I am having some trouble to find a solution to the problem above. To achieve the 'always the same results' I am treating this fight as Turn Based Strategy game, with little fixed time intervals between the turns.

To calculate the pathfind of the soldiers, I am using the Unity3d navmesh framework. And then I move manually my agents according to the 'NavMeshAgent' 'steeringTarget' property.

But this method doesn't cover the obstacle avoidance algorithm, and my agents overlaps.

So, I am looking for a solution to my problems, It should be a manual obstacle avoidance algorithm, or a way to unity navmesh work in fixed time intervals, or a completely new approach to my path-finding problems.


texts: Unity Tile pallete isn't appearing in window tab

texts:
I'm trying to add a tile pallette to my scene in Unity. But when I go to

Window - 2D there is no tile pallette option

I'm using

v2019.2.11f1 (Personal)


texts: Rigify to Unity converter stretches 3d model in blender

texts: My 3d model animations works perfectly in blender. But whenever I use "Rigify to Unity Converter" add-on it stretches the mesh as if it was pinned at a certain point (T-pose hand and foot position). How can I fix such a problem?


texts: Problem in multiplayer game lobby trying to pass map name to MasterServer.RegisterHost

texts:
I'm working on an online multiplayer game, so I have lobby where users can see the hosts list. Every host in the hosts list has some information like "host user name" and "map name".

I'm using this code to register the host and  load "host user name":

public void something()
{
    var useNet = !Network.HavePublicAddress ();
    Network.InitializeServer (6, 25000, useNet);
    MasterServer.RegisterHost ("roomname", hostUserName , "unity");
}

public void btn_Refresh()
{
    MasterServer.RequestHostList ("roomname");
    data = MasterServer.PollHostList ();

    for (int i=0; i<data.Length; i++)
    {
        ButtonRoom [i].gameObject.SetActive(true);
        TextNameRoom [i].text = data [i].gameName;
    }
}

I also need "map name", exactly like "host user name", so I added another value to MasterServer.RegisterHost() like this:

public void something()
{
    var useNet = !Network.HavePublicAddress ();
    Network.InitializeServer (6, 25000, useNet);
    MasterServer.RegisterHost ("roomname", hostUserName, mapName, "unity");
}

but now I have an error that RegisterHost() can't have 4 arguments:

  No overload for method RegisterHost takes 4 arguments

What other way could I pass the map name? Thank you.


texts: Why my canvas isn't showing anything after I put code in the loop for tile map?

texts:
My canvas stop showing anything when I want to display a tile 25 times. No errors. Here is the code:

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

var StyleSheet = function(image, width, height) {
  this.image = image;
  this.width = width;
  this.height = height;

  this.draw = function(image, sx, sy, swidth, sheight, x, y, width, height) {
    image.onload = function() {
      context.drawImage(image, sx, sy, swidth, sheight,x, y, width, height);
    }
  }
}

var Loader = function(src) {
  this.image = new Image();
  this.image.src = src;

  this.image.onload=function(){
    var sprite = new StyleSheet(background, 16, 16);
    for (i = 0; i < 25; i++) {
      for (j = 0; j < 25; j++) {
        sprite.draw(background, 30, 30, 36, 36, i * 36, j * 36, 36, 36);
      }
    }
  }
  return this.image;
}

var background = new Loader("https://opengameart.org/sites/default/files/PathAndObjects.png");
console.log(background);


texts: How do I sync multiplayer game state more efficiently than full-state updates?

texts:
I've done a little game network coding before, but primarily with TCP for games without real-time needs.  I am working on a 2D Java game with networked multiplayer.  For learning, I want to do this myself, without an existing network API.

How do I efficiently represent the game state sent to clients from a server?  There is the most obvious but probably least efficient way, which would be to create some sort of game state context object with each player's location, animation state, etc., and send that out to each player every update.  That doesn't seem terribly difficult to implement, but would probably be too large to achieve anything close to real-time interaction (of course my experience with this is limited so I may be incorrect).

Is there a solid way any of you have used before to only transmit changes in state, and is there even a large enough disparity in performance that it is worth the extra work?


texts: Using buttons on Smartphone shooter games

texts:
Just a simple and probably stupid question.

I noticed that many iOS and Android shooter games tend to avoid using traditional buttons in favour to autofire.

The very first reason to do so is to have more space in the screen available for graphics. However this takes away some satisfaction to the user when "pressing the virtual button". I understand that the fact that smartphone buttons would be only "virtual" is a good design reason to remove them and add autofire, but I was wondering which sort of comments your users (if u are one of those developers) have given you about this choice.

In short:

Does autofire add to the gameplay?
Does a game without autofire (and
hence buttons) result inadequate for a smartphone and/or become less fun to play?


texts: How to get samsung gear vr controller rotation & position in unity

texts:
I am trying to get Samsung Gear VR(Oculus) rotation & position so when I turn the samsung controller left or right(like a magic wand)...it should give me rotation(Quaternion) & position(Vector3) readings?

How can I do that? I'm using Mobile version of Oculus Gear VR not the PC one. Also, GetLocalControllerRotation() returns void and doesn't return me a Quaternion

Does the controller come with a Gyroscope with the help of which I can the rotation or position readings?


texts: Can I use the default depth buffer when drawing to FBO?

texts:
How to attach default depth buffer to FBO?
How to use depth renderbuffer buffer attached to FBO (after drawing to it) as a default depth buffer?

Basically I want to use the same depth buffer for both the FBO and backbuffer rendering.


texts: How can switch GLSL "version #120" to "version #330"?

texts:
I am using GLSL "version #120" and i want to change it with "version #330".
I added "GLM" library for this purpose. But i have some problems. Therefore i will ask you what is equal to this setting ?

My version #120 init():

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45,aspectRatio, 1, 1000);
glMatrixMode(GL_MODELVIEW);

My version #120 draw():

glClearColor(0.5,0.5,0.5,1.0);
glLoadIdentity();
//-------Camera--------
glRotatef(-camPitch,1.0,0.0,0.0);
glRotatef(-camYaw,0.0,1.0,0.0);
glTranslatef(-CamLoc.x,-CamLoc.y,-CamLoc.z);

//----Objects---------
glPushMatrix();
    glTranslatef(obje_1LocX,obje_1LocY,obje_1LocZ);
    drawObject_1();
glPopMatrix();

glPushMatrix();
    glTranslatef(obje_2LocX,obje_2LocY,obje_2LocZ);
    drawObject_2();
glPopMatrix();
....
....etc

Also one mini question. Can I continue using glPushMatrix() and glPopMatrix() at "version #330" ?

EDIT : I did it, i think.  But is it good setup ?

i delete codes inside init() and it is my new
draw() function:

glClearColor(0.0,1.0,1.0,1.0);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

glUseProgram(program3);
    glm::mat4 projection = glm::perspective(glm::radians(45.0f), 1280.0f / 720.0f , 0.1f, 10000.0f);
    //------Camera----------
    glm::mat4 view = glm::lookAt(
    glm::vec3(0,120,-1000), // Camera is at (4,3,3), in World Space
    glm::vec3(0,0,0), // and looks at the origin
    glm::vec3(0,1,0)  // Head is up (set to 0,-1,0 to look upside-down)
    );

    glm::mat4 model = glm::mat4(1.0f);

    glm::mat4 MVP = projection * view * model;

    int mvpIndex = glGetUniformLocation(program3, "MVP");
    glUniformMatrix4fv(mvpIndex, 1, GL_FALSE, glm::value_ptr(MVP));

    //----Objects---------

    drawObject_1(); // it will be drawing at origin right ?

    //----And i want to draw second object at x=400 y=0 z=0-----
    model = glm::translate(model, glm::vec3( 400.0f,  0.0f,  0.0f) );

    MVP = projection * view * model;
    mvpIndex = glGetUniformLocation(program3, "MVP");
    glUniformMatrix4fv(mvpIndex, 1, GL_FALSE, glm::value_ptr(MVP));

    drawObject_2(); // it will be drawing at x= 400.0f y=0 z=0 right ?

glUseProgram(0);


texts: What is a good approach to dynamically change actor Position?

texts:
In my card game there are 2 players with each player having a hand(a ListArray of  of Cards.In this case its handPlayer1).
The Card class extends Actor.This is the code I use to deal the cards to the first player(I call this in the show() method) :

 for (int i = 0; i < 6; i++) {
        handPlayer1.get(i).setPosition(20 + i * 35, TABLE_HEIGHT - CARD_HEIGHT - 30);
    }

For now whenever a player plays a card it is removed from their hand and moved to the table.If the player draws a card it is added to the hand of the player like so :

deck.get(deck.size() - 1).addAction(Actions.moveTo(handPlayer1.get(handPlayer1.size() - 1).getX() + 20, 30, 0.1f));

But the problem is that sometimes the cards go out of screen bounds when the player has too much cards and are not visible.

.What is a good way to manipulate the positioning of Actors so that the hand stays in the center and all cards are a set distance from one another? I have read up on Groups but I don't know if adding the cards to a Group would change anything.(Picture below for reference)


texts: 2D Collision Resolution getting stuck on walls

texts:
I've been writing this collision detection system using a tutorial from an article I read and I just cannot for the life of me get it to function 100% correctly. Here's the code for starters:

BoundingBox aBox;
aBox.Convert(a);
BoundingBox bBox;
bBox.Convert(b);

Vector2 aMin = aBox.GetTopLeft();
Vector2 aMax = aBox.GetBotRight();
Vector2 bMin = bBox.GetTopLeft();
Vector2 bMax = bBox.GetBotRight();

Vector2 minDistance;

float left = (bMin.x - aMax.x);
float right = (bMax.x - aMin.x);
float top = (bMin.y - aMax.y);
float bottom = (bMax.y - aMin.y);

// Check for intersection internally
if (left > 0 || right < 0) return;
if (top > 0 || bottom < 0) return;

// Find the minDistance
if (abs(left) < right)
    minDistance.x = left;
else
    minDistance.x = right;

if (abs(top) < bottom)
    minDistance.y = top;
else
    minDistance.y = bottom;

// Null axis with biggest value
if (abs(minDistance.x) < abs(minDistance.y))
    minDistance.y = 0;
else
    minDistance.x = 0;

The problem right now is that the character is fine walking and hugging the top of a block and the bottom of a block, but once he has to walk UP two blocks, he gets stuck in between them. Coincidentally, walking down works perfectly fine. Just wondering if anyone has a solution to this problem, it would be much appreciated!

Here's a gif to better display the problem:


texts: Does my companion app infringe copyrights?

texts:
I'm making an android app that is supposed to be just a companion app for a board game. Twilight Imperium 4 is the game, and it has a boatload of techs/actions cards/strategy cards with tons of text on how they work, so the point of the app is to make it easier to look through game effects. It does not intend to be a copy of the game or to replace the gameboard at all.

So, given this context, would it be ok to try and sell it on GooglePlay or would this violate copyright in some way?


texts:
I'm having interesting problem with rotating a sprite in MonoGame. Here is how origin, destination rectangle and scale are created:

  Vector2 origin = new Vector2(tx.Width / 2, tx.Height / 2);

  Rectangle dstRectangle = new Rectangle((int)e.Xpos, (int)e.Ypos, (int)(tx.Width), (int)(tx.Height));
        dstRectangle.X += (tx.Width / 2);
        dstRectangle.Y += (tx.Height / 2);

  Vector2 scale = new Vector2(tx.Width * (float)TxScaleFactor, tx.Height * (float)TxScaleFactor);

And here is the draw function:

 Editor.spriteBatch.Draw(texture: GlowWhite, destinationRectangle: dstRectangle, color: Tint * (Alpha * 0.6f), rotation: rotation, scale: scale, origin: origin);

Now, with angle 0.0f, everything is fine but any additional rotations become weird:

Zero rotation, white background is WinForms picturebox, below is MonoGame

90 deg

And 180 deg

Its like there is some kind of offset - I've tried to change 0 to 90, and back 0 and next to 180 - result is always the same (apparently, there is no adding). I'm guessing that problem is related to origin, destination rectangle or scale. Sprites are rotated in place as you can see (no issues with that) but something with rotation isn't right. Any ideas?


texts: I have created a unity game that uses admob to show only rewarded video ads and there are no banner/interstitial ads in my game. Is it mandatory to take user consent (for EU countries) for showing the rewarded ads and if so how do I go about implementing it. I followed some online tutorials to implement admob ads but there was no mention of gdpr in any of those. Can someone please help?


texts: how to change the number of rendered frames in Blender

texts:
i´m using blender to render an animation in single pictures and i want to make an 16 frames animation out of an 24 frames one without changing the set keyframes. Is there an option to skip every 3rd frame and just render the rest? I only found the frame step option, which allows you to render every 3rd, but not 2 frames and skip the 3rd.
If anyone could help, thank you very much!


texts: How to display full website in Unity WebGL?

texts:
I want to display the complete website within the WebGL in Unity. I have tried Awesomium plugin but it doesn't work in WebGL. Please tell me is there any way to display the webpage.

Thank you.


texts: Change players state and controls in-game

texts:
I'm using Unity 3D

Let's say the player is an ice cube. You control it like a normal player. On press of a button, ice transforms (with animation) into water. You control it completely different than the ice cube.

Another great example would be: Player is human being and has normal FPS controls. On press of a button human transforms into birds and now has completely different controls.

Now, my question is, what would be easier and better:

make one object with animation transition and to stay in that state of anim. until button is pressed again
make two object: ice and water. Ice has an animation of turning into water. So replace ice (with animation) with water object

And if anyone knows this one too: how to switch between 2 different types of player controls.


texts: How to support JS/Python scripting a C++ game engine?

texts:
I'm currently writing an Entity/Component/System architecture game engine in C++, and I have the beginnings of a lua scripting system in place, which seems to be quite popular, but I feel Javascript or Python would be better.

My requirements are:

Able to bind C++ function calls to the scripting language.
Able to return data to the calling script.
Able to support heavily templated libraries, such as glm (optional, but desirable)
Must be lightweight.
Must have open source license, or similar, with no restrictions on any potential commercial use.

How would I go about doing this, in a similar way to Lua?


texts: I played Nuclear Throne yesterday a few hours and I noticed that the whole game looks pixellated. I like this effect and I'd like to know how to recreate it in my own games.


texts: MP4 AAC is a well supported playback format according to the docs, but the MonoGame content project only seems to compile MP3/WAV/WMA formats. I tried to put raw aac files in my android game but the content manager wouldnt load them, only raw wav files work, but they are large in size. I would like to know how to load aac or ogg audio files.