texts: How do you properly implement level boundaries in a physics room?

texts:
I have an issue with creating a proper boundary in GameMaker Studio when using a physics enabled room.

My room has a gravity of 0, as it is in Space. My player object has the default values, but a friction of 10 with a box shaped collision shape. I also use View0 on a 1280x720 room with a 1280x720 view. That is to be able to do screen shakes and other neat effects.

I really struggle with containing my player object properly to the room. When I use a collision with view0_boundary and add

phy_position_x = phy_position_previousx;
phy_position_y = phy_position_previousy;

then my ship would get stuck at the screen borders very frequently.

I also tried adding some sprites that block the player off the room and created a sprite, 1280x720 and spawned them at the borders. I gave my player empty events for them and set their density to 0, making them static. However, this resulted in the same problem, I got stuck in them.

I need a smooth solution for this, obviously, to have a fun experience. I have this problem quite for a while, so please help me understanding how to do this properly.


texts: How to create high quality and fast portal effect?

texts:
EDIT:
So I've gotten the portal visual effect working with no performance hit, and I've got the physics set up of objects with rigidbodies moving through portals seamlessly, and objects with character controllers moving through it seamlessly. The only thing I'm trying to figure out now is blending two camera views to get the proper first person transition effect. Any ideas on how I'd blend those two? I'm thinking something using a depth only shader, or the normalized viewport rect. My main problem is calculating that in real time, and with angles.

So I've been working on creating a portal effect in Unity3D. Obviously I've taken Valve's Portal as a great influence to programming this. Currently I'm simply using a camera's rendertexture to get the graphical effect across, and then some code to do the rest. The problem is at 2048x2048 it looks as high quality as Portal's, but causes heavy FPS loss. To solve this I'd either have to lower the texture quality or the number of times I update the texture.

Valve has accomplished a high quality portal effect without causing high frame rate loss. How can I do the same? Does anybody have any good ideas for rendering to a high resolution texture without causing frame loss?

I'm considering making my own code for rendering to textures rather then using Unity's built in system, it's doable but would definitely be a hassle. So any thoughts, ideas, or suggestions are highly appreciated.


texts: Given a vector, A, which represents a point, and a unit vector, B, which represents the looking direction, how would I rotate A so that B is the axis that's looked down on? Let's say the looking-axis is originally (0,0,1) and I want it to become B by rotating A accordingly. So it needs to rotate by (0,0,1) - B.


texts: Issue with Texture2D memory leak in Unity

texts:
I have a simple method that converts RenderTexture data into Texture2D
public static Texture2D RenderTextureToTexture2D(RenderTexture renderTexture, int width, int height,
    TextureFormat textureFormat = TextureFormat.RGB24, bool mipChain = false) {

    Texture2D tex = new Texture2D(width, height, textureFormat, mipChain);
    RenderTexture.active = renderTexture;

    tex.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
    tex.Apply();

    RenderTexture.active = null;
    // Here I want some way to release memory occupied by tex
    // I want to release tex here because i believe everytime this method executes tex is not getting garbage collected and stays in memory
    // Only problem is I cannot release it before, and after returning, it is obvious I cannot do that.
    return tex;
}

The above mentioned method is working exactly as intended. However, if I call this method multiple times, or in update it starts using so much memory

How can I avoid this problem?
Edit
I cannot share the entire code but this is minimal code to reproduce the issue
[SerializeField] private RenderTexture renderTexture;
private Texture2D mTexture;

private void Start() {
    mTexture = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.BGRA32, false);
}

private void Update() {
    mTexture = TextureUtils.RenderTextureToTexture2D(renderTexture, renderTexture.width, renderTexture.height, TextureFormat.BGRA32);

    // Some agora sdk stuff to share the mTexture over the network for screen sharing
}


texts: Simple thruster like behaviour when rotating sprite

texts:
I'm prototyping some 2D game concepts with XNA and have added some basic keyboard inputs to control a triangle sprite.

When I press key up the sprite accelerates in it's current facing direction, when I release the key it brakes down.

For rotation, when I press left/right keys I rotate the sprite.

Currently the sprite immedately changes direction when I rotate it. What I want is for it to keep moving in the same direction when I rotate, until I hit key up, adding thrust in whatever direction the sprite is pointing at.

This would simulate thrusters on a classic space shooter like Asteroids.

I'm adding an image to describe the behaviour I'm after and some code samples of how I'm doing things at the moment.

This is my player struct, holding information of the sprite.

    public struct PlayerData
    {
        public Vector2 Position;  // where to draw the sprite
        public Vector2 Direction; // travel direction of sprite

        public float Angle;       // rotation of sprite

        public float Velocity;
        public float Acceleration;
        public float Decelleration;
        public float RotationAcceleration;
        public float RotationDecceleration;

        public float TopSpeed;
        public float Scale;
    }

This is how I'm currently handling thrusting / braking (when pressing/releasing key up) (simplified, removed some bounds checking etc):

player.Velocity += player.Acceleration * 0.1f;
player.Velocity -= player.Acceleration * 0.1f;

And when I rotate the sprite left and right:

player.Angle -= player.RotationAcceleration * 0.1f;
player.Angle += player.RotationAcceleration * 0.1f;

This runs in the update loop, keeps the direction updated and updates the position:

Vector2 up = new Vector2(0f, -1f);
Matrix rotMatrix = Matrix.CreateRotationZ(player.Angle);
player.Direction = Vector2.Transform(up, rotMatrix);

player.Direction *= player.Velocity;

player.Position += player.Direction;

I am following along various beginner tutorials and haven't found any describing this, but I have tried some on my own without success. Do I need to change my velocity and acceleration fields to Vectors instead of floats to accomplish this type of movement? I realise my Angle and the Direction vector is currently tied together and I need to disconnect these somehow to be able to rotate freely without changing the direction of the movement, but I can't quite figure out how to do this while keeping the acceleration/decceleration functional.

Would appreciate an explanation rather than pure code samples.

Thanks,


texts: How can I estimate the perfomance of graphics cards I don't have?

texts: I'm developing a voxel game with OpenGL and want to optimize the number of rendered faces. How can I estimate how many faces at most a modern graphics card of a certain brand is able to compute, while still managing to render at 60fps?


texts: How can I separate processing input and update?

texts:
I know that game loop is broken up into three distinct phases: processing inputs, update, and render, but I just can't see how I can make processing input and update independent of each other.

Let's say I have a button. If I click on the button, it will increment the number by one on the screen. How can I make this possible? Is it OK to update the logic while processing the input?

For example:

 while (!ended)
 {
   while (SDL_PollEvent(&event))
   {
       IF MOUSE EVENT
          IF USER CLICKED ON THE BUTTON
              NUMBER += 1;
   }

   update(); // no job for update as number was incremented above
   draw();
 }

Why would I need a distinct update function if we could just update logic/values while processing input like the code above?

Please show me an example using SDL poll event system.

 while (!ended)
 {
   while (SDL_PollEvent(&event))
   {

   }

   update();
   draw();
 }


texts: Oculus Rift on Motion Simulator Platform

texts:
I currently develop a VR environment for an existing (physically) large motion simulator platform. The user can sit on this motion platform and gets accelerated and tilted to induce the feeling of motion in a research car simulator environment.
The Oculus Rift positional tracker is already mounted on the moving platform in front of the user, just as you would do on your PC.

The 3D engine I currently use is Unity 5.3.
The rotation angles and linear accelerations of the platform are already fed into Unity. The results are however not what I aimed for.
While the rotational compensation works well as long as we tilt the platform, once the angular velocity goes to zero, the tracker gets reset without being called by me or firing an event that it has done so.
The linear acceleration compensation always jitters around the true resting point.

I already tried using the native Unity VR implementation and also the Oculus plugin. However, the sensor fusion is not available at this level.
The Oculus forums have many topics about this problem, but I could not find any solutions.

Are there alternatives that one might try in order to use the Oculus on a moving platform?

What I would like to do ideally is to subtract the induced motion from the Oculus sensor data before getting processed further. I already considered patching e.g. LibOVR, but I could not find any helpful Sensor fusion related functions there, either.


texts: Complex Game AI for Turn-based Strategy Games

texts:
I'm doing some research for a turn-based Strategy game project and looking for good resources on this topic. The game is a typical war game where countries can fight each other, deploy units and have these units move around on a hexagonal tilemap, attack each other, etc.

I'm particularly interested in how the AI of Civilization V is organized! According to Wikipedia the game uses four different AI systems for different layers of the game's AI:

tactical AI controls individual units
the operational AI oversees the entire war front
the strategic AI manages the entire empire
the grand strategic AI sets long-term goals and determines how to win the game

Conceptually this looks like it makes a lot of sense to achieve a complex AI and it makes me curious to find out about how these different AI systems work (and work together). The tactical AI is probably the most easy to understand since it handles the decision-making for a single unit (move, attack, repair, retreat, etc.) but I think the other AI systems are where it really gets interesting. For example what does the operational AI do and how does it do that? I'm sure these are best-kept secrets by Firaxis Games but it would be cool to get some discussion started on this to find out more about it.

Also if anyone knows any good books that handle turn-based strategy game AI it would be great to know. Obviously this is a sparsely seeded topic on the web. I got "Programming Game AI by Example" but that book is more about single agent behavior AI than high-level goal-oriented AI.


texts: How do I move a sprite to the mouse position?

texts:
So, I'm trying to make my sprite walk to the X-coordinate of my mouse click.
This is my code:

currentMouseState = Mouse.GetState();
            MouseState mouseState = Mouse.GetState();
            if (lastMouseState.LeftButton == ButtonState.Released && currentMouseState.LeftButton == ButtonState.Pressed)
            {
                int mouseposx = mouseState.X;
                if (playerPosition.X < mouseposx)
                    {
                        playerPosition.X += 3;
                    }
                if (playerPosition.X > mouseposx)
                    {
                        playerPosition.X -= 3;
                    }
            }`

The problem is that the sprite will walk only 3 pixels and then stop. If I use while instead, like this:

  currentMouseState = Mouse.GetState();
            MouseState mouseState = Mouse.GetState();
            if (lastMouseState.LeftButton == ButtonState.Released && currentMouseState.LeftButton == ButtonState.Pressed)
            {
                int mouseposx = mouseState.X;
                while (playerPosition.X < mouseposx)
                    {
                        playerPosition.X += 3;
                    }
                while (playerPosition.X > mouseposx)
                    {
                        playerPosition.X -= 3;
                    }
            }

it will simply teleport to the X-coordinate instead. I tried adding a delay using Thread.Sleep(ms), but that just made it freeze and then teleport anyway.

So, what should I do?

EDIT:
This is the new code, by Byte56.

currentMouseState = Mouse.GetState();
            MouseState mouseState = Mouse.GetState();
            if (lastMouseState.LeftButton == ButtonState.Released && currentMouseState.LeftButton == ButtonState.Pressed)
            {
                if (playerPosition.X - mouseState.X < 3)
                {
                    playerPosition.X = mouseState.X;
                }
                else if (playerPosition.X < mouseState.X)
                {
                    playerPosition.X += 3;
                }
                else if (playerPosition.X > mouseState.X)
                {
                    playerPosition.X -= 3;
                }
            }

edit3:

 void update()
        {
            // Check if the player has reached the target, if not, move towards it.
            if (playerPosition.X - playerTarget.X < 3)
            {
                playerPosition.X = playerTarget.X;
            }
            else if (playerPosition.X > playerTarget.X)
            {
                playerPosition.X -= 3;
            }
            else if (playerPosition.X < playerTarget.X)
            {
                 playerPosition.X += 3;
            }

        }

and

 currentMouseState = Mouse.GetState();
            MouseState mouseState = Mouse.GetState();

            if (lastMouseState.LeftButton == ButtonState.Released && currentMouseState.LeftButton == ButtonState.Pressed)
            {
                // This will give the player a target to go to.
                playerTarget.X = mouseState.X;
            }
            update();


texts: How can I use different fonts for different objects in Unity?

texts:
In Unity 3.5, I have a font that is strangely linked to four game objects. I want to put separate fonts on each object.

In the Inspector, when I click on the circle icon next to the "Text" attribute, I can select a font.  But, then it changes the font on the other three objects as well.

I was hoping Unity would have something like a material ID from 3DS Max. If I could put a new material ID on the other objects, hopefully I could assign a new font to the text mesh. Regardless, is there a way to assign a different font to each of my objects?


texts: Unity3d iOS build restarts when regaining focus from browser

texts:
I have an app made in Unity3d for android and iOS. In it, the user has the ability to link their accounts with Facebook and Twitter. For Facebook I use their Unity plugin, for Twitter, I open an external browser page that lets them accept or decline Twitter integration that then redirects to a php page the calls the app URI to return focus to Unity.

On Android this all works perfectly using an Intent in the Manifest. In IOS I'm running into issues though and I don't really know my way around XCode.

I'm using the newest version, XCode 7 Beta 2. The App runs as expected but for both the Facebook and Twitter authentications, upon returning focus to the App from the Browser, it completely restarts the App as if just launched rather then returning from a suspended state.

In the Unity build I have "Run in Background" selected. I setup the URL Scheme in XCode. Its a pretty basic app so I don't think its being closed due to Memory usage.

Any ideas or any settings I can change in XCode that might be preventing it from resuming?

*Note, if I just hit Home and send the App to the background it will properly resume, its only when called by the URI from the browser that it seems to completely restart.


texts: How to use large texture atlases in my shaders on mobile devices

texts:
This is a frustrating discovery. I have ported my desktop game to mobile and discovered that floating point precision in my shaders is not good.

I have large animations which I store per frame on a texture atlas. I try to keep as many non-unique frames in their own sections and piece them together e.g. a sword that doesn't animate for 4 frames is a node that attaches to the hand piece. This preserves memory.

However the texture atlases are so big that, when I use shaders, it breaks the animation completely.

Here's an example of one of the shaders that wraps the animated backgrounds (scrolling clouds)

precision highp float;
precision highp int;
precision highp sampler2D;

varying vec2 vTexCoord;
varying vec4 vColor;
uniform sampler2D texture;

// this script animates and wraps an animated background from one atlas
uniform float x; // frame start x
uniform float y; // frame start y
uniform float w; // frame width
uniform float h; // frame height
uniform float offsetx; // wrap by x amount
uniform float offsety; // wrap by y amount

void main()
{
    vec2 origin = vec2(x, y);
    vec2 size   = vec2(w, h);

    // Get the texture coordinate
    vec2 texCoord = vTexCoord;

    // Make its lower-left be at (0,0) and it's upper right be at (1,1)
    texCoord = (texCoord - origin) / size;

    // Apply the offest
    texCoord = texCoord + vec2(offsetx,offsety);

    // Apply the wrapping
    texCoord = fract(texCoord);

    // Convert back to texture atlas coordinates
    texCoord = (texCoord * size) + origin;

    gl_FragColor = texture2D(texture, texCoord) * vColor;
}

For most backgrounds, the animations are small and don't cause problems. But some backgrounds are large and their texture atlas is large. The floating point precision breaks down and the animation tears.

I don't have much mobile experience. How can I use large textures atlases for animations without the x/y coordinates breaking due to loss of floating point precision?


texts: How do I implement realistic recovery from weapon recoil?

texts:
I want to create an equation determining how fast a gun recovers back to its center after it has fired. I have a weapon system functioning based on constants (recoil amount, bullet spread, etc.) similar to modern FPS games. The weapon system is creating great realistic recoil and bullet spread when the weapons are fired. However, at what speed should each weapon return back to its center?

How do I implement it realistically? Games such as Battlefield and COD have stats for Recoil Decrease and Centerspeed respectively, however how these stats are used to determine a time or speed at which the gun rotates itself back to zero mystifies me.

I am experimenting with using a simple lerp between the weapon's current rotation (caused by recoil) to its original rotation at zero. The issue is how to determine that rate at which it returns in a realistic way. Is there a common way that this is implemented?


texts:
I am developing a kart racing game.  In it, the players fight with each other while racing.

There were several ways I tried to add attack AI to the enemies and the player.

When the user clicks on the attack function, it throws raycasts in the certain area; if enemy is found then the user gets presented with the weapon and auto attacks occurred.

Later I moved on from this code for two reasons, first very dirty and highly unoptimised and second it's only able to calculate limited distances (not for missile weapons which are long range); a new approach needed to be implemented.

After thinking and researching I tried Physics.Overlap; this did solve my optimization problem with short range weapons but still the problem of long range persists.
Thinking around more I came up with other ways to implement long range attack, i.e., by spawning one collider just a little behind the player and it will go foreword until a certain distance and if the enemy gets found it will inform the player and the weapon will be spawned and attacked.

Though that third approach looks good so far, the problem arises when the game gets high pace as the collider sometimes do not catch the other players or get too slow to catch the other players and result of that buggy attack look.

So I would like to know: is there any other way to implement long range attacks considering it is a kart racing game?

Any help will be appreciated


texts: How did the SNES handle palettes of multiple sprites?

texts:
(This is assuming all graphics are stored in 4 bpp)

I understand that the SNES has a 256 color palette split into 16 palettes (each with 16 colors), and 8 of these represent palettes usable by sprites. Each sprite has a number representing which of these 8 palettes it uses. My question is how and when are the colors of these 8 palettes set typically.

Does the SNES copy the palette of a sprite into one of these 8 palettes when it is rendered? If so that would mean that only 8 sprites could be rendered simultaneously, and two sprites using the same colors would not share the palette which would be a waste of memory.


texts: How to make Lists (and Arrays) in Unity only take GameObjects of a certain "type"

texts:
If I were coding in generic C# I can create a list that only stores a certain type of object. If I accidentally try to add anything other than that type to the list I will be promptly told and can fix the problem quickly.

List<Foo> my_list = new List<Foo>();
my_list.Add(Bar) //Error

However because I'm using Unity my script needs to be attached to a GameObject, and that needs to be stored in the List.

List<GameObject> my_list = new List<GameObject>();
GameObject Foo = new GameObject; Foo.AddComponent<Foo>();
GameObject Bar = new GameObject; Bar.AddComponent<Bar>();
my_list.Add(Foo) //Fine
my_list.Add(Bar) //Works, but I don't want it to

I only want the list to store "Foo" GameObjects (GameObjects with the Foo component), however there is nothing to stop me accidentally storing any type of GameObject, which could (and already has) caused me hours scratching my head trying to debug the problem.

Is there a way to subtype a GameObject so that it has the effect of List<GameObject(Foo)> my_list? Is there a way to do it with arrays too?


texts: Triggering an animation on a gameobject with a collider2D

texts:
I'm creating platforms that break on trigger. The animation works and the colliders are set like they should, but I can't seem to figure out how to trigger the "stepBreak" animation I have.

This is what I have, so far:

using UnityEngine;
using System.Collections;

public class breakablePlatforms : MonoBehaviour
{
    public GameObject steps;
    private Animator animator;

    void Start()
    {
        animator = GetComponent<Animator>();
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        if(other.tag == "Player")
        {
            animator.Play("stepBreak")
        }
    }
}

These are my animations and transitions:


texts: Why is SCNNode.rotation property a four dimensional vector?

texts:
I don't understand why SCNNode's rotation property is a SCNVector4 instead of a SCNVector3. The documentation states that:

  The four-component rotation vector specifies the direction of the rotation axis in the first three components and the angle of rotation (in radians) in the fourth. The default rotation is the zero vector, specifying no rotation. Rotation is applied relative to the node’s pivot property.

What's the fourth axis? I tried adding a light (SCNLight) and if I don't specify the value of the 4th float in the vector the light has no effect (the scene is dark). Why? shouldn't a 3-dimensional vector (x,y,z) be enough?


texts: How to find intersections using MapBox Unity SDK

texts:
I'm currently using MapBox's Untiy SDK, which allows me to render 3D Buildings and roads. I want to place a gameobject at each intersection in an area. But, I'm having trouble finding a good way to do that.
The roads are gameobjects attached to a "Tile" gameobect. The roads have a local position 0,0,0 with meshes on them that dictate their rendered position. A long road can cross multiple tiles, and thus the same "road" may exist as two or more gameobjects on two or more tiles. The Mesh itself is rectangular prism extruded from some line data by Mapbox.
I have tried to use colliders with no success. For one, in order to get points of intersections between two colliders, they need to have rigidbodies attached to them and it's too expensive to do that, since there are hundreds of roads. Furthermore, many of the meshes have bad verts in them, which wont allow mesh colliders to work anyway, and box colliders wont work for non-straight roads. Some road meshes are sprawling, twisting, and winding and could "collide" with a number of roads without actually touching them.
I am not above brute force looping through every mesh's vertex in every tile to detect intersections, but I am as of yet unsure of the best way to do this or if it is necessary.
I am also not sure if MapBox has some hidden feature for this the way Google Maps Unity SDK allows for access to the road lattice and intersections. If I could get some info about the line that represents the road, it would be easy to tell if roads overlap.
The best way I can figure is to loop through the verts on a road to determine if the lines between verts overlap that of the roads within the same time, but am not sure if that is the best course of action


texts:
I am trying to figure out how to calculate the angle to rotate a sprite in z axis to look towards the mouse.

I declared one index -and vertexbuffer and set following vertices in it:
        VertexBuffer vBuffer;
        IndexBuffer iBuffer;

    VertexPositionColor[] vertices = new VertexPositionColor[4];
    short[] indices;

       vertices[0] = new VertexPositionColor(new Vector3(0, 0, 0) + position, Color.Blue);
        vertices[1] = new VertexPositionColor(new Vector3(1, 0, 0) + position, Color.Blue);
        vertices[2] = new VertexPositionColor(new Vector3(0, 1, 0) + position, Color.Blue);
        vertices[3] = new VertexPositionColor(new Vector3(1, 1, 0) + position, Color.Blue);

        indices = new short[] { 0, 1, 3, 3, 2, 0 };

        vBuffer = new VertexBuffer(GraphicsDevice, typeof(VertexPositionColor), 4, BufferUsage.WriteOnly);
        iBuffer = new IndexBuffer(GraphicsDevice, IndexElementSize.SixteenBits, 6, BufferUsage.WriteOnly);

        vBuffer.SetData<VertexPositionColor>(vertices);
        iBuffer.SetData<short>(indices);

Rendering:

            GraphicsDevice.SetVertexBuffer(vBuffer);
        GraphicsDevice.Indices = iBuffer;

      effect.View = Matrix.CreateLookAt(new Vector3(0, 0, -5), new Vector3(0, 0, 1), new Vector3(0, 1, 0));
        effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, GraphicsDevice.Viewport.AspectRatio, 0.1f, 1000.0f);
        effect.VertexColorEnabled = true;

        effect.World = Matrix.CreateRotationZ(radians);
        effect.CurrentTechnique.Passes[0].Apply();

        GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 2);

The variable radians is set in the update-method :

            center = new Vector3(0, 0, 0) + position;
        mousePosition = new Vector3(Mouse.GetState().X, Mouse.GetState().Y, 0);

        mousePosition = GraphicsDevice.Viewport.Unproject(mousePosition, effect.Projection, effect.View, Matrix.Identity);

        Vector3 dir = center - mousePosition;

        radians = (float)Math.Atan2(dir.Y, dir.X);

Now I want to solve this problem by avoiding using the method atan2.

Given is the xy-plane.
How is it possible to calculate the angle of a vector with the direction (0,0,0) to (mouseX,mouseY,0)?
Trying to use a reference vector and calculating then the dot product, dividing it by length to put it in the acos function had given false results.

Can You suggest a solution to this?

Thank you.

EDIT: I just read http://www.euclideanspace.com/maths/algebra/vectors/angleBetween/ which states that many acos implementations give a result between zero and pi... makes sense.


texts: "Unfortunately game has stopped" error on Android device

texts:
In Unity 2018.4.3f1, I am able to build my APK successfully, but when I try to launch it on my mobile device, it shows: "Unfortunately game has stopped".

I don't know the problem is. Here are the project settings I'm using:


texts: How can we generate 3D architecture in a racing game's background procedurally with respect/similar to the real world?

texts:
In the last few days, I jumped into searching is there a conventional/convenient way to build 3D architecture quickly, most likely by some accessory software like CityEngine, BIGEMAP, or google maps' Maps SDK for Unity.
However, I couldn't figure out the most suitable solution that typically suits the requirement of "generate 3D architecture models by the racing road which is referencing the real world map", or just simply "build a massive amount of 3D architecture models",  efficiently and handily.
I want to achieve buildings similar to those seen in Need For Speed and Asphalt. Their buildings in the scene are quite outstanding to me.

How can I generate buildings similar to this?


texts:
I am trying to implement collision response in my libgdx game. I'm using Rectangle objects as my bounbing boxes. This makes collision detection very easy, however I can't quite get the response working correctly. At the moment I have this:

float overlapX = getOverlap1D(dynamicBounds.x, dynamicBounds.x + dynamicBounds.width, blockBounds.x, blockBounds.x + blockBounds.width);
float overlapY = getOverlap1D(dynamicBounds.y, dynamicBounds.y + dynamicBounds.height, blockBounds.y, blockBounds.y + blockBounds.height);

if (overlapX < overlapY)
{
      if (dynamic.getVelocity().x < 0)
      {
            dynamic.getPos().add(overlapX, 0);
      }
      else
      {
            dynamic.getPos().sub(overlapX, 0);
      }
      dynamic.setVelocityX(0);
}
else
{
      if (dynamic.getVelocity().y < 0)
      {
            dynamic.getPos().add(0, overlapY);
      }
      else
      {
            dynamic.getPos().sub(0, overlapY);
      }
      dynamic.setVelocityY(0);
}

private float getOverlap1D(float min1, float max1, float min2, float max2)
{
    return Math.max(0, Math.min(max1, max2) - Math.max(min1, min2));
}

Using this, corners are handled in a very unpleasant way, resulting in less than extraoridnary results like this.
Where am I going wrong that allows this to happen?


texts: How to randomly spawn obstacles for infinite runner?

texts:
I am trying to create randomly generated path properly? Think of flappy bird (its not really) but my code/algorithm is all wrong. If I make BarMax, BarMin too large, then player can cheat cos in centre there will always be space. Make it too small and pipes are spawned randomly and sometimes very close to each other (unlike flappy). So my player sometimes could run into a situation where its impossible to move past two pipes. My adjacent pipes are really close together as well unlike flappy birds big gap between pipes.

So this is what i dont want to happen.  I have also thought about spawning sets of pre-configured pipes but then i thought they might run into this impossible situation at some point too. I had my level set-up like this  So when a bar touches the looper, it spawns again - code is above.

int numBGPanels = 35;

float BarsMax = 1.5f; float BarsMin = -1.5f;

float widthOfBGObject = 1; float offset = 0.75f; Vector3 pos;

void Start() {
    StartBarsPosition(); }

void OnTriggerEnter2D(Collider2D collider) {

    if(collider.tag == "Bars") {       // this is not getting called cos theres no collider attached atm
        pos = collider.transform.position;
        pos.x += widthOfBGObject * numBGPanels * offset;

        pos.y = Random.Range(BarsMin, BarsMax);
        collider.transform.position = pos;

    }

}

void StartBarsPosition() {
    GameObject[] bars = GameObject.FindGameObjectsWithTag("Bars");

    foreach(GameObject bar in bars) {
        Vector3 initialpos = bar.transform.position;
        initialpos.y = Random.Range(BarsMin, BarsMax);
        bar.transform.position = initialpos;
    }

}


texts: I have basic experience in Python, and I want to know which is the best library to use in development. I was looking originally at Pygame but found it a bit lacking in tutorials. Are there any good ones for Pygame? And if not, is there any nice alternative to the Pygame library, or Python itself?


texts: Lock enemy's y-axis when using Vector3.MoveTowards to follow the player

texts:
I am using the following code to make a zombie move towards me, but when playing the scene the zombie seems to be moving towards me, but also off the ground and not fixed on the y-axis

 public GameObject ThePlayer;
public float TargetDistance;
public float AllowedRange = 10;
public GameObject TheEnemy;
public float EnemySpeed;
public int AttackTrigger;
public RaycastHit Shot;

void Update()
{
    transform.LookAt(ThePlayer.transform);
    if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out Shot))
    {
        TargetDistance = Shot.distance;
        if (TargetDistance < AllowedRange)
        {
            EnemySpeed = 0.01f;
            if (AttackTrigger == 0)
            {
                //TheEnemy.GetComponent<Animation>().Play("Walking");
                transform.position = Vector3.MoveTowards(transform.position, ThePlayer.transform.position, EnemySpeed);
            }
        }
        else
        {
            EnemySpeed = 0;
            //TheEnemy.GetComponent<Animation>().Play("Idle");
        }
    }

    if (AttackTrigger == 1)
    {
        EnemySpeed = 0;
        //TheEnemy.GetComponent<Animation>().Play("Attacking");
    }
}

void OnTriggerEnter()
{
    AttackTrigger = 1;
}

void OnTriggerExit()
{
    AttackTrigger = 0;
}

What can i do to ensure that it is sticking to the y axis at all times


texts: How can I deploy a Xbox 360 game onto a disc?

texts: I'm making some games for Windows now since about 3 years using the Microsoft XNA Framework and C#. Now I finally came to buy myself a Xbox 360 and now I want to deploy some games I converted to Xbox 360 onto a CD to give it away to my friends. What tools would I need and how can I do this?


texts: Blender to Unreal or Unity - will combining animations into one clip for a parent object to store effect workflow?

texts: Hey so I have a gun and a set of rigged hands in blender, and I was wondering if I made a parent object for the gun, hands and everything, took all the animations respectively (such as right hand reload, left hand reload, gun reload, etc) and combined them all into one animation called reload, would there be problems in the future when working in Unreal or Unity? Would I be able to apply the same animation to all the objects that are a part of the action and have them work respectively?


texts: Big game in Flash - how to create levels structure

texts:
I'm building a game in Flash similar to the structure of Angry Birds or Cut the Rope (where there are a number of "rooms" and unique levels created within each "room").

The user gets through the game by playing through a room to unlock the next room. I have all the logic to unlock rooms and move between them. The problem I've come to is that I'm not sure how to build out the levels in each room. Let me provide an example.

Let's say I have 15 rooms. Each room has 10 levels, each with their own objects whose attributes change as the levels increase (ie. speed, position, collisions). There can be 2 to 5 objects out of a possible 10 that are randomly generated and placed on the stage, each level. This all adds up, with so many combinations and a total of 150 levels.

Ideally I would like to use a single class that controls the level creation for all rooms. Right now I have a Menu Class, one Class for each room to build the background, one LevelCreation Class, and one for the pause/lose menu. Does this seem like a feasible Class structure? Or should there be a LevelCreation Class for each room?

Switching between levels, re-initialize existing structure or create new one? is sort of helpful in reusing objects when advancing from level 3 to level 4, but I'm lost on how to set up the individual levels. So as a second part to the question: in my LevelCreation class(es), what is the best way to store the level attributes? In an array (or multiple arrays)?

I've also taken a look at How should I manage game levels in a flash games? but it seems to focus more on save/load data and not on how to build the levels. Structuring various game states and unique levels seems to be the closest I could get to an answer, but I guess I'm too much of a noob to quite understand what the answer to the question is saying.

I hope this all makes sense and I appreciate any help that I can get. Please let me know if I need to provide more details.


texts: Basic Character Controller Not Working Properly in Unity

texts:
I've been trying to setup a simple mouse camera which I had all the code working fine, except when I move with wasd and move my mouse to turn the camera simultaneously the input freezes up and gets stuck repeatedly inputting whatever the last input was. I've tested the simplest way to replicate the issue and it doesn't even need a camera for the issue to come up. If anyone would like to test and try to replicate the issue these are the steps its super fast and simple.

create new project(basic PC 3D project)

create a plane, and a cube

Add a basic character controller script to the cube (this time I used the official Unity code to be sure it's not an issue with code)

and that's it, that's actually all that was needed to create the issue for me. And to explain to anyone who may want to test it the issue is as follows: when you use wasd keys normally, everything works fine and the controls are responsive. However if you hold down one of the wasd keys while also moving your mouse (just wiggling the mouse should suffice) suddenly things will lock up and the cube will keep moving for a bit even after you let go of the respective wasd keys. In general if you hold a direction while simultaneously wiggling the mouse for a longer period of time, it will extend the amount of time the cube keeps moving after you let go of the direction. And this was done on Unity version 2020.1.16f1
If anyone has any idea what the issue may be its really appreciated.


texts:
a beginner game developer here. I have recently taken upon learning about 3D game development and I am stuck on a simple matrix problem.

The image is found from this article: http://www.codinglabs.net/article_world_view_projection_matrix.aspx
I am trying to represent this matrix in my code but I am not sure what precisely is meant by FOVx and FOVy. What is the difference and how would I represent this in my perspective matrix? I am not using any 3D api.


texts:
I have a projecile(Hook) and the tail of the projectile(yellow balls)

TailProjectile class draws a ball at the exact position of the projectile(hook) and let it there until the projectile ends

I'd like to draw the ball at the start of the hook(red circle) because by now it draws at the projectile image position(blue point)

How can I do it independent of the rotation of the hook?

This is how I calculate the rotation of the projectile

distanceY = endPosition.Y - initialPosition.Y;
        distanceX = endPosition.X - initialPosition.X;

        if (distanceX < 0)
            animation.SprtEffects = SpriteEffects.FlipVertically;
        animation.Rotation = (float)Math.Atan2(distanceY, distanceX);

Then I pass the projectile to the tail and draw the ball

        if (hasTail)
            tail.Update(gameTime,  position , animation.Rotation,animation.SprtEffects);

And at the TailProjectile update class :

  public void Update(GameTime gameTime,Vector2 p,float rotation,SpriteEffects sprtEffect)
    {
        if (Vector2.Distance(animations[animations.Count - 1].Position, p) > distanceBetween)
        {
            Animation tempAnimation = new Animation();
            tempAnimation.LoadContent(content, image, "", p);
            tempAnimation.Rotation = rotation;
            tempAnimation.SprtEffects = sprtEffect;
            tempAnimation.DrawColor = color;
            animations.Add(tempAnimation);
        }

And the Animation Draw:

spriteBatch.Draw(image, position + origin, sourcRect, drawColor * alpha, rotation, origin, scale, sprtEffects, 0.0f);

Edit: Using rotation matrix solve half of the problem :

My problem now is how can I calculate it for angles higher than 90º ? (third picture of the image)

 double xO, yO;
        xO = originpoint.X * Math.Cos(rotation) - originpoint.Y * Math.Sin(rotation);
        yO = originpoint.X * Math.Sin(rotation) + originpoint.Y * Math.Cos(rotation);
        initialAnimation.Position = new Vector2((float)xO + initialAnimation.Position.X, (float)yO + initialAnimation.Position.Y);


texts:
I'm using Lua. I have a hex map. It is randomly generated into an table.

hexmap[y][x].color = "red"

I wish to find each "group" of hex's. i.e. all hex's of the same color that connect to each other will belong to one group.

As an example, in the following image:

The result should be:

1 blue group (all hex's connect)
3 green groups
1 black group

Any suggestions?

Thank you.


texts: Can I run old projects after updating Unity?

texts:
Today I decided to upgrade unity from 5.0.0 to 5.5.0.

But before updating it, I wanted to know: Can I run/build my projects made in Unity 5.0.0 in Unity 5.5.0?


texts: How to smoothly display opponents in realtime multiplayer game

texts:
I'm implementing a small-scale multiplayer racing game. As of right now, the client sends updates to the opponents on a fixed interval (or as fast as possible), containing location on the map etc. Each client will then reposition that opponent on that location.

Obviously, this will not run smoothly due to network lag. The vehicles will jump between each location.

One solution for this would be to include the speed and direction with each update-package, and then keep the vehicle running as that until next update, and then animate a movement to the new position. Repeat.

This only works if the player drives predictably, e.g not reversing after update etc. It is not important that the sync is exact, but should be pretty close to the reality location-wise.

How to smoothly show opponents in a realtime multiplayer game?


texts: Who should handle animations when game logic is separated from rendering?

texts:
Suppose I have a tile-based game and I want the step to be 1 tile but also want the movement to be smooth while the player is getting there. If I understand correctly, the only way to achieve this would be making a series of small movements where the increment is a percentage of a tile.

My question is: should the game logic thread send the animations to the rendering thread? What is the best way to go about it?


texts: Is there any simple game that involves psychological factors?

texts:
I need to find a simple game in which several people need to interact with each other. The game should be simple for an analysis (it should be simple to describe what happens in the game, what players did). Because of the last reason, the video games are not appropriate for my purposes. I am thinking of a simple, schematic, strategic game where people can make a limited set of simple moves.

Moreover, the moves of the game should be conditioned not only by a pure logic (like in chess or go). The behavior in the game should depend on psychological factors, on relations between people. In more details, I think it should be a cooperation game where people make their decisions based on mutual trust. It would be nice if players can express punishment and forgiveness in the game.

Does anybody knows a game that is close to what I have described above?

ADDED

I need to add that I need a game where actions of players are simple and easy to formalize. Because of that I cannot use verbal games (where communication between players is important). By simple actions I understand, for example, moves on the board from one position to another one, or passing chips from one player to another one and so on.


texts: Libgdx Tiled | Using setTile results in a NullPointerException

texts:
So, I'm attempting to change the texture of a block when the player comes in contact with it by using cell.setTile(tileSet.getTile(926). I've already looked at similar questions and I guess the layer in Tiled is coming up as null, but I have no clue how to fix it.

I'm sorry it's a long post.

Here's the World Creator

public class B2DWorldCreator {

public B2DWorldCreator(PlayScreen screen) {
    World world = screen.getWorld();
    TiledMap map = screen.getMap();

    BodyDef bdef = new BodyDef();
    FixtureDef fdef = new FixtureDef();
    PolygonShape shape = new PolygonShape();
    Body body;

    //create static bodies for every wall in the game
    for (RectangleMapObject object : map.getLayers().get(2).getObjects().getByType(RectangleMapObject.class)){
        new Wall(screen, object);

    }

}
}

Here's the Tile class

public class Tile {
protected World world;
protected TiledMap map;
protected Rectangle bounds;
protected Body body;
protected PlayScreen screen;
protected MapObject object;
protected Fixture fixture;

public Tile(PlayScreen screen, MapObject object) {
    this.screen = screen;
    this.map = screen.getMap();
    this.world = screen.getWorld();
    this.object = object;
    bounds = ((RectangleMapObject) object).getRectangle();

    BodyDef bdef = new BodyDef();
    FixtureDef fdef = new FixtureDef();
    PolygonShape shape = new PolygonShape();

    bdef.type = BodyDef.BodyType.StaticBody;
    bdef.position.set(bounds.getX() + bounds.getWidth() / 2, bounds.getY() + bounds.getHeight() / 2);

    shape.setAsBox(bounds.getWidth() / 2, bounds.getHeight() / 2);
    fdef.shape = shape;

    body = world.createBody(bdef);
    fixture = body.createFixture(fdef);
}

public void setCategoryFilter(short filterBit) {
    Filter filter = new Filter();
    filter.categoryBits = filterBit;
    fixture.setFilterData(filter);

}
}

Here's the wall class where I call the problematic line at 31.

public class Wall extends Tile {
private TiledMapTileSet tileSet;
private TiledMapTileLayer layer;
private TiledMapTileLayer.Cell cell;

public Wall(PlayScreen screen, MapObject object){
    super(screen, object);
    fixture.setUserData(this);
    setCategoryFilter(AdventureCompany.WALL_BIT);
    tileSet = map.getTileSets().getTileSet("PlaceHoldernoTree.tsx");

}

public void onContact(){
    cell = new TiledMapTileLayer.Cell();
    if(object.getProperties().containsKey("Door")){
        layer = (TiledMapTileLayer) map.getLayers().get(1);
        cell = layer.getCell((int) body.getPosition().x / 16, ((int) body.getPosition().y / 16));
        System.out.println(cell.getTile());
        cell.setTile(tileSet.getTile(926));
    }

}
}

My Contact Listener

public class WorldContactListener implements ContactListener {
private AssetManager manager;

public WorldContactListener(AssetManager manager) {
    this.manager = manager;
}

@Override
public void beginContact(Contact contact) {
    //these are what came in contact
    Fixture fixA = contact.getFixtureA();
    Fixture fixB = contact.getFixtureB();

    int cDef = fixA.getFilterData().categoryBits | fixB.getFilterData().categoryBits; // this will be used to activate specific collision results
    Gdx.app.log("Contact", "ya boi");
    switch(cDef) {
        case AdventureCompany.EXPLORER_BIT | AdventureCompany.WALL_BIT:
            if(fixA.getFilterData().categoryBits == AdventureCompany.WALL_BIT)
                ((Wall) fixA.getUserData()).onContact();
            else
                ((Wall) fixB.getUserData()).onContact();

            break;
    }

}

And finally, the Tmx file header

    <?xml version="1.0" encoding="UTF-8"?>
<map version="1.0" tiledversion="1.1.5" orientation="orthogonal" renderorder="right-down" width="64" height="64" tilewidth="16" tileheight="16" infinite="0" nextobjectid="135">
 <tileset firstgid="1" source="test6.tsx"/>
 <tileset firstgid="925" source="PlaceHoldernoTree.tsx"/>
 <layer name="Background" width="64" height="64">
  <data encoding="base64">


texts: Transparent alpha mode in Shader Graph creates unwanted jagged outline

texts:
I am currently working on a transparent shader and noticed that all my works have a jagged dark outline. I guess I've used the wrong settings somewhere, but I've been fiddling around with a couple settings without any success. I have created a basic shader, which shows the shader settings I use and the problem.

It might be a little hard to see on the screenshot, so please have a look in full resolution. There's a small black outline around the circle on the yellow background.


texts:
The idea is to access the function BlockWasDestroyed(); from Combo class.
Instead of var combo = gameObject.GetComponent(Combo); I've also tried with

var combo = GetComponent(Combo);
var combo:Combo = gameObject.GetComponent(Combo);
var combo:Combo = GetComponent(Combo);

But the console keeps telling it's null. However it could work when the function was static, but thing is now that function is calling another function, and so the errors happen once again.
Here's my code so far:
Brick.js
#pragma strict

public class Brick extends MonoBehaviour{

    function OnCollisionEnter(col : Collision){
        if(col.gameObject.name == "Ball"){
            var ballb = gameObject.GetComponent(BouncingBall);
            var combo = gameObject.GetComponent(Combo);
            combo.BlockWasDestroyed();
            ballb.velocityZ = ballb.velocityZ * -1;
            Score.score += 20;
            Destroy(this.gameObject);
        }
    }
}


texts: How can I avoid repeatedly setting up SDL in VS 2013?

texts:
Do I have to set up SDL 2.0.3 every time I make a new project?

I tried putting sdl.dll in system32 so that I don't have to include it in my project folders, but that didn't work.


texts: What sort of AI is applicable to a board game of this complexity?

texts:
I am thinking of creating an AI for the card/board game Summoner Wars (by PlaidHat Games). It's a very nice tactical game for two players, with simple rules but quite deep.

I have considered min-max trees, Monte Carlo Tree Search (UCT), expert systems (i.e. a set of coded rules/behaviors) but I don't think any would give a good result.

Here are the facts that make creating an AI difficult:

1. The basic rules are simple, but each card has its own twist/exception on the rules. The game is of the expandable card game kind.

This makes it hard to use an expert system. Because of their cards' special rules, some factions play very differently from each other. Coding a strategy for each faction doesn't scale as the number of factions increase and simply doesn't work with custom-built decks.

Because of that, evaluating the board position without simulating what the opponent could do is very hard as well.

2. The number of possible actions is too big.

The cards are played on a 8x6 grid battlefield. During your turn you can summon new units, play events (sometimes with a choosable target), move up to 3 units, attack with up to 3 units and discard cards from your hand. Exploring all the possible ways you can do this stuff is just too expensive. You definitively have to prune your search tree (for a min-max AI).

3. It's hard to evaluate actions without thinking about the future.

It's hard to prune "bad moves" because depending on your cards (and your opponent's) some seemingly stupid or useless actions can be key to victory.

For instance, some human players kill their own units (a bad move in the short term).

Other example: the last phase of the game allows you to discard some cards from your hand to build more magic. That's key to be a good player but very hard to decide. Do I need more Magic? How much? Discarding more cards exhausts my deck faster (which is bad). And if yes: which ones? (knowing that I won't be able to play them.) And of course this is even twisted by the fact that some factions love to discard more cards because of some special effects.

Also, because the rules actually depend on the cards being played, you can't easily evaluate the position at the end of your turn. You also need to simulate your opponent's turn to see if some special abilities may ruin your position.

In my opinion, 2. and 3. make a min-max tree search unsuitable.

4. It's a game with hidden state.

There are the shuffled draw piles, your opponent hand... I don't mind if the AI "cheats" and looks at them, but it must not be obvious to the player! For instance there are some events that you can only play if you have less units on the battlefield that your opponent. It would be very annoying if the AI played aggressively all the time... and kills its own units to reduce headcount just the turn before I draw one such event!

5. It's a game with randomness.

Drawing cards of course, but I don't think this is a key factor for the strategy. Especially since most cards in the draw pile are the same.
On the other hand, combat is done with dice. So if the AI decides to attack a unit, it's hard to say what the outcome will be (with which probability). Especially since many cards in play may change the actual rules regarding this (like: the number of dice rolled, change the value on some dice, remove one die roll, allow re-rolls, change the threshold value for a hit, and so on...)

MCTS was promising, but I have 2 issues with it. First how to handle the random aspects (dice rolls). Second, no paper on MCTS points it out, but I think that it only works well for games where every move brings you closer to the end of the game. Playing Summoner Wars randomly can easily result in an unending game (moving units around on the board)!

I know this is a long question, but does anyone have any idea how to write an AI for such a game? The goal is not to be a perfect player, but to provide a challenge to a human... and the game is very subtle, tactical and precise (for a human player at least).


texts: Is it feasible to use a DHT to span an MMO over many servers for improving reliability?

texts:
At the moment I have an idea for how to handle distributing MMO servers. At the core is a bunch of worker nodes that all share the same set of distributed hash tables. Each DHT stores a specific game component. Each frame a coordinator server (which there can also be many of) pushes work out to all of the connected worker nodes and wait for them to complete all of the assigned tasks.

The system is also divided up into four parts: the client, which obviously the player uses. The proxy server that sits behind load balancers and users connect to. All they do is process incoming user packets, verify them and passes the request to the work cluster. The work cluster receives packets from proxies and append them to a process queue and wait for the frame event from the controller node to process them.

I just want to know if adding a DHT to the worker nodes like this would be feasible? This should allow redundency and high availability out of the box as DHT's are quite good at that.


texts: How to convert coordinates into local object coordinates in libgdx?

texts:
How to convert click coordinates (Gdx.input.getX (), Gdx.input.getY ()) to local object coordinates?
The screenToLocalCoordinates method does not work and does not convert coordinates.
current-some button
Vector2 mouseScreenPosition = new Vector2(Gdx.input.getX(), Gdx.input.getY());
 Vector2 mouseLocalPosition =current.screenToLocalCoordinates(mouseScreenPosition);


texts: How can I return a Dragged Object From a Layer Group to its Original Position?

texts:
I'm trying to work on a card system, I have a drag system going nicely and the cards are setup on a horizontal layer group, however, when the player drops the card outside of the "casting area" I would like it to return to it's original position before it was dragged. Because of the layer group, even though I'm storing the original position having it go back to it produces funkiness and going below the "card hand" area.

I've tried Update and Coroutine approaches using something like this:

 IEnumerator CardReturn(Transform card, Vector3 destination, float speed)
 {

     while (transform.position != destination)
     {
         card.position = Vector3.MoveTowards(
             card.position,
             destination,
             speed * Time.deltaTime);

         yield return null;
     }

transform is the object transform and destination is the original position of the object placed at the start method.

Just to be clear, I want the card to physically move back, not just snap back.

Any help greatly appreciated!

Update: I have tried swapping a place holder in the position, here are images of what happens in that case: 1. Starting hand, 2. Placeholder in position for the card when pulled, 3. What happens when the card attempts to return to that position.


texts:
I want to get rid of a co-routine and do this with a void.

How could I convert his IEnumerator into a void?

private IEnumerator pChangeFoV()
{
    float zValue =70f;

    for (float t = 0f; t < FoVDuration; t += Time.deltaTime)
    {
        float fNew = Mathf.Lerp(_camera.fieldOfView, zValue, t / FoVDuration);
        _camera.fieldOfView = fNew;
        yield return 0;
    }
    _camera.fieldOfView = zValue;
}

Thank you for the help!


texts: How to render a large, seamless platforming world without scene transitions?

texts:
In the game Limbo for example, the whole 2-3 hours of gameplay takes place in one continuous world. The player navigates from one area to another seamlessly, with no obvious loading or transitions.
It looks like the whole game world (ie. all the ground sprites and every puzzle) is always active on and off camera. Is that feasible?
How can I make a large world like this without overwhelming the player's device with all the content that needs to be loaded?


texts: Why does collision only work sometimes when there are multiple objects in the game?

texts:
when i was making a pygame in python for the first time
i kinda have a problem where sometimes the player and the object would touch and the game would not close as intended i dint seem to find the solution to this problem mostly it would work but sometimes the collision would occur but the player would clip right through
i have tried numerous collision techniques which i have heard but none seem to work as well
the problem would still exit

here is my code

import math
import pygame
import random
RED=(255,0,0)
BLUE=(0,0,255)
bg_COLOR=(0,0,0)
WHITE=(255,255,255)

pygame.init()
font = pygame.font.SysFont('monospace', 15)
wid=720
hight=600

player_size = [40,40]
flag=0
player_pos = [int(wid/2),hight-2*player_size[1]]

enemy_size = 50
enemy_pos = [random.randint(0,wid-enemy_size),0]

en_list=[enemy_pos]
speed=10
en_num=4
block_evade=0

screen = pygame.display.set_mode((wid,hight))
pygame.display.set_caption('x wing shooter alpha v1')
game_over = False

clock = pygame.time.Clock()
def score_count(block_evade,block_attack=0):
    text = font.render('score:', 1,WHITE)
    text2 = font.render(str(block_evade + block_attack),1,WHITE)
    screen.blit(text,(0,0))
    screen.blit(text2,(50,0))

def game_quit():
     pygame.display.quit()
     pygame.quit()

def spawn_en(en_list):
    delay = random.random()
    if len(en_list)<en_num and delay < 0.2:#
        x_pos=random.randint(0,wid-enemy_size)
        y_pos=0
        en_list.append([x_pos ,y_pos])

def create_en(en_list):
    for enemy_pos in en_list:
        pygame.draw.rect(screen,BLUE,(enemy_pos[0],enemy_pos[1],enemy_size,enemy_size))

def detect_col(player_pos, enemy_pos):
    p_x=player_pos[0]
    p_y=player_pos[1]

    e_x=enemy_pos[0]
    e_y=enemy_pos[1]
    x1=int(e_x+enemy_size/2)
    x2=int(p_x+player_size[0]/2)
    y1=int(e_y+enemy_size/2)
    y2=int(p_y+player_size[1]/2)
    distance =int(math.sqrt((math.pow(x2-x1,2))+(math.pow(y2-y1,2))))

    if(e_x + enemy_size >= p_x > e_x):
        if(e_y + enemy_size >= p_y > e_y):
            return True
    elif(p_x + player_size[0] >= e_x > p_x):
        if(p_y + player_size[1] >= e_y > p_y):
            return True
    elif(distance <= int(enemy_size/2)):
        return True

def fall_en(en_list):
    block_evade=0
    for idx, enemy_pos in enumerate(en_list):
        if enemy_pos[1] >= 0 and enemy_pos[1]<=hight:
            enemy_pos[1]+=speed
        else:
            en_list.pop(idx)
            block_evade+=1
    return block_evade

def col_check(en_list, player_pos):
    for enemy_pos in en_list:
        if detect_col(player_pos,enemy_pos):
            return True
        else:
            return False

while not game_over:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
           game_quit()
           flag=1
           break
    if event.type == pygame.KEYDOWN:
        x = player_pos[0]
        y = player_pos[1]
        if event.key == pygame.K_LEFT and player_pos[0] >= 0:
            x-=10
        elif event.key == pygame.K_RIGHT and player_pos[0] <= wid-player_size[0]:
            x+=10
        elif event.key == pygame.K_DOWN  and player_pos[1] <= hight-player_size[1]:
            y+=10
        elif event.key == pygame.K_UP  and player_pos[1] >= 0:
            y-=10
        player_pos = [x,y]

    if flag != 1:
        screen.fill(bg_COLOR)

    spawn_en(en_list)
    block_evade+=fall_en(en_list)
    if col_check(en_list, player_pos):
        game_over=True
    create_en(en_list)
    score_count(block_evade,0)
    pygame.draw.rect(screen,RED,(player_pos[0],player_pos[1],player_size[0],player_size[1]))

    clock.tick(20)

    pygame.display.update()

else:
    game_quit()


texts: Managing game state / 'what to update' within an XNA game 'screen'

texts:
I'm trying to figure out how best to manage state within my game screens - please bare with me though! At the moment I'm using a heavily modified version of the fantastic game state management example on the XNA site available here. This is working perfectly for my 'Screens' - 'IntroScreen' with some shiny logos, 'TitleScreen' and a 'MenuScreen' stacked on top for the title and menu, 'PlayScreen' for the actual gameplay, etc. Each screen has the a bunch of sprites, and an 'Update' and 'Draw', managed by a 'ScreenManager'.

In addition to the above, and as suggested as an answer to my other question here, most screens have a 'GameProcessQueue' class full of 'GameProcess'es which lets me do just about anything (animations, youbetcha!), in any order, in sequence or parallel.

Why mention all this? When I talk about managing game state I'm thinking more for complex scenarios within a 'Screen'. 'TitleScreen', 'MenuScreen' and the like are all relatively simple. 'Play Screen' less so. How do people manage the different 'states' within the screen (or whatever you call it) that 'does' gameplay? (for me, the 'PlayScreen')

I've thought about the following:

Enum of different states in the Screen, 'activeState' enum-type
variable, switching on the enum in the Screen Update() loop to
determine what Screen Update 'sub'-function is called. I can see this getting hairy pretty fast though as screens get more complex and with the 'PlayScreen' becoming a behemoth mega-class.
'State' class with Update loop - a Screen can have any number of 'States', 1+ of which are 'active'. Screen update loop calls update on all active states. States themselves know which screen they belong to, and may even belong to a 'StateManager' which handles transitioning from one state to the next. Once a state is over it's removed from the ScreenState list. The Screen doesn't need a bunch of GameProcessQueues, each State has its own.
Abstract Screen further to be more flexible - I can see the similarities between what I've got (game 'Screens' handled by a ScreenManager) and what I want (states within a screen, and a mechanism to manage them). However at the moment I see 'Screens' as high level and very distinct ('PlayScreen' with baddies != 'MenuScreen' with 4 words and event handlers), where as my proposed 'States' are more intrinsically tied to a specific screen with complex requirements. I think.

This is for a turn-based board game, so it's easier to define things as a discrete series of steps (IntroAnimation -> P1Turn -> P2Turn -> P1Turn ... -> GameOver -> .... Obviously with an open-world RPG things are very different, but any advice in this scenario is appreciated.

If I'm just going OOP-crazy please say so. Similarly I'm concious there's a huge amount on this site re: state management. But as my first 'serious' game after a couple of false starts I'd like to get this right, and would rather be harassed and modded down than never ask :)


texts:
When I want to load another scene and show my loading screen to the user - my loading screen is a game object holding a canvas, I use coroutines, but when I type something like this: LoadingScreen.Show ();
        Application.LoadLevel ("PlayerMenu");

Loading screen is shown less than a second, so I wanted to use coroutines, I typed this:

IEnumerator LoadLevel(string levelName) {
    LoadingScreen.Show ();
    yield return new WaitForSeconds (2f);
    Application.LoadLevel (levelName);
}

The problem when calling the coroutine is that my LoadingScreen.Show() code is not executed, so basically I'm just waiting 2 seconds looking at the background of my current scene and then it goes to another scene, I'm confused here as to what is going on, shouldn't my LoadingScreen.Show() code be executed and then I would see the loading screen and wait 2 seconds and the next scene will appear. Anyone has an idea?


texts:
I could not find a game that has modeled Earth completely (i.e., The entire planet and full round model). Does UE4 have a limitation, such as maximum map size, that limits modeling the entire Earth?

Edit:
Context: The goal is to create a flight simulator using UE4 with centimeter granularity for modeling earth.


texts:
I am trying to implement a method which should be called each 10ms with a precision not less than 0.1ms (better 0.05ms). This method is very complex and it is generating sound samples which are placed to float[] buffer to be played with OnAudioFilterRead function.

I have tried both Coroutines and InvokeRepeating - both are bad, because they can call the method with period from 7ms to 13ms which is not acceptable.

The only idea I have is another Task with while() cycle checking the Time.realtimeSinceStartup permanently. But I feel like this is a bad idea.

Can you help me? Thanks.


texts: How to code a 4x shader/filter which emulates arcade crt display behavior?

texts:
I want to write a shader/filer probably in adobe Pixel Bender that will do the best job possible in emulating the fill of an oldskul monochromatic arcade CRT screen. Much like this here:

http://filthypants.blogspot.com/2012/07/customizing-cgwgs-crt-pixel-shader.html

Here are some attributes I know will exist in this filter:

It will take in a low res image 160 x 120 and return a medium res image 640 x 480.
It will add scanlines
It will blur the color channels to create that color bleeding effect
It will distort the shape of the image from a perfect rectangle into a rounder shape.

The question is, could you please provide any other attributes that are beneficial to emulating an arcade CRT feel and links and resources on coding these effects.

Thanks


texts: Unity: Opacity over Distance with Surface Shaders

texts:
I want to tweak the alpha value based on the distance to the camera. But I see no way of passing the vertex position on to the surface function using surface shaders. Not a problem with frag shader.
It's for fading out vegetation and creating LOD systems.
Shader "asdf" {
SubShader {
    CGPROGRAM
    #pragma surface surf StandardSpecular alphatest:_Cutoff addshadow vertex:vert

    struct v2f {
        float4 pos : TEXCOORD1;
    };

    struct Input {
        float2 uv_Maintex;
    };

    v2f vert (inout appdata_base v) {
        v2f o;
        o.pos = mul(unity_ObjectToWorld, v.vertex);
        return o;
    }

    void surf (Input IN, inout SurfaceOutputStandardSpecular o) {
        //Need vertex or pixel distance here:
        //float dist = length(v2f.pos.xyz - _WorldSpaceCameraPos.xyz);
        //o.Alpha = saturate(50/dist);
    }
    ENDCG
}
}


texts:
I want to understand how I can convert world position of an object into local position. Especially how to deal with a rotation of objects.
I'm testing transform.InverseTransform(...) methods. When parent and child has 0 rotation, this methods easily convert world into local position. I don't know how to deal with a situation, when one of the objects has not zero rotation.
In the example below my parent object has (0,0,10) position and (0,0,0) rotation. Child position (0,0,0) and rotation (90,0,0).
        Debug.Log (string.Format ("World position: {0}\nLocalPosition: {1}\nInverseTransformPoint: {2}\nInverseTransformVector: {3}\nInverseTransformDirection: {4}\nTransformPoint: {5}\nTransformVector: {6}\nTransformDirection: {7}",
        transform.position.ToString (),
        transform.localPosition.ToString (),
        transform.InverseTransformPoint (transform.position).ToString (),
        transform.InverseTransformVector (transform.position).ToString (),
        transform.InverseTransformDirection (transform.position).ToString (),
        transform.TransformPoint (transform.localPosition).ToString (),
        transform.TransformVector (transform.localPosition).ToString (),
        transform.TransformDirection (transform.localPosition).ToString ()));

The example debug result:
World position: (-1.0, -0.7, 10.0)
LocalPosition: (-1.0, -0.7, 0.0)
InverseTransformPoint: (0.0, 0.0, 0.0)
InverseTransformVector: (-1.0, 10.0, 0.7)
InverseTransformDirection: (-1.0, 10.0, 0.7)
TransformPoint: (-2.1, -0.7, 9.3)
TransformVector: (-1.0, 0.0, -0.7)
TransformDirection: (-1.0, 0.0, -0.7)

What should I add to transform.InverseTransformPoint (transform.position) to get transform.localPosition?


texts: Choosing between multiple shaders based on uniform variable

texts:
I want to choose from  2 fragment shaders based on the value of an uniform variable.
I want to know how to do that.

I have onSurfaceCreated function which does compile and link to create program1 and glGetAttribLocation of that program1

In my onDrawFrame I do glUseProgram(program1). This function runs for every frame.

My problem is that, in the function onDrawFrame(), I get value of my uniform variable. There I have to choose between program1 or program2.
But program1 is already compiled linked and all. How to do this?
How will I change my program accordingly and use that since it is already done in onSurfaceCreated.?


texts: How do I communicate that something is a tutorial button

texts:
I made an (ios) arcade game that is rather unconventional, and as a result many people wont exactly know what to do or what the controls are when they first open it. As a results I have had to add a rectangular "Tutorial" button on my main menu screen so that when I hand it to people, or other people hand it to people (etc) its all ok.  FYI: When the game first opens it does go to a tutorial, I just wanted it to be accessible for repeats if necessary

In the original build I designed all the buttons and had labels on them, however the artist inside of me says that doesn't look good, so I had a friend redesign them.

The new buttons are bi-colored and very minimalist (usually with the outline of a shape in them).  We came up with simbols that work for "return", "play", and "leaderboard" that work... however we can not come up with one for "tutorial".

What would be a clear symbol that could be put on a "tutorial" button?

Here is a picture of the screen. That grey shape is meerly a placeholder.  The button on the top right opens a "Credits" page.


texts:
I want to create a game that due to some assumptions doesn't make sense as a tablet game.

I already created some frame (controllers, autowiring, build scripts, etc.) that would help me later on, but since Slick2D, that I currently basing it on, is no longer really supported I am considering switching to libGDX while it still not time expensive.

My question is: is it possible to easily get rid of all of Android dependencies? GUI scaffold generator doesn't allow to do that and I would like to know is it just generator's issue or is the library itself tied to Android dependencies?

It's my main concern that would help me decide whether or not switch from Slick.

EDIT:

Basically when I use GUI generator to scaffold project it creates at least 3 Eclipse projects:

core project,
Android project - depending on core,
desktop project - depending on Android.

While it shouldn't a be problem to merge them into 1 bigger project and remove virtually dead code, I want to know if there would be left some Android dependencies that I couldn't remove to make it still runnable on desktop.


texts: Improving an O(N^2) function (all entities iterating over all other entities)

texts:
A little bit of background, I'm coding an evolution game with a friend in C++, using ENTT for the entity system. Creatures walk around in a 2D map, eat greens or other creatures, reproduce and their traits mutate.

Additionally, performance is fine (60fps no problem) when the game is run in real time, but I want to be able to speed it up significantly to not have to wait 4h to see any significant changes. So I want to get it as fast as possible.

I'm struggling to find an efficient method for creatures to find their food. Each creature is supposed to look for the best food that is close enough to them.

If it wants to eat, the creature pictured in the center is supposed to look around itself in a 149.64 radius (its view distance) and judge which food it should pursue, which is based on nutrition, distance, and type (meat or plant).

The function responsible for finding every creature their food is eating up around 70% of the run-time. Simplifying how its written currently, it goes something like this:

for (creature : all_creatures)
{
  for (food : all_entities_with_food_value)
  {
    // if the food is within the creatures view and it's
    // the best food found yet, it becomes the best food
  }
  // set the best food as the target for creature
  // make the creature chase it (change its state)
}

This function is run every tick for every creature looking for food, until the creature finds food and changes state. It's also run every time new food spawns for creatures already chasing a certain food, to make sure everyone goes after the best food available to them.

I'm open to ideas on how to make this process more efficient. I'd love to reduce the complexity from \$O(N^2)\$, but I don't know if that's even possible.

One way I already improve it is by sorting the all_entities_with_food_value group so that when a creature iterates over food too big for it to eat, it stops there. Any other improvements are more than welcome!

EDIT: Thank you all for the replies! I implemented various things from various answers:

I firstly and simply made it so the guilty function only runs once every five ticks, this made the game around 4x faster, while not visibly changing anything about game.

After that I stored in the food searching system an array with the food spawned in the same tick it runs as. This way I only need to compare the food the creature is chasing with the new foods that appeared.

Lastly, after research into space partitioning and considering BVH and quadtree, I went with the latter, as I feel like it's much simpler and better suited to my case. I implement it pretty quickly and it greatly improved performance, the food search barely takes any time at all!

Now rendering is what's slowing my down, but that's a problem for another day. Thank you all!


texts: LibGDX camera position shifted on movement

texts:
I'm programming a game with LibGDX and Box2D and I want my camera to follow my player. But as I zoom in (because Box2Ds metric system, using camera.zoom = x) the camera is shifted when the player moves (the camera follows the player):

Shifted View

Normal View

That only happens when the player moves, so there can't be a problem with the coordinates. My Question is how to remove this shifting as the player moves.

Here's some of my code:

Render Loop (excerpt):

@Override
public void render(float delta) {
    //set the camera position to player's position
    cam.position.set(player_body.getWorldCenter().x, player_body.getWorldCenter().y, 0);
    cam.update();

    world.step(Gdx.graphics.getDeltaTime(), 6, 2);
    world.clearForces();

    handleInput();

    Gdx.gl.glClearColor(.05f, .05f, .05f, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    batch.setProjectionMatrix(cam.combined);

    debugRenderer.render(world, cam.combined);

}

Make the player move:

if (Gdx.input.isKeyPressed(Keys.W)) {
    player_body.setLinearVelocity(transX, transY);
    player.setMoving(true);
}


texts: Need help making a semi-simple javascript game

texts:
I'm currently trying to make a fairly simple game in JavaScript and it isn't going too well.

Before I started, I thought I'd only need to know three things (on top of what I already know) which were:

How to 'spawn' an object (i.e. a bullet) by pressing an on-screen button.
How to make that bullet move across the screen.
How to make that bullet collide with something.

I thought the first two would be pretty simple, but I cannot find anything online to help me with them. Source code and tutorials appear to be either too simple or too complicated, and I'm starting to worry this project will be a lot more complicated than I thought.

So, can anyone help me do any of the listed things? If so it'd be much appreciated!


texts: XNA - Link between Create Rotations matrices

texts:
A friend of mine have been coding some rotations on my XNA project, but the order of the matrices rotation are not good. Some are of form :

Matrix.CreateRotationZ(1.21f) * Matrix.CreateRotationY(-0.13f)

and other:

Matrix.CreateRotationY(1.01f) * Matrix.CreateRotationX(-0.5f) * Matrix.CreateRotationZ(0.80f)

How can I find the values X, Y, Z so the rotations are in the correct order: (X,Y,Z) ?

Matrix.CreateRotationX(X) * Matrix.CreateRotationY(Y) * Matrix.CreateRotationZ(Z)


texts: What can be a game-play element in a game with Shakespeare's plays as the main theme?

texts:
I was thinking of learning about making games, so I thought of an idea about making a game on a play, since the content is already there. I actually found well parsed XMLs of Shakespeare's plays. I thought of a few rather simple game-play elements, but none seem fun. I thought of a 'word shooter' but it wouldn't be much fun since there are so many speech lines. Then I thought of a game where you have to match which of the characters currently on the screen said a particular dialog.

I know that this game probably will not be much fun, but I could try to make it fun.
What I may be able to do right now is make an application which 'enacts' the whole play. You can skip right to any act or a scene in an act etc.
It will be a 2d game and i will use pygame.


texts: Is it possible/recommended to make a universal game library interface in C

texts:
Lets say I want a game to be able to run with SDL, Allegro, on Game parks or Tiny Arcade and I don't want to recode everything everytime I port my game.

The C and C++ language separate definition in .h files and source in .c files. My teacher said it could be possible use the same .h declaration file but have different .c implementation files.

So in theory I could write something like this in the .h (the syntax is not perfect)

typedef myBitmapStruct;
void myBlittingFunction ( myBitmapStruct bmp, int x, int y );

Then I could have different .c for each game library. myBitmapStruct will refer to a BITMAP in the allegro implementation, or an sdl_surface in the SDL implementation, etc.

So in theory I think it could work, in practice it might lead to optimization issues. Since first it needs an additional method call because library functions are encapsulated. Second it might been additional code to make conversion or adjustments. For example allegro 5 use an on grid coordinate system, so 0.5 must be added to any x, y coordinates passed in parameter.

Do you think it could be recommended to do a such universal interface?

Did other people already attempted to do this before?


texts:
I'm developing top-down rpg game and got some problems using https://libgdx.badlogicgames.com/gdx-ai/docs/com/badlogic/gdx/ai/steer/behaviors/FollowPath.html

I have a path (picture 1), in this case 2 points - corner and target.

Pic.1
Then I try to make the character move (passing my path to libgdx FollowPath Steering Behavior).

private FollowPath<Vector2, LinePathParam> followp= new FollowPath<Vector2, LinePathParam>(this, new LinePath<Vector2>(astar.findPath(position, target)),0f,0f);

(astar.findPath(position, target) - function that returns Array of points(path).
Experimenting with 3rd and 4th parameters (passOffset and predictionTime) made it worse.)
And it gains such result (purple line on Picture 2).

Pic.2
But how can I get  such result (green line on Picture 3)?

Pic.3


texts: How to use caching to increase render performance?

texts:
First of all I am going to cover the basic design of my 2d tile-based engine written with SDL in C++, then I will point out what I am up to and where I need some hints.

Concept of my engine
My engine uses the concept of GameScreens which are stored on a stack in the main game class. The main methods of a screen are usually LoadContent, Render, Update and InitMultithreading. (I use the last one because I am using v8 as a JavaScript bridge to the engine.
The main game loop then renders the top screen on the stack (if there is one; otherwise, it exits the game) - actually it calls the render methods, but stores all items to be rendered in a list. After gathering all this information the methods like SDL_BlitSurface are called by my GameUIRenderer which draws the enqueued content and then draws some overlay. The code looks like this:
while(Game is running) {
    Handle input
    if(Screens on stack == 0) exit

    Update timer etc.
    Clear the screen

    Peek the screen on the stack and collect information on what to render

    Actually render the enqueue screen stuff and some overlay etc.

    Flip the screen
}

The GameUIRenderer uses as hinted a std::vector<std::shared_ptr<ImageToRender>> to hold all necessary information described by this class:
class ImageToRender {
private:
    SDL_Surface* image;
    int x, y, w, h, xOffset, yOffset;
};

This bunch of attributes is usually needed if I have a texture atlas with all tiles in one SDL_Surface and then the engine should crop one specific area and draw this to the screen.
The GameUIRenderer::Render() method then just iterates over all elements and renders them something like this:
std::for_each(
    this->m_vImageVector.begin(),
    this->m_vImageVector.end(),
    [this](std::shared_ptr<ImageToRender> pCurrentImage) {
        SDL_Rect rc = { pCurrentImage->x, pCurrentImage->y, 0, 0 };
        // For the sake of simplicity ignore offsets...
        SDL_Rect srcRect = { 0, 0, pCurrentImage->w, pCurrentImage->h };
        SDL_BlitSurface(pCurrentImage->pImage, &srcRect, g_pFramework->GetScreen(), &rc);
    }
);
this->m_vImageVector.clear();

Current ideas which need to be reviewed
The specified approach works really good and IMHO it is really has a good structure, however the performance could be definitely increased. I would like to know what do you suggest, how to implement efficient caching of surfaces etc so that there is no need to redraw the same scene over and over again?
The map itself would be almost static, only when the player moves, we would need to move the map. Furthermore animated entities would either require updates of the whole map or updates of only the specific areas the entities are currently moving in. My first approaches were to include a flag IsTainted which should be used by the GameUIRenderer to decide whether to redraw everything or use cached version (or to not render anything so that we do not have to Clear the screen and let the last frame persist). However this seems to be quite messy if I have to manually handle in my Render method of the screen class if something has changed or not.

Edit: Possible optimizations I was reminded of
I have been rendering every frame all tiles of the map one by one which became... yeah quite some heavy work to do for both CPU and GPU. Currently I am working on drawing all layers into one surface for each layer which holds all static tiles. In my current test it is much easier to draw n surfaces (where n is the number of layers) rather than about n*3600 small 16x16 tiles.
Though I am not thinking right now of culling this could be worth some thoughts. However I have to find out how to efficiently render entities, like items to interact with (signs, doors, ...) and NPCs which actually can walk on their own - but that is another problem and not really linked to this one.


texts: How can I chain together Stencil tests from the same re-occurring routine, but keep the tests separate?

texts:
Sorry for the bad title; I don't know how else to explain this.

I have a class called a Container. An instance of Container has other elements "inside" it. These elements have independent positions that are relative to the position of the container.

So if I move the container, the elements inside of it are moved along with it; but keep their distance relative to each other.

This Container is therefore like a window through which you can view it's contents.

So, I would like to use a Stencil buffer for this. I have the following code:

glEnable(GL_STENCIL_TEST);
glClear(GL_STENCIL_BUFFER_BIT);
glStencilMask(0xFF);    // everything is written to the buffer
glStencilFunc(GL_ALWAYS, 1, 0xFF);
glStencilOp(GL_KEEP,GL_KEEP,GL_REPLACE);
glColorMask(GL_TRUE,GL_FALSE,GL_FALSE,GL_FALSE);

glBindVertexArray(m_screenQuad->GetVAO());

glDrawElements(GL_TRIANGLES,m_screenQuad->GetMesh()->GetIndices()->size(),GL_UNSIGNED_INT,0);

glBindVertexArray(0);
glStencilFunc(GL_EQUAL, 1, 0xFF);
glStencilOp(GL_KEEP,GL_REPLACE,GL_REPLACE);
glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_TRUE);

// draw the things that are visible through this window. The window is defined by m_screenQuad

glDisable(GL_STENCIL_TEST);

This works great.

The problem I'm having arises when one of the things that are visible through the window, are also another window.

In the above example you can see that I didn't mask out the red channel, this was to reveal that when the bounds of an "interior" container went outside the edge of he exterior container, the whole stencil doesn't work as planned.

Here's some screen shots with the above code (again, note that the red it to show the different bounds being drawn by the m_screenQuad objects).

Here's another image where the object inside the first Container is a subsequent Container. Each calls the same code above, with the second one being called at the // draw the things that are visible through this window. The window is defined by m_screenQuad line.

As you can see, the bounding m_screenQuad being drawn in the same way by the internal Container overlaps with the external Containers m_screenQuad and effectively extends the Stencil Mask further than it should.

How do I separate these two different Stencil tests so that they don't affect each other? Consider that the internal Container may be smaller than the external one, so it would need to truncate/cut it's internal contents as well.


texts: raylib - isometric camera, rotating to four corners of isometric map in 3d

texts:
I am exploring raylib and am trying to create a 3d isometric map of cubes. Normally this is done by setting the camera to isometric with an angle x of 30 and angle y of 45 (sometimes it is angle x of -30 and angle y of 45).
I am not sure how to set the angle of the camera, I see there is an up vector, but its values seem to be limited to smaller values than 30 or 45. With this camera setup It appears to be isometric, though I'm not sure why.
Camera camera = {0};
camera.position = (Vector3){10.0f, 7.5f, 10.0f}; // Camera position
camera.target = (Vector3){0.0f, 0.0f, 0.0f};     // Camera looking at point
camera.up = (Vector3){0.0f, 1.0f, 0.0f};         // Camera up vector (rotation towards target)
camera.fovy = 10.0f;                             // Camera field-of-view Y
camera.type = CAMERA_ORTHOGRAPHIC;               // Camera mode type

This has the cube at position 0, 0, 0 at the top of the screen. This picture illustrates what I am seeing approximately:

If I change the position of the camera to:
camera.position = (Vector3){-10.0f, 7.5f, -10.0f}; // Camera position

Then I appromxiately see this:

Although it appears much higher on the screen. How do I go about rotating the camera from the first picture to the second picture? Also, how do I rotate the block at 0, 0, 0 to any other corner if the map has an even number of rows, columns?
I should add that simply tweening from 10, 7.5, 10 to -10, 7.5, -10 eventually does get to the second picture, but it inverts the map first (looks very strange), I want a circular rotation towards the second picture. The Orbital camera mode almost does what I want, but it seems move the map as well.


texts: what can be done to improve the ultimate insane real time strategy game AI?

texts:
I had this chat with a friend of mine about whether an AI can be created or not that could beat any human without resource cheating in a real time strategy game. An AI that would play almost perfectly. The AI of today's games have many areas that can be improved, most of them rely on resource cheating, a better early base developement because of that, and attacking in waves.

Still, the question is what would need to be done to improve on this to obtain the ultimate AI. Also, if you have any example of a game where a certain feature was used it would be great.

Edit: There is little clarification i can provide for those who haven't read the title or the few paragraphs describing the problem. This is about real time strategy games and the ultimate AI. That means Strarcraft, Warcraft, Generals, Red Alert, Age of Empires, AI War etc. Games that have more than one difficulty level, but the focus here is on the ultimate challenge.

tenpn has a fantastic post filled with great resources. Thank you, tenpn! I wish more people would contribute in that direction.


texts: How do I draw a texture to a MSTerrain object?

texts:
I'm using Farseer to make a game in XNA and I can't seem to figure this out.

I've decided to use MSTerrain for making my game's terrain because I wanted destructible terrain and MSTerrain seemed like the best bet. Unfortunately, I'm stumped on how to actually show the terrain. When I generate the terrain it's visible in debug view, but MSTerrain does not have a Draw method, so I'm wondering how it is supposed to be drawn to the screen? Is it worth pursuing?

I'm starting to think that MSTerrain is more trouble than it's worth, is there another better way to do this with bodies?


texts: Assign player currentLocation based on array coordinates

texts:
I wanted to incorporate changing location in an rpg, so I began by creating a class Location and assign every Location to a multi-dimensonal array, like so:

WorldMap[0, 0] = new Location("Majula");

I created two int variables named LocationY and LocationX set to the starting location. Now I got a command handler, when I type "Move South", I update the position with this dead simple code:

LocationY++;

Mind you, this is just for testing purposes, I just like to break a game into many small components that gets added as I get, or know better.

Now when I want to get my current location, I call it like this:

Console.WriteLine("He then headed south, until he arrived at {0}", WorldMap[PlayerLocationY, PlayerLocationX].Name);

That's cool and all, and it works, but I don't like typing too much if I can avoid it, so I wanted to change the call of WorldMap[PlayerLocationY, PlayerLocationX].Name to something more readable like currentLocation.Name.

So I tried this bit of code:

Location currentLocation = WorldMap[PlayerLocationY, PlayerLocationX];

Obviously, I get a NullReferenceException... I'm completely clueless, and I'm sure I'll probably say to myself "duh" when I'll get an answer.

And yeah, still learning, Console still rocks my socks!


texts:
I have some pretty decent general programming skills and elementary C/C++ skills. I am a complete noob in game/graphics programming and I would like to start.

I want to gradually learn, starting off by something like Pong, and gradually making more difficult stuff for learning. My ultimate goal is to make some COD:BO zombies clone (I love this game).

So what libraries/engines can you guys recommend, first to even start drawing stuff on the screen, and later more sophisticated stuff for getting a FPS going.


texts:
As a quick fun project, I tried writing a solitaire game. But when getting to writing up the rules systems, I felt dirty, because my code felt completely unstructured and inextensible, mainly because my game logic was complete spaghetti code.

I've run into this problem before, and always feel awkward when writing this part of my program, so I was wondering, are there any tried and tested best practices when it comes to defining rules in a game?


texts: Maya name clash with FBX motion capture file and FBX avatar on the 'root'

texts:
I'm attempting to re-target motion capture data from radical motion to an avatar I created with Character Creator. After creating a character definition for one, I import the other and it appears they are merging their 'roots'. Both their hierarchies contain a :root with no namespace. I tried modifying namespaces before importing but that isn't working either.
Any thoughts?


texts:
I'm making a 2D game in Unity. Basically there's just a rocket that goes where ever the user touches. With the code that i have right now, the rocket instantly rotates towards the point and moves there straight.

Vector3 dir = targetPos - transform.position;
float rotZ = Mathf.Atan2(dir.x, dir.y) * Mathf.Rad2Deg;
rb.MoveRotation(-rotZ);
thrust = 10.0f;
rigidbody2d.AddForceAtPosition(transform.up * Thrust, transform.up);

This code is placed in the Update function.

I want the rocket to start moving in which ever direction It's currently facing and slowly rotate towards the point as it goes there.


texts: How to render sprite array efficiently in j2me game?

texts:
I am working on a landscape java game.

I have a sprite array like this;

Sprite stickArray[] = new Sprite[10];

and initializing it like this with visibility as false.

for (int j = 0; j < stickArray.length; j++) {

        if (stickArray[j] != null) {

            stickArray[j].setPosition(stickX, stickY);
            stickArray[j].setVisible(false);
        }
    }

Later I want to position it like one after another vertically on repeating a key.pressBool is false initially.

public void keyRepeatInGame(int keyCode) {
    int gameKey = getGameAction(keyCode);
    Graphics g = getGraphics();
    if (gameKey == FIRE || keyCode == KEY_NUM5) {
        pressBool = true;
    }
}

Later I have written code like this;
Initially one Sticksprite is there.above this sprite, I want to place each sticks on clalling keyrepeat()in space key.

for (int i = 0; i < stickArray.length; i++) {
            if (pressBool) {
                if (i == 0) {
                    stickArray[i].setPosition(stickSprite.getX(),
                            stickSprite.getY() - stickSprite.getHeight());
                    stickArray[i].setVisible(true);
                } else {
                    stickArray[i].setPosition(stickArray[i-1].getX(),
                            stickArray[i-1].getY() - stickArray[i].getHeight());
                    stickArray[i].setVisible(true);
                }
            }
        }

This code is working partially.Stick is getting added on the sprite,all at once.

How can I change the code to make the sticks repeatedly getting added on calling keyrepeat() only, and make it visible one by one properly?


texts: What method is best to display respawn times?

texts:
I'm currently working on multiplayer game and am trying to work out how to display respawn times.   I had a few ideas in mind, taking inspiration from other games I've played before.

Text Based

Progress Bar

Visual Timer

Is there another way to display respawning for players that improves visual feedback? Meaning, is clear and effective at conveying exactly how long a player has to wait to respawn?


texts: Is there anyway I can make a plane visible from both sides?

texts: In Unity i have a model of a tree with leaves made of a plane and a texture, when I upload it to unity the texture is only visible on one side so how can I change it to be visible from both sides without increasing the polygons. And I am not familiar with complicated shader programming and stuff so could you please explain in detail. Thanks I'm advance.