texts: How can I calculate where my camera can be to avoid showing something outside a region?

texts:
I have a landscape model, which goes from the coordinate -45, -45 to 90, 90.

The edge of the model just cuts off and i would like to somehow stop the screen from ever passing these points. Basically sticking a boundary so that you can't see off the side. The game is always in top view, with the camera directly facing down.

However the problem is that the player can zoom in and out, obviously you have a wider range of view when zoomed out. (There is a limit to how far you can zoom out, you couldn't zoom out say, so that opposite sides of the map are seen at once).

I am assuming using something like Viewport.Project or Unproject, which changes screen coordinates to 3d space and the other way round, could somehow help me in the situation.

My initial idea may lag too much, which would be a while loop saying "While projection of screen point.X is less that -45, add 1 to the camera.X" etc.

Does anyone have any ideas for this? To sum it up, i need to find a way of stopping anything outside the area of -45, -45 to 90, 90 from being shown on the screen.

Thanks for any help!


texts:
I am new to data oriented design and I am currently developing a physics engine as a hobby project. I am really interested in data orinted design but I am not sure how to apply data oriented design to my physics engine. I am using Box2D as a reference and when I look at the source code, erin catto use linked list as a container for rigid bodies. The reason why he use linked list over array is stated here. This is what he stated at the forum

  I could use an array of body pointers. That would have worse cache
  performance. First you have to get the array element, then the element
  data. I would also need some extra logic to ensure the array is big
  enough.

  I'm not sure how I would use an array of bodies. If I resize the
  array, the pointers become invalid. I could return an index when you
  create a body, but then the array would have holes as bodies are
  freed. Traversing the body array would then involve extra logic to see
  if the body is allocated or destroyed. Also, it may be cumbersome for
  users to have to use an index rather than the object itself. If I
  return the current body pointer from the index, there will likely be
  many bugs where users hold onto that pointer and it becomes invalid.

  Finally, when islands are created the set of bodies is likely no to be
  contiguous in memory.

I will add that when the physics engine do a broadphase collision detection, It will return a list of collider pairs that will most likely located randomly at memory. From what I understand, you need something like handle so the data can be moved around in memory. With handle, you only need to move the last object to the slot that holds the deleted object. Using handle over pointer will add an extra level of indirection which results in more cache misses. So is it really beneficial to store a set of rigid bodies or their components as array?

Edit: I believe there are parts of physics engine that benefit from storing rigid body using array. For example the integration phase. But I am not sure if the benefits outweight the disadvantages.


texts: How long will it take to jump from point A to point B?

texts:
I need to know how long it takes to jump from one point to another. Because if the jump time takes for example 2.0f(float jumptime = 2.0f), a jump animation is played during a time interval of exactly 2.0f. The difficult thing is, I need to know the jump time before the jump was executed.

Is it possible to calculate that right before the jump is executed or is it impossible to calculate that?

I use the following formula to let an object(ball) jump from one platform to another platform:

impulse = Vector2(distance.x / time * mass + gravity.x / 2 * time * mass, distance.y / time * mass + gravity.y / 2 * time * mass);

Description of the jump

Update:

My calculations:

float gravity = 3, timetopeak, timetoground, totaljumptime, waytothetop, waytotheground;

timetopeak = jumpForce.Y / -gravity;
waytothetop = (float)(0*timetopeak + 0.5*-gravity*timetopeak*timetopeak);
waytotheground = Ball.Position.Y + waytothetop - (PlatformB.Position.Y - PlatformBHeight / 2.0f - BallHeight / 2.0f);
timetoground = (float)(Math.Sqrt(2 * waytotheground / -gravity));
totaljumptime = timetopeak + timetoground;
Ball.ApplyLinearImpulse(ref jumpForce);
//I divide the totaljumptime because the animation has 5 frames.
BallAnimation = new Animation(totaljumptime/5, 32, 32, Animation.Sequences.forwards, 0, 5, false, true);

Are my calculations correct? Because the totaljumptime is very small and my animation runs much too fast.


texts:
I am currenty studying game development and practicing making games.

I use a lot of OOP in my games. For example, each missile that is shot is an instance of a Missile object, and added to a list of Missile objects. Each tank in the game is a Tank object. Etc.

The entire design of the program is based on this. For instance, having a list of Missile objects allows me every frame to move the missiles, draw them, etc. And having an instance of a Tank object for every tank allows me to check for each tank if it collides with something, etc.

It's hard for me to imagine how a game (which is more complex than Pac-Man) could be programmed in a non-OO language. (With no disrespect to non-OO programmers of course). Not only in terms of how long it will take, but mostly in terms of how a game could be designed this way.

I can't imagine designing a game without using object oriented programming, because my entire understanding of how to design a game-program is based on OOP.

I would like ask: Today, are there any games that aren't programmed using OOP, in a similiar fashion to what I described above? Are there any 'professionl' games that don't use OOP as a major factor in the development process?

If so, could you give me an idea of how, for example, collision detection between a tank and N number of missiles could be implemented, without OOP?


texts: How can I place nice-looking tile-based cliffs automatically?

texts:
Legend of Zelda: A Link to the Past had some pretty nice cliffs. I'd like to create something similar, but am having trouble figuring out how to place them.

Image is from:
How did LoZ: A Link to the Past handle sub-tile collisions?

Anyways, I have a bunch of tiles like in the above image. How can I simplify how they are placed in the game world?
I currently have a 50x50 grid and a painter class in Java that tells the system where to place the tile:
Painter.fill(this, 15, 30, 13, 50, Terrain.EMPTY) would fill X-15 and Y-30 with a set of EMPTY tiles (basic ground tiles) 13x50 tiles wide.
I can also apply 'for' loops to paint the entire map with a type of tile, or tell it to only make a row X-tiles long, like this:

for (int i=0; i < LENGTH; i++) {
        if (map[i] == Terrain.EMPTY && map[i+50] == Terrain.WATER){
            map[i] = Terrain.CLIFF_S_BOTTOM;
            map[i-50] = Terrain.CLIFF_S_MID;
            map[i-100] = Terrain.CLIFF_S_TOP;
        }
    }

Is there a simpler way I could be telling my code to place lots tiles in a particular formation quickly?

EDIT: I just learned about the concept of bitmasking. I think this will solve most of my problems, but I'm still open to other ways of solving the problem.

Enums keep appearing as a possible alternative to the bitmask solution. Are they viable for this application?


texts:
I have not worked with ECS before, so I was following the tutorial by Unity's Mike Geig on Youtube to convert gameObjects to ECS from Unite Copenhagen, and this code does nothing, and there are no errors:

using Unity.Entities;
using Unity.Transforms;
using UnityEngine;

public class SpawnAsteroidECS : MonoBehaviour
{
    public GameObject AsteroidPrefab;

    EntityManager manager;
    Entity AsteroidEntityPrefab;

    void Start()
    {
        manager = World.Active.EntityManager;
        AsteroidEntityPrefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(AsteroidPrefab, World.Active);
    }

    void Update()
    {
        if (Input.GetKey(KeyCode.Mouse0))
        {
            for (int i = 0; i < 100; i++)
                SpawnTheAsteroids();
        }
    }

    private void SpawnTheAsteroids()
    {
        Entity asteroid = manager.Instantiate(AsteroidEntityPrefab);

        manager.SetComponentData(asteroid, new Translation { Value = transform.position });
        manager.SetComponentData(asteroid, new Rotation { Value = Quaternion.identity });
        print("Done");
    }
}

What am I not doing?

EDIT: The entity debugger does show that there are entities, but i dont actually see it in the game.


texts: opengl : Running at least 25 windows with different Draw callback

texts:
I need to run at least 25 windows concurrently with each window rendering a different game state.
I am storing all the 25 game states in the array of type GameState allGameStates[25].

For each of the window, i am currently doing this to register a different draw callback for each of the 25 windows.

 glutCreateWindow(title);
 glutDisplayFunc(allGameStates[i].Draw);

The issue here is that glutDisplayFunc requires a parameter of type function ptr, and i cannot pass in a member function ptr.(i am using GLUT which is in C)

It is not feasible to make the Draw function static as i require the Draw function to render differently accordingly to the other variables in the game state object.

How do i overcome this problem?


texts: Persistent Data for Multiplayer, Browser-Based Games

texts:
What is generally used to store persistent data in online games - browser games/facebook apps, in particular?

I have used MySQL in web development before - but I've read that it's not very scalable, especially if many transactions are happening constantly (which is what will happen inside of a game).

I'm writing the back end in Node.js using Heroku, so it would be really nice if there were a Node package to go with it.

Any insight would be much appreciated.


texts: What is a good balance between client and server actions?

texts:
I'm working on a voxel-based game right now which will have a lot of events, like clicking a block or object.

Say I want to open an interface when I click a certain block. Should I handle this on the client, or send a packet to the server with the action and it's details such as what the ID of the block is, its position et cetera, and then send a packet back to the client with the action OpenInterface with the interface ID?


texts: Should the interaction between the player and world objects be handled from the player class or as an event from the object classes?

texts:
Suppose you're making a 3D platformer like Super Mario, if you jump on a Goomba, does Mario (the class) know that it just landed on a Goomba and then tell that Goomba to die, or does the Goomba realize that he is being smashed and dies ?
I want to go with the first approach but it will end up with a huge If/then (or Switch/Case) script, also the reason why this is "problematic" is that many objects will make the player have a "reaction", for example if you land on a Goomba, you don't just kill it, but it forces you to jump, that jump event, what's the best way to handle it ?
Thanks


texts: Names for specific regions on earth for global RTS

texts:
I am developing a global real-time strategy game that uses Google Maps to represent the earth. I am cutting up the globe into 32 squares with each square exactly 45 degrees latitude and longitude. The squares are also aligned to the grid starting from 0,0.

I would like to give each square a nice name that meets the following criteria (in order of priority):

Every square name must be unique
Best representation of the land and water contained in the square. Any name is acceptable (country, continent, significant geology, significant body of water) but it must be the most prominent thing in that square
A combination of names is acceptable if there are 2 or more prominent / recognisable elements in the square
As short as possible so it can be easy to remember / type
Exacting precision is not important - this is a game, so the names should be major things in those squares that most lay people on earth would immediately recognise or at least be familiar with
If possible, the least offensive / non-contested / most globally accepted name of the main region in the square

I have come up with the following, but I would like to know if there is a system already out there that better meets my needs (note that I've accidentally swapped my lat/lngs - sorry!). Alternatively, if anyone has much more knowledge of geology/geography than I do, please suggest a better naming convention and names as some of the names are too long and many contain more country names than I'm happy with (I'd prefer neutral region names):

Here is a map of the world with the 45 degree grid squares shown to help you to visualise the problem:

Edit: Influenced by Phillip's answer, I have revised the approach using continents and oceans to be as neutral as possible:

The only grid squares I'm not 100% sure about are "Middle East" (is this still PC, or is there a better term - Arabia perhaps?), and the Antarctic territories (but since no-one lives there permanently and most countries seem to dispute Antarctic ownership anyway, I think I'm less concerned about this one). Please let me know if this approach is now as appropriate and neutral as possible.

Edit: Further updated based on Theraot's comments:

Notes:


texts:
I'm currently trying to develop a Voxel Engine using Direct3D 9 and C++.
To keep the memory usage low, i'm only passing the position, the orientation and the offset of the current voxels texture in the texture atlas of each vertex to the vertex shader.

The vertex shader then calculates the normal and passes it to the pixel shader. I found this article which covers, how to texture voxels with just their position and normal in glsl.

This is the part that calculates the texture coordinates in my pixel shader (SM3):

float2 tileUV = float2(dot(input.normal.zxy, input.pos3D),
    dot(input.normal.yzx, input.pos3D));
float2 texcoord = input.texOffset + tileSize * frac(tileUV);

This code works fine for faces that point in negative z-direction (normal [0,0,-1]), however, the back is flipped by 180° and the sides and top/bottom squares are flipped by 90°/270°.

I am not sure, if this is correctly translated from glsl, because this behaviour should be the expected one in hlsl, if I calculate it by hand. Is there anything that I have overseen or should I aim for a different approach?

Edit:

I have now managed to successfully texture the faces by replacing the previous calculation with the following:

if(input.normal.y != 0.0f) // handle top/bottom surfaces as front/back faces
{
    input.pos3D.y = input.pos3D.z;
    input.normal.z = -input.normal.y;
    input.normal.y = 0.0f;
}
texcoord.x = input.texOffset.x + tileSize * frac(float3(1.0f, 1.0f, 1.0f) +   cross(frac(input.pos3D), input.normal)).y;
texcoord.y = input.texOffset.y + tileSize * (1.0f - frac(input.pos3D.y));

Is there any way that I can simplify/optimize the equation? I may also mention that the voxels are all axis aligned and clamped to integer coordinates.

Edit2:

This is the modified formula of zogi's answer which works as expected.

float3 n = abs(normal.xyz);
float2 texcoord = float2(input.texOffset.x + tileSize * dot(n, frac(input.pos3D.zxx)),
    input.texOffset.y + tileSize + tileSize * dot(-n, frac(input.pos3D.yzy)));


texts: Given a point on a 2D grid of discrete points, and a normalized direction vector, how to I find the next point in that direction?

texts:
Say you have a point on a grid, lets call it P and your have a direction vector called V, how do i find the closest point from P in V's direction ?

Example:

1|2|3
4|P|5
6|7|8

V = (0.5 , 0.5)

In this basic example the next point is 3.
How do I make a general algoritm for more complex cases, say V = ( 0.44, -0.56) ?

EDIT:  Just to clarify something in my question. The next point has to be a neighbor to point P.


texts: Get algorithm (Chance-to-Hit) from Input and Output

texts:
I am currently working on a chance-to-hit formula for an rpg. It consists of the following parts:

AttackSkill: The used Attribute of the Attacker (Range: 1-10)
AttackBonus: A Modifier from Skillbonuses (Range 0.5 - 3)
DefenseSkill: The used Attribute of the Defender (Range: 1-10)
DefenseFitness: How suitable is this defense against the attack? (Range: 0.1 - 5)
DefenseBonus: A Modifier from Skillbonuses (Range 0.5 - 3)

This is the Input. I am looking for a way to map this to the following Output:

Difficulty: How hard it is for the Attacker to hit (Range 0-10 float, later round to int)

What could I do to get the algorithm out of the value pairs? If possible, the output should be biased in direction of Difficulty 6 (like a normal distribution).


texts: A question regarding how to respond to 'events'

texts:
What is the best practice to use when events happen in a game? For example:

You have a sensor. When a particular game actor is near that sensor, a sound must be played and a door must be closed.
When a collision between characters A with animation i and character B with animation j happens, a special graphical effect, a sound effect and a decrease of life points of A and B should come into effect. Furthermore, A and B must be forced to return to some specific animation.
The user presses the left-key, so actor A must be moved.

What I would like to know is: do you play sound, move the player, close the door (calling the relevant methods, like PlaySound(..), CloseDoor() or MovePlayerLeft()) directly in the event handler or do you use some sort of message based system, so that when the actor manager code is called, it sees that the player must be moved to the left and moves it to the left. Also, when the sound manager code is called, it sees that a particular sound must be played and plays it and so on...

Ps.
I would really be happy to see some reference to books/papers/articles to read something related.


texts: Swapping a mesh from MCS female to a custom mesh

texts:
I'm trying to swap a mesh from the MCS female CBJacket with a custom mesh that's supposed to be a lab coat. But it keeps turning in to a ball of spiky mesh! I made sure the avatar and armature for the custom fbx was the same as the official one but i'm not getting any where with this problem.

any help (as always) is greatly appreciated


texts:
I am working on a simple tile-based multiplayer game. I am rather experienced programmer, but not so experienced game developer.

The players will see each other depending if there is a blocking object between them or not. The objects can be moved around, so the map is not static.

If A moves (or performs other action) and B sees that (LOS is not blocked) then B client will be notified and will update it's view. If B does not see A, then B will not be notified.

Question:

Should I notify client A about B's movement regardless of LOS, perform all the LOS checking on the client-side and update the view accordingly, or...
should I do all the LOS server-side and notify client A only in case of visible movement?

I know than, in principle, I should not trust client-side and not send anything to the client that is not necessary (client code can be hacked and show movement out of LOS). But, if there is a significant number of players at once, then I am afraid than the server will not cope with tracking all LOS for all the events and all the players.

How to cope with this problem? Is there some "standard" solution here?
I know that it might be a premature optimization (I don't have this problem yet), but protocol and map data structure will depend on that.

P.S.

The client and the server will be open source, so hacking the client will be easy


texts: Get MonoBehaviour components from Prefab

texts:
I need to assign the script values for the following Prefab in Unity 3.5

The structure is the following

Kinect_Prefab

 -MonoBehaviour

    ·Script: Missing Mono Script

 -MonoBehaviour

    ·Script: Missing Mono Script

 -MonoBehaviour

    ·Script: Missing Mono Script

 -MonoBehaviour

    ·Script: Missing Mono Script

All the components have the same name.

I have tried to obtain all of them in an array, but the GetComponents method does not seem to work properly.

var mono : MonoBehaviour[];
mono = Kinect_Prefab.GetComponents(MonoBehaviour);

The thing is the resulting array is empty.

Any idea what might be wrong?

EDIT: When I do GetComponents(MonoBehaviour) I get the following error

InvalidCastException: Cannot cast from source type to destination type.

I have tried receiving the components in var mono : Component [] but I still don't receive anything


texts: How do you come up with ideas for new games?

texts: What is the best way in your opinion to find new ideas for games? I want to invent something really new (like Gish, World of Goo, Crayon Physics etc), but I'm having problems coming up with new, creative ideas.


texts: How to determine the maximum supported level of anisotropic filtering for a graphics card

texts: In software, at runtime, (C++ if it matters), is there a way to find out the maximum level of anisotropic filtering supported by the graphics card?


texts: Unity3d - Transform rotation(angle) help

texts:
Im trying to rotate an object 90 degrees to the left but instead of rotating straight left it rotates 270 degrees to the right.

Here's the part of the code which controls the rotation:

rotationDestination = new Vector3(60, 270, 0);
if (Vector3.Distance(transform.eulerAngles, rotationDestination) > 0.2f) {
  transform.eulerAngles = Vector3.Lerp(transform.rotation.eulerAngles,
                                       rotationDestination,
                                       rotationSpeed * Time.deltaTime);
}

If I try to make the Y axis -90 a.k.a (60, -90, 0) then it rotates constantly to the left.

How do I make it rotate straight to the left (90 degrees) ?

Thank you.


texts: Bullet physics: how to make a soft body "static" (kind of)?

texts:
I'm fairly new to Bullet and started using it a week ago. I mainly played with rigid bodies and everything works as expected but now that I also need to add soft bodies into my simulation, things got a bit complicated.

What I want: I have to create a simple but unrealistic scene: the main object is a deformable ball levitating at the center of the world, it does not rest on anything and only "floats" there. Then, I should be able to throw various rigid bodies towards the ball so that it deforms BUT DOES NOT MOVE.

What I tried: My issue is that I don't know how to make my main soft body float in the center of the scene. I tried setting the mass of each of its node to zero but then it does not deform anymore, obviously. I also changed its total mass and it gives the same result (I'm not sure if it's the same as setting all masses to 0). I also tried to give it the STATIC flag but that doesn't change anything.

What I could try (but seems overcomplicated): A possibility would be to hang the ball to a fixed position with a point-to-point constraint but I'm afraid that it will deform the ball and could create an unwanted swinging motion. Another idea I had is to enclose the ball into an invisible box made of planes that would keep it in the air but that would not react with other bodies (notably the rigid ones that I will throw) but I'm afraid that this solution would be cumbersome to implement and that the faces of the box would be discernible when the ball is pressed against it.

In summary: I need to have a spherical soft body that keep the same center. It I throw something towards it, I should see its surface riple but it should not move "globally". Is there any way to cleanly do that?

Thank you for your help!

(I asked the same question on the Bullet forum but had no answers)


texts: How to detect a sign-out from Google Play achievements or leader-boards UI?

texts: I am making an android game in Unity (C#), in which I've used the Google's official plugin for Google Play Services. My question is how to detect that a player has clicked on sign out button on Google's UI


texts: Fixing rootmotion by calculating a lerp force

texts:
I have a json full of rotation and forward + right force for rootmotion. The problem is the end position in the animations don't end on a straight line. You can see where I end up and what my desired position is. The problem is I can only add or subtract from the forward and right movement force. And the rotation of the character changes each frame. So I have to find a way to calculated a forward&right force for current rotation to slowly lerp to the desired position while using the rootmotion data.
I am working on unity


texts:
I want to make my text slide like so:

This is from the game "Crossy Road". The movement is normally smoother that in the .GIF

Here are some more frames from the GIF to make you understand what I mean:

I'm sorry for the bad formatting, I need at least 10 reputation to post more than 2 links.

The text and the orange background seem to "expand" while moving smoothly to the right.


texts: Why do I keep getting an exception about "an element with the same key already exists" in this code?

texts:
I'm trying to follow this tutorial about object pooling in Unity

I got to minute 17:22. But when I run the game I get this exception:

ArgumentException: An element with the same key already exists in the dictionary.

System.Collections.Generic.Dictionary`2[System.String,System.Collections.Generic.Queue`1[UnityEngine.GameObject]].Add (System.String key, System.Collections.Generic.Queue`1 value) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/Dictionary.cs:404)
ObjectPooler.Start () (at Assets/Scripts/ObjectPooler.cs:31)

This script is attached to a new empty GameObject:

using System.Collections.Generic;
using UnityEngine;

public class ObjectPooler : MonoBehaviour
{
    [System.Serializable]
    public class Pool
    {
        public string tag;
        public GameObject prefab;
        public int size;
    }

    public List<Pool> pools;
    public Dictionary<string, Queue<GameObject>> poolDictionary;

    private void Start()
    {
        poolDictionary = new Dictionary<string, Queue<GameObject>>();

        foreach(Pool pool in pools)
        {
            Queue<GameObject> objectPool = new Queue<GameObject>();

            for (int i = 0; i < pool.size; i++)
            {
                GameObject obj = Instantiate(pool.prefab);
                obj.SetActive(false);
                objectPool.Enqueue(obj);

                poolDictionary.Add(pool.tag, objectPool);
            }
        }
    }
}

Like in the tutorial I'm making size of 1 of the Pools in the Inspector then giving as tag name: Cube then drag a cube prefab to the Prefab then set the size to 150.

But I'm getting this exception when running the game.


texts: Mono Develop unable to load plugins or editor

texts:
When I load up MonoDevelop, it gives me an error, saying how it could not load the C# editor and plugins for my project. I have had this problem for as long as I can remember, and I can still use MonoDevelop to create scripts.
However, MonoDevelop no longer acts like an IDE, more like Notepad+. The lack of plugins causes MonoDevelop to lose even the most basic form of line suggestion. How do I fix this error, and restore the IDE capabilities of MonoDevelop?

Could not load project 'Welp.CSharp.Plugins.csproj' with unknown item type '{E097FAD1-6243-4DAD-9C02-E9B9EFC3FFC1}'
Could not load project 'Welp.CSharp.csproj' with unknown item type '{E097FAD1-6243-4DAD-9C02-E9B9EFC3FFC1}'
Could not load project 'Welp.CSharp.Editor.csproj' with unknown item type '{E097FAD1-6243-4DAD-9C02-E9B9EFC3FFC1}'


texts: I am developing a game, a word game. I have UIView, in this I have to show the keyboard, without using UITextField. Could you please suggest me something on how to do this?


texts: GLSL Fragment Shader compiles fine on certain computers

texts:
I got this piece of code in a fragment shader:

if (color.a < 0.01f)
    discard;

It runs fine on an older graphic card but can't even compile on my newer (maybe not new, but..) GTX 770. I got the most recent drivers and everything. The versions is correct. OpenGL 4.4. The shader compiles like normal if I remove the discard statement.

I've been searching around and I'm finding nothing about this. Does the discard just not work on certain graphic cards or what?


texts: RigidBody.MoveRotation Resetting to (0,0,0);

texts:
I'm trying to rotate a character on along the y axis but rather than continuing to rotate, it rotates then the y rotation goes back to 0. I'm not sure what I'm doing wrong. The same thing happens if I change the rotation in the inspector. The line that's causing this is the second one in the Look Function.

public void Look()
{
    Quaternion Rotation = transform.rotation;
    Rotation = Quaternion.Euler(transform.rotation.x , transform.rotation.y + Input.GetAxis("Mouse X"), transform.rotation.z);
    rb.rotation = (Rotation);
}


texts:
I'm looking for a good 2d engine or library (that supports physics) for Android. I have a restriction - language should be C#.
It's not a requirement to use Mono Droid, but it seems that it is an only way.

What can you suggest?


texts: Is it possible to skin Qt 4.5 such that it has a 'game-like' interface?

texts: Is it possible to skin Qt 4.5 such that it looks less like an application framework but more of a game? I guess this probably means replacing the canvas, the title-bar and the artwork of the various widgets. Will such an approach be platform independent too?


texts: Enemies Bullet Shooting At Player Problem How To Fix?

texts:
I am trying to make my enemies shoot  at my player rect where ever the position the player is and when it collides with the rect it should remove the -1 health ***my problem is that when the enemy shoots its bullet dont attack the player it just hoover over its head

        for shootss in shootsright:
            if shootss.x < 1000 and shootss.x > 0:
                if shootss.x < playerman.rect.x:
                    shootss.x += 7
                else:
                    shootss.x -= 7
            else:
                shootsright.pop(shootsright.index(shootss))
        if len(shootsright) < 2:
            shootsright.append(Bools(round(enemyshoots1.x+enemyshoots1.width-107),round(enemyshoots1.y + enemyshoots1.height-50),(0,0,0)))

this part its suppose to remove -1 of the player health when the enemy bullets collides with it

     for shootss in shootsright:
            if playerman.rect.colliderect(shootss.hitbox):
                playerman.health -=1
                shootsright.pop(shootsright.index(shootss))

and this is my enemy class

shotsright = pygame.image.load("shooting2.png")
shotsleft = pygame.image.load("shooting1.png")
class enemyshoot:
    def __init__(self,x,y,height,width,color):
        self.x = x
        self.y =y
        self.height = height
        self.width = width
        self.color = color
        self.shootsright = pygame.image.load("shooting2.png")
        self.shotsleft = pygame.image.load("shooting1.png")
        self.shootsright = pygame.transform.scale(self.shootsright,(self.shootsright.get_width()//3,self.shootsright.get_height()//3))
        self.shotsleft = pygame.transform.scale(self.shotsleft,(self.shotsleft.get_width()//3,self.shotsleft.get_height()//3))

        self.rect = pygame.Rect(x,y,height,width)
        self.health = 10
        self.hitbox = (self.x + -20, self.y + 30, 31, 57)
    def draw(self):
        self.rect.topleft = (self.x,self.y)
        window.blit(self.shootsright,self.rect)
        self.hits = (self.x + 20, self.y, 28,60)
        pygame.draw.rect(window, (255,0,0), (self.hitbox[0], self.hitbox[1] - 60, 50, 10)) # NEW
        pygame.draw.rect(window, (0,255,0), (self.hitbox[0], self.hitbox[1] - 60, 50 - (5 * (10 - self.health)), 10))
        self.hitbox = (self.x + 60, self.y + 80, 81, 87)

black = (0,0,0)
enemyshoots1 = enemyshoot(1100,240,100,100,black)
enemyshooting = [enemyshoots1]

my bullet class

# enemys bullets
ksud = pygame.image.load("heart.png")
class Bools(object):
   def __init__(self, x, y,color):
       self.x = x
       self.y = y
       self.ksud = pygame.image.load("heart.png")
       self.hitbox  = self.ksud.get_rect()
       self.rect  = self.ksud.get_rect()
       self.rect.topleft = (self.x,self.y)
       self.speed = 10
       self.color = color
       self.hitbox = (self.x + 57, self.y + 33, 29, 52) # NEW
   def draw(self, window):
        self.rect.topleft = (self.x,self.y)
        player_rect = self.ksud.get_rect(center = self.rect.center)
        player_rect.centerx += 0 # 10 is just an example
        player_rect.centery += 0 # 15 is just an example
        window.blit(self.ksud, player_rect)
        self.hitbox = (self.x + 97, self.y + 33, 10, 10) # NEW
        window.blit(self.ksud,self.rect)

```


texts: Advices on Linking Between Entity Component System in C++

texts:
After reading a few documentation about entity-component system, i decided to implement mine. So far, I have a World class which contains the entities and the system manager(systems), Entity class which contains the components as a std::map, and a few systems. I am holding entities as a std::vector in World. No problem so far. What confuses me is the iteration of entities, i can't have a crystal clear mind on that, so i still can't implement that part. Should every system hold a local list of entities which they are interested in ? Or should I just iterate through the entities in the World class and create a nested loop to iterate through systems and check if the entity has the components the system is interested in ? I mean :

for (entity x : listofentities) {
   for (system y : listofsystems) {
       if ((x.componentBitmask & y.bitmask) == y.bitmask)
             y.update(x, deltatime)
       }
 }

but I think a bitmask system will kinda block flexibility in case of embedding a scripting language. Or having local lists for each system will increase memory usage for classes. I am terribly confused.


texts:
I am using this code in Update method in XNA RenderControl in Windows Forms:

...
Mouse.WindowHandle = renderControl1.Handle;
MouseState stat=Mouse.GetState();
...

Everything works fine but when I want to record it with Fraps I get this result: http://www.youtube.com/watch?v=oDmzAIx_wU0 mouse position is moved but in screen everything is OK. When first line is removed I have moved cursor on screen but not in video. Is posible to have same result in both cases?


texts: How can I connect 2D skeletal animation to the physics engine?

texts:
I'd like to use skeletal animations in my 2D game, and since I already use Box2D as the physics engine, I'd like to enable (but not enforce) ragdoll animations as well. I need some help in figuring out how the Animation and Physics entity components relate to each other.

How should data be represented on disk? Should the actual model/ skeleton be different from the animation? Here's what I currently have in mind: each texture has a corresponding Box2D body (forearm.jpg and forearm.body, for example). I also have a separate hero.model file that references the *.body files, and several *.anim files that reference the model and the textures.

The reason I don't think I should reference the textures in the model directly, but reference them in the animation, is so I can have the character blink (for example): its head would be one body, but different sprites can be pasted over it at different keyframes as to make it blink.

Should I actually move the limbs while animating? While the character is still alive (and ragdoll should be off), what should I do with the physical limbs? When I animate, should I just render the sprites with the correct transform, or should I actually move the physical limbs to their current position according to the animation? If yes, how can I get over the fact that Box2D doesn't handle moving bodies directly too well?

How to enable more complex communication? Architecturally speaking, how should I implement communication between the Animation and Physics components so that interaction is kept to a minimum, but to also be able to do create more complex entities, like for example a wheel on a robot being rendered with the rotation of the physical wheel, while the rest of the robot is rendered according to the animation's keyframes.


texts:
I downloaded a 3d model of a car. By judging by the skins and images available model treats wheels and car body as separate nodes. I want to access its child nodes (wheels) to specify animation.

But I don't know the names of its child nodes. Is it possible to figure out names of its child nodes by looking at the file content. I have a obj file of the 3D model.
I am using JMonkey 2.

EDIT
here is the link thefree3dmodels.

Thank you in advance


texts: Resolving a collision between point and moving line

texts:
I am designing a 2d physics engine that uses Verlet integration for moving points (velocities mentioned below can be derived), constraints to represent moving line segments, and continuous collision detection to resolve collisions between moving points and static lines, and collisions between moving/static points and moving lines.

I already know how to calculate the Time of Impact for both types of collision events, and how to resolve moving point static line collisions. However, I can't figure out how to resolve moving/static point moving line collisions.

Here are the initial conditions in a point and moving line collision event. We have a line segment joined by two points, A and B. At this instant, point P is touching/colliding with line AB. These points have unit mass and some might have an initial velocity, unless point P is static. The line is massless and has no explicit rotational component, since points A and B could freely move around, extending or contracting the line as a result (which will be fixed later by the constraint solver). Collision is inelastic.

What are the final velocities of the points after collision?


texts:
I'm taking a texture from a shared texture handle and rendering it on the screen. I do this by creating a simple mesh that covers screen space, and then sampling the texture like so

float4 main(PixelInput pixelInput) : SV_TARGET
{
    return sourceTexture.Sample(textureSamplerState, pixelInput.uv);
}

However, the texture on the screen appears significantly darker than the source texture. I suspect this is because the type of the texture from which I am sampling is DXGI_FORMAT_R8G8B8A8_UNORM_SRGB but my back buffer is DXGI_FORMAT_B8G8R8A8_UNORM. For technical reasons, I am unable to change the format of either.

I tried the following conversion to linear color space

    float4 sRGBA = sourceTexture.Sample(textureSamplerState, pixelInput.uv);
    float3 sRGB = float3(sRGBA.x, sRGBA.y, sRGBA.z);
    float3 RGB = sRGB * (sRGB * (sRGB * 0.305306011 + 0.682171111) + 0.012522878);
    return float4(RGB, sRGBA.w);

But this seemed to make no difference at all (which I found surprising in and of itself).

There are no other shader effects or interesting pieces being applied.

What here might cause the effect of the darker rendering?

Thanks in advanced, let me know if there is any additional interesting information!


texts:
I've two objects A and B. A impact B causing B movement.

I want programmatically "amplify" B movement mantaining B resulting direction.

I've try adding a script like this

void OnCollisionEnter(Collision col) {
    // Controllo se è un tag
    if (_forceAlreadyApplied==false) {

        _rb.AddForce (_forcePower * transform.forward, ForceType);
        _forceAlreadyApplied = true;

    }
}

The problem is that transform.forward obviously change B direction.

Maybe this is a wrong approach.

My question is: how to "amplify" current speed ?

Thanks


texts: Should I post a playable demo on Kickstarter?

texts:
I am asking this question way in advance of my progress, but I am still curious and would like if to know in case I ever make it this far. So I'll phrase this hypothetically in the future.

The game I am making has a fully functional demo. It has programmer art and only one level. All of the "extra" features are missing. It is bug free and the core mechanics are fully implemented, but there are very few enemy types, and planned features like a leveling system are missing.

For game designers, it is relatively clear what the game will be, as the mechanics are clearly seen and understood. But I don't know how it will be perceived by non-game designers.

When I look at other kick starters, I have seen video game kickstarters that range from only text, to videos of developers talking about the game, to videos of actual gameplay. But I have not seen a single link to a playable demo.

Would it help or hurt to link to the playable demo that would show where the game is headed? Would the potential funders look at the unpolishedness of it and write it off, or would they take it for what it is: a concept?


texts: What harm would be done if a user were able to play the client side of a multiplayer game without logging in?

texts:
I am currently developing a multiplayer game for a university project. The purpose of the assignment is to learn about the use of a cluster architecture, but I have a question concerning security.

The multiplayer role-playing game that I'm developing for class utilizes a client-server architecture. The client holds all of the game assets and a 2D game engine. The server provides authentication to log into a user account, provides access to characters and their progression, etc. The server also provides the positions of non-player characters and other players on the same server, and also provides their actions and movements.

My question is whether a tech savvy user that modified the source code of the client could "play the game" without authenticating, forcing a kind of single player version of my game? I am imagining a user sending the client his/her own custom information about where to spawn enemies and whatnot. Maybe he/she would simply want to move around the game world freely.

1) Does this scenario seem possible?

2) Most importantly, what harm could this cause to a multiplayer game? Perhaps I have content that I don't want someone to be able to access without properly purchasing the game, or if they have been banned for some reason.

3) If this is a problem I should try to mitigate, how could I go about preventing this kind of thing from happening?


texts: How do I make an area in the screen clickable with XNA?

texts:
I am programming a penalty shoout game, my question is how make an area in the screen clickable with XNA? I know that for seeing the mouse I have to use:

this.IsMouseVisible = true;

But I want this for the direction of the soccer ball? Any ideas?

I want something like this or this but I don't find anything about this in XNA.


texts: What are valid ranges of space dimensions used in OpenGL?

texts:
I want to know what the valid ranges of all the spaces in OpenGL are.

Specifically:
Maximum and Minimum Clip space X, Y, and Z (gl_Position)
Maximum and Minimum gl_FragCoord X, Y, and Z
Maximum and Minimum gl_FragDepth value


texts: How should I move 2D objects in OpenGL ES 2?

texts:
I am a bit confused about what I need to move a basic square. Should I use a translation matrix or just change the object vertices? Which one is better?

I use a simple vertex shader, gl_Position = myPMVMatrix * a_vertex, along with a VBO.


texts: Creating object in front of player, with some distance

texts:
I want to create objects in front of player with some distance, so that prevents hit with player immediately. So first, I get the global player position and direction vector which player towards:

var player_position = player.transform.origin
var player_forward_vector = player.global_transform.basis.z

And then give additional distance:

var spawn_position = player_position
spawn_position.z -= player_forward_vector.z + 100

And then set the position:

var asteroid_instance = asteroid_scene.instance()
asteroid_instance.transform.origin = spawn_position

When I run the game, first it seems work, however when I rotated the player, still object spawned same position, not in front of where I'm looking at.

Here's the video to demonstrate:
https://youtu.be/zvMU9ad33SA

Why object doesn't created in front of player, instead keep spawns in same location? Any advice will very appreciate it.

Here's the full code of spawning object. Note that asteroid is just Rigidbody object with collision shape as child.

# AsteroidSpawner.gd
extends Node

onready var player: Player = get_tree().get_root().find_node("Player", true, false)
var asteroid_scene: PackedScene = preload("res://Asteroid/Asteroid.tscn")

func _ready():
    spawn_asteroids()

func spawn_asteroids():
    while true:
        spawn_asteroid()
        yield(get_tree().create_timer(2), "timeout")

func spawn_asteroid():
    var spawn_position: Vector3 = get_spawn_position()

    var asteroid_instance = asteroid_scene.instance()
    asteroid_instance.global_transform.origin = spawn_position

    # Push towards player
    var direction_to_player: Vector3 = player.transform.origin - spawn_position
    var speed = min(rand_range(5, 10), 10)
    asteroid_instance.add_force(direction_to_player * speed, Vector3())

    add_child(asteroid_instance)

func get_spawn_position() -> Vector3:
    var player_position = player.global_transform.origin
    var player_forward_vector = player.global_transform.basis.z
    var spawn_position = player_position
    spawn_position.z -= player_forward_vector.z + 100

    return spawn_position


texts: Moving IK target with Unity's New Input System

texts: I'm currently converting our 2D game from the old input system to the new input system in the hopes of making it available to more people in the future. Currently I am using the mouse position to aim a flashlight by moving the IK target of that arm to the mouse position by getting the vector of the mouse cursor and converting it using screentoworldpoint. My question is, how can I implement a similar function using the new input system with a joystick? Currently I am getting a vector2 from the joystick which ranges from (-1,-1) to (1,1) depending on the position and angle of the joystick. I would like to have the same code for both inputs so I don't have to use an if else statement and determine what input is being used but if that is unavoidable I understand. I would just like to know the best way to go about aiming an IK target using a joystick with the new input system.


texts:
I'm working on the event system for my engine, and have some trouble deciding what types of parameters my events should have to be both generic and specific at the same time. I want to be able to notify entities in the world about anything that is happening using something similar to the observer pattern, but merely the notification message itself is not enough, some messages need to carry additional information such as location, radius, damage, and so on. How do I encapsulate all these different kinds of parameters in one event type without making it very bloated like it would be if every event held a field for every type of parameter?

Some examples to show what I would like to achieve and what I have considered so far:

struct Event {
    TYPE     type;
    int      x, y, z;
    unsigned radius;
    float    damage;
    unsigned cost;
    float    healing;
    ...
void Observer::notify(Event event) {
    if (event.type == explosion)
        handle_explotion(event.x, event.y, event.z, event.damage);
    else if (event.type == healing)
        add_hitpoints(event.healing);
    ...

That would make the Event type very bloated, and the handling gets tedious quickly. I considered having fewer parameters, but they would remain unspecified:

struct Event {
    int arg1, arg2, arg3, arg4;
    const char * str1, str2, str3;
    bool b1, b2, b3;
    ...

This would cut down on the amount of parameters because all types are condensed into the same few fields. However from a user point of view this approach is much worse because now I have to remember what each parameter was supposed to represent every time; was arg3 the radius or the damage in an explosion? To fix this maybe the parameters could live in a std::map, but that still makes handling obnoxious:

struct Event {
    std::map<const std::string, int> int_data;
    std::map<const std::string, float> float_data;
    ...
void Observer::notify(Event event) {
    if (event.type == collision)
        resolve_collision(event.int_data["x"], event.int_data["y"],
                          event.int_data["z"], event.int_data["width"],
                          event.int_data["height"]
    ...

I considered making the event hold some kind of general data field that can be cast to the appropriate type:

struct Event {
    void * data;
    TYPE type
};
void Observer::notify(Event event) {
    if (event.type == weapon_augment)
        modify_weapon((Weapon *)(event.data));

This makes instantiating and deleting the event somewhat more tedious, but at least it allows me to use specific types for every event handler.

What is the conventional approach to solving this problem? Even better, what is your own ingenious solution? Thanks.


texts: Attempt to fix sprite sheet pixel bleeding in OpenGL 2D causing sprite distortion

texts:
While working on a project, I encountered the common problem of pixel bleeding when trying to draw subregions of my sprite sheet. This caused sort of "seams" to appear at the edges of my sprites. You can see the issue here, on the right and top of the sprite .
Doing some searching, I found others with a similar problem, and a suggested solution (here, and here for example) was to offset my texture coordinates by a bit, such as 0.5. I tried this, and it seemed to work. But I have noticed that sometimes, depending on where the sprite or camera is, I get a bit of distortion on the sprites. Here, the left side appears to be cut off, and here, the bottom seems to have expanded. (I should note, the distortion happens on all sides, I just happened to take screenshots of it happening on the bottom and left.) It may be a little difficult to see in screenshots, but it is definitely noticeable in motion. For reference, here is the part of the sprite sheet that is being displayed here
Does anybody have any idea what is going on here? I didn't actually notice this issue until recently. I originally set out to resolve the pixel bleeding when I saw it occurring between my tile sprites. This new issue does not occur with them using my current half-pixel offset solution (or if it does, it's not noticeable).
Code:
Texture parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

Texture coordinate calculation
std::vector<glm::vec4> Texture2D::GetUVs(int w, int h)
{
std::vector<glm::vec4> uvs;
int rows = Width/ w;
int columns = Height / h;

for(int c = 0; c < columns; c ++)
{
    for(int i = 0; i < rows; i ++)
    {
        float offset = 0.5;
        uvs.emplace_back(glm::vec4(float(((i) * w + offset))/Width,
                              float(((1 + i) * w - offset))/Width,
                              float(((c) * h + offset))/Height,
                              float(((1 + c) * h - offset))/Height));
    }
}
return uvs;

Where Width and Height are the dimensions of the sprite sheet, and w and h are the dimensions of the subregion, in this case 32 and 32.
How I pass the uvs to the shader
GLfloat verticies[] =
{
    uv.x, uv.w,
    uv.y, uv.z,
    uv.x, uv.z,

    uv.x, uv.w,
    uv.y, uv.w,
    uv.y, uv.z
};

this->shader.Use().SetVector2fv("uvs", 12, verticies);

Where uv is the uv at an index in the uvs vector that was returned above in the GetUVs function.
Vertex shader
#version 330 core
layout (location = 0) in vec2 vertex;

out vec2 TextureCoordinates;

uniform vec2 uvs[6];
uniform mat4 model;
uniform mat4 projection;

void main()
{
    const vec2 position [6] = vec2[]
    (
        vec2(0.0f, 1.0f),
        vec2(1.0f, 0.0f),
        vec2(0.0f, 0.0f),

        vec2(0.0f, 1.0f),
        vec2(1.0f, 1.0f),
        vec2(1.0f, 0.0f)
    );

   TextureCoordinates = uvs[gl_VertexID];
   gl_Position = projection * model * vec4(position[gl_VertexID], 0.0, 1.0);
}

Fragment shader
#version 330 core
in vec2 TextureCoordinates;
out vec4 color;

uniform sampler2D image;
uniform vec4 spriteColor;

void main()
{
    color = vec4(spriteColor) * texture(image, TextureCoordinates);
}

Thanks for reading. I have asked this question a few places and not gotten any response, so any help is greatly appreciated.


texts: Simulate mouse input message for free look in fps games

texts:
This question was previously asked in stackoverflow where no one gives an answer. I also found a similiar question here, but in my situation, I hook and simulate mouse inputs and send them to the game window.

Here is the body of the original question:
After hooking windows mouse and keyboard APIs, I wanted to simulate the mouse input message for free look technique (Move the mouse to rotate the player character's view). Before coding, I used spy++ to monitor a fps game observing which mouse-related message was sent to the window of the game's program. I got these following lines when I moved the mouse:
P WM_INPUT nInputCode:RIM_INPUT hRawInput:065A04FD
S WM_NCHITTEST xPos:2504 yPos:889
R WM_NCHITTEST nHittest:HTCLIENT
S WM_SETCURSOR hwnd:0016089A nHittest:HCLIENT wMouseMsg:WM_MOUSEMOVE
R WM_SETCURSOR fHaltProcessing:True
P WM_MOUSEMOVE fwKeys:0000 xPos:419 yPos:183
...

So I wrote these lines of codes (sent WM_INPUT message using codes in How to simulate raw input / Send a WM_INPUT message to an application the right way?, Simulating Raw Input on Windows, and codes in github):
// ...
// mData->px and mData->py indicating the mouse position in client window are double type.
WORD xCor = static_cast<WORD>(mData->px);
WORD yCor = static_cast<WORD>(mData->py);
LPARAM lParamMouseMove = (yCor << 16) | (xCor & 0xFFFFFFFF); // lParam for mouse movement message

// prepare for sending WM_INPUT
LONG _mouse_position.x = static_cast<long>(mData->px);
LONG _mouse_position.y = static_cast<long>(mData->py);
WPARAM wParamRawMouse = RIM_INPUT;
HGLOBAL hRaw = ::GlobalAlloc(GHND, sizeof(RAWINPUT));
RAWINPUT* pRaw = reinterpret_cast<RAWINPUT*>(::GlobalLock(hRaw));

memset((void*)pRaw, 0, sizeof(RAWINPUT));
pRaw->header.dwType = RIM_TYPEMOUSE;
pRaw->header.dwSize = sizeof(RAWINPUT);
pRaw->header.hDevice = GetRawMouseDevice();  // can return the mouse HANDLE correctly
pRaw->header.wParam = wParamRawMouse;

RAWMOUSE rawMouseInfo;
memset((void*)&rawMouseInfo, 0, sizeof(RAWMOUSE));
rawMouseInfo.usFlags = MOUSE_MOVE_RELATIVE;
rawMouseInfo.lLastX = _mouse_position.x - _last_mouse_position.x;  // get the mouse's location change
rawMouseInfo.lLastY = _mouse_position.y - _last_mouse_position.y;
rawMouseInput.data.mouse = rawMouseInfo;
rawMouseInfo.ulExtraInformation = 0;
rawMouseInfo.ulButtons = 0;
rawMouseInfo.usButtonFlags = 0;
rawMouseInfo.ulRawButtons = 0;
pRaw = &rawMouseInput;

::GlobalUnlock(hRaw);

// mainGameWnd is the main window handle
PostMessageA(mainGameWnd, WM_INPUT, wParamRawMouse, (LPARAM)hRaw);
SendMessageA(mainGameWnd, WM_NCHITTEST, 0, MAKELPARAM(_mouse_position.x, _mouse_position.y));
SendMessageA(mainGameWnd, WM_SETCURSOR, (WPARAM)mainGameWnd, MAKELPARAM(HTCLIENT,WM_MOUSEMOVE));
PostMessageA(mainGameWnd, WM_MOUSEMOVE, 0, lParamMouseMove);
// ...

And I used spy++ to monitor my own program:
P WM_INPUT nInputCode:RIM_INPUT hRawInput:0000023822711808
S WM_NCHITTEST xPos:492 yPos:373
R WM_NCHITTEST nHittest:HTNOWHERE
S WM_SETCURSOR hwnd:001B0794 nHittest:HCLIENT wMouseMsg:WM_MOUSEMOVE
R WM_SETCURSOR fHaltProcessing:True
P WM_MOUSEMOVE fwKeys:0000 xPos:492 yPos:373

It didn't work, when I moved the mouse, the character's view didn't change and the cursor just moved.
So how to correctly send the four message? Do some magics beyond sending message for free look in games? By the way, this question mentions camera, I think in this hooking situation, the camera is still handled by the game and I just need to send mouse-related message to the game. No need to consider the camera. Am I right?


texts: Fastest 3D collision detection between two oriented bounding boxes (OBBs)

texts:
I am at the point in my game where I need to add a collision system. I tried jBullet, and while it did work, it wasn't what I was looking for. I just want a simple way to test if two oriented bounding box (OBB) trees are colliding.

I was going to do collision by using the tree.  Make an AABB for broadphase, then if that passes test if each OBB in tree collide with the other tree.

I did find a few things on the internet, but I couldn't understand them completely. What I am asking for is a website or resource that explains 3D OBB collisions well?

I learned that GJK is faster than SAT, and it appears to be able to tell me how far the boxes penetrate each other. I found some GJK stuff, but they were not boxes; instead, more complex and confusing things.

I just want to be able to make an OBB from 3 vectors: center, size, and rotation of each axis. Then be able to test collisions with those. Thank you in advance for anything you post.


texts: Client interpolation for 100% serverside game

texts:
I'm developing an online browser MMO 2d war game.

And I'm having some issues with the interpolation. The server sends updated positions to the clients every 90 ms.

I've managed to make it smooth, and it works very well on low latency, but if the latency is high, everything skates around like its on ice (OVERLY SMOOTH).

I would like to achieve normal movement (visually), and I don't care about input-lag, as 3-400 ms input lag doesn't matter for this game.

This is how I'm doing it now (simplified for readability):

The "Server" object is the one processing the updates send by the server, and "animate()" is the gameloop.

    var Server = {
        msAhead: 0,
        Time: Date.now(),
        SetData: function (data) {

            //Set date.now() to calculate ms since last update
            var now = Date.now();

            //calculates ms since last update
            var ms = now - this.Time

            //sets new time (for calculating ms next update)
            this.Time = now;

            //Keeps track of how many milliseconds the server is ahead (position vice)
            this.msAhead += ms;

            //Attatch a reference with the players new position to each player
            $.each(data["players"], function (id, data) {
                Players[id].target = data;
            });
        }
    }

    var Time;
    function animate() {
        //Sets time if first call
        if (!Time) Time = Date.now();

        //Sets new time and calculate ms between frames, sets deltatime
        var now = Date.now();
        var ms = now - Time;
        var delta = ms * 0.001;

        //reset info for next frame
        Time = now;

        //Calculate and normalize lerp
        var lerp = ms / Server.msAhead;

        //update the "msAhead" so we know that we are closer to our target position
        Server.msAhead -= ms;

        //normalize lerp (it can be off on the first frames since time isn't set yet, or is heavy spikes occur)
        if (lerp > 1) lerp = 1;
        if (lerp < 0) lerp = 0;

        //Update player positions lerping towards the target position set by the server object
        $.each(Players, function (id, player) {
           player.position = Lerp(player.position, player.target.position, lerp)
        });

        //Request next animationframe
        requestAnimationFrame(animate);
    }

EDIT:
I can simulate my goal on high latency by doing:
var now = Date.now() + 300;
in the animation loop.

But that will crash (stop updating) low latency players, since the client will think its ahead of the server, and lerp will become negative (zero).


texts: For my first game I implemented a tetris clone in javascript. My "canvas" and an HTML <table> with every <td> representing a single block. Instead of having a gameloop redraw every single pixel, I only update pixels that have changed, like a piece being rotated and moved down. Is that a bad practice?


texts:
I have a multiplayer cooperative game (PVE) in where there can be up to 200 enemies at a time (somewhere around that) and I was wondering how devs generally synchronize these? I already have packets being sent every 0.2 seconds or so to players telling other player's position, health points and things like that, and I have no idea how much of the network I can actually use (in a P2P UDP connection).

I really don't wanna leave the clients to sync the enemies positions themselves, as myself as a player have played games like these and its so annoying to have you shooting an enemy in one corner of the map and your friend shooting the same enemy on the other corner. But I have no idea if sending every 0.3 seconds or so updates from 200 enemies and their position is reasonable.

TL;DR: How would devs synchronize a high number of entities for multiple players and what is the limitation of a UDP connection? Is there a number of packets per second that you would work towards?


texts:
Each entity and camera have a Transformation object that holds position info as vec3, rotation info as quat and scale info as vec3.
When I need a matrix (that being either model or view matrix), I construct the matrix out of given data. That gives me the freedom to change any of transformation info without having to worry about order of change.
Now, I'm trying to implement it in a fly-camera. The two constraints are pitch that has to be limited from -90° to 90° and roll which should not occur.
While rotating the camera along X and Y axis, a sort of drift happens along the Z axis. In order to combat that, after all changes to rotation are applied, I get the angle of rotation around the Z axis and then rotate it by -angle, effectively resetting the Z-rotation to 0.
That all works nicely in theory, but not so much in practice.
You see, when I go over ~55ish° both in the positive or negative Y-rotation, the camera starts freaking out and fluctuating. It seems that every frame it switches from some negative z rotation, to positive z rotation of the same value. It looks like this (moving camera to the left, negative Y-rotation):

Of course, since the object is only in the one place at one time, I had to edit the screenshot in paint to give you a better idea of what's going on. It really does look like there are two objects at the same time, both flickering as crazy.
Also note that if I were to move camera further to the left, the Z-rotation offset would increase, moving both objects further from the horizontal plane.
At this point, the Y-rotation would also start to fluctuate ever so slightly. You couldn't see it on screen, but printing out angle each frame would show that it's fluctuating at about 3rd digit after the dot (0.00####).
Once I get far enough, the camera would just give up and just show the object rapidly changing it's Z-rotation with no apparent pattern.
My guess is that quaternion rotation is imprecise for some reason. You can tell by the fact that my strict Z-rotation starts to influence the Y-rotation after the Z-drift gets severe enough.
Here's a snippet of code, for what it's worth:
transformation->rotateAroundY(angleY);

GLfloat roll = transformation->getRoll();
transformation->rotateAroundZ(-roll);

angleY is delta Y of mouse position between this and previous frame.
rotateAround#(angle) calls this code:
rotation *= glm::tquat<GLfloat>(glm::angleAxis(glm::radians(angle), axis));

where rotation is the quaternion, while axis is tvec3<GLfloat> representing the axis around which the rotation takes place.
How do I combat this? How can I consistently reverse unintentional Z-drift without making the camera freak out?


texts: How to import texture from Maya to unity?

texts: I am trying to export a model from Maya with animation but when I import into unity I am getting the model but the texture is not there. From the internet I found that while importing the model I need to enable media that also does not work for me.Is there any way that I can import Material texture in fbx file


texts: Unity: OnTriggerEnter2D does not get called when using Raycast

texts:
In a previous post I talked about creating wires (using Bézier curve) using LineRenderer. I am using a PolygonCollider2D to wrap the wire (see below):

GameObject wire = new GameObject ();
LineRenderer lineRenderer = wire.AddComponent<LineRenderer> ();
PolygonCollider2D wireCollider = wire.AddComponent<PolygonCollider2D> ();

After drawing the curve and attaching the collider (as described in previous post), I added a new component to my gameObject (a WireController):

WireController wireController = wire.AddComponent<WireController> ();

The WireController currently has only one method:

void OnTriggerEnter2D(Collider2D other) {
    Debug.Log ("I'm hit!");
}

I use a Physics2D.Raycast to check if my mouse pointer is at any point interacting with the wire:

void CastRay() {
    Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    RaycastHit2D hit = Physics2D.Raycast (ray.origin, ray.direction, 100);

    if (hit) {
        Debug.Log (hit.collider.gameObject.name);
    }
}

If I call CastRay() inside a Update() loop, if (hit) returns true (if the mouse pointer is over the gameObject, in this case, the wire), but the OnTriggerEnter2D method never gets called.

A few observations:

collider.isTrigger = true;
The WireController is attached to the newly created gameObject (it's visible in the Unity editor at runtime)

Any help is much appreciated!


texts: how do I modify Texture2DArray values in shader

texts:
I'm using HLSL Shader Model 5.0. I'm using a Texture2D with the vertex positions for a mesh. In the Shader I'm trying to displace patchepositions along the normal of the patches I'd like to actualize the new position to the texture out of the shader, so the next patch is using the modified value.
There is the Load function for loading values out of the texture, but is there a function to store values back into the texture? I didn't find anything.
How do you guys managing similar problems? thx


texts: I want to know how can I make the control of the Pong Ball in Plain Javascript. I would like to know how to make the ball faster when it hits the edges just like the original pong game, or how if the ball hit's the middle of the paddle it would go straight and slow. I just want to get a feel for how it works.


texts: body_entered signal won't emit when rigidbody collided to rigidbody

texts:
I have multiple rigidbody object floating away in the space. When they hit each other, they push away each. I want to destroy object if they hit something, but connect body_entered signal won't invoked when they impact each other:

func _ready():
    connect("body_entered", self, "destroy")

func destroy(body):
    print("HIT!")
    queue_free()

How do I check Rigidbody hit something?


texts: "CVar system" - are CVar always looked up or cached?

texts:
Many famous game such as Quake or Half-Life use CVars to allow easy and flexible game parameter manipulations.

You can simply open up the console and write something like

sv_cheats 1

to enable cheat codes.

CVars are used intensively during the game - if they were set or retrieved by string name lookup there would certainly be a performance hit. Therefore, I'm assuming CVars are somehow cached.

How would this kind of system be implemented? I thought about storing pointers to the real values in a map having the CVar names, and then use the real values in the game.
Is this a viable approach? Do the AAA games have a better one?

Example:

struct Game
{
    std::map<std::string, int*> cVars;
    int volume, sensitivity; // Example game parameters

    Game()
    {
        cVars.emplace("volume", &volume);
        cVars.emplace("sensitivity", &sensitivity);
    }

    void setCVar(std::string mName, int mValue)
    {
        *cVars[mName] = mValue;
    }
};


texts: Reopening Unity project after two week break, project is trashed

texts:
I've spent about 6 months using Unity nearly every day. Then I take a two-week break, re-open my project, and the entire build is trashed.
There are 166 errors, here are a few:
Assets\TextMesh Pro\Examples & Extras\Scripts\ChatController.cs(6,14): error CS0101: The
namespace '<global namespace>' already contains a definition for 'ChatController'

private Renderer renderer;Assets\Scripts\Board\Tile.cs(23,22): warning CS0108: 'Tile.renderer'
hides inherited member 'Component.renderer'. Use the new keyword if hiding was intended.

Assets\TextMesh Pro\Examples & Extras\Scripts\ObjectSpin.cs(8,18): error CS0101: The namespace
'TMPro.Examples' already contains a definition for 'ObjectSpin'

I've re-imported Text Mesh Pro Examples & Extra, restarted my project multiple times, to no avail. This is very concerning to me because it makes me feel like Unity is not a stable plaform ... Are Unity projects attacked by gremlins if not used every couple days?


texts: Optimize state changes within a render queue

texts:
I am refactoring some parts of the game engine I am working on. This engine is made in C# with XNA.

The part I have trouble with is shader/material and the render queue. In the new version I will give ability to indicate differents render states per pass
within a technique (blend state, rasterizer state, ...). In my engine, all renderables have a material and each material is associated to one technique (thus to one or
more passes).

Later, when the game will be running, I will add renderable objects to the render queue and then sort it based on the pass used by each material. What I want
to achieve is to reduce states changes between draw calls by first grouping same passes together and then passes with nearly identical states to be as closed as possible to minimize changes.
But this solution seems to be problematic when it comes to use technique with more than one pass with completely different states. Passes within a same technique can
be completely separated in the render queue and not rendered one after the other. If I say that it's because I have always see multi-passes technique render in a loop and all passes
rendered immediately like that :

foreach(EffectPass pass in technique.Passes)
{
    /* Update parameters */

    pass.apply();
    graphicsDevice.Draw(...);
}

But I don't know if I can deferred pass rendering from a same technique instead of using them one after the other as in the previous example.

Here is an example of what will probably happen with the solution I try to build:

Shader1

TechniqueA

Pass1 (State A)
Pass2 (State C)

Shader2

TechniqueB

Pass1 (State A)

Shader3

TechniqueC

Pass1 (State A)

Now I have three models to draw, Model1, Model2 and Model3, each one use a different technique from the previous list. If I add those three models in the render queue I will end up with the following render queue :

-> Set state A -> Draw Model1(Pass1) -> Draw Model2(Pass1) -> Draw Model3(Pass1) -> Set state C -> Draw Model1(Pass2)

We can see that the Model1 will be drawn two times (two passes for the Technique A) but the draw call are separated by others draw call.

I don't know how to resolve this. What will be a good solution to this problem? How can I design my render queue to reduce state changes as much as possible between draw calls.

EDIT:

After searching a little more, I have found this helpful article : http://realtimecollisiondetection.net/blog/?p=86. It seems to be an elegant way to sort object by depth and materials. And in the material id, I can had a pass id to sort same pass together that will allow to reduce state changes.

Currently my renderer draw objects directly in the backbuffer without lights nor shadows, everything is flat. So I will just loop over my render queue and call draw methods. But in a future I will probably implement deferred rendering.

I don't know a lot about it but I know that I have to render my objects in different render target to gather differents informations (Z-buffer, Normal buffer, G-Buffer, ...). I assume that for z-buffer and normal buffer I will use the same shader on every objects no matter which material they use. But for the G-buffer I will use the materials of each object so that means different shaders with different number of pass. If I use the solution in the previous link, if I have an object with a material that needs to do two or more passes, my render queue will have at least two times the object (one for each pass). But for Z-buffer or normal buffer isn't it useless to have the same object multiple times?

What I see is that I will need to have at least two different render queue : one for G-buffer in which an object can be multiple times depending on the number of pass the material require and another render queue for Z-buffer or other buffer in which each objects are only one time. Am I right?


texts: How can I make tree foliage work with baked lighting?

texts:
I have an issue in Unity where my trees are black and it seems to be due to the fact that I'm using baked lighting in my scene. Luckily, it seems that I'm not the only one who's experienced this. I found a post on the unity3d subreddit which goes into more detail about basically the same problem. I'll repost it here for convenience:

  So, I have some custom trees using the "Nature/Tree Soft Occlusion"
  shaders and they looked great before baking a lightmap. However, now
  that I have baked the lightmap, the trees have turned black. Or
  rather, when I tried baking with the trees set to static, they turned
  invisible, and now that Ive tried without, they're black. Also,
  they're not casting shadows.

  Anyone know how to fix this issue? Perhaps I need to use light probes?

  http://imgur.com/a/21At5 --> before and after (fyi the bark is not
  using the nature/occlusion shader. The shader definitely seems to be
  the root of the issue, but Im just not sure how to fix it without
  using a different shader)

Ultimately, the author of this post eventually "solved" his problem by just switching to realtime lighting instead of baked lighting. Unfortunately, this is not an option for me. However, the author did receive some useful comments before giving up.

One of the comments asks if the leaves have properly laid out UVs. The commenter goes on to say that the leaves all need to have their own unique space in the UV grid. I think this makes sense because I enabled the Generate Lightmap UVs option on my tree model in Unity. But it did nothing. The author apparently also had no luck with that option.

In any case, Maya was suggested (among other software) to check these leaves' UVs. Unfortunately, I've never used Maya and I absolutely can't make heads or tails out of it. I'm just using a borrowed copy from a friend so I've never gone through any tutorials or anything for it. I'm just trying to check this one thing, but I am really at a loss.

EDIT:

According to some comments from DMGregory, he suggests that since trees get spawned and varied dynamically, there's no single mesh to pull apart and check its UVs. His logic seems to make sense, so perhaps Maya is not the solution that I'm looking for. Now, though I'm having trouble with figuring out how to get my tree shaders to work with lightmapping. Details are in the comments.


texts:
I want to center location on a place where someone uses their scanners sweep. I know this is possible with the defilers ability dark swarm but i wonder if it is possible with scanner sweep from ComSat Station. There is a unit that is called scanner sweep so maybe it is possible. I tried it with many triggers but none of them seem to work.

Does anybody have an idea how a trigger that would move the location to the scan would look like?

It doesn't matter which player scans I just want the location to move with each scan.


texts:
I'm not really aware of the legal issues surrounding game clones.

I'm around halfway done of making a clone, but it's not just the same gaming concepts, I'm literally using the original game's files (which I do not intend to distribute in any way) in my clone. My original intention was to add features to the game (Firefly studios's first Stronghold) while still using the same art.

Is it ok to distribute the source of my clone?


texts: Dividing sprites and checking for empty ones

texts:
So I have a sprite. I would like to divide this sprite into 5x5 sprites. Now what I am confused with is how I can go through each of these sprites and check if a sprite is completely empty/no pixels then remove that sprite

This is my code for dividing the sprite

public class TextureDivider : MonoBehaviour {

     public Texture2D source;

     // Use this for initialization
     void Start () {

         GameObject spritesRoot = GameObject.Find("SpritesRoot");

         for(int i = 0; i < 8; i++)
         {
             for(int j = 0; j < 8; j++)
             {
                 Sprite newSprite = Sprite.Create(source, new Rect(i*128, j*128, 128, 128), new Vector2(0.5f, 0.5f));
                 GameObject n = new GameObject();
                 SpriteRenderer sr = n.AddComponent<SpriteRenderer>();
                 sr.sprite = newSprite;
                 n.transform.position = new Vector3(i*2, j*2 , 0);
                 n.transform.parent = spritesRoot.transform;
             }
         }
     }
 }


texts: Java, Crashing with a Shader on Intel HD Graphics

texts:
I just got a new computer (Acer Aspire ES1-311) which has an integrated Intel HD Graphics card, and I noticed that this fisheye shader crashes my game (LibGDX game, VM Crash):

varying vec2 v_texCoords;
uniform sampler2D u_texture;
uniform vec2 pos;
uniform float radius = 100;
uniform float scale = 1;
void main()
{
    vec2 textureCoordinateToUse = v_texCoords;
    float dist = distance(pos, v_texCoords);
    textureCoordinateToUse -= pos;
    if (dist < radius)
    {
        float percent = 1.0 + ((0.5 - dist) / 0.5) * scale;
        textureCoordinateToUse = textureCoordinateToUse * percent;
    }
    textureCoordinateToUse += pos;
    gl_FragColor = texture2D(u_texture, textureCoordinateToUse);
}

I've tried to update the drivers from the official site, but the driver application says that they might be incompatible with my computer!

However, does anyone spot anything "wrong" in the shader that might cause the crash?

Thanks.


texts:
I'm trying to figure out if I'm approaching my simple fixed-timestep implementation correctly, following examples such as: Gaffer (without RK4), and DeWitters

Currently, I have a game object which contains position and velocity data members, with position calculated by

 position = position + (velocity * dt)

However, unless the velocity is set to a value of two decimal places, the update makes the position change in an instant (e.g. Velocity = 0.05 works, but this does not seem logical; to me Velocity should be >0?; even a value of 0.5 makes the update appear instant). Therefore, I have come to the conclusion that I have implemented by game loop incorrectly.

Note, I'm using SDL and C++, however the following is all Psuedocode:

bool quit = false;
World world;

Uint32 frameTime = SDL_GetTicks();
double accumulator = 0.0;
const double dt = 1.0 / 60.0;
int fCount = 0;
while(!quit){
    fCount = 0;
    double newTime = SDL_GetTicks();
    double nextFrameTime = newTime - frameTime;

    if(nextFrameTime > 0.25)
        nextFrameTime = 0.25;

    frameTime = nextFrameTime;  //Line of error, should be frameTime = newTime
    accumulator += nextFrameTime;

    while(accumulator >= dt){
        world.Update(dt);  //A simple counter revealed Update being called 15-16 times during this loop
        accumulator -= dt;
        fCount++;
    }
    //fCount is equal to 15 when dt = 1.0/ 60.0, fCount = 8/9 when dt = 1.0/30.0
    double interpol = accumulator / dt;
    world.Render(interpol);
}

If there isn't any apparent issue with this code then perhaps I have messed up my position/physics calculations based on Update(dt).

Any help is appreciated


texts: Using XBOX controllers on PC for an XNA game

texts: Does anybody know how to do this? I have been trying to figure this out with no luck.


texts:
I have a game in which sprites will be removed and added under different circumstances, and so I created Rects of type List<Rectangle> to hold the bounding rectangle for each sprite.

List<Rectangle> Rects = new List<Rectangle>();

Within Initialize():

playerTexture = Content.Load<Texture2D>("player");
cowTexture = Content.Load<Texture2D>("cow");
player = new Player(playerTexture, new Vector2(100, 100));
Rects.Add(player.Bounds);
for (int i = 0; i < 5; i++)
{
    Cow cow = new Cow(cowTexture, graphics);
    cows.Add(cow);
    Rects.Add(cows[i].Bounds);
}

What I want to do is iterate through every rectangle in the list and move it when the player approaches the edge of the screen. This is the code with which I have tried to do this:

for (int i = 0; i < Rects.Count; i++)
{
    if (player.Bounds.Left < 60)
    {
        Rects[i].Offset(2, 0);
    }
    if (player.Bounds.Right > GraphicsDevice.Viewport.Width - 30)
    {
        Rects[i].Offset(-2, 0);
    }
    if (player.Bounds.Top < 60)
    {
        Rects[i].Offset(0, 2);
    }
    if (player.Bounds.Bottom > GraphicsDevice.Viewport.Height - 30)
    {
        Rects[i].Offset(0, -2);
    }
}

But when my player gets to the edge of the screen, he very happily leaves and none of the sprites move. What am I doing wrong?


texts:
I often tend to do a lot of premature optimazation when dealing with graphics. There are a few principles I always try to follow:

Keep the number of D3D components to a minimum. (Render states, buffers, shaders, etc.)
Only bind components if absolutely necessary. (Not bound already, etc.)
Specialize the components as much as possible. (Only set necessary BindFlags, etc.)

This lead me to building very elaborate wrappers for managing the created components and the current pipeling state. Not only does this consume a lot of my valuable development time, it also adds another big layer of complexity.

And worst of all: I don't even know if it is all worth the trouble.

Some of my optimization considerations may already be implemented on a lower level and I am just replicating them, additionally wasting time on the CPU. Other considerations may be completely unnecessary, since the effect on performance is negligible.

So my questions are:

Which of the above guidelines are valid and to which extent should I follow them?
How does the GPU handle state changes?
What happens if I change a state that is never used? (No draw call being made while it is active.)
What are the actual performance penalties for binding the various different components?
What other performance considerations should be made?

Please don't just tell me, that I just should not care about performance until I hit actual limits. While that is obviously true from a practical point of view, I am mainly interested in the theory. I somehow need to combat the urge of building the optimal graphics framework and I don't think I can do that with the usualy "premature optimization lecture".

Managing components

I am currently writing DirectX 11 applications in C# using SlimDX as a managed wrapper. It is a very low level wrapper and my current abstraction is built on top of it.

There are some obvious advantages when using a Direct3D abstraction. Setting up the environment, loading shaders, setting constants and drawing a mesh is much simpler and uses a lot less code. Also, since it manages creation and disposing of most components they can be automatically reused everywhere and I almost completely avoid memory leaks.

How do you usually manage all the graphics components and resources?
Can you recommend any managed wrappers doing something similar to my example below?

Here is an example of my current implementation. I am quite happy with the interface. It has enough flexibility for my needs and is very simple to use and understand:

// Init D3D environment
var window = new RenderForm();
var d3d = new Direct3D(window, GraphicsSettings.Default);
var graphics = new GraphicsManager(d3d.Device);

// Load assets
var mesh = GeometryPackage.FromFile(d3d, "teapot.gp");
var texture = Texture.FromFile(d3d, "bricks.dds");

// Render states
graphics.SetViewports(new Viewport(0, 0, 800, 600);
graphics.SetRasterizer(wireFrame: false, culling: CullMode.Back);
graphics.SetDepthState(depthEnabled: true, depthWriteEnabled: true);
graphics.SetBlendState(BlendMethod.Transparency);

// Input layout
graphics.SetLayout("effect.fx", "VS", "vs_4_0",
    new InputElement("POSITION", 0, Format.R32G32B32_Float, 0),
    new InputElement("TEXCOORD", 0, Format.R32G32_Float, 0)
);

// Vertex shader
graphics.SetShader(Shader.Vertex, "effect.fx", "VS", "vs_4_0");
graphics.SetConstants(Shader.Vertex, 0, 4, stream => stream.Write(wvpMatrix));

// Pixel shader
graphics.SetShader(Shader.Pixel, "effect.fx", "PS", "ps_4_0");
graphics.SetTexture(Shader.Pixel, 0, texture);
graphics.SetSampler(Shader.Pixel, 0, Sampler.AnisotropicWrap);
graphics.SetConstants(Shader.Pixel, 0, 1, stream => stream.Write(new Color4(1, 0, 1, 0);

d3d.Run(() =>
{
    // Draw and present
    d3d.BackBuffer.Clear(new Color4(1, 0, 0.5f, 1));
    graphics.SetOutput(d3d.BackBuffer);
    graphics.Draw(mesh);
    d3d.Present();
}


texts:
When manually setting the drawing order of game components by setting

int DrawableGameComponent.DrawOrder

can one use any integer numbers as long an order is defined like

component1 => drawing order: 2
component2 => drawing order: 5
component3 => drawing order: 10
component4 => drawing order: 323

or do these integers have to be consecutive and starting with zero like

component1 => drawing order: 0
component2 => drawing order: 1
component3 => drawing order: 2
component4 => drawing order: 3

?


texts: How do I get A.I. that follows a list of movement commands to move smoothly in a tilemap based game?

texts:
This is for a school project so it's not intended to be sold/fun/or a complete game, rather just a demonstration of stuff we've learned without resorting to frameworks and stuff.

My ai agents choose a random point in the grid and generate a sequence of actions to take to get there using breadth first search. They do this indefinitely until they're killed (something I haven't gotten to yet).  Each action corresponds to one tile movement so I'm having trouble translating that into smooth movement transitioning from one tile to the next rather than just stuttering to it.  What I have at the moment is limiting how many actions can be taken per second so the agent doesn't just teleport around the game because it's moving so fast.  Can I modify what I have here to achieve smooth movement, or do I need to take a different approach in how to generate my action sequence?

I had smoothish movement when my MAX_VELOCITY = 1 by just rounding down if the time step made the agent move past more than one tile, but it didn't work for higher numbers, like MAX_VELOCITY = 10. The player character moves at MAX_VELOCITY = 10 which I think is perfect.

Edit:  I'm thinking of something now though I don't know if it'll work or if it's the right way to do it.  If I only use enough of the time step to advance to the next square, then I could use the rest of the timestep on the next action, or something like that until I'm out of time.

Edit2:  It seems to work properly.  There's some collision detection issues coming up, but it looks pretty much as smooth as the player character movement.  I'll leave the answer unchosen for now since my solution isn't very good but I'll post what I have here once I figure out the collision detection issues.

@Override
public void move(double dt) {
    this.elapsedTime += dt;
    if (this.actionsIndex == this.actionsToGoal.length() || this.actionsIndex == -1) {
        long startTime = System.nanoTime();
        if (this.goal != null) { //Debugging stuff
            startingPosition = new Point((int) this.posX, (int) this.posY);
            System.out.println("Arrived at goal");
            System.out.println(startingPosition.toString());
            System.out.println(goal.toString());
        }
        chooseGoal();
        this.frontier.clear();
        generateActionSequence();
        double timeTaken = (System.nanoTime() - startTime) / 1000000000.0;
        this.elapsedTime += timeTaken;
    }

    if (this.actionsIndex != -1) {
        while (elapsedTime >= 1.0 / this.actionsPerSecond && this.actionsIndex != this.actionsToGoal.length()) {
            char action = actionsToGoal.charAt(this.actionsIndex++);
            switch (action) {
                case State.LEFT:
                    this.posX -= MAX_VELOCITY;
                    break;
                case State.RIGHT:
                    this.posX += MAX_VELOCITY;
                    break;
                case State.UP:
                    this.posY += MAX_VELOCITY;
                    break;
                case State.DOWN:
                    this.posY -= MAX_VELOCITY;
                    break;
            }
            elapsedTime -= 1.0 / this.actionsPerSecond;
        }
    }

}


texts: C# Divide points based on players damage

texts:
How can i divide points based on highest damage? For e.g i have monster which drop 50 experience points and 4 different players has dealt damage to this monster. But i will like to split the experience points based on the players damage.

So far i got this:

private Dictionary<Player, int> damageMap = new Dictionary<Player, int>();

public void TakeDamage(Player attacker, int damage)
{
    damageMap.Add(attacker, damage);
}

private void OnDeath()
{
    foreach (KeyValuePair<Player, int> entry in damageMap)
    {
        Player player = entry.Key;
        int damage = entry.Value;

        player.addExperience(50);
    }
}


texts: Why does my libGDX TextureRegion.split code not work properly?

texts:
I am using scene2d in libGDX on Android as part of a game I am working on. I have a simple splash screen, which I am trying to display a single image on. The image comes from a file with two tiles in it, and I am using TextureRegion.split() to access it. My problem is, the entire image gets displayed instead of just the first tile.

Here are code snippets to illustrate what I am doing. You should be able to put this in a basic libGDX app to test it out. The image I am using is a png with dimensions of 460 width X 342, (2 tiles of 460X171). I am using the latest libGDX, as obtained from the libGDX setup tool.

What is wrong with my code?

TextureRegion[][] tiles =
    new TextureRegion(
        new Texture( Gdx.files.internal( "foo.png" ) ) )
            .split( 460, 171 );

Stage stage;
Table table;

stage = new Stage();
table = new Table();

table.setFillParent(true);
stage.addActor(table);

Texture fooTex = tiles[ 0 ][ 0 ].getTexture();

Image fooImg = new Image( fooTex );
fooImg.setPosition(
    ( Gdx.graphics.getWidth() / 2 ) - ( fooImg.getWidth() / 2 ),
    ( Gdx.graphics.getHeight() / 2 ) - ( fooImg.getHeight() / 2 ) );

stage.addActor( fooImg );


texts: How to build a hidden 3D snapping grid effect?

texts:
Looking to build a 3D grid similar to the image below taken from Google Blocks.

Seems like it consists of these main components:

A set of spheres that can go transparent.
A stencil that follows the controller's location.
When stencil overlaps with spheres, they show up, otherwise, alpha fades to zero.

Any advise on how to approach building this?


texts: Inventory structure for games like Dragon Warriors

texts:
I'm wandering what would be a suitable way of storing items in inventory.
Many games have an inventory that stores different items with its quantity. For example, [ "Herbs" x5, "Torch" x2, ..].

so I came up with a data structure like this in Java;

HashMap> inventory // where Integer -> item id, ArrayList -> there are same items stored in the list

but I thought Is this a good way to store items even if the number of items in each list becomes larger (x99 items) ?

or should I just store the quantity of items instead of storing objects in list? in this case, is using tuple going to be ok? like HashMap>


texts:
I'm currently developing a 3D game engine in C# using OpenTK.

I have basic game objects, and each game object has transform (translation, rotation and scaling). A game object can have components (much like Unity).

One game object (The camera game object) has three components, A camera, free move and a free look component. The free move component allows the user to move the camera around the scene, whilst the free look camera is SUPPOSED to rotate the camera. However, I get this odd effect:

https://youtu.be/rcdWZcaEqSY

(Note that, the plane isn't changing position, it seems the camera is ... turning upside down?)

On top of that, once I rotate the camera, moving the camera (using the arrow keys) gets really weird, up can become down, left can become right. It's all very odd.

Anywho, here is the update method for my Free Look component:

protected override void OnUpdate(object sender, UpdateEventArgs e)
{
    Rectangle bounds = Game.GetCurrentGame().Window.Bounds;

    Vector2 center = new Vector2(bounds.Left + (bounds.Width / 2), bounds.Top + (bounds.Height / 2));

    Vector2 mousePosition = new Vector2(System.Windows.Forms.Cursor.Position.X,
                                            System.Windows.Forms.Cursor.Position.Y);
    Vector2 deltaPosition = center - mousePosition;

    bool rotX = deltaPosition.X != 0;
    bool rotY = deltaPosition.Y != 0;

    if(rotY)
        Transform.Rotate(new Vector3(0, 1, 0), MathHelper.DegreesToRadians(-deltaPosition.X * sensitivity));
    if(rotX)
        Transform.Rotate(new Vector3(1, 0, 0), MathHelper.DegreesToRadians(-deltaPosition.Y * sensitivity));

    if (rotY || rotX)
        System.Windows.Forms.Cursor.Position = new Point((int)center.X, (int)center.Y);

    base.OnUpdate(sender, e);
}

here is the Rotate method in my transform class:

public void Rotate(Vector3 axis, float angle)
{
    rotation = (Quaternion.FromAxisAngle(axis, angle) * rotation).Normalized();
}

I hope someone can help me get to the bottom of this, I've been so frustrated!

If there's any other code you need to see, just let me know.


texts:
I posted this question on stack overflow first, but I guess no one is very interested in video games there...

What are some path finding algorithms used in games of all types? (Of all types where characters move, anyway) Is Dijkstra's used a whole lot? I would think not, as it doesn't actually trace out the steps to take to get somewhere, right? If I'm understanding it right, it only determines which object is the closest. I'm not really looking to code anything; just doing some research, though if you paste pseudocode or something, that would be fine (I can understand Java and C++). I'm basically looking for a quick overview of path finding in general.

I know A* is like THE algorithm to use in 2D games. That's great and all, but what about 2D games that are not grid-based? Things like Age of Empires, or Link's Awakening. There aren't distinct square spaces to navigate to, so what do they do?

What do 3D games do? I've read this thingy http://www.ai-blog.net/archives/000152.html, which I hear is a great authority on the subject, but it doesn't really explain HOW, once the meshes are set, the path finding is done. IF A* is what they use, then how is something like that done in a 3D environment? And how exactly do the splines work for rounding corners?


texts: SDL: How would I add tile layers with my area class as a singleton?

texts:
I´m trying to wrap my head around how to get this done, if at all possible. So basically I have a Area class, Map class and Tile class. My Area class is a singleton, and this is causing some confusion. I´m trying to draw like this: Background / Tiles / Entities / Overlay Tiles / UI.

void C_Application::OnRender()
{
    // Fill the screen black
    SDL_FillRect( Surf_Screen, &Surf_Screen->clip_rect, SDL_MapRGB( Surf_Screen->format, 0x00, 0x00, 0x00 ) );

    // Draw background

    // Draw tiles
    C_Area::AreaControl.OnRender(Surf_Screen, -C_Camera::CameraControl.GetX(), -C_Camera::CameraControl.GetY());

    // Draw entities
    for(unsigned int i = 0;i < C_Entity::EntityList.size();i++)
    {
        if( !C_Entity::EntityList[i] )
        {
            continue;
        }

        C_Entity::EntityList[i]->OnRender( Surf_Screen );
    }

    // Draw overlay tiles

    // Draw UI

    // Update the Surf_Screen surface
    SDL_Flip( Surf_Screen);
}

Would be nice if someone could give a little input. Thanks.


texts: What is an appropriate level of granularity for component-based architecture?

texts:
I'm working on a game with a component-based architecture. An Entity owns a set of Component instances, each of which has a set of Slot instances with which to store, send, and receive values. Factory functions such as Player produce entities with the required components and slot connections.

I'm trying to determine the best level of granularity for components. For example, right now Position, Velocity, and Acceleration are all separate components, connected in series. Velocity and Acceleration could easily be rewritten into a uniform Delta component, or Position, Velocity, and Acceleration could be combined alongside such components as Friction and Gravity into a monolithic Physics component.

Should a component have the smallest responsibility possible (at the cost of lots of interconnectivity) or should related components be combined into monolithic ones (at the cost of flexibility)? I'm leaning toward the former, but I could use a second opinion.


texts: How to sync the actions in a mutiplayer game?

texts: I connect the clients with UDP (its a peer to peer connection on a multicast network) and the clients are sending their positions in every frame (in WP7 it means the default 30 FPS) to each other. This game is kinda a pong game, and my problem is the next: whenever the opponent hits the ball the angle will not be the same on both mobiles. I think its because the latency (1 pixel difference can cause a different angle). So my question is: how can I sync the hitting event?


texts: UV interpolation is wrong with a wide FOV

texts:
How should I take FOV into account when interpolating UV coordinates? This picture shows the result today. Everything works fine with a narrow fov, but when I make it really wide, things deviate. The black line is expected to be straight.
I'm writing a software renderer myself, so I can't just invoke some OpenGL function. Any advice is appreciated.

https://bitbucket.org/jevring/threedee