texts: Processing move between tiles with an animation in isometric map

texts:
In my isometric map, entities can only be in the center of the floor tile.
So it's tile per position.
This is my map with an entity:

(source: gyazo.com)
Entity can either move forward, left, or right.
Where forward is X + 1, left is X - 1, Y - 1, right is X + 1, Y + 1.
I simply can move these entities by doing tile.updateX(1) for forward, etc.
But I want to make an animation for this move, so it can look like this:

(source: gyazo.com)
Can you see how that small shit moving smoothly through the tiles?
I've tried doing it like this:
public void updateShip() {
    this.move = true;
    this.moveX = 2;
    this.moveY = 1;
}

moveX and moveY are the offsets im going to add in the move.
and in the update method:
@Override
public void update() {
    if (move) {
        // Update animation every 17ms
        if (System.currentTimeMillis() - this.moveTime >= 17) {

            // adding relative offsets
            tiles[5][5].relativeX += moveX;
            tiles[5][5].relativeY += moveY;

            // adding moved token
            moved++;

            // timer to move Y coordinate
            if (System.currentTimeMillis() - turnY > 50){
                moveY++;
                turnY = System.currentTimeMillis();
            }

            // timer to move X coordinate
            if (System.currentTimeMillis() - turnX > 125){
                moveX++;
                turnX = System.currentTimeMillis();
            }

            // If moved more than 29 px, cancel animation and locate
            // to the right spot.
            if (moved >= 29) {

                // stops move
                move = false;

                // sets location
                tiles[5][5].updateX(1);
                tiles[5][5].updateY(1);

                // clears relatives offets
                tiles[5][5].relativeX = 0;
                tiles[5][5].relativeY = 0;
            }

            // upadates time
            this.moveTime = System.currentTimeMillis();
        }
    }

In the tile's grapics class, I draw the tiles like this:
public void render(Graphics g) {

    int width = this.getWidth() - offX;
    int height = this.getHeight() + offY;

    int x = (this.x * GRID_WIDTH / 2) - (this.y * GRID_WIDTH / 2) - width / 2;
    int y = (this.x * GRID_HEIGHT / 2) + (this.y * GRID_HEIGHT / 2) - height;

    x += relativeX;
    y += relativeY;

    g.drawImage(this.sprite.getImage(), x, y);
}

Ignore how messy my design is for now, I am just trying to figure out how moving to sides can be animated with a isometric grid.
however, with my method I could animate forward moving, I just keep the moveX to 2, and moveY to 1, and it will always move forward.
But with my code, this is what it does:

(source: gyazo.com)
What am I calculating wrong?
Ignore that fact that I need the sprites of the ship's sides. First I need to test without.
Update I think I did it:
private float moveX = 0.045f;
private float moveY = 0.000f;

@Override
public void update() {
    if (move) {
        Tile tile = tiles[5][5];

        if (moveX > 0.001)
            tile.updateX(moveX);

        if (moveY < 0.045)
        tile.updateY(moveY);

        moveX -= 0.001f;
        moveY += 0.001f;
    }
}

(source: gyazo.com)


texts:
For one of my exams, we have to make an AI for some sandbox survival game.

Well to be exact, we have been given a framework, and need to make a plugin that contains the AI logic.

So far, I already have the movement down, items, enemies, ... (movement uses a navmesh)

This is an image that show how the "world" could look like. (The AI has no way to get the exact layout of the map.)

The AI does have a navmesh, but can only ask for the closest node to a certain vector (so that it can use that node to move to). It starts with nothing, and the world doesn't change once the program starts. However, the pickups respawn (only inside houses) and thus I want to map all the houses. The agent has an FOV (I can't really see how big it is) and items, enemies and houses inside that FOV suddenly reveal all their data (position, size, ...)

However, following the checkpoints is not the most optimal way of exploring the world... The teachers want us to have "smart world exploration logic".
This is the part I am struggling with. Is there some kind of algorithm or logics to exploring this world?

I guess the question I'm asking is "How do I determine the goal to move to, if there's nothing in FOV?"

Maybe there's some "smart" wandering I could do? However, all I know for wandering is ones where it constantly changes its direction withing a certain limit.


texts: Trying to make pitch black night - some meshes still dimly lit

texts:
I have a directional light as a "sun". At night, I need a pitch black scene, but a mesh I'm using as terrain somehow stays faintly lit when the light intensity is 0.

At night:

The direction light "sun" is rotated so it's beneath my world.
The sun light is set to black, intensity to 0
I tried setting fog and ambient light color in RenderSettings to black
I tried setting ambient intensity to 0

Notice how the background is lighter than the character. Something is causing that light to remain.

However, if I enter playmode with the light object inactive, the coloring works fine.


texts: XNA Game arhitecture, sharing vertices between objects

texts:
I'm practicing primitives rendering in XNA and I want to create something like pipe or tunnel.
I have base class called PipeSegment from which I inherit classes like RotatingSegment and NormalSegment (and whatever I imagine).
To combine this segments I have created class called Pipe, which have List of PipeSegment objects.This is what I have so far :

It's ok, except the fact that I'm generating way more vertices than necessary.
For each segment I'm generating 36 vertices for 'front side', and 36 for 'back side'.

Illustration :

Now, my question.
How can I optimize this, how to generate less vertices ?
Is there any way to 'share' vertices between Segments to preserve my current code structure and is my code structure suitable for this ?

Thanks


texts: Swinging a sword in Xcode with Sprite Kit

texts:
I'm working on making an RPG in Xcode, and I'm having a major gameplay issue when it comes to having my character swing his sword in a way that is realistic and gameplay compatible.

Right now, when the player taps the screen and the sword is in one of the player's hand, it rotates the upright sword 90 degrees.  The sword which is a parent of the player floats in front of the player because of a collision issue

I'm looking for any advice anyone can give on how to add a sword to the game and have it swing in a way that looks somewhat realistic and can damage enemies that are more than a single pixel away from the player


texts: Rotating one object to track another in worldspace

texts:
This should be pretty straightforward, but its been awhile and my brain has officially turned off for the holidays :-) To keep things simple, lets assume everything is in 2D space.

I've got a large circle, who's centre will be the origin (0,0).  Now lets say I've got Object A, who is sitting inside this circle at the origin, and is facing a direction (0,1), the positive y direction. Circumference of the circle shouldn't matter for what I'm trying to do.  Now let's say I have two incoming parameters (which I have no control over).  One of these parameters is a rotation (in Radians), and the other is a translation.  If I apply this rotation to Object A while it's in the centre of the circle, followed by the translation, the object will now be on the outside of the circle but its direction will be facing the origin.  In other words, the incoming parameters will translate the object to be outside but facing the centre of the circle, where it was originally inside and facing the positive y direction.

Here's where I'm stuck:  If I also have a random point inside the same circle, and I want Object A to be translated to the exact same position it would normally be translated to (outside the circle) from those two incoming parameters, but facing the direction of this point instead (which could be anywhere inside the circle), what's the most efficient combination of operations to apply to it to accomplish this, assuming object A always starts in the origin, and this is the only information I have (the translation/rotation parameters, and the position of the point I wish to track).  Assume the point can move around anywhere inside the circle, and the object will remain outside in the exact same position but its direction will "track" the point regardless of where it is.

UPDATE for clarification:  Sometimes a picture is worth a thousand words ;-)  See attached image... #1 is where the object starts at.  #2 is what would happen if I apply the incoming translation and rotation parameters.  #3 is what I'm trying to achieve.  I do know that the "random" point is located at (0, 0.5) in this example.  How do I get from #1 to #3 in the least amount of steps.


texts: Tools for editing 2D sprite-based game levels

texts: What are good free and widely used tools for editing 2D sprite-based game levels? I'm looking for one that allows exporting data to a custom format. One that I know of is Blender — a 3D tool, primarily, but can be used for 2D art as well — which also supports Python scripts for exporting data.


texts: Path Finding for an Arena based map in 3D using NavMesh

texts:
I have a 3D arena map (consider a small island surrounded by water on all sides) for a multiplayer Tank fight game.
The moveable areas are marked using a Navigation Mesh made by the Arena designer.

My question is what would be the best way for navigation in such an environment ?
Specially considering the case when there is a Bridge at the center of the arena and you could walk under it or even above it ?

If suppose the enemy is standing at the top of the Bridge and my AI is at one of the edges of the map ? How can it know whether the enemy is above or below the bridge and how can it navigate till it ?


texts: Can the GUI be used to create game objects?

texts:
I want to be able to position 10 various game objects (sprites) within the area of the screen which will be dynamically sized accordingly to the screen size of the device. The area in which I want to position the items will be about 70% of the screen. The objects will be rectangles with irregular size (slightly irregular). The object should be positioned randomly (or in grid) within this area but they should not overlap. The objects will be a drop targets for other object which I will drag onto them.

To summarize I need:

The area in which I can place objects.
Random object position-er.

As I have been reading and watching various tutorials I have become very confused about how should I approach this.

Should I use a Rect to draw the area on which I will then place the objects, or should I use GUI/UI elements i.e. panel? Are the GUI/UI elements suitable for achieving this or are they meant to be only used to create games menus not for actual game play?


texts: LibGDX Scene2D and updating labels inside a table

texts:
I have a (Scene2d) Table containing a Label, both added to a Stage, and I'm properly calling stage.act(float) and stage.draw(). However, if I modify the text of the Label (using setText()) to be wider than the Table, the Table doesn't automatically widen, which I can tell because it's being rendered with a background. This is surprising to me since the setText(CharSequence) method calls invalidateHierarchy(), which I'd assume would be sufficient. I suspect if I were to then call pack() on the Table instance it would be sized correctly, but that seems like a code smell to me. (Calling pack() on the Label itself appears to do nothing.)

Should I be calling pack() on the Table anyway? Or should I be recursing up the parent hierarchy of the Label calling pack() as I go? Or is there some other sane way of handling this...

Thanks!


texts: Inverting the Z coordinate of the light vector

texts:
I noticed that in some vertex shaders they invert the Z coordinate of the light vector, i.e.

// Compute denormalized light vector in world space
float3 vLightWS = g_LightPosition.xyz - vPositionWS.xyz;
// Need to invert Z for correct lighting
vLightWS.z = -vLightWS.z;

Shouldn't be that the light vector starts at the light's position and ends at the vertex position, but in order to use it in the diffuse lighting calculation it is reverted to start at the vertex position and end at the light's position as float3 vLightWS = g_LightPosition.xyz - vPostionWS.xyz suggests?

In this case what is the meaning of the Z coordinate inversion?


texts: Does marking a GameObject as static actually improve performance?

texts: I'm currently working on a small game that will include somewhat large levels. Each level will have a somewhat large amount of GameObjects lying around as props. I was told by a friend of mine that marking the GameObjects that the map is comprised of as static will improve performance. However, I am aware that this can greatly increase the amount of space the built game takes up on the disk. Does the performance boost gained from marking GameObjects as static outweigh the cost of increased build size? Is there even a performance increase at all?


texts: How to store renderer vertex / index data in scene graph objects?

texts:
I have a SceneNode class which contains a Mesh instance. The Mesh class stores client side information such as vertex and index arrays (before they're uploaded to the GPU). I also have an abstracted Renderer class, for GL and D3D, which render the SceneNodes. However, I'm not sure where I should store the API specific variables, e.g. GLuint via glGenBuffers for GL, and an ID3D11Buffer for D3D.

The few options I've considered are:

Create a derived Mesh class for each API, e.g. GLMesh / D3DMesh
Create a derived MeshData class for each API, which is stored in the main Mesh class
Store a map of Mesh to API variables in each renderer, e.g. perform a lookup of Mesh to GLuint / ID3D11Buffer for each object that is rendered (variables would have to be generated after the scene had been updated, but before rendering).
Separate the logic of rendering from scenes, by visiting the SceneGraph after update, and generating a RenderGraph of all renderable nodes in the scene.

What's the recommended way of doing this?


texts: Why is it a bad idea to store methods in Entities and Components? (Along with some other Entity System questions.)

texts:
This is a followup to this question, which I answered, but this one tackles with a much more specific subject.

This answer helped me understand Entity Systems even better than the article.

I've read the (yes, the) article about Entity Systems, and it told me the following:

Entities are just an id and an array of components (the articles says that storing entities in components isn't a good way of doing things, but doesn't provide an alternative).
Components are pieces of data, that indicate what can be done with a certain entity.
Systems are the "methods", they perform manipulation of data on entities.

This seems really practical in many situations, but the part about components being just data classes is bothering me. For example, how could I implement my Vector2D class (Position) in an Entity System?

The Vector2D class holds data: x and y coordinates, but it also has methods, which are crucial to its usefulness and distinguish the class from just a two element array. Example methods are: add(), rotate(point, r, angle), substract(), normalize(), and all other standard, useful, and absolutely needed methods that positions (which are instances of the Vector2D class) should have.

If the component was just a data holder, it wouldn't be able to have these methods!

One solution that could probably pop up would be to implement them inside systems, but that seems very counter-intuitive. These methods are things that I want to perform now, have them be complete and ready to use. I don't want to wait for the MovementSystem to read some expensive set of messages that instruct it to perform a calculation on the position of an entity!

And, the article very clearly states that only systems should have any functionality, and the only explanation for that, which I could find, was "to avoid OOP". First of all, I don't understand why should I refrain from using methods in entities and components. The memory overhead is practically the same, and when coupled with systems these should be very easy to implement and combine in interesting ways. The systems, for example, could only provide basic logic to entities/components, which know the implementation themselves. If you ask me - this is basically taking the goodies from both ES and OOP, something that can't be done according to the author of the article, but to me seems like a good practice.

Think about it this way; there are many different types of drawable objects in a game. Plain old images, animations (update(), getCurrentFrame(), etc), combinations of these primitive types, and all of them could simply provide a draw() method to the render system, which then doesn't need to care about how the sprite of an entity is implemented, only about the interface (draw) and the position. And then, I would only need an animation system which would call animation-specific methods that have nothing to do with the rendering.

And just one other thing... Is there really an alternative to arrays when it comes to storing components? I see no other place for components to be stored other than arrays inside an Entity class...

Maybe, this is a better approach: store components as simple properties of entities. For example, a position component would be glued to entity.position.

The only other way would be to have some kind of a strange lookup table inside systems, that references different entities. But that seems very inefficient and more complicated to develop than simply storing components in the entity.


texts: What's the difference between Raytracing and Physically-based-rendering?

texts:
I know raytracing is a technique based on the route calculation done by the light, following the rays through the interaction with the surfaces, and that Pbr is a collection of render techniques that are more or less based on the theory which matches that of the physical world, aiming to mimic light in a physically plausible way.

Is it possible to implement both into a Rendering engine?
What's the difference?


texts: What are world coordinates and pixel coordinates in LibGDX

texts: I searched the Internet for these two terms, but there is no reference to them. I just started learning LibGDX, so please explain in the simplest way possible


texts: Can SpriteBatch be used to fill a polygon with a texture?

texts: I basically need to fill a texture into a polygon using the SpriteBatch. I've done some research but couldn't find anything useful except polygon triangulation method, which works well only with convex polygons (without diving into super math which is definitely not something I'm pretty good at). Are there any solutions for filling in a polygon in a basic way? I of course need something dynamic (I'll have a map editor that you can define polygons, and the game will render them (and collision detection will also use them but that's off topic), basically I can't accept solutions like "pre-calculated" bitmaps or anything like that. I need to draw a polygon with the segments provided, to the screen, using the SpriteBatch.


texts: Finding a specific point in a graphic model in code

texts:
I'm not really sure what I'm asking, so sorry for the bad title. I'm still new to game programming and especially the "game specific parts" like models and graphics.

Let's say I have a model of a space ship. On this model there's are a couple of locations where I want to place thrusters and there's another spot for a large main thruster. I think I have most of the physics figured out. I can place thrusters at positions relative to the center of mass and the ship behaves appropriately when they're fired. Now, back to the model - how do I place my engines (in the simulation), how to get the relative X, Y and Z values from the model?

Obviously, the naive solution would be to open up the model in a modelling program and find the coordinate where I want the engines to be placed and then put those values in my database. That would mean that every time I change the model or create a new ship I'd need to redo this procedure and handle a lot of values. Surely this can't be how it's done? Is there a way to "mark" a point in a model and find that point from code? Am I missing something obvious?

I'm using C# and XNA, by the way.


texts: Unity 2d text not rendered properly in scene mode

texts:
I am a beginner in Unity and trying to add a text box to my scene. I have done this before and was able to do it properly.

Problem

But recently I created a new project, added a text element to it, but text is not rendered properly in that text box. Anything I type in it is shown as boxes.

Here is the screenshot for it.

While text is shown properly in play mode. I also tried adding custom fonts in it but it didn't made any effect.

What can be the cause for this.


texts: Synchronisation on a non authoritative networked peer to peer scene

texts:
I currently have a piece of coursework that requires 3 or more 3d simulations connected via p2p to maintain a simulation that is visually consistent amoung all peers. A big issue is that I'm not allowed to use any form of authoritative server/peer logic and I'm struggling with potential designs.

The coursework has the following relavant constraints

each peer must be connected at the start and will have the same initial empty simulation
The network will be LAN only
Hardware is consistent in all computers in the network

I'm thinking about implementing it along the lines of

Each peer will regularly create a snapshot of all objects that have moved since the last snapshot
Each peer will maitain a local copy of the snapshot in addition to broadcasting it to all other peers
Each peer will combine the other snapshots possibly via averaging and and adding it to the current local state. I'm thinking I could also possibly use timestamps of each snapshot to weight the combination.
each peer runs their local simulation briefly
then repeat the process

Can anybody see any potential problems with this or recommend anything?


texts: What's a good way to check that a player has clicked on an object in a 3D game?

texts:
I'm programming a 3D game (using C++ and OpenGL), and I have a few 3D objects in the scene, we can say they are boxes for this example. I want to let the player click on those boxes to select them (ie. they might change color) with the typical restriction like if more than one box is located where the user clicked, only the one closest to the camera would get selected.

What would be the best way to do this? The fact that these objects go through several transforms before getting to window coordinates is what makes this a bit tricky.

One approach I thought about was that if the player clicks on the screen, I could normalize the x,y coordinates of mouse click and then transform the bounding box coordinates of the objects into clip-space so that I could compare then to the normalized mouse coordinates. I guess I could then do some sort of ray-box collision test to see if any objects lie as the path of the mouse click. I'm afraid I might be over complicating it. Any better methods out there?


texts: Problem in blitting a clean, crisp sprite

texts:
I am having a bit of a tooling problem...and I am unsure of how to solve it.

I am currently using PyGame to try and write a simple Minesweeper clone, except my sprites that I made are hexagon based and therefore have diagonal lines.

I drew up a nice, clean, crisp vector sprite set which looks very nice in Inkscape, however once I export it everything goes to hell.  I'm going to outline what I've done below and hopefully somebody here can set me straight :D

Disclaimer: Unfortunately I'm behind a proxy and cannot provide screenshots at the moment..I'll do my best to describe.

If I attempt to use a color key (0xFF00FF), then when I set the color key in PyGame I get a bunch of jagged pink edges along my sprite.  I believe this could be an anti-aliasing issue with Inkscape, but unfortunately my Googling didn't turn up a way to disable it.

If I import my PNG into Photoshop or the Gimp and delete the background, then I run into an issue where the background appears to be black when running the game.  I have tried to follow the instructions I saw on SO, but to no avail.

I am open to suggestions, but at this point I'm debating importing another library which can handle SVG graphics, in order to keep my clean, crisp diagonal lines.


texts: Using old planes in video game; copyright?

texts: So i'm developing a small video game for class and for reasons we need to stay away from copyright material. I was wondering if I would have to worry about old WW2 planes being considered copyright material? I could just make some fantasy inspired planes, but i believe having them in the game could be a lot of fun.


texts: Texture not rendering in correct order in xna 4?

texts:
I am making a simple board game. In the game there is a fixed background called myTexture and others are textureGoat and textureTiger whicha are to be placed on top of the background(myTexture). But i am having problem that fourth and fifth component is not displaying however, the sixth component( i.e. myTexture) is appearing. Here is my code, please look at it

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.Green);

        // TODO: Add your drawing code here
        spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);

        //placing tiger
        spriteBatch.Draw(textureTiger, new Rectangle(22, 25, 50, 50), Color.White);//first component
        spriteBatch.Draw(textureTiger, new Rectangle(22, 407, 50, 50), Color.White);//second component

        spriteBatch.Draw(textureTiger, new Rectangle(422, 25, 50, 50), Color.White);//third component
        spriteBatch.Draw(textureTiger, new Rectangle(422, 407, 50, 50), Color.White);//fourth component

        //placing goat
        spriteBatch.Draw(textureGoat, new Rectangle(125, 110, 50, 50), Color.White);//fifth component

        //placing background
        spriteBatch.Draw(myTexture, new Rectangle(0, 0, 500, 500), Color.White);//sixth component

        spriteBatch.End();
        base.Draw(gameTime);
    }


texts:
Consider some time in between two vsyncs. Suppose the first display buffer is being used to display the current image, and suppose the game was really fast and computed and rendered the next image to the second display buffer and the next one after that to the third display buffer. That is the rendering to the second and third display buffer happens so fast that it occurs before the next vsync.

Suppose input from the user comes in now. What you would like is for the results of the input to show up on the next vsync or (probably more typical) the vsync after that. However, with the third display buffer already rendered the input can only effect the image after that. Meaning the input will only take effect at best 3 vsyncs later.

I wish i had an image to show the exact timings of what I mean.


texts: How should I handle quaternion types, in my game engine?

texts:
I've recently been coding a quaternion class, for my game engine, and have run into a problem. Firstly, should I be using unit quaternions for my engine? Secondly, should I have the functions automatically normalise the quaternion, or should I leave it to the user?

What are the benefits and detriments for each of the possible options?


texts: vector rotations for branches of a 3d tree

texts:
I'm attempting to create a 3d tree procedurally.  I'm hoping that someone can check my vector rotation maths, as I'm a bit confused.

I'm using an l-system (a recursive algorithm for generating branches).

The trunk of the tree is the root node.  It's orientation is aligned to the y axis.

In the next iteration of the tree (e.g. the first branches), I might create a branch that is oriented say by +10 degrees in the X axis and a similar amount in the Z axis, relative to the trunk.

I know that I should keep a rotation matrix at each branch, so that it can be applied to child branches, along with any modifications to the child branch.

My questions then:

for the trunk, the rotation matrix - is that just the identity matrix * initial orientation vector ?

for the first branch (and subsequent branches)  - I'll "inherit" the rotation matrix of the parent branch, and apply x and z rotations to that also.

e.g.

using glm::normalize;
using glm::rotateX;
using glm::vec4;
using glm::mat4;
using glm::rotate;

vec4 vYAxis     = vec4(0.0f, 1.0f, 0.0f, 0.0f);
vec4 vInitial   = normalize( rotateX( vYAxis, 10.0f ) );

mat4 mRotation  = mat4(1.0);

// trunk rotation matrix = identity * initial orientation vector
mRotation *= vInitial;

// first branch = parent rotation matrix * this branches rotations
mRotation *= rotate( 10.0f, 1.0f, 0.0f, 0.0f );     // x rotation
mRotation *= rotate( 10.0f, 0.0f, 0.0f, 1.0f );     // z rotation

Are my maths and approach correct, or am I completely wrong?

Finally, I'm using the glm library with OpenGL / C++ for this.  Is the order of x rotation and z rotation important?


texts: Do Apple and Google ask for a share if custom payment is done in a free app?

texts:
I have a multiplatform game (web/iOS/Android) in the making. In the free version the core game is still fully playable but people who choose to pay will get more social features (and no ads, of course).

I was thinking that rather than having a free and a paid version for all the platforms I may release the apps just for free and if the users want more, they have to register and pay a one-time fee (through a payment gateway or PayPal). The extra content would then be available in all the clients they have access to. Theoretically, this means a better value for the players and less maintenance and headache for me (obviously I have to handle all the payment troubles myself).

Does it fit into the business model of Apple/Google? Or will they still claim their share of the registration fee?


texts: Basic 2d platform collision detection algorithm has a slight bug

texts:
I'm trying to implement collision detection between Player (the main character) and a Platform. They are both modelled as rectangles; when player hits the side of a platform he should bounce off it and when player hits the top of a platform he should glide (move) along it. The problem I'm facing is that sometimes the player bounces when he lands on top of the platform (near an edge) rather than glide along it.

For the collision detection, I'm using the Intersector class (LibGDX). If you are unfamiliar with this class, all it does is create the new rectangle that occurs when two rectangles intersect (i.e. the rectangle shaded green below).

Code:

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

    // An object from a list of objects that the player can collide with
    GameObject go1 = list.get(i);

    // True if the object is of type platform
    boolean playerPlatformCollision = (go1.getType() == ObjectType.PLATFORM);

    // If the two objects being compared are Player and Platform
    if (playerPlatformCollision) {
        Rectangle objectRect = go1.getRect();

        // If the Player and Platform overlap
        if (player.getRect().overlaps(objectRect)) {

            // The resulting rectangle from the overlap (as shaded green in the above pic)
            Rectangle intersection = new Rectangle();
            Intersector.intersectRectangles(player.getRect(), objectRect, intersection);

            // If the Player collides with bottom side of platform
            if (intersection.y > player.getRect().y) {
                player.setySpeed(-getySpeed()); // Make him bounce downwards
            }

            // If the Player collides with left side of platform
            if (intersection.x > player.getRect().x) {
                player.bounce(); // Make him bounce
            }

            // If the player collides with the top side of platform
            if (intersection.y + intersection.height
                < player.getRect().y + player.getRect().height)
            {
                player.setGravity(false);
                player.onPlatform(true);
            }
            else {
                player.onPlatform(false);
            }
        }
    }
}

Is there any sort of trick I can use for this? Haven't been able to find anything online that works.


texts: How do I implement collision detection with a sprite walking up a rocky-terrain hill?

texts: I'm working in SDL and have bounding rectangles for collisions set up for each frame of the sprite's animation. However, I recently stumbled upon the issue of putting together collisions for characters walking up and down hills/slopes with irregularly curved or rocky terrain - what's a good way to do collisions for that type of situation? Per-pixel? Loading up the points of the incline and doing player-line collision checking? Should I use bounding rectangles in general or circle collision detection?


texts:
I found an example with strings

...
List<String> inventory = new List<>(skin), sell = new List<>(skin);
inventory.setItems("Axe", "Fuel", "Helmet", "Flux Capacitor", "Shoes", "Hammer", "Trash Can", "The Hitchhiker's Guide To The Galaxy", "Cucumber");

Table table = new Table(skin);

table.add("Inventory");
table.add("Merchant").row();
table.add(inventory).expand().fill();
table.add(sell).expand().fill();
...

result:

https://bitbucket.org/dermetfan/somelibgdxtests/src/d787e98e84647d06ffbe9add3165e87bcabef7e3/core/src/net/dermetfan/someLibgdxTests/screens/DragAndDropTutorial.java?fileviewer=file-view-default

How to replace strings with images?

My code:

...
List<Image> inventory = new List<>(skin), sell = new List<>(skin);
inventory.setItems(Image(texture1), Image(texture2), Image(texture3));
...

Result:


texts: How to change game background image when press button in unity?

texts:
In my game provide two background user can wish to change game background when user press button so how I can do this.

I use a sprite for background.


texts: unity job system for 2d or more dimmension arrays?

texts:
I need to send a 2d array to a job system but execute function of IJobParallelFor just accepts one dimension. This is the example:

public  struct CalculateJob : IJobParallelFor
    {
        public NativeArray<Vector3> vertices;

       public int rows;
       public int x, y;

        public void Execute(int i)
        {

        }
    }


texts: Simplified math formula to calculate stock price based on supply/demand

texts:
I am making an overly simplified version of a stock simulator game, because I:

am fascinated with how the stock market works
learn better & faster from a project like this, rather than text-books

Before writing any actual code, I started making an Excel spreadsheet to simulate the fluctuations of 1 company's stock based on how many people buy/sell the stock on any given day, so that when I have the code, I have something to compare it against to know that it works.

Variables I have access to:

a) Total amount of stock issued - 10000
b) Starting stock price when the company goes public - $10.00
c) Stock available on any given day
d) Stock bought/sold on that day - for example, 150 on day 1
e) Stock bought/sold the previous day - when first starting the simulation, this number is 0
f) Company profits on any given day - For simulation purposes, profits are calculated daily, not quarterly or yearly
g) Stock price - This is what I need calculated

I tried using (d-e)/a which gives me a difference, like 0.015 which I use to get the stock price for the next day.
But it just seems too simple, since buying 100% of the stock on day 1 and then selling 100% of it on day 2, brings down the price to $0.00. Perhaps this would work given enough random participants who all buy/sell the stock, but in this case, I need the simulation to work with just 1 person. And the simple function I wrote just gives too much power to that 1 person.

PS: For simulation purposes, I assume there is always a buyer and always a seller for the stocks.

PPS - Edited to provide the test numbers I'm starting with


texts: Why game roms are lighter than their original version?

texts:
I would like to know if you could help me with this question , I was wondering

Why the rom made of a videogame is ligther than the game itself or an indie game of today? I mean a rom can be 20mb while an indie game can be 200mb! An Snes rom, GBA or even a ds file is lighter than an actual game of today... why is this? why old videogames roms were so ligth but yet finished?

How can I make a game like that: complete but light?
Thank you!


texts: Instantiation of multiple objects with varying velocities

texts:
I am looking to multiple objects of the same prefab at the same time with varying velocities.

public GameObject prefab;
public float xDirection;
public float yDirection;
void Update () {
        GameObject prefab1 = Instantiate
        (prefab,transform.position,quaternarion.identity) as GameObject;
        GetComponent<RigidBody2D>().velocity = new Vector2 (xDirection,yDirection);
}

I want to create three instances at once, but have the x/y direction be different. I am looking at creating an instance at three separate velocities. I know I can do something like this using

void Update () {
if (Input.GetKey(KeyCode.space)){
    xDirection = 1f;
    yDirection = 1f;
    shootObject();
    xDirection = 2f;
    yDirection = 2f;
    shootObject();
    xDirection = 2f;
    yDirection = 2f;
    shootObject();
    }
}
void shootObject () {
    GameObject prefab1 = Instantiate
        (prefab,transform.position,quaternarion.identity) as GameObject;
        GetComponent<RigidBody2D>().velocity = new Vector2 (xDirection,yDirection);
}

but I feel like there is something else that I should be able to do to simplify this even further since this seems to be very messy code.

(I apologize if something seems a little odd. Have only been coding for around a few weeks.)

Thank you for the help!


texts: How to only allow user to rotate a game object clockwise?

texts:
I have a game object which can be rotated by the user:

public class RotatableObject : MonoBehaviour
{
    private void RotateAccordingTo(Hand hand)
    {
        Quaternion desiredRotation = hand.CurrentRotation;
        desiredRotation.y = 0;
        desiredRotation.z = 0;

        this.transform.localRotation = desiredRotation;
    }
}

Right now, the user is able to rotate it both counter-clockwise and clockwise.

I wish to modify the code so that the object does not rotate when the user tries to turn it counter-clockwise. It rotates only if the user is turning it clockwise.

How can I achieve this effect?


texts:
I was reading some SDL2 tutorials and I noticed that you need to pass your window surface handle to any drawRect calls. Should I create a global surface handle or pass the handle by reference into draw functions?

Also for dealing with characters sprites, code structure-wise, which method would be more maintainable: each character object encapsulate its own set of sprites, or have a Sprites class hold all sprite information, and retrieve from there?

Edit: By Jon's advice, I'll probably look at generating one big texture sheet and reading off of that to reduce texturing binding overhead. As for the surface handle, I've created it as a private member variable in my Game class, and will pass it to any Draw calls that need it.


texts: How to assign a button in the main storyboard to launch the GameViewController.swift file

texts: I am quite new to swift and I have constructed a main menu in the main.storyboard file, how do I assign the 'Play Now' button to launch the GameViewController.swift file where I actually plan to program the game.


texts:
It looks like that it's being sampled from the least detailed MIP level, at least RenderDoc sees the texture as it should be, and what the actual texture looks like is the same as MIP 9th. I'm using DirectXTex, so I think the shader resource view should be correct.
    DirectX::ScratchImage* pImageData = new DirectX::ScratchImage();
    LoadFromDDSFile(path.c_str(), DirectX::DDS_FLAGS_NONE, nullptr, *pImageData);
    const DirectX::TexMetadata& textureMetaData = pImageData->GetMetadata();
    const DirectX::Image* image = pImageData->GetImage(0, 0, 0);
    DirectX::CreateShaderResourceView(
        GetDevice(gfx),
        image, textureMetaData.mipLevels,
        textureMetaData,
        &pShaderResourceView);

and the sampler is
    D3D11_SAMPLER_DESC samplerDesc;
    samplerDesc.Filter = D3D11_FILTER_ANISOTROPIC;
    samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
    samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
    samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
    samplerDesc.MipLODBias = 0.0f;
    samplerDesc.MaxAnisotropy = 4;
    samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
    samplerDesc.MinLOD = 0;
    samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;

    DX::ThrowIfFailed(GetDevice(gfx)->CreateSamplerState(&samplerDesc, &pSamplerState));
    pImageData->Release();

then
    GetContext(gfx)->PSSetShaderResources(0u, 1u, &pShaderResourceView);
    GetContext(gfx)->PSSetSamplers(0u, 1u, &pSamplerState);

Input layout might be relevant
    const std::vector<D3D11_INPUT_ELEMENT_DESC> inputElemDesc =
    {
        {"Position", 0u, DXGI_FORMAT_R32G32B32_FLOAT, 0u, D3D11_APPEND_ALIGNED_ELEMENT,
        D3D11_INPUT_PER_VERTEX_DATA, 0u},
        {"TexCoordinate", 0u, DXGI_FORMAT_R32G32_FLOAT, 0u, D3D11_APPEND_ALIGNED_ELEMENT,
        D3D11_INPUT_PER_VERTEX_DATA, 0u},
        {"Normal", 0u, DXGI_FORMAT_R8G8B8A8_UNORM, 0u, D3D11_APPEND_ALIGNED_ELEMENT,
        D3D11_INPUT_PER_VERTEX_DATA, 0u}
    };

Vertex shader
struct VertexIn
{
    float3 position : Position;
    float2 texCoord : TexCoordinate;
    float3 normal : Normal;
};

struct PSstruct
{
    float4 PosH : SV_Position;
    float3 PosW : Position;
    float3 NormalW : Normal;
    float2 Tex : TEXCOORD;
};
PSstruct main(VertexIn vin)
{
    PSstruct vout;

    vout.Tex = vin.texCoord;;
    return vout;
}

pixel shader. I removed light related code, I'm fairly sure that here it's not important. And I temporarily disabled it
Texture2D cubeTexture : register(t0);
SamplerState cubeSample : register(s0);

struct PSstruct
{
    float4 PosH : SV_Position;
    float3 PosW : Position;
    float3 NormalW : Normal;
    float2 tex : TEXCOORD;
};
float4 main(PSstruct pin) : SV_TARGET
{
    float4 texColor = float4(1, 1, 1, 1);
    texColor = cubeTexture.Sample(cubeSample, pin.tex);
    float4 litColor = texColor;
    return litColor;
}


texts: How can I forward GLFW's keyboard input to another object?

texts:
I'm having trouble trying to execute keyboard events in a another class with GLFW3. The problem I'm having is that GLFW3 uses a static function for input as shown:

static UI u;
...
...
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
    u.controls(window, key, action);
}

u is also static and controls holds the the input for WSAD keys (the only way I could get get key events). From here, pressing a key works displaying which key is pressed in the console window. The trouble I'm having is trying to used the key pressed to manipulate a variable in another class.

I have another class called MainMenu that has the function update(). Is there a way I can use my UI class within this function?


texts:
I have hooked Present method of the IDirect3DDevice9 interface, and I want to be able to start video capturing.

Taking a screenshoot like this work

if (GetAsyncKeyState('O') & 1) {
pDevice->CreateOffscreenPlainSurface((rect.right - rect.left),(rect.bottom - rect.top),D3DFMT_A8R8G8B8,D3DPOOL_SYSTEMMEM,&back_buffer, NULL);
pDevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &back_buffer);
D3DXSaveSurfaceToFile(L"C:\\screenshot.bmp", D3DXIFF_BMP, back_buffer, 0, NULL );

IDirect3DSurface9_Release(back_buffer);

}

I seem to fail to lock the surface with 0x8876086C(D3DERR_INVALIDCALL)

HRESULT APIENTRY hook_Present(IDirect3DDevice9* pDevice, const RECT* pSourceRect,const RECT* pDestRect, HWND hDestWindowOverride,const RGNDATA* pDirtyRegion) {
IDirect3DSurface9*back_buffer;
D3DDEVICE_CREATION_PARAMETERS cparams;
RECT rect;
pDevice->GetCreationParameters(&cparams);
GetClientRect(cparams.hFocusWindow, &rect);
if (GetAsyncKeyState('R') & 1) {
    if(dx9Capturing == 0) {
        //Create the AVI file
        // etc code
        dx9Capturing = 1
    }
    else if(dx9Capturing == 1) dx9Capturing = 2; // stop capturing
}

if(dx9Capturing == 1) {
    // Capture the current frame
    pDevice->CreateOffscreenPlainSurface((rect.right - rect.left),(rect.bottom - rect.top),D3DFMT_A8R8G8B8,D3DPOOL_SYSTEMMEM,&back_buffer, NULL);
    pDevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &back_buffer);
    D3DLOCKED_RECT  lockedRect;
    if(FAILED(back_buffer->LockRect(&lockedRect,&rect,D3DLOCK_READONLY))) {
        MessageBoxA(NULL, "Failed locking the back buffer!", "Error", MB_OK);
        return orig_Present(pDevice, pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion);
    }
    for(int i=0;i<rect.bottom;i++)
        {
            memcpy((BYTE*)pBits+(rect.bottom-i-1)*rect.right*BITSPERPIXEL/8,(BYTE*)lockedRect.pBits+i*lockedRect.Pitch,rect.right*BITSPERPIXEL/8);
        }
    back_buffer->UnlockRect();
    pAviFile->AddNewFrame(rect.right,rect.bottom,pBits);
}

return orig_Present(pDevice, pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion);

}

Hooking Reset and I still have the same problem

HRESULT APIENTRY hook_Reset (IDirect3DDevice9* pDevice,D3DPRESENT_PARAMETERS* pPresentationParameters) {
HRESULT hr;
if(pFont) {
    pFont->Release();
}

D3DPRESENT_PARAMETERS d3dpp;
D3DDISPLAYMODE d3ddm;
direct->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &d3ddm );
ZeroMemory( &d3dpp, sizeof(d3dpp));
    d3dpp.Windowed = true;
    d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
    d3dpp.BackBufferFormat = d3ddm.Format;
    d3dpp.Flags =  D3DPRESENTFLAG_LOCKABLE_BACKBUFFER;
hr =  orig_Reset(pDevice, &d3dpp);
return hr;

}


texts: Unity3d : Access the OnClick parameters of Button in a script

texts: I have a button and I have attached another script "PlaySound" for this button, which plays audio on button click. As soon as the audio gets completed, I want to stop the animation which I am triggering here in OnClick of Button. How do I access the Ellen gameObject and 0 parameter which I set in the Inspector window (check the picture) in the PlaySound script


texts: How to know the size of object in Unity in world units?

texts:
Suppose I have some external package with objects. Suppose I place some of these object to the scene. Now how to know actual size of object in world units?

I found no any rulers or something in Unity.

The I thought I can place primitive cube and compare it, but then I realized that I don't know the size of cube too.

Is is possible to "measure" arbitrary object in Unity somehow?


texts: Optimize maximum performance "Frustum.contain ()" on XNA?

texts:
I wonder if it is possible to optimize the performance of "BoundingFrustum" requesting return of the visible elements that are found only on the part of the ground before the player .. Checker and not all over the field unnecessarily?

This picture shows a Region 250X250 or 62,500 cubic! I thought it would be optimized to calculate the "Frustum" in half of the region! 31'250 cubic or less

Here my incomplete function:

foreach (Octree.Node node in regions.Where( /* ? only before the player... */).Where(r => arcadia.camera.Frustum.Contains(r.boundingBox) != ContainmentType.Disjoint))
{

}

Here's a better picture of what I want.

Here is a complete example of the world loaded in my games! Where each region has 62,500 cubic. My problem is that if the player looks towards another region, I have to calculate my "Frustum" in four parts! Or 4 * 62'50 = 250,000 cubic cubes. And every call my function 'update ()'


texts: In trying to get vertex positions on a Blender-generated mesh in Unity, they seem to be badly off?

texts:
I've imported a number of track-terrain pieces into a game I'm working on, and I would like to get the mesh vertex arrays so I can position objects at their exact end. However, when I try to collect the arrays, they're off by a huge amount. A vertex located at the start of the object is 0,-0,-0.01 and a vertex located at the end of the object is.. 1, 0, 0.1. This doesn't seem to make any sense.

These are also -after- the coordinates are transformed into world space.

For a mesh that is 16 meters long and comprised of 70 points, I would expect vertex 65 to be at 3,0,16.

This is the code I am using to collect the information.

CurrentObject = Instantiate(TerrainObjects[0]) as Transform;
meshFilter = CurrentObject.GetComponent<MeshFilter>();
vertices = meshFilter.mesh.vertices;
CurrentObject.transform.parent = gameObject.transform;
//Vector3 EndVectorLocation = transform.InverseTransformDirection(vertices[10]);

Debug.Log(transform.TransformPoint(vertices[10]));

Have I missed something in getting the correct transform positions?


texts: How can I change the acceleration of an object to arrive at a particular time?

texts:
I'm trying to write some code to change an acceleration factor so a ball will arrive at a destination in a desired time.

The problem is I don't know time (t) but I do know I want it to arrive at (t - x) where I can feed the value of x.

The ball has an initial velocity so the equations of motion I imagine to use is:

s = ut + 0.5at^2

I have the distance (s), the starting velocity (u) and the current acceleration (a).

Ultimately, I want to be able to get a new acceleration value (a) that will make the ball arrive, for example, 100ms later than it's intention with the current (a) value.

Any pointers, much appreciated! (I'm using javascript).


texts: Designing AI in a 1 on 1 battle similar to Pokemon

texts:
I am designing a game where the battle system is similar to Pokemon. That is, a 1 on 1 battle with only a few (4-6) moves to choose from.  As the game is taking shape, I'm starting to think about some of the more difficult coding areas such as enemy AI and I have a few questions.  I have already thought about some possibilities for designing the AI and wanted also to hear your feedback.

I am thinking of trying a universal AI for my game where all monsters will utilize the same logic for determining what move they will use.  It will be based around equations/values assigned to each move and determining which is the best to make.  For example, if the monsters move will be resisted (1/2 damage) by the opponent then it receives a lower effective value than the others and moves that do extra damage due to vulnerability will receive higher effective value.  Also, I was thinking of adding a variable that reduces the value if the move has been used repeatedly to avoid the computer always using the same move.  I feel that this is currently limited just to making the computer use the highest damage move.  Any suggestions?

SO for my questions.

How does designing AI logic for each monster/Pokemon vs having a general set of rules for all effect the size of my game in terms of code and effectiveness of the AI?
Are there any resources that discuss designing AI in this manner?  I found very little on the AI in Pokemon games and I'm unsure what other games might be similar in mechanics.

Thanks for your time!


texts: Distributed Rendering in the UDK and Unity

texts:
At the moment I'm looking at getting a game engine to run in a CAVE environment. So far, during my research I've seen a lot of people being able to get both Unity and the Unreal engine up and running in a CAVE (someone did get CryEngine to work in one, but there is little research data about it).

As of yet, I have not cemented my final choice of engine for use in the next stage of my project. I've experience in both, so the learning curve will be gentle on both. And both of the engines offer stereoscopic rendering, either already inbuilt with ReadD (Unreal) or by doing it yourself (Unity). Both can also make use of other input devices as well, such as the kinect or other devices. So again, both engines are still on the table.

For the last bit of my preliminary research, I was advised to see if either, or both engines could do distributed rendering.

I was advised this, as the final game we make could go into a variety of differently sized CAVEs. The one I have access to is roughly 2.4m x 3m cubed, and have been duly informed that this one is a "baby" compared to others.

So, finally onto my question:

Can either the Unreal Engine, or Unity Engine make it possible for developers to allow distributed rendering? Either through in built devices, or by creating my own plugin / script?


texts: Real time shadow casting in a 2D isometric game

texts:
I'm writing a small 2d isometric engine in C++ and I'm trying to implement real time shadow casting. I followed a simple approach described on this page and here is the result (light is located at the same position than the yellow cube):

The result is very nice but there are missing shadows on walls and on the top of cubes. Here is an example of how it should look like (I've draw expected shadows in green):

All the cubes drawn are simply made of 3 2D quads located at a X-Y position and with a Z depth (z = x + y). I use OpenGL with an orthographic matrix (glOrtho). Shadows are drawn using the stencil buffer.

I'm looking for resources or solutions that would help me complete this shadow casting implementation.

Thanks a lot!


texts: How do you import submeshes on a skeletal mesh?

texts:
I'm trying to help out a friend on an Unreal issue.  He has a Unity scene he's trying to convert to run on Unreal, and getting the models right has been a bit of a bumpy road.
Like many models, this has several sub-meshes on it.  Some of them are mutually exclusive and should only have one out of a group of submeshes turned on at once, so that the same basic model can be repurposed as multiple different characters with different base geometry.  In Unity, this "just works."  Import the FBX file and you get a prefab with all of the submeshes as sub-objects, and everyone's happy.
In Unreal, it's a bit more complicated.  A bit of searching came up with this question from 4 years ago, which is exactly the problem I'm having here, and says exactly how to deal with it: unselect the "Combine Meshes" option in the importer.  Except that this model is rigged, and for whatever reason, when you check the "Skeletal Mesh" option in the importer, the Combine Meshes option vanishes and everything gets lumped together in one single blob of mutually exclusive geometry!
I find it difficult to believe this this would work perfectly right out of the box in Unity, while Unreal, which has been around almost a decade longer, has no support at all for such a fundamentally important operation.  But at least at first glance, that appears to be the case.  Are there any more experienced Unreal devs out there who know how to get sub-meshes to import correctly on a skeletal mesh?


texts: How can I "grow" regions representing countries in a 2D grid?

texts:
My friend started to make a 'country-generator' type of thing. We have some starting points, and we want to 'grow' countries from them randomly until the whole area is filled. What's is an effect effective way to create something like this?

This is an image of a desired possible end result:


texts: Function, that is searching for nearest enemy Transform only works sporadically. What am I doing wrong?

texts:
so I am trying to implement a "Zelda"- or "Dark Souls"-like z-targeting system. You'll see in the code, that the function compiles a list of every enemy in the current scene. I'm still in the prototyping phase so the only credential for the targeting is the distance between enemy and player. The script is attached to my player and there are three enemies in the scene.

Now for the problem: The function is not reliable. Sometimes it updates the 'target', sometimes it doesn't. The debug.log fires as expected, only the most important thing appears to zoom in and out. This function is supposed to toggle the lockon as well, which doesn't reliably work either.

Tips on how to make the code lighter are appreciated as well!

Edit: Added the FixedUpdate(), which is a hot mess right now:

void FixedUpdate ()
{

    // Store the input axes.
    h = Input.GetAxisRaw ("Horizontal");
    v = Input.GetAxisRaw ("Vertical");

    stateInfo = anim.GetCurrentAnimatorStateInfo(0); // 0 is for the base layer.
    if (!stateInfo.IsName("Swing")) {
        if( Input.GetButtonDown("Fire1")){
            anim.SetTrigger("isAttacking");
        }
    }

    if (controller.isGrounded) {
        CalcMovement (h, v);
    } else {
        movement.y -= gravity * Time.deltaTime;
    }
    if (Input.GetButtonDown ("Jump")) {
        movement.y = jumpSpeed;
    }
    if (Input.GetButtonDown ("Fire3")) {
        LockOnEnemy ();
    }
    ProcessEvasion ();
    controller.Move(movement * Time.deltaTime);

    Debug.DrawRay(transform.position, -Vector3.up, Color.blue, transform.position.y + 0.1f);

}

void LockOnEnemy()
{
    //we default to check == false
    bool check = false;

    //we will ONLY scan for new targets if current target is null
    if (target == null)
    {
        GameObject[] enemyList = GameObject.FindGameObjectsWithTag("Enemy");
        if (enemyList.Length > 0)
        {
            int enemyID = -1; //default this to 'invalid' value (just good practice!)
            float closestEnemyDistanceSqr = float.MaxValue; //max lockon distance here (use float.MaxValue unless you have a good reason not to!)

            //find closest enemy (only change is I'm looking at squared magnitudes, as they do the job and are more efficient)
            for (int i = 0; i < enemyList.Length; i++)
            {
                float enemyDeltaSqr = (transform.position - enemyList[i].transform.position).sqrMagnitude;
                if (enemyDeltaSqr < closestEnemyDistanceSqr)
                {
                    closestEnemyDistanceSqr = enemyDeltaSqr;
                    enemyID = i;
                }
            }

            //store the target. we can safely assume enemyID is no longer -1, as we know there is at least 1 enemy in enemyList
            target = enemyList[enemyID].transform;
            Debug.Log("Found: Enemy( " + enemyID + ") at " + Mathf.Sqrt(closestEnemyDistanceSqr));
        }

        //now we set check to true regardless of whether we found an enemy - is this what we want
        check = true;
    }

    //if check is false (i.e. we didn't go through the above if statement), we clear 'target'.
    if (check == false)
    {
        this.target = null;
    }
}

Please note: This version of the code has been commented and cleaned up by the user wibble82, over at unity.answers. Unfortunately nobody could really help me there.


texts: Ocean visible through the island's lake in Unity3D?

texts:
I'm working on a puzzle game featuring islands: there is a plane with a water shader, and objects colliding with that plane.

Now I'd like to make lakes on the islands, with different (higher) water levels than the ocean's.

The problem is that if I put a water plane in a "hole", I can see the ocean below at best, or even worse, the upper water surface just glitches out and disappear.

One option is that I move the lake's basin higher than the ocean's see level. This works, but I it doesn't look so good, because the lake becomes too shallow.

Another option is that I cut holes in the ocean's plane, but that seems a bit overengineered, isn't it?

Is there a better solution?

Also having a water plane for every "lake tile" causes some problems:

but I want to have dynamic lakes, so having a 2x2 water plane for a 2x2 group of lake tiles isn't a walkable path.


texts: How can I implement a percentage chance to perform some action?

texts: Let's say that there is an X% chance that a character will shoot a target, or some other action. How do I determine if the action should be taken or not (how do I implement the percentage chance)?


texts:
I need to render two shapes with opengl (let's say a cube and a triangular prism) and one of them has texture and the other one has lightning fx. The thing I want to do is first draw texture and lightning and then render the shapes. I made a research, the only thing I could find is this is called gpu batching. Do you have any ideas or any tutorials etc. about this subject? How can I do this?

Edit: This video explains what I want to do:
Crysis 2 - Rendering Pipeline

Edit: I heard that it is not possible for gpu to render different fxs for different geometries back to back. So I need to group geometries by fxs.(Cube has texture put it in the texture array, prism has lightning put it in the lightning array...then loop these arrays and render the scene) My aim is to first render fxs and then render geometries to render the whole scene.


texts: How can I check if component is enabled?

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

public class CameraInformation : MonoBehaviour
{
    public string currentCameraState;

    // Start is called before the first frame update
    void Start()
    {
        var components = new List<Component>();
        foreach (var component in GetComponents<Component>())
        {
            if (component != this)
            {
                var fullName = component.GetType().FullName;
                if (fullName.StartsWith("Cinemachine"))
                {
                    currentCameraState = component.
                }
            }
        }
    }

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

    }

    private void OnEnable()
    {

    }

    private void OnDisable()
    {

    }
}

At this line I want to assign the string the component status if it's enabled true or false.


texts: In Unity - displaying long lists of information to screen? Tables?

texts:
Hello folks I'm making a little game for fun in unity, Its a boxing management sim. I've got the code done to create boxers and give them many properties such as names, weights, stats, etc.
I've made another screen , lets call it 'office screen' for now. In that I want to open a panel which will show all the boxers in the game (ideally I'd like to be able to make the player be able to filter these results by which company he's signed to etc - but I think that might be out of my skill range so maybe i will just make a separate screen for Owned Boxers)

But I cannot seem to find a way to display all these infos in a table with columns such as Name ; Age ; Company ; etc;

I have had a go just using the UI Text components and panels. But thing is, there will be approx 100 boxers or more and this number will always change also.

Any ideas for this in Unity specifically?

EDIT: I am storing all the data just as variables (i think fields) in a class called Boxer which is assigned as a component of a new GameObject i instantiate at the time each boxer is created. So each boxer has its own gameobject.

EDIT 2 :D i've found this: https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/models-data/displaying-a-table-of-database-data-cs
would this be the sort of thing I can add to Unity (assuming I can follow along with the guide)?

Thanks for any help


texts: How can I draw a linerenderer line between two vector3 positions using the mouse left button click?

texts:
This code is drawing a line but it's not drawing it on the camera in front of the camera.

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

public class DemoScriptDraw : MonoBehaviour
{
    private List<Vector3> _positions = new List<Vector3>();
    private LineRenderer lr;

    private void Start()
    {
        lr = this.GetComponent<LineRenderer>();
    }

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Vector3 pos = Input.mousePosition;
            pos = Camera.main.ScreenToWorldPoint(new Vector3(pos.x, pos.y, lr.transform.position.z));
            _positions.Add(pos);

            if (_positions.Count == 2)
            {
                SpawnLineGenerator(_positions[0], _positions[1], Color.red);
            }
        }
    }

    void SpawnLineGenerator(Vector3 start, Vector3 end, Color color)
    {
        GameObject myLine = new GameObject();

        myLine.AddComponent<LineRenderer>();
        myLine.AddComponent<EndHolder>();
        LineRenderer lr = myLine.GetComponent<LineRenderer>();
        lr.material = new Material(Shader.Find("Particles/Alpha Blended Premultiply"));
        lr.startColor = color;
        lr.useWorldSpace = true;
        lr.endColor = color;
        lr.startWidth = 0.1f;//0.03f;
        lr.endWidth = 0.1f;//0.03f;
        lr.SetPosition(0, start);
        lr.SetPosition(1, end);
    }
}

The result is that the line is seen in the scene view window but not in the game view window:


texts: I'm currently using 800x480 resolution and FitViewPort and I divided that by PixelPerMeter variable which is equal to 10 and that helped to move my box2d body faster. But when I tried to use fonts I could easily see pixels. What am I doing wrong and what can I do to fix that ?


texts: Are there official button images for the xbox controller that I can get for free?

texts: If you want to support xbox controllers, it is always wise to use the native images that the controller uses. Can one obtain those from Microsoft without being a registered, aka paying developer?


texts: I'm making a tile based game, and I'm working for support of tilesets. I'm trying to make it so that a Texture2D is set as a chosen PNG file. I can do this with no problem f I load the image into the content pipeline, but the level editor will be used by people without access to the content pipeline. How do I go about doing this?


texts: common math algorithms that aren't physics/object based

texts:
I'm starting to customize my game a lot more beyond just the engine and I'm curious what sorts of algorithms and concepts exist. There are a ton of solutions for physics and geometry-like questions, but I'm curious apart from that what is the most common. I know of things like LERP, etc. What else do you find most useful?
Thanks,


texts: Transparent JPanel, Canvas background in JFrame

texts:
I wanna make canvas background and add some elements on top of it. For this goal I made JPanel as transparent container with setOpaque(false) and added it as first of JFrame container, then I added canvas with black background (in future I wanna set animation) to JFrame as second element.

But I can't undestand why i see grey background, not a black.
Any suggestions?

public class Game extends JFrame {
    public Container container; //Game container with components
    public Canvas backgroundLayer; //Background layer of a game
    public JPanel elementsLayer; //elements panel (top of backgroundLayer), holds different elements

    private Dimension startGameDimension = new Dimension(800,600); //start game dimension

    public Game() {
        //init main window
        super("Astra LaserForces");
        setSize(startGameDimension);
        setBackground(Color.CYAN);
        container=getContentPane();
        container.setLayout(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //init jpanel elements layer
        elementsLayer=new JPanel();
        elementsLayer.setSize(startGameDimension);
        elementsLayer.setBackground(Color.BLUE);
        elementsLayer.setOpaque(false);
        container.add(elementsLayer);

        //init canvas background layer
        backgroundLayer = new Canvas();
        backgroundLayer.setSize(startGameDimension);
        backgroundLayer.setBackground(Color.BLACK); //set default black color
        container.add(backgroundLayer);

    }

    //start game
    public void start() {
        setVisible(true);

    }

    //create new instance of game and start it
    public static void main(String[] args) {
        new Game().start();
    }
}


texts: Transferring my OpenGL PC game to PS4 and/or XBox One

texts:
I want to transfer my OpenGL PC game to consoles, PS4 and/or XBox One.

It's a complex application, where many calculations (incl. fast fourier transformations) via FBOs and Transformfeedback are performed within OpenGL. What is the best way to bring it to the PS4?

Or is it easier to implement the game in an engine like Unity or Unreal. As far as I know they have console support? An advantage would be that we could offer our methods as plugin/asset. We are planning to do this too.

There are a lot of glsl-shaders and OpenGL-Api-Calls. Is it possible at all to "translate" that into an engine like unreal? Or would we have to use the engines "predefined" rendnering mechanisms? We basically need shaders operating on floating point textures, changing render targets frequently and transform feedback if possible. We also need low level acces to shading attributes like changing pointsize in the vertex shader etc.

And I really would like to know which is less work. I could image that it is possible to absctract all the Api-Calls in classes/functions and then where first all the OpenGL-calls are implemted and then we would do an implemetation for the console api. Is this realistic on the PS4 Api?

I know that Direct X will have a different design and therefore abstraction itself won't be enough. I believe porting to an engine might be even more work as you have to respect its structures.


texts: How can I divide tile-based space into largest the possible squares?

texts: I'm trying to find a way to take a tilemap like the top image and divide it into square spaces like the colored areas in the second image.


texts: HTML5 realtime MMO games, should I do server side physics update or client side?

texts: I am using socket.io and HTML 5 canvas to build a MMO game as a practice. I finished the client side first and currently I am working on server side. Apparently the position/physics update is on client side for now. But I am facing the decision of moving the position update logic and physics update to the server or leaving them on the client side. If I put the update on the server side I will pass the mousemove/keystrokes to the server. But if I update positions only on clients side I will pass the positinos/directions/speed to the server. Which approach is better in my case?


texts: What are some standard mathematical tests for projection matrices?

texts:
I'm trying to double check my math in my projection matrices.  I'm thinking about "unit tests" when I ask this.  I'm looking for 4 or 5 unit tests that would be appropriate to give one confidence that the projections are correct.

This is a little more than an obvious question.  Let me explain...  When I did this with a quaternion, the potential tests were very logical.  The perspective transforms by comparison are somewhat non-intuitive.  For a quaternion, if I start with the unit Y vector {0.0, 1.0, 0.0} and I rotate it a quarter turn about the x-axis, I know that the answer is the unit vector in the negative z direction.  It's a logical answer.  Is there something equally logical/obvious for orthographic and perspective projections?

I've gone through many math books and many tutorials over the years.  I'd like to once and for all "prove" that my ortho and perspective matrices are always projecting correctly.

If I composed an ortho matrix using left, right, bottom, top, near, far as follows:

              0.0f, 1.0f,
              0.0f, 1.0f,
              0.0f, 1.0f

I might get the following matrix (right-handed / OpenGL style)

  2.000000,   0.000000,   0.000000,  -1.000000
  0.000000,   2.000000,   0.000000,  -1.000000
  0.000000,   0.000000,  -2.000000,  -1.000000
  0.000000,   0.000000,   0.000000,   1.000000

I'd like to know if that matrix is computed correctly.

Then for a test, I'd multiply a vertex such as {1.0f, 1.0f, 0.0f} against the matrix and get back {1.0f, 1.0f, -1.0f}.  Is it correct?  ...and I'd like to do that on several standard points.

I'm having trouble visualizing "standard" or "logical" tests for this.  Something that at a glance, just makes sense.  (like the quaternion example above)


texts: How to write shaders that can be compiled for DirectX, OpenGL, and Vulkan

texts:
I recently finished writing the DirectX renderer for my game engine.
Now I have an OpenGL, DirectX as well as a not yet finished Vulkan renderer.
Well, the majority of the renderers work perfectly now but I have a problem: I need a shader programming language.
The problem is that OpenGL and Vulkan use GLSL but DirectX uses HLSL (and Apple's Metal API uses MSL). So I searched for a High Level Shader Language and found only C for graphics from NVIDIA. But since this project was deprecated I looked for something else: Without success.
It's a bit annoying to write for 3 shader programming languages at the same time, so I'm looking for a language that can be translated into the native language immediately when the game starts (or is simply compatible with a lot of rendering APIs)
After several weeks of finding nothing, I decided to write my own language for it. But before I invest too much time I want to know if there is another solution to this problem.


texts:
I'm converting view coordinates to texture coordinates for both my shadow maps and Screen space reflections.
I keep seeing this conversion in examples:

            var T = new Matrix
            {
                M11 = 0.5f,
                M22 = -0.5f,
                M33 = 1.0f,
                M41 = 0.5f,
                M42 = 0.5f,
                M44 = 1.0f
            };

            Matrix m = view * projection * T;

What is T and why does this "work"? I'm saying "work" because I not satisfied with the result but the problem may not lie here.

I would like to use and inverted view and projection and then adjust the coordinates from -1,1 to 0,1. But that doesn't work at all.
What have I misunderstood?


texts:
I have a problem with my Ortho Matrix. The engine uses the perspective projection fine but for some reason the Ortho matrix is messed up. (See screenshots below).

Can anyone understand what is happening here?

At the min I am taking the Projection matrix * Transform (Translate, rotate, scale) and passing to the Vertex shader to multiply the Vertices by it.

VIDEO Shows the same scene, rotating on the Y axis.
http://youtu.be/2feiZAIM9Y0

 void Matrix4f::InitOrthoProjTransform(float left, float right, float top, float bottom, float zNear, float zFar)
{
    m[0][0] = 2 / (right - left);
    m[0][1] = 0;
    m[0][2] = 0;
    m[0][3] = 0;

    m[1][0] = 0;
    m[1][1] = 2 / (top - bottom);
    m[1][2] = 0;
    m[1][3] = 0;

    m[2][0] = 0;
    m[2][1] = 0;
    m[2][2] = -1 / (zFar - zNear);
    m[2][3] = 0;

    m[3][0] = -(right + left) / (right - left);
    m[3][1] = -(top + bottom) / (top - bottom);
    m[3][2] = -zNear / (zFar - zNear);
    m[3][3] = 1;
}

This is what happens with Ortho Matrix:

This is the Perspective Matrix:


texts: How to transform a subset of a vertex in a vertex buffer?

texts:
float linePos[6]={0.0f,5.0f,0.0f,0.0f,30.0f,0.0f};
...

glGenBuffers(1, &buffer);
glBindBuffer(GL_ARRAY_BUFFER, buffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(float)*3*2, linePos, GL_STATIC_DRAW);

...
glUniformMatrix4fv(UniformColor.modelToWorldMatrixUnif, 1, GL_FALSE, glm::value_ptr(modelMatrix.Top()));
//this just transforms all vertices

glLineWidth(3);
glDrawArrays(GL_LINES,0,2);

I want to make some animation changing the position (ex.translate) of one end the line(linePos[0]) but not the other. How can I do that?


texts: What's a good entity hierarchy for a 2D game?

texts:
I'm in the process of building a new 2D game out of some code I wrote a while ago.

The object hierarchy for entities is like this:

Scene (e.g. MainMenu): Contains multiple entities and delegates update()/draw() to each
Entity: Base class for all things in a scene (e.g. MenuItem or Alien)
Sprite: Base class for all entities that just draw a texture, i.e. don't have their own drawing logic

Does it make sense to split up entities and sprites up like that? I think in a 2D game, the terms entity and sprite are somewhat synonymous, right?

But I do believe that I need some base class for entities that just draw a texture, as opposed to drawing themselves, to avoid duplication. Most entities are like that.

One weird case is my Text class: It derives from Sprite, which accepts either the path of an image or an already loaded texture in its constructor. Text loads a texture in its constructor and passes that to Sprite.

Can you outline a design that makes more sense? Or point me to a good object-oriented reference code base for a 2D game? I could only find 3D engine code bases of decent code quality, e.g. Doom 3 and HPL1Engine.


texts: I'm not quite sure what I need to do, but I have a ball falling from the sky and it needs to bounce when it hits an object. Do I configure the ball in some way or do I need to setup a spring object or possibly do something on collision?


texts: How to link OpenGL with my own static library?

texts:
My game project is split up into three parts:

Core (lib)
Editor (exe)
Game (exe)

I'm using OpenGL in both my Core and Game parts, but as soon as I try to call an OpenGL function in my Core library the application crashes.  I assume this is because the static library is not being linked with OpenGL.  The build process goes like this:

# core library
g++  -c  ... -std=c++0x -g  -o ... -I. -I.
ar rcus libCore.a ...

# game exe
g++ -o Game ... -L. -L../Core/Debug/   -lCore -lglew32 -lglfw -lopengl32

Where ... stands for the various files.  How can I link OpenGL with my static library?


texts: How to connect a skeleton to an animator at the parent

texts:
I have two different meshes with similar armatures. And the parent contains the Animator Component with a universal avatar and animation controller.
The animations doesn't apply when the bones are not the imminent child of the Animator. Is there a way to get this working?


texts: Unity2D: Scaling and Locking Image to anchor points

texts:
I have a script that uses Index to change an objects sprite using OnClick to move through the sprites, like a slideshow. I want the image to scale to the size of my anchor points, because I've notice that when I stretch the game or put the game on maximize play the image stays the same size and doesn't scale to the size of my anchor points. How would I do that?
This is my script:

public Sprite[] Images;
//Index starts at one because we are setting the first sprite in Start() method
public int _Index = 1;

void Start(){
    //Set the image to the first one
    this.gameObject.GetComponent<SpriteRenderer>().sprite = Images[0];
}

public void onClick(){
    //Reset back to 0 so it can loop again if the last sprite has been shown
    if (_Index >= Images.Length)
        _Index = 0;

    //Set the image to array at element index, then increment
    this.gameObject.GetComponent<SpriteRenderer>().sprite = Images[_Index++];
}

Thank you. :)


texts: How to make 2D water like in this video?

texts:
I wanna make water and waves for my little 2D PC game like in this video:
http://www.youtube.com/watch?v=ooU6cTeirlQ
I don't know how to write a similar shader. Does anybody know how to write a similar shader?
Or is it possible to do the waves without shaders?


texts: Making AI follow player in pacman game with grid

texts:
I have an AI that I want to navigate a maze in order to follow the player. I thought of creating a large grid with the help of FloatRects, so I do it like this:

private List<FloatRect> grid;
//...
for(int y = 0; y < screenHeight; y += 16)
{
    for(int x = 0; x < screenWidth; x += 16)
    {
        grid.Add(new FloatRect(x, y, 16, 16));
    }
}

making each rectangle 16x16. Now I want to make the AI find the path that crosses the least amount of rectangles in order to cross the player, while avoiding walls. How do I approach this?


texts:
I am attempting to make a map editor for my game, just so I can visualize how the end result would be.

To my world I can add cubes (2 triangles) or corners (1 triangle), which are then added to a list of the vertices to draw, and the indices are added to a list of indices. Everything draws fine here, and I can set different colours for each vertex.

I would like to implement texturing, so that when you add a primitive to the scene it will let you choose a texture (that, I can handle), but then also blend with other primitive's of different textures if they are touching (everything is on a grid).

I would guess that I would have to store the texture name for each primitive, and somehow set that texture when drawing it. But I fail to see how you can set the effects texture when you are using one DrawUserIndexedPrimitives<> to draw the entire scene.

If anyone has a work around for this, or ideas on other ways of doing this, you help would be greatly appreciated.

Edit 1

I have incorporated the technique from this website here - http://toyfactorygame.com/wp.php/2010/05/06/simple-fast-gpu-driven-multi-textured-terrain/ (similar to Blau's answer below), and have the current working result...

Which maps to this...

Using each color channel as a texture..

Output = tex2D(TextureSampler0, input.TexCoords) * input.Color.r;
Output += tex2D(TextureSampler1, input.TexCoords) * input.Color.g;
Output += tex2D(TextureSampler2, input.TexCoords) * input.Color.b;
Output += tex2D(TextureSampler3, input.TexCoords) * input.Color.a;

But doing it this way means I can only be setting 4 textures to blend together each DrawPrimitives call.

Is there another way I can achieve multi texturing with more than 4 (preferably unlimited) textures? I know this is possible, as games like C&C generals allow you to set textures anywhere you want on the map.

Thanks.

Twitchy


texts:
Shimmering

I understand shimmering in textures is caused by sub-pixel accuracy aliasing against the regular grid of pixels on the screen when drawn.  I have a good example of it here, whereby I'm attempting to scroll/pan a 2d texture by modifying the texture coordinates rather than by moving some actual geometry.  The texture is "wrapped" and my idea was to fill in the bit falling off the left (or right), filling it in on the other side, to effect a single scrolling/panning surface of (almost) infinite size.

Unfortunately with random noise on the texture, when I'm zoomed all the way out the shimmering is kind-of horrific.  When I zoom in a bit it seems OK, which is kind-of confusing to me.

But anyway, is there a filter of some kind I can put into my shader to prevent this shimmering?  I'm at something of a loss here.

(To complicate matters my texture is actually just L16 luminance and I'm palettising it in the shader - the L16 is sampled with LINEAR, the palette texture is POINT, though I'm pretty sure this makes little difference to the shimmering).

Please note that with the video, YouTube has done its absolute best to remove any detail from it, meaning it's difficult to see the shimmer under the encoding artifacts.


texts:
I am trying to "muffle" the sounds that are being played in my game and the best way I can think of doing this, is by lowering the treble of the sound.

I have looked through all the members of the Song / SoundEffect / SoundEffectInstance classes and I cannot find a way to alter the sounds.

How can I accomplish this?


texts:
I have the following code that generates game objects, in my game. The problem with it is that some game objects are out of the terrain area. I want to place them at random, but also make sure they will be inside the terrain area.

I know that I get the terrain size with terrain.terrainData.size, but I'm not sure how to use it. How do I create random game objects on a terrain, but only inside the terrain area?

Here is my current script:

using UnityEngine;

public class Teleport : MonoBehaviour
{
    public Vector3 terrainArea;
    public float spinSpeed = 2.0f;
    public int cloneTeleportations;
    public GameObject prefab;

    private bool rotate = false;
    private bool exited = false;
    private Transform[] teleportations;
    private Random rnd = new Random();

    private void Start()
    {
        GameObject go = GameObject.Find("Terrain");
        Terrain terrain = go.GetComponent(Terrain);
        terrainArea = terrain.terrainData.size;

        for (int i = 0; i < cloneTeleportations; i++)
        {
            GameObject Teleportaion = Instantiate(prefab,
                new Vector3(Random.Range(i * 10.0F, i * 50.0F), 0,
                Random.Range(i * 10.0F, i * 50.0F)), Quaternion.identity);
            Teleportaion.transform.parent = this.transform;
            Teleportaion.transform.tag = "Teleportation";
        }
    }
}


texts: What is road map for Windows 3D game development in C#

texts:
I used WPF 3D to make a demo program a while ago. I'm now want to give some other things a shot but find working in WPF 3D ... confining. I have looked at Managed Direct3D but read that it's dead. I have looked at wrappers for OpenGL but they seem to be work in progress or documentation/tutorial sparse. XNA seems like a decent platform but I have a feeling there is something better.

Does anyone know of a road map for C# 3D game development on Windows platform?


texts: How should I implement card effects in a card game?

texts:
I've been trying to program a video game adaptation of the popular trading card game "Magic: The Gathering". If you've played MTG before, you'll know most cards have an effect, which is activated at a certain time, usually when it's played. But I'm unsure how to implement effects into my game.

I'm thinking of creating a method that assigns a card its effect when it's played based on the card's name, but that doesn't really work when a card's effect isn't supposed to be activated when it's played, like in the case of Deathrattle cards, or when it's a continuous effect. I've thought of creating a thread for each effect which activates it whenever needed, but... that's a LOT of unique threads. I haven't found any similar java programs anywhere, so I wanna ask here. How do you think card effects should be handled?


texts: How do I save a procedurally-generated map as binary level-data in C++?

texts:
For example, I'd like to do something as simple as a generating an array matrix using Conway's Game of Life and then filling each cell with particular data to be saved to a binary file.

Additionally, how do I load the binary level-data?  :)


texts: Your recommendation for path construction from a single background image?

texts: So I currently have my background as a single PNG and some obstacles (like blocks as part of that PNG). In order to create a path, I currently store pixels above a unique green color (my hill) and use this to move the character. My question is, is it better to create something like a collision layer mask or somehow convert my PNG to a bunch of tiles? Is this possible?


texts: How do I animate a custom ability with a continuous beam in Starcraft 2?

texts: I'm building an ability that drains energy from the target unit and gives it to caster unit.  I've tried to associate an actor that hooks in to the ability's start event to create the continuous beam, but the beam never appears.  What's the right way to do this?


texts: What is a fast way to darken the vertices I'm rendering?

texts:
To make a lighting system for a voxel game, I need to specify a darkness value per vertex. I'm using GL_COLOR_MATERIAL and specifying a color per vertex, like this:

glEnable(GL_COLOR_MATERIAL);

glBegin(GL_QUADS);

glColor3f(0.6f, 0.6f, 0.6f);
glTexCoord2f(...);
glVertex3f(...);

glColor3f(0.3f, 0.3f, 0.3f);
glTexCoord2f(...);
glVertex3f(...);

glColor3f(0.7f, 0.7f, 0.7f);
glTexCoord2f(...);
glVertex3f(...);

glColor3f(0.9f, 0.9f, 0.9f);
glTexCoord2f(...);
glVertex3f(...);

glEnd();

This is working, but with many quads it is very slow.. I'm using display lists too. Any good ideas in how to make vertices darker?


texts: Creating a card dangling affect using 2d sprites

texts:
I'm working on a 2d card game for iOS and using Cocos2d. When a player picks up a card and drags it I would like to make it appear that the card is lifted off the table and dangling just below their finger. So when they move their figure the card is slightly delayed an looks like its being dragged in a fluid animation. When the player stops moving the card sort of bounces or sways for a second.

I've been trying to find someplace that does this but I can't come up with anything so I'm wondering is it even possible in a 2d environment? How would I go about doing this, answers can be abstract, i.e. not cocos2d.

Thanks,


texts: Do you prototype mobile touch games on the desktop with mouse input? What tricks do you use?

texts:
So I've been prototyping games that if completed would be mobile apps most likely.

But, I'm developing them in XNA on the desktop because its the environment I like the most.

I know I could target windows phone and be testing the touch interface rapidly on that device but I don't own one and I imagine the build and deploy to the phone loop slows you down a bit.

Does anyone else prototype games that would eventually use a touch interface using mouse controls initially?

What tricks do you use to ensure that it will eventually translate well when you move to touch controls?


texts: GetComponentsInChildren().text - does not contain a definition

texts:
My Slider GameObject has a GUIText child. I am writing a C# script that should change the text component in the GUIText, but instead of this I am getting:

error CS1061: Type UnityEngine.GUIText[]' does not contain a definition fortext' and no extension method text' of typeUnityEngine.GUIText[]' could be found (are you missing a using directive or an assembly reference?)

 public Slider timeSlider;
 int i = 5;

 timeSlider.GetComponentsInChildren<GUIText>().text = 'Some Text' + i;
 //timeSlider.transform.GetComponentsInChildren<GUIText>().text = 'Some Text' + i; // doesn't work either

From the documentation I understand that GUIText should have a 'text' variable - Would anyone know why ().text is invalid?

Thank you!

How the hierachy is:


texts: What is the cleanest way to code predictable client/server components

texts:
Lots of classic games that I've read the source code to do things like

if (clientside)
    // ...

or the same but with serverside. The code is littered with this and it becomes an extreme nightmare to test. This is especially so when the games I've looked at all happen to use global variables for the above so testing goes out the window, and I am fortunate enough to be able to write tests for such things (hobby projects with no time constraints!)

I'm at a point where I need to care about this now (especially with having to deal with prediction and actions, scripts, etc, in a level). As such, I've gone searching for how people architected solutions to this problem such that there was the ability to have clientside prediction of some stuff, while preventing the code from becoming a gigantic series of if statements strewn about everywhere.

What is the best way to approach this? I am willing to trade a bit speed for clean code with good OOP. Is there a good example that I can learn from? Or am I stuck with littering if (client/serverside) everywhere?

Ideally I want to write the least code possible, write it in the cleanest way possible, and have something that I can easily reason about without having a ton of branching thinking "ok what if condition A, not B, C and D, not E" when trying to figure something out.

I've been trying to see if there's a way to make some kind of common base class which shares all the code between them, and then making a bunch of abstract methods that either the Client implementation or Server implementation would do their own stuff on top of it, but part of me is worried that because I've neither done anything like this before nor seen anyone ever do it this way, I'm scared of wasting a significant amount of time on something that may be architecturally bad. This is primarily why I'm posting this.

In short: What is the cleanest way to architect the code? Are there any examples or articles I can learn from?

Edit: The code should all be in one binary, so people can host a multiplayer server from an offline experience.

Note: This question is completely different from how to do prediction, unlagged, etc, and as such is not about that (and I already know exactly what I need to do). It's about the implementation of such things such that I can write a client that supports predicting and server code that reduces the amount of duplication as much as possible.


texts: Can someone explain Flappy Bird's physics to me?

texts:
I am having a difficult time trying to understand the Flappy Bird physics. I know it seems simple but I kind of suck at math. I am trying to see if I can make a simple game like this but it is just the dang physics that are throwing me off. I have something like gravity effecting the bird but when you click the screen and I add some amount to the y position but it doesn't look good. You guys have any ideas?

Stuff like:

velocity += -9.8 * Gdx.graphics.getDeltaTime();
position.y += 0.5 * velocity;

That is falling but when I tap the device I would like to know how to add upward force but when it loses it continue falling.


texts: Milkshape3D Animation on Windows 7 64-bit

texts:
when I run Milkshape 3D on my 64-bit Windows 7 machine, certain joints expand when I try to rotate them.

For example, my model's leg has hip, knee, foot and toe joints. So to do a walking animation I would rotate the hip joint, then rotate the knee joint. Then as soon as I start rotating the foot, the foot joint moves away from the knee rather than just rotating around the axis.

These images show what I'm talking about:

I've tried to run Milkshape in comaptibility mode and with the Mesa software OpenGL renderer, but it doesn't work. At the moment my workaround is to run Milkshape in a 32-bit Windows XP virtual machine.

Does anyone know what causes it and how to solve it?


texts: I found this article on implementing an input pipeline for Android, but I don't really understand how it works. I also don't completely understand the programming concept of a pipeline or a pool either. Could someone explain these concepts and how they work as this input pipeline?


texts:
I've made a game where you can shoot some cans, but I want to add an effect when a can is shot. You know, a kind of explosion or something like that. The way the game works now is: when the can is shot it disappears destroy(gameobject), but I want to add an effect before it disappears. Any suggestions? I want to keep it simple. The effect has to be in within the same method where I destroy the cans.

   public void Shot()
{
    //Effect should be here
    Destroy(gameObject);
}


texts: Which 3D file format should my engine use if I don't want to have to change it later?

texts:
Is there a de facto format for exporting a 3D model from modeling software to a game engine?

I know it varies by engine and situation, but what is the general idea that comes to a skilled game developers mind when this question comes up?

In my mind obj format comes up, but it doesn't support animation.

So, what could be the best format which supports/covers more or less every feature that an modern engine can cover? FBX? Collada?

Some professional insight would help.


texts:
I'm looking for good sources to outsource virtually every aspect of an iPhone game:

Writing
Graphics
Programming

I have a good amount of programming experience so putting everything together should not be a problem.

What are some reputable sources for outsourcing this kind of development?
Is it feasible to approach game development from this angle?


texts: Why does my health bar disappear whenever my character takes damage?

texts:
I'm making a health bar for my game that looks like this:

public void healthBar(Canvas canvas)
{
    float healthScale = happy.getHP() / happy.getMaxHP();
    Rect rect = new Rect(20, 20,(120 * (int)healthScale), 40);
    Paint paint = new Paint();
    paint.setColor(Color.RED);
    canvas.drawRect(20, 20, 220 * healthScale, 40, paint);
}

This is called every time my game renders. When the game starts it's where I want it, but as soon as my character ("happy") takes any damage, it dissapears. And I know that his hp only gets subtracted by 5 every time he gets hit. So this should not happen?

Example:

@Startup: happy.getHP() == 100, happy.getMaxHP == 100.
when damaged HP -=5, -> happy.getHP() == 95 -> healthscale == 0,95 -> 220 * 0,95 == new width for Rect(?)


texts:
i want to make some kind of an Eye Tail effect for this charakter:

I found the Unity Trail Renderer effect but the start of the Trial is perpendicular to the dragged/moved direction:

Can i make the start of the Trail look like the eye block of the charakter? So that if he move left or right, the Trail is only as width as the Eyes height and if the moves up or down, the Trail is correspondingly width. Or is there a better method for making a cool Eye Tail effect?


texts: Game not responding on different computer with Intel graphics

texts:
I have a game that uses SDL2 and OpenGL 3.3 with Visual Studio. It runs fine on the computer that built it, but it did not work on other Windows computers.

Initially, it would complain about missing DLLs from the VC++ runtime. I solved the first issue by statically linking the runtime libraries into the EXE.

However, the second issue was that the program freezes right before it could call OpenGL functions to generate vertex buffer and vertex array objects. Of note, not all of the OpenGL functions freeze the program, since glClear appears to work.

I then noticed that some computers with dedicated graphics cards and up-to-date drivers can successfully play the game, but the computers with integrated graphics cards such as Intel HD 4000 still froze up in the same place. This is puzzling, since the specifications for Intel HD 4000 state that OpenGL 3.3 should be supported.

The computers I have tested with all managed to generate an OpenGL context with SDL2 and load OpenGL functions with GL3W without any errors, though some of the unsuccessful ones had a zero-bit depth buffer.

Does anyone know what might be causing the issue?