texts:
I've been searching for information on implementing line-of-sight in my game. I've found some great resources for 2D implementations that produce pixel-perfect results, but there's very little info on 3D implementations.

So far, I've found these methods that could be used to achieve line-of-sight:

Shadow maps
Shadow volumes
3D grids / octrees

However, each of these seems to have limitations. Shadow maps are quite expensive to calculate, especially for omni-directional line-of-sight (just like omni-directional shadows). Shadow volumes have special requirements for geometry and are rather difficult to produce. 3D grids and octrees are not pixel-perfect and require an additional renderer on top of the grid implementation.

Have I missed something here? Which method would be the most suitable for a top-down 3D game?


texts:
On obj_player I have a Create and Step event

Create:

/// Intialize Variables
grav = 0.2;
hsp = 0;
vsp = 0;
jumpspeed = 7;
movepseed = 4;
move = key_left + key_right

Step:

//Get the player's input
key_right = keyboard_check(vk_right);
key_left = -keyboard_check(vk_left);
key_jump = keyboard_check_pressed(vk_space);

//React to inputs
move = key_left + key_right;
hsp = move * movespeed;
if (vsp < 10) vsp += grav;

if (place_meeting(x,y+1,obj_wall))
{
    vsp = key_jump * -jumpspeed
}

//Horizontal Collision
if (place_meeting(x+hsp,y,obj_wall))
{
    while(!place_meeting(x+sign(hsp),y,obj_wall))
    {
        x += sign(hsp);
    }
    hsp = 0;
}
x += hsp;

//Vertical Collision
if (place_meeting(x,y+vsp,obj_wall))
{
    while(!place_meeting(x,y+sign(vsp),obj_wall))
    {
        y += sign(vsp);
    }
    vsp = 0;
}
y += vsp;

Error Message:

FATAL ERROR in
action number 1
of Create Event
for object obj_player:

Variable obj_player.key_left(100007, -2147483648) not set before reading it.
 at gml_Object_obj_player_CreateEvent_1 (line 7) - move = key_left + key_right

Whats wrong with this code? Ive been stuck on it for a couple days now, just really confused as I have seen this code work in action and for other people in this video https://www.youtube.com/watch?v=IysShLIaosk


texts: Why are my target-following objects rotated the wrong way?

texts:
I writing a script that would make my players reach a target destination. It looks like this so far:

private void MoveTowardsGoal() {
    if (Vector3.Distance (reachGoalTarget.transform.position, transform.position) > 2.0f) {
        rDirection = (reachGoalTarget.transform.position - transform.position).normalized;
        if (rAcceleration < rMaxSpeed) {
            rAcceleration += 0.5f;
        }
        rVelocity = rDirection * Time.deltaTime * rAcceleration;
        transform.Translate (rVelocity,Space.World);
    }
}

It works fine: The objects move towards the destination point. However, I want them to move looking at the target in the forward direction (forward z axis). Currently they move with their x axis facing front.

I tried a simple rotation inside Start() like transform.LookAt(reachGoalTarget.transform). With this, they look in the forward direction but then they completely move off their initial positions by rotating themselves to reach the goal.

What am I doing wrong?


texts: How to send dynamic data to a vertex shader OpenGL ES 2 Android

texts:
I'm very new to Android development and OpenGL ES 2.0.

I have been working through a book called "OpenGL ES 2 for Android A Quick Start Guide" which has been useful, but at times I get a bit lost as it doesn't explain some topics in enough depth in my opinion.

I currently have a vertex_shader.glsl file that looks like the following:

uniform mat4 u_Matrix;

attribute vec4 a_Position;
attribute vec4 a_Color;

varying vec4 v_Color;

//uniform double vehicleWidth;
//uniform double screenHeight;

void main() {
    v_Color = a_Color;

    gl_Position = u_Matrix * a_Position;
    //gl_PointSize = vehicleWidth * (2.0 / screenHeight);
    gl_PointSize = 15.0;
}

The parts that are commented out is what I wish to implement into the program.
The vehicleWidth is something that will be a static value at the start of the page, but can change when the user inputs a different value for it. The screenHeight variable is the minimum value my camera can see in Google Maps.
This value will change as often as the user changes the zoom level of the screen.

The information is being sent through two other classes: Color Shader Program

public class ColorShaderProgram extends ShaderProgram {
    // Uniform locations
    private final int uMatrixLocation;

    // Attribute locations
    private final int aPositionLocation;
    private final int aColorLocation;

    public ColorShaderProgram(Context context){
        super(context, R.raw.simple_vertex_shader,
            R.raw.simple_fragment_shader);
        // Retrieve uniform locations for the shader program.
        uMatrixLocation = glGetUniformLocation(program, U_MATRIX);
        //Retrieve attribute locations for the shader program.
        aPositionLocation = glGetAttribLocation(program, A_POSITION);
        aColorLocation = glGetAttribLocation(program, A_COLOR);
    }

    public void setUniforms(float[] matrix){
        // Pass the matrix into the shader program.
        glUniformMatrix4fv(uMatrixLocation, 1, false, matrix, 0);
    }

    public int getPositionAttributeLocation() {
        return aPositionLocation;
    }

    public int getColorAttributeLocation() {
        return aColorLocation;
    }
}

And the Shader Program:

public class ShaderProgram {
    // Uniform constants
    protected static final String U_MATRIX = "u_Matrix";
    protected static final String U_TEXTURE_UNIT = "u_TextureUnit";

    // Attribute constants
    protected static final String A_POSITION = "a_Position";
    protected static final String A_COLOR = "a_Color";
    protected static final String A_TEXTURE_COORDINATES = "a_TextureCoordinates";

    // Shader program
    protected final int program;
    protected ShaderProgram(Context context, int vertexShaderResourceId,
                        int fragmentShaderResourceId){
        // Compile the shaders and link the program.
        program = ShaderHelper.buildProgram(
            TextResourceReader.readTextFileFromResource(
                    context, vertexShaderResourceId),
            TextResourceReader.readTextFileFromResource(
                    context, fragmentShaderResourceId));
    }

    public void useProgram() {
        // Set the current OpenGL shader program to this program.
        glUseProgram(program);
    }
}

My question is, how do I set up the vertex_shader.glsl file so that I can send in dynamic information every time it renders?

EDIT: Also, how would I alter my ColorShaderProgram/ShaderProgram classes to allow me to send dynamic information into the GLSL file?


texts:
I would like to model a rotating "turret" on top of a tank-like object in 2D from the side view like pictured here:

tank with turret http://uofitorn.net/static/images/tankwithbox2dturret.png

Notice the faint outline of a gun protruding to the upper left courtesy of libgdx's debug renderer (the actual gun sprite is not being rendered).

How do I best implement this using Box2d?  Should I use two bodies?  If so, how?  Or one body with two fixtures?

I tried using two bodies connected by a Revolute Joint, but the turret "gun" does not maintain a constant angle but instead rotates down until it is vertical and then just hangs there.

Or should I not model the turret aspect of the tank in box2d at all?


texts:
Yesterday i asked this question on how to create a 2D line branch;
Creating a 2D Line Branch

And thanks to the answered provided, i now have this nice looking main branch; *coloured to show the different segments in the final item.

Now is the time now to branch things off as discussed in the article;
http://drilian.com/2009/02/25/lightning-bolts/

Again however i am confused as to the meaning of the following pseudo code;

splitEnd = Rotate(direction, randomSmallAngle)*lengthScale + midPoint;

I'm unsure how to actually rotate this correctly. In all honesty i'm abit unsure what to-do completely at this part, "splitEnd" will be a Vector3, so whatever happens in the rotate function must then return some form of directional rotation which is then * by a scale to create length and then added to the midPoint.

I'm not sure. If someone could explain what i'm meant to be doing in this part that would be really grateful.


texts: How can I convert an image from raw data in Android without any munging?

texts:
I have raw image data (may be .png, .jpg, ...) and I want it converted in Android without changing its pixel depth (bpp). In particular, when I load a grayscale (8 bpp) image that I want to use as alpha (glTexImage() with GL_ALPHA), it converts it to 16 bpp (presumably 5_6_5).

While I do have a plan B (actually, I'm probably on plan 'E' by now, this is really becoming annoying) I would really like to discover an easy way to do this using what is readily available in the API.

So far, I'm using BitmapFactory.decodeByteArray().

While I'm at it. I'm doing this from a native environment via JNI (passing the buffer in from C, and a new buffer back to C from Java). Any portable solution in C/C++ would be preferable, but I don't want to introduce anything that might break in future versions of Android, etc.


texts:
So below is the usual XNA Game Component override method. If I want to add a touch input detector (lets say, I want to draw a rectangle under touched screen area), where do I put it and how? Googled it, but I found no satisfying solutions.

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

protected override void LoadContent()
{
    _spriteBatch = new SpriteBatch(GraphicsDevice);
    base.LoadContent();
}

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

public override void Update(GameTime gameTime)
{
    base.Update(gameTime);
}

public override void Draw(GameTime gameTime)
{
    base.Draw(gameTime);
}

Thanks


texts: Is the 'partially checked' build sufficient to run the debug version of Direct3D 9?

texts:
To run Direct3D 9 in debug, it is necessary to "install a 'checked' version of the OS".

The checked version of Windows comes in both full and partial flavors. It seems that the partial version is much less obtrusive to install than the full version. But, will that be sufficient to run Direct3D 9 in debug mode?


texts:
I'm just starting out HTML5 game developement (and game dev in general) and watching all the videos and tutorials available something has crossed my mind.

Everyone keep saying I should set the cookie's (or cached files) to be expired after a certain amount of time. So that when it reaches that time the browser automatically downloads all assets again, even if it's the same asset's.

Wouldn't it be possible to manually define the version of the game?
For example the user has downloaded all the files for 1.01 of the game, when updating I change a simple variable to 1.02.
When the user logs in it would compare his version to the current and if they are not equal only then it downloads the files?

This could even be improved to download only specific files depending on what needs to be updated?

Would this be possible or am I just dreaming? What are the possible downsides of this approach?


texts: Should I assign a unique ID to individual units of game currency?

texts:
I am currently making a MMORPG.

At the moment, I am working on the currency part of the game but I'm confused whether I should assign a unique serial number for every unit of the currency generated.

I'm hoping to use this system to trace any misuse of the virtual currency but is this a common practice and if not, would this be a good idea on operational and / or performance point of view?


texts: How to make a Blend-Effect like yomawari did?

texts:
I would like to know, how to make that effect, I have seen in the game named Yomawari. The little girl has a lamp and its cone revals the dark spirits around her. But only if they are in the light. I think it's like the additive blending, but I dont get it to work. I use monogame and c#.

Here is a sample: https://youtu.be/kPLRXP7ovB0?t=1241

All ideas are wellcome (sourcecode preferred ;))

Greetings
Kai

My current test code: (DL: https://github.com/EnemyArea/yomawari-lights)

    protected override void Draw(GameTime gameTime)
    {
        var blend = new BlendState
        {
            ColorBlendFunction = BlendFunction.Add,
            ColorSourceBlend = Blend.DestinationColor,
            ColorDestinationBlend = Blend.Zero
        };

        var lightBlendState = new BlendState
        {
            ColorSourceBlend = Blend.Zero,
            ColorDestinationBlend = Blend.SourceColor
        };

        var mousePosition = Mouse.GetState().Position;

        // Draw lights
        this.GraphicsDevice.SetRenderTarget(this.blackpixel);
        this.GraphicsDevice.Clear(Color.DarkGray);
        this.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Additive);
        this.spriteBatch.Draw(this.lichtRund, new Vector2(mousePosition.X, mousePosition.Y), null, Color.White, 0f, new Vector2(this.lichtRund.Width * 0.5f, this.lichtRund.Height * 0.5f), 1f, SpriteEffects.None, 0);
        this.spriteBatch.End();
        this.GraphicsDevice.SetRenderTarget(null);

        // Draw hidden
        this.GraphicsDevice.SetRenderTarget(this.renderTarget);
        this.GraphicsDevice.Clear(Color.White);
        this.spriteBatch.Begin(SpriteSortMode.Deferred, blend);
        this.spriteBatch.Draw(this.testeye, new Vector2(this.GraphicsDevice.Viewport.Width / 2f, this.GraphicsDevice.Viewport.Height / 2f), null, Color.White, 0f, new Vector2(this.testeye.Width * 0.5f, this.testeye.Height * 0.5f), 1f, SpriteEffects.None, 0);
        this.spriteBatch.Draw(this.blackpixel, Vector2.Zero, Color.White);
        this.spriteBatch.End();
        this.GraphicsDevice.SetRenderTarget(null);

        // Combine all
        this.GraphicsDevice.Clear(Color.Black);

        this.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
        this.spriteBatch.Draw(this.background, Vector2.Zero, Color.White);
        this.spriteBatch.End();

        this.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
        this.spriteBatch.Draw(this.renderTarget, Vector2.Zero, Color.White);
        this.spriteBatch.End();

        this.spriteBatch.Begin(SpriteSortMode.Deferred, lightBlendState);
        this.spriteBatch.Draw(this.blackpixel, Vector2.Zero, Color.White);
        this.spriteBatch.End();

        base.Draw(gameTime);
    }

it results into that:  but is should look like

another sample


texts: 2.5D UI, perspecitve view, distort objects by angle but not position

texts:
Instead of thousand words, a few pictures to explain what I want to achieve

How do I get the merit of UI objects rotation in perspective projection, but ignore the position of an object(as in Overlay Canvas)?

UPDATE 1

Can you include an example of what your full UI or scene would look like?

A usual bar which is used to hold stuff like score. Same base prefab is used for mana/health and any other UI parameter on screen. But bars have different rotations, so here is one solution - have a unique sprite for every special rotation and have a bunch of prefabs(nah). Or have one sprite, one prefab and set the rotation in scene(that's the way).

Is there a reason you are asking for this in perspective projection?

Just because I want to be able to rotate UI objects in scene and show the "depth" of rotated object. I'm not particularly stuck onto perspective projection, as long as I can achieve the "want" look without actually redrawing sprites for every unique angle.

so I'm not sure what you are asking for. Are you asking how to skew an image in 2D, so that it looks like a 3D perspective projection?

I know it sounds crazy, since it's obvious that in perspective looking at object which is above camera you get that "looking from down" look. And yet I feel you are onto something(and now am I), one way of thinking is actually to skew a 2D image to simulate rotation as in perspective view!


texts: When an animation involves movement, where is the movement better to implement?

texts:
For context, I am using Blender and Unity. Regarding the question, as an example, in some games, when you get hit, your character tucks a bit and gets knocked back a few distance. The tucking animation I want to implement in Blender but how about the knockback distance? Do you move your model in Blender (tuck and knockback), or do you do the tuck animation only (tuck in place) and then handle the knockback in Unity (basically triggering the tuck animation and then moving the model backwards a bit).

My question basically is, what's commonly done and if there's any specific reason, why?


texts: Flash AS3 sidescrolling tiles optimization

texts:
I'm trying to make a sidescrolling game in Flash that will run on a low performance laptop.

While studying the subject from Tonypa I saw that he builds a Bitmap by making copys of the BitmapData of each tile from the Tile Sheet and placing it on the bigger Bitmat with the size of the screen.

But when I came to think on how to scroll my map I ran into some optimization doubts.
I came up with two choices:

Create a MovieClip, place a Bitmap instance for each tile that is shown on the screen + 1 row in it, then move them all. Then when the tile ran off the screen I would move it to end of the MovieClip and replace their BitmapData for the next row in my map.
Use a Bitmap with copys of each tile in it (as shown in Tonypa's tutorial) but 1 extra row, move the whole Bitmap, and when it comes the time to replace rows, redraw the whole Bitmap and move it back to the origin position.

The first idea is how a co-worker of mine suggested, the second one is my own, but none of us has enough technical knowledge to be sure on a technique that would be optimal in performance, can anyone help?


texts: How to find boundaries in an isometric tilemap?

texts:
I have an issue with my 2D isometric engine. I'm using my own 2D camera class which works with matrices and need to find the tilemaps boundaries so the user always sees the map.

Currently my map size is 100x100 (with 128x128 tiles) so the calculation (e.g. for the right boundary) is:

var maxX = (TileMap.MapWidth + 1) * (TileMap.TileWidth / 2) - ViewSize.X;
var maxX = (100 + 1) * (128 / 2) - 1360; // = 5104 pixels.

This works fine while having scale factor of 1.0f but not for any other zoom factor. When I zoom out to 0.9f the right border should be at 4953.

I'm using the following code for transformation but I always get a wrong value:

var tempTransform = Matrix.CreateScale(Scale, Scale, 1);
var maxXVector = new Vector2(maxX, 0);
var maxXTransformed = Vector2.Transform(maxXVector, tempTransform).X;

The result is 4593. Logically this value does not seem to be that wrong since a decrease by 10 percent of the map width (5104) should be something around 510

What am I doing wrong?

Here are some pictures so you can see what I mean:

Zoom 1.0f

Zoom 0.9f

Thanks for your help!


texts:
I'm doing some experiments on my own to improve my general skills with HLSL and so forth. In other words, I'm not doing any serious game development, but only looking to expand my knowledge within the field.
I'm trying to figure out how I can increase the resolution of a texture, and multiply it X amount of times.
Consider the following low-resolution picture:

A typical scenario for me would be to scale up this picture 3 times in the shader without interpolation, and draw the new result:

I've been experimenting with a shader that transfers the small picture on to a texture as a variable on the shader. I got that far. Now I just need it to take that texture using tex2D or something else, and scale it up.
How would I do that?


texts: How can I handle sharing storage units in multiplayer?

texts:
I have recently come across a certain problem in programming my MMORPG: the synchronization of shared storage units.

With shared storage unit I intend something like a "chest" that can be accessed by multiple users. Any user can take items from it or put items in it or even move items around and merge items stacks in the chest. To get the idea, think about the guild chest in WoW.

At the moment my approach with non-shared storage is to apply any transaction on the client (move/split/merge they take place instantly on the client) and then communicate to the server the change which also does validation and stuff. This works just fine: it's rather impossible that one client issues a transaction that would conflict with another of its transactions as he always sees an updated state of the storage (because he/she is the only one issuing transactions on that storage).

How do you keep a storage synchronized among its co-owners when they share a storage unit and therefore can issue conflicting transactions? For example: two players issue at the same time a move transaction of the same item.

An approach I was thinking about is scratching client-side prediction for shared storage but that adds some overhead to my work as clients at the moment are not aware (code-wise) that a storage unit is shared. Is there a smarter way to do it?


texts:
Edit: I've slightly edited this question because I've found the symptom for my problem, but not why the actions I've noticed cause the issue.

I have what appears (via the inspector) to be two identical 2D objects containing only a transform and a Sprite Renderer.

One was created by dragging a png from a folder onto the screen, and it displays normally.

The other was created by going to the hierarchy and right click > 2D Object > Sprite, and dragging the desired picture into the object's 'Sprite' Field.

Both objects appear in the development view, but only the first one appears in the game view. Why does the second object not appear?

All other settings for Unity (environment, camera, etc) are the default for a 2D project.

Here are the inspectors for...

The sprite that is displaying:

The sprite that is not displaying:

And my Camera:


texts: How to make a sprite jump up and return to original position?

texts:
I am just trying to make my game character, which is a texture (ball), to jump up in the air and then return back down to the position that it started at when the screen is pressed. I was just wondering if someone could give me a code example or help me to do this with my current code which is below. I have basically just drawn the background and the ball texture and positioned the ball where I want it to start the jump. The ball texture is what I want to make jump straight up.

    public class MyGdxGame extends ApplicationAdapter {
    SpriteBatch batch;
    Texture background;
    Texture ball;

    @Override
    public void create () {
        batch = new SpriteBatch();
        background = new Texture("gamebackground.png");

        ball = new Texture("ball2.png");
        ball.setFilter(Texture.TextureFilter.Nearest, Texture.TextureFilter.Nearest);
    }

    @Override
    public void render   () {
        batch.begin();
        float scaleFactor = 2.0f;
        batch.draw(background, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight    ());
        batch.draw(ball, 80, 145, ball.getWidth() * scaleFactor, ball.getHeight() *     scaleFactor);
        batch.end();
    }

    @Override
    public void dispose () {
    }
}


texts: How do I provide a fully programmable pipeline for rendering?

texts:
I am writing a game engine and I want people who use it allow to define the rendering pipeline. Just they can define the scene geometry, characters, items, light sources, and so on. So the term programmable pipeline doesn't refer to using custom shaders in OpenGL, which is the case anyway.

To provide a programmable pipeline, I want to abstract the OpenGL level so that people who use the engine don't directly have to struggle with framebuffers, render targets, and so on. The definition of the pipeline have to be done in scripting. The engine will then load the definition and create the framebuffers, render tagets and so on at initialization time.

Are the already approaches to this kind of a programmable pipeline in game engines? How can I let the people who use the engine define the pipeline on a sensible abstraction level? I do not want them to create all their render targets on their own. It would be better to just define connections beweent passes and the shaders which should be used.

Another problem is to connect geometry and lights with the pipeline if it is customizable. How can I approach this challenging goal? Every idea, as answer or comment, is appreciated.


texts:
I have panel with some images and buttons. when I click on a button with "gold" name it works, and if I click on any thing other I got error //NullReferenceException: Object reference not set to an instance of an object//

public GameObject gold;

void Update()
{

   if (Input.GetMouseButtonDown(0) && EventSystem.current.IsPointerOverGameObject())
        {
        gold = EventSystem.current.currentSelectedGameObject; // error line
        if (gold.GetComponent<Button>().name == "Gold")
        {
        print (" you got some gold ^-^");
        }
        else
        {
            gold = null;
        }
    }

}


texts:
Would you know how to create a dash line that moves towards the direction of the target, and if it collides with a wall, goes to the opposite angle? I have seen atan2 but I am not sure what it does, and I am quite confused about the movement of the dashed line. A point can be found with cos() and sin() depending on a radius... should I change the radius to place each dash? Then how to move them with the same speed?

Example here :

Any advice would be much appreciated.

Thanks


texts: How and where to handle collisions? [Java]

texts:
Okay, so in my game I have a Level class, which hold an ArrayList of entities. In addition to this, I store the Player here (naturally enough). In my Entity class, I have a method which checks for collisions. This method looks like this:

public boolean collision(Entity other) {
     return cBox.intersects(other.cBox);
}

Now, in my Level class, under the update() method, I check for collisions like this:

for (int i = 0; i < entities.size(); i++) {
    if (entities.get(i).collidable() && entities.get(i).collision(player)) {
        player.notifyCollision();
    }
}

The notifyCollision() method simply ticks a boolean named collision to true in the player class.

This leads me to the question: If I have, say a Chest, an Enemy and some Spikes, where all of them are entities on a map (every entity except for the player is part of the entities ArrayList under the Level class), how would I handle the collisions, and where would I do this?

Say that I want to open a chest if the player is standing in front of it, or hurt the player if it collides with an enemy etc. Would I simply go with the notifyCollision() method, and then have another method named handleCollisions() in the Player class, which would be called if a collision were notified? Or would I have a handleCollision() method under the Chest, Enemy and Spike class, and handle them from here?

Because, the question is really how and where to handle the collisions.


texts: Unity - Mecanim & Rigidbody on Third Person Controller - Gravity bug?

texts:
I'm working on a third person controller which uses physX to interact with the other objects (using the Rigidbody component) and Mecanim to animate the character.

All the animations used are baked to Y, and the movement on this axis is controlled by the gravity applied by the rigidbody component.

The configuration of the falling animation:

And the character components configuration:

Since the falling animation doesn't have root motion on XZ, I move the character on XZ by code. Like this:

    // On the Ground
    if (IsGrounded())
    {
        GroundedMovementMgm();

        // Stores the velocity
        velocityPreFalling = rigidbody.velocity;
    }
    // Mid-Air
    else
    {
        // Continue the pre falling velocity
        rigidbody.velocity = new Vector3(velocityPreFalling.x, rigidbody.velocity.y, velocityPreFalling.z);
    }

The problem is that when the chracter starts falling and hit against a wall in mid air, it gets stuck to the wall. Here are some pics which explains the problems:

Hope someone can help me. Thanks and sory for my bad english!

PD.: I was asked for the IsGrounded() function, so I'm adding it:

    void OnCollisionEnter(Collision collision)
    {
        if (!grounded)
            TrackGrounded(collision);
    }

    void OnCollisionStay(Collision collision)
    {
        TrackGrounded(collision);
    }

    void OnCollisionExit()
    {
        grounded = false;
    }

    public bool IsGrounded()
    {
        return grounded;
    }

    private void TrackGrounded(Collision collision)
    {
        var maxHeight = capCollider.bounds.min.y + capCollider.radius * .9f;
        foreach (var contact in collision.contacts)
        {
            if (contact.point.y < maxHeight && Vector3.Angle(contact.normal, Vector3.up) < maxSlopeAngle)
            {
                grounded = true;
                break;
            }
        }
    }

I'll also add a LINK to download the project if someone wants it.


texts: set which display on which monitor in unity

texts:
I'm working on a project that has multi screen to show environment. the question is options not working when there is multi screen. for example in single screen you can set which screen shows the game but it seems there is not such option.

how can I set which display or which camera get displayed on which monitor in script? for example: camera display 1 to screen 2 and....?

thank you for helping


texts: I have a model that I made in Blender and also I have a gun reloading animation, the model has a rig. So it appears that the animation of the rigged model is devided into 25 different animations but in Unity I can't play all of them at once, if I play only one animation from 25 it will only animate one object (eg. hands) not the magazine or anything else. My question is how is it usually done to play animations from Blender in Unity properly or make animation properly in Blender.


texts: How can I determine which Trigger is hit?

texts:
I have a GameObject. It has 3 BoxCollider2Ds:

Body Collider - Not a trigger - Determines if body is hit
Weapon Collider - Trigger - Determines if weapon is hit
Vision Collider - Trigger - Determines what the GameObject sees

I can tell the Body Collider apart from the other colliders, because it has a different method (OnCollisionEnter2D).  However, I cannot tell the Weapon Collider and Vision Collider apart.  They both access the same method (OnTriggerEnter2D), and pass in the collider they are hitting.  I cannot determine which one is hit.

I could put each trigger on a separate child GameObject, and send a message to the parent, but this is very slow and feels messy to me.  What is the best way I can determine which trigger I am hitting?

From the Unity Docs for reference:

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    public bool characterInQuicksand;
    void OnTriggerEnter2D(Collider2D other) {
        characterInQuicksand = true;
    }
}


texts:
I am developing a game in Java using LWJGL2 and Slick, and I am encountering an issue when rendering a graphic.
Instead of filling the quad with the texture, it appears to be partly repeating it. The image is simply a white box, but this is how it is appearing when the program is run:

I am loading the image using Slick:

this.texture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("Res\\image.png"));

and I am using this code to render it:

texture.bind();
GL11.glBegin(GL11.GL_QUADS);
            GL11.glTexCoord2f(0,0);
            GL11.glVertex2f(position.x,position.y);
            GL11.glTexCoord2f(1,0);
            GL11.glVertex2f(position.x + size.x,position.y);
            GL11.glTexCoord2f(1,1);
            GL11.glVertex2f(position.x + size.x,position.y + size.y);
            GL11.glTexCoord2f(0,1);
            GL11.glVertex2f(position.x,position.y + size.y);
    GL11.glEnd();

If I remove all the code for textures and just render a coloured quad, it displays as expected.
Could you please point me in the right direction as to where I am going wrong?


texts: How to avoid movement speed stacking when multiple keys are pressed?

texts:
I've started a new game which requires no mouse, thus leaving the movement up to the keyboard. I have tried to incorporate 8 directions; up, left, right, up-right and so on. However when I press more than one arrow key, the movement speed stacks (http://gfycat.com/CircularBewitchedBarebirdbat). How could I counteract this?

Here is relevant part of my code:

var speed : int = 5;

function Update () {
    if (Input.GetKey(KeyCode.UpArrow)) {
        transform.Translate(Vector3.forward * speed * Time.deltaTime);
    } else if (Input.GetKey(KeyCode.UpArrow) && Input.GetKey(KeyCode.RightArrow)) {
        transform.Translate(Vector3.forward * speed * Time.deltaTime);
    } else if (Input.GetKey(KeyCode.UpArrow) && Input.GetKey(KeyCode.LeftArrow)) {
        transform.rotation = Quaternion.AngleAxis(315, Vector3.up);
    }
    if (Input.GetKey(KeyCode.DownArrow)) {
        transform.Translate(Vector3.forward * speed * Time.deltaTime);
    }
}


texts: How to create an RTS gameplay experience where all phases of a match are equally engaging without spikes in required concentration?

texts:
In games such as Starcraft Brood War, players at the start of the game don't have as much to do compared to later on when they have to manage multiple battles and multiple bases at once. This means at the start of the game, the gameplay is fairly dull, whereas later in the game it becomes so frantic that only extremely high APM players can play competently.

This is especially a problem in Total Annihilation where being able to quickly react to incoming enemy bombers allows for the minimization of damage from the bombing run, which means a player who can react faster has an advantage over a player with a slower reaction time.

In general, for any RTS game with a fog of war such that when enemy units are discovered, fast reactions would grant an advantage, this is a problem.

I want to create a game which not only removes micro but also removes any requirements for fast reactions throughout the game. In other words the gameplay experience should be "flat" without any spikes in activity, and there should be no surprises possible.

Players should not be sitting around waiting for something to happen and then have to frantically try to click as fast as possible once that something happens. In other words the game should feel more like a slow and steady tug of war than paintball. There are such games in other genres, such as fighting games where, ignoring the power-up bar, gameplay does not change much at all over time.

In my opinion, this means that all changes perceived by the players must be a constant stream throughout the game (to avoid spikes in gameplay) as well as that players must have plenty of time to react to each change, and that reacting faster to the change gives no advantage.

How can I go about designing this kind of game? I can't even think of any RTS game that comes remotely close to this.


texts:
In my game there is a bird flying and on touch it throws different artifacts projectile downwards. And these artifacts should hit the containers moving right to left on the screen. Now if user keeps on tapping rapidly it make a line of artifacts and it didn't miss a single container. So what I want to do is to restrict user to throw 3 artifacts at a time and when one of them got destroyed it'll make room for one more. Here is how I'm doing it:
In my player.cs I'm using a static int named inventory and then in Update() method I've the code where it increment the inventory.

if (Input.GetTouch(i).phase == TouchPhase.Began){
                OnShoot ();
                inventory++;
                Debug.Log ("Inventory: " + inventory);
            }

and in OnShoot() I'm checking if (inventory < 4) then Instantiate otherwise if (inventory > 4) set inventory = 0;.
 Now in the artifacts.cs if it hit the container and get destroyed or got destroyed going out of the bound missing the container it should Player.inventory--;
This code works fine but if the user speed of tapping is more then it again started throwing like in a line form as described above.


texts:
I'm making a simple text-based RPG, where the player is the owner of five creatures that battle other teams for loot, experience and glory. I am using Python, and a curses emulator. I have a static ASCII over-world map. My character, represented by a glyph, can move about this static map. There are locations all over the map that the character can visit, that break down into two categories:

Towns, which are a series of menus that will allow the player to buy equipment for his team, hire new recruits or do other things.
Arenas, where the player's team will have a "battle" interface with actions he can perform, messages about the fight, etc. Later, I may include an ASCII representation of the fight; but for now, just screens of information, with action prompts, will be displayed.

What kind of design or structure should I use to implement movement between an over-world map and a menu system?

Right now, the game goes through a master loop that waits for keyboard input, and then moves the player about the screen. Upon keyboard input, the player  coordinates are checked against a list of location objects, and if the player coordinates match a locations coordinates, then... I am not sure.

I'm not sure if I should call a separate function, to initiate either a menu or combat mode, or if I should create some kind of new GameMode object that contains a method for drawing the screen and printing the necessary info. If I go that way, I am not sure how to pass my players team data into this object.

My main concern is passing around the program flow into all of these objects. Should I be calling straight functions for different parts of my game, and objects to represent "things" within my game? I was reading about the MVC pattern, and how this kind of problem might benefit from decoupling the GUI from the game logic and user input, but I have no idea how this applies to my game.


texts:
What is a simple way to simulate flashing candle / torch / fire light?
I'm not asking about animating the flames, I'm only interested in the light surrounding the fire, similar to what this device does: https://www.youtube.com/watch?v=dPsVr4pU8Tg


texts: IsolatedStorageException : Could not find file

texts:
I'm trying to save/load player data from a file using the persistenceDataPath using the following code:

private void Save()
    {
        if (File.Exists (Application.persistentDataPath + "/playerInfo.dat"))
        {
            FileStream file = File.Open (Application.persistentDataPath + "/playerInfo.dat", FileMode.Open);
            data.userExperience = userExperience;
            bf.Serialize (file, data);
            file.Close ();
        }
    }

private void Load()
{
    if (File.Exists (Application.persistentDataPath + "/playerInfo.dat"))
    {
        FileStream file = File.Open (Application.persistentDataPath + "/playerInfo.dat ", FileMode.Open);
        PlayerData data = (PlayerData)bf.Deserialize (file);
        userExperience = data.userExperience;
        file.Close ();
    }
}

[Serializable]
class PlayerData
{
    public int userExperience;
}

It works fine if I play the game with Unity Editor. However, on Android, when I try to execute this line of code in Load():

FileStream file = File.Open (Application.persistentDataPath + "/playerInfo.dat ", FileMode.Open);

I get this error:

The file does exist since the code pass through the if(File.Exist...) and it works when I try to access the file from the Save() method.

I really don't know what it could be since the code that open the file in Save() and Load() is the same.


texts: Rigidbody or Character Controller for a momentum based sidescrolling shooter/platformer?

texts:
I'm working on a side scrolling game where among other movement options the player can perform a "bullet jump". The bullet jump fills a similar role to a double jump, but instead of just jumping in midair, it launches the player in the direction of the mouse cursor. Unfortunately, I can't seem to find any way of doing this using Character Controller, so I've turned to Rigidbody physics to handle the air launch of the player.

As I can't use both Rigidbody and Character Controller, I'm forced to pick one, and as I'm a novice, I decided I'd turn to Stack Exchange for help. I am aware that Character Controller was the given answer for this question on many other occasions, but due to the momentum focus of the game and the nature of the bullet jump mechanic, I feel it's worth asking this question in the context of my specific game.


texts: Is there a simpler way to simplify the if statement?

texts:
The code below generate angle and radius based brightness gradient. As you can see I need to use 3 if statement to define 3 circle, wonder is there a single code that can create nth circle corresponding to brightness gradient, imagine I want to create 20 circle, using 20 if statement is very unpractical.
Shader "Unlit/testDisplay"
{
   Properties
  {
       _MainTex ("Texture", 2D) = "white" {}
 }
SubShader
{
    // Render with transparent objects, after the opaque pass.
    Tags { "RenderType"="Transparent" "Queue"="Transparent"}
    LOD 100

    // Don't write to the depth buffer.
    ZWrite Off
    // Additive blending (add light/glow).
    Blend One One

    Pass
    {
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag

        #include "UnityCG.cginc"

        struct appdata
        {
            float4 vertex : POSITION;
            float2 uv : TEXCOORD0;
        };

        struct v2f
        {
            float2 uv : TEXCOORD0;
            float4 vertex : SV_POSITION;
        };

        sampler2D _MainTex;
        float4 _MainTex_ST;

        v2f vert (appdata v)
        {
            v2f o;
            o.vertex = UnityObjectToClipPos(v.vertex);
            // Shift our texture coordinates so 0 is in the center,
            // and we go to -2 ... +2 at the edges.
            o.uv = (v.uv -0.5f) *4.0f;
            return o;
        }

        fixed4 frag (v2f i) : SV_Target
        {
            //Define boundary value for radius
            float radius=length(i.uv);
            if(radius>0&radius<0.5)
            radius=0.5;
            if(radius<1&radius>=0.6)
            radius=1;

            if(radius<1.5&radius>=1.01)
            radius=1.5;

            if(radius<2&radius>=1.51)
            radius=2;

            //convert to polar coordinates
            float angle=atan2(i.uv.y,i.uv.x);
            float angle1=frac(angle/(2*3.142f));
            float result=-4*radius+angle1+13*frac(_Time.x);
            return result;

        }
        ENDCG
    }
}

}


texts: I'd like to pause my game when my app is hidden (user pressed home button or changed app). How can I detect that ?


texts: Does vector transformation order matter?

texts:
Theoretical question - imagine a car object. There are two (or more) 'forces' acting on this car, these forces will affect where the car will steer. But the forces are calculated using car's location in relation to the world, car's steering on the other hand relies on a vector within car's local space. Therefore these forces need to be translated to the car's own space before they can be applied on the car's steering.

Now the question is - should the vectors that represent these forces be summed first and the resulting force then translated to the car's domain? Or should both forces first be translated and then summed, within car's domain? Or does it not matter?


texts: Switching character and keeping animations in Unity default third person controller

texts:
This is probably a ridiculous question, but I am doing a school project in Unity and am trying to create a basic game. For movement I want to use third person controller and since this is very basic I wanted to keep the default 3d model of character as well (Ethan). But since it is so colorless I had a friend of mine to color it up and then export it back to unity.
The problem is that it's a different model now and animations don't work anymore so I want to know how to correctly switch them to keep default animations? The models are the same otherwise so animations should be possible to apply.
Since nothing I tried so far didn't help I really hope someone can give me some instructions.. :) Thanks


texts: Is knowing physics necessary for game development?

texts:
Is knowledge of physics necessary to design quality games? How important is it? Be realistic and explain a few novice examples of how's mandatory.

What kind of physics is necessary, non-calculus-based or calculus-based? Do I need to know Physics III (modern, heat, light, waves)? In summary, what part (and level) of physics must one know?


texts: Drawing sprite shapes with triangles instead of textures

texts:
If I want to use no textures in a game (ie. no png images), could I just break down my drawing into triangles, combined into the shape I want to draw, and draw those triangles instead?

For example, I found this in Google Images, showing how an "arrow" graphic could be drawn as a triangle mesh instead of a textured sprite:


texts:
I am trying to learn how to use Shaders for a 2D XNA project I am working on. To test them out, I was trying to make a white triangle become colored using a super simple Pixel Shader, and I can't get it to work.

This is my Pixel Shader:

float4 ThePixelShader(float4 texCoord : TEXCOORD0) : COLOR0
{
    return(125,15,105,1);
}

technique MandelbrotSet
{
    pass Pass0
    {
        PixelShader = compile ps_2_0 ThePixelShader();
    }
}

And this is the code I was using to draw my Plain white triangle onto the screen, and trying to use the shader to change its color.

        GraphicsDevice.Clear(Color.Black);
        spriteBatch.Begin();
        //MandelbrotEffect.Parameters[""].SetValue();
        MandelbrotEffect.CurrentTechnique = MandelbrotEffect.Techniques["MandelbrotSet"];
        foreach (EffectPass pass in MandelbrotEffect.CurrentTechnique.Passes)
        {
            pass.Apply();
            spriteBatch.Draw(Dot, new Rectangle(10, 10, 200, 200), Color.White);
        }
        spriteBatch.End();

I'm guessing I am doing something dumb, but I can't figure out what. The triangle is drawn on screen as just a plain white triangle, what it would look like without a shader.

EDIT: Changed my drawing code to look like this.

        GraphicsDevice.Clear(Color.Black);
        //MandelbrotEffect.Parameters[""].SetValue();
        MandelbrotEffect.CurrentTechnique = MandelbrotEffect.Techniques["MandelbrotSet"];
        spriteBatch.Begin(0, BlendState.Opaque, null, null, null, MandelbrotEffect);
        spriteBatch.Draw(blank, Vector2.Zero, Color.White);
        spriteBatch.End();

Now it does draws the box fullscreen, and I know the shader is working because changing the Alpha value does change the Alpha value of the full screen image, but still the colors don't change.

Thoughts?


texts: Need help in getting sequential impulse method working

texts:
i have made a very very simple physics system based on sequential impulse method - with single contacts only and no angular rotation at all. Contact points are calculated using separating axis theorem.

Unfortunatly with small gravity my test-simulation is stable, but with increasing gravity it gets more and more unstable. My player and my moving elevator just goes crazy...

The solver is basically the same as box2d, but without any angular rotation at all - so no need for clipped contact points.

It does the following:

Integrating the external forces (gravity, player input)
Calculating all contact points using SAT for each unique body pair.
Solving movement iteratively by applying impulses so it just touches the surface (restitution is set to zero)
Integrating the new velocity to get a new position
Re-calculate contact distances
Solving position errors iteratively by applying impulses to the position by using baumgarte stabilization method

All the solver code is nearly a port of box2d Box2D/Dynamics/b2ContactSolver.cpp.
Even the coefficients are set to the same values and the world uses meters as units.

Does someone know this stuff and could help me to learn this properly please?
Since months i am fighting with this kind of physics programming and has always issues :-(
Unfortunatly i dont have any algebra knowledge, even though i understand the most of it.

Here is the short code in a javascript environment:
http://jsbin.com/xoqiquxoyo/1/


texts: Proper way to do texture mapping in modern OpenGL?

texts:
I'm trying to do texture mapping using OpenGL 3.3 and GLSL 150.

The problem is the texture shows but has this weird flicker I can show a video here.

My texcords are in a vertex array. I have my fragment color set to the texture values and texel values. I have my vertex shader sending the texture cords to texture cordinates to be used in the fragment shader. I have my ins and outs setup and I still don't know what I'm missing that could be causing that flicker.

Here is my code:

Fragment shader

#version 150

uniform sampler2D texture;
in vec2 texture_coord;

varying vec3 texture_coordinate;
void main(void) {
    gl_FragColor = texture(texture, texture_coord);
}

Vertex shader

#version 150

in vec4 position;
out vec2 texture_coordinate;
out vec2 texture_coord;
uniform vec3 translations;

void main() {
    texture_coord = (texture_coordinate);
    gl_Position = vec4(position.xyz + translations.xyz, 1.0);
}

Last bit

Here is my vertex array with texture coordinates:

GLfloat vVerts[] = {
   0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
   0.0f, 0.5f, 0.0f, 1.0f, 1.0f,
   0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
   0.5f, 0.0f, 0.0f, 1.0f, 0.0f}; //tex x and y

If you need to see all the code, here is a link to every file.

Thank you for your help.


texts:
I have a very simple 3D maze program that uses a first person camera to navigate the maze. I'm trying to scale the blocks that make up the maze walls and floor so the corridors seem more roomy to the camera. Every time I scale the model, the camera seems to scale with it, and the corridors always stay the same width.

I've tried apply the scale to the model in the content pipe (setting the scale property of the model in the properties window in VS). I've also tried to apply the scale using Matrix.CreateScale(float) using the Scale-Rotate-Transform order with the same result. If I leave the camera speed the same, the camera moves slower, so I know it's traversing a larger distance, but the world doesn't look larger; the camera just seems slower.

I'm not sure what part of the code to include since I don't know if it is an issue with my model, camera, or something else. Any hints at what I'm doing wrong?

Camera:

Projection = Matrix.CreatePerspectiveFieldOfView( MathHelper.PiOver4, _device.Viewport.AspectRatio, 1.0f, 1000.0f );

Matrix camRotMatrix = Matrix.CreateRotationX( _cameraPitch ) * Matrix.CreateRotationY( _cameraYaw );
Vector3 transCamRef = Vector3.Transform( _cameraForward, camRotMatrix );
_cameraTarget = transCamRef + CameraPosition;
Vector3 camRotUpVector = Vector3.Transform( _cameraUpVector, camRotMatrix );
View = Matrix.CreateLookAt( CameraPosition, _cameraTarget, camRotUpVector );

Model:

World = Matrix.CreateTranslation( Position );


texts: the countdown timer inside while loop not working

texts:
i am instantiating prefab cars ... the clones had a random countdown timer with each one off them and its working very well but the its not  decreasing its not counting down the timer is inside the spawn method the spawn method is inside the WHILE loop and the while loop is inside the UpDate() ... i  tried  to move the countdown to Update() but didnn't worked ... any ideas ...Thank You!

void Update()
{
    p -= Time.deltaTime;

        while (carNumber < cars && p <= 0 )
        {
            SpawnCars();
            print(carNumber);
            p = 5;
    }

}

and this is the spawn method:

 public void SpawnCars()
{
    if (spawnAllowed)
    {
        // choose a random strat point 1/6
        randomSpawnPoint = Random.Range(0, spawnPoints.Length);
        // choose a random car 1/6
        randomSpawnCars = Random.Range(0, Cars.Length);
        // clone randomly a car(1/6) from a random pre_set-points(1/6)
        GameObject obj = Instantiate(Cars[randomSpawnCars], spawnPoints[randomSpawnPoint].position, Quaternion.Euler(-90, 180, 0)) as GameObject;
        // carNumber will count how many cloned car
        carNumber++;
        // destroy the  cloned car after N sec
       // Destroy(obj, 8);
        // every cloned car will take a tag with it
        obj.gameObject.tag = "select" + k;
        k++;
        rcf = obj.GetComponent<RayCastForward>();
        //textCDT
        time = Random.Range(4f, time);
        TextMesh txt = FindObjectOfType<TextMesh>();

//the Timer:
        time -= Time.deltaTime;
        coolDown = time.ToString("0");
        txt.text = ""+coolDown;

    }
}

edit: i forgot to tell that the timer  is inside SpawnCars().


texts: I need help in Unity OnTriggerEnter not changing my bool in an other script C#

texts:
I want to change a bool in 2 separate scripts in Unity but it's not changing OnTriggerEnter or stay or exit. I've tried everything but nothing helped me.

This is the script where I store the bool and the animator script:

public Animator _T1anim;
public bool Open;

void Awake()
{
    _T1anim = GetComponent<Animator>();
    _T1anim.SetBool("Open", false);
    _T1anim.SetBool("Close", true);
}
public void Update()
{
    if (Open != true)
    {
        CloseDoor();
    }
    else
        OpenDoor();
}
public void OpenDoor() {
        _T1anim.SetBool("Open", true);
        _T1anim.SetBool("Close", false);
}
public void CloseDoor()
{
    _T1anim.SetBool("Close", true);
    _T1anim.SetBool("Open", false);
}

and I want to change the "Open" Bool to true with the OnTriggerEnter in a different script. The T1_1 T11 is the reference to the first script.

T1_1 T11;

void Awake()
{
    T11 = GetComponentInParent<T1_1>();
}
public void OnTriggerEneter(Collider other)
{

    if (other.tag == "Player")
    {
        T11.Open = true;
    }

}
}

This is the animator controller:


texts: How to protect your real time online shooter from potential bots

texts:
I'm looking to create a multiplayer top down shooter. While I've read about different topics, I can see them I've got some real challenges ahead, but I'm all up for it.

One thing I can't understand is how am I supposed to be protecting the game from people who try to create bots?

What I mean is, as far as I understand, it's impossible to protect the network traffic in a way that players won't be able to create programs that listen to what's going on and understand it.

So what worries me is that people can create bots that listen to the current location of rival players, and send communication that mimic as if the player is shooting in the exact "perfect" location to win that match.

So what kind of techniques are used to protect real time games from such bots?

Also I'd like to mention that I've tried searching for discussions (as this sounds like something many people struggle with), but couldn't find anything about it specifically, only as a part of broader questions about networking in real time games. If I should have looked harder feel free to put me in my place :)


texts: What are the challenges and benefits of writing games with a functional language?

texts:
While I know that functional languages aren't the most commonly used for game writing, there are a lot of benefits associate with them that seem like they would be interesting in any programming context. Especially the ease of parallelization I would think could be very useful as focus is moving toward more and more processors.

Also, with F# as a new member of the .NET family, it can be used directly with XNA, for example, which lowers the threshold quite a bit, as opposed to going with LISP, Haskell, Erlang, etc.

If anyone has experience writing games with functional code, what has turned out to be the positives and negatives? What was it suited for, what not?

Edit: Finding it hard to decide that there's a single good answer for this, so it's probably better suited as a community wiki post.


texts: Applying the input for the always-moving player in the multiplayer game

texts:
I've read several articles published on gambrielgambetta.com, gafferongames.com plus some pages about how Valve handles multiplayer networking in its games but I still can't get it how to implement the client-side prediction for my game where the player's always moving and he controls the speed by pressing the spacebar. When the client input has arrived the server already had simulated the world using the old velocity values. So we get a stretch in time.

Let's imagine that the player is moving between the 0.0 and 1.0 values. The current position is 0.2. The normal speed is 0.1. The "crawling" speed is 0.05.

Let's assume the server and the client have framerates both fixed and the latency is two steps high.

  STEP 0
  server 0.2
  client 0.2

  STEP 1
  server 0.3 (+0.1)
  client 0.3 (+0.1)

  STEP 2
  server 0.4 (+0.1)
  client 0.4 (+0.1)

  STEP 3 (Spacebar's pressed)
  server 0.5 (+0.1)
  client 0.45 (+0.05)

  STEP 4 (Spacebar's still pressed)
  server 0.6 (+0.1)
  client 0.5 (+0.05)

  STEP 5 (Spacebar's still pressed. Finally, the input has arrived)
  server 0.65 (+0.05)
  client 0.55 (+0.05)

  STEP 6 (Spacebar's still pressed)
  server 0.7 (+0.05)
  client 0.6 (+0.05)

  STEP 7 (Spacebar's released. Input was sent)
  server 0.7 (+0.05)
  client 0.7 (+0.1)

  STEP 8
  server 0.75 (+0.05)
  client 0.8 (+0.1)

  STEP 9 (Input has arrived)
  server 0.85 (+0.1)
  client 0.9 (+0.1)

It looks like nothing's wrong with this data while every multiplayer game's trying to hide the latency. But what if the periods of pressing the spacebar are different and the latency is different and the server and client have different framerates. I can't use the input duration when updating the player position because it allows the player to cheat (just lower the duration and you will start moving slower). And the server reconciliation works not very good since I'm getting the effects derived in the statistics above. When pressing the spacebar the player just jumps back and starts moving slower. So I need to compensate that somehow.

The core of the problem is how to handle the player input when the user can only decrease the speed of the character while the character's moving with the predefined speed.


texts: How do I generate terrain like that of Scorched Earth?

texts:
I'm a web developer and I am keen to start writing my own games.

For familiarity, I've chosen JavaScript and canvas element for now.

I want to generate some terrain like that in Scorched Earth.

My first attempt made me realise I couldn't just randomise the y value; there had to be some sanity in the peaks and troughs.

I have Googled around a bit, but either I can't find something simple enough for me or I am using the wrong keywords.

Can you please show me what sort of algorithm I would use to generate something in the example, keeping in mind that I am completely new to games programming (since making Breakout in 2003 with Visual Basic anyway)?


texts:
I'm using C++, Box2D and SFML.

I convert a Tiled map to world in my platformer game and I get stuck when I go against a block when I go forward like that :

I can use a circle as foot of my character but sometime, it make me jump a bit. Is there a solution or I must only do shape ?


texts:
Could anybody provide working code using SharpDX with D3D11, which does instancing and uses SharpDX's content pipeline?

I have several problems there. I came to understand that one should use a SharpDX.Direct3D11.InputLayout to describe the vertex shader's input. There I already have a problem. I use SharpDX's content pipeline, so the shaders are compiled in compile time and not in runtime. Where do I get the shader's byte code then? It shouldn't be that hard, but it seems it's inaccessable from the effect object.

My other question is how can I set the created SharpDX.Direct3D11.InputLayout before the current DrawIndexedInstanced call?


texts:
I am having trouble making my game's main loop to run at exactly N fps. Let's say i want game to run at constant 60 fps. Here is part of my code:

int ticksPerSecond = 60;
int skipTicks = 1000 / ticksPerSecond;
int maxFrameskip = 10;

// ...

while(true)
{
    loops = 0;
    while (Environment.TickCount > nextGameTick && loops < maxFrameskip)
    {
        OnUpdate();
        nextGameTick += skipTicks;
        loops++;
    }

    Render();
}

As a result i am getting around 64 fps, not 60. Why is that and what am i doing wrong here?


texts: How to draw Shadow Volumes in one draw call?

texts:
I've got a simple app that draws 3D cubes using instance rendering and I'm implementing Shadow Volume. Each cube's vertex, uv, normal and index data are statically stored in 4 vertex array buffers. On each frame, I draw 10 cubes by uploading 10 world-view-projection matrices (one for each cube) to a 4th dynamic vertex array buffer (using vertex attr divisor) and then
calling glDrawElementsInstanced once with 10 as primecount.

All my cubes are render properly in 1 draw call \o/

Now... I want to draw their shadow volumes in one draw call too! (for 1 directional light). I'm on Mac so I've acces to OpenGL 4.1. Here's my progress so far:

I upload all vertices twice (once with the w attribute to 1 and once to 0). This will help me drawing the extruded silhouette in my vertex shader.
On the CPU, I find each cube's silhouette (according to their orientation) and I create one list of indices for each cube (so 10 lists total) representing their shadow volume.
And then I'm stuck...

I can't find a way to upload multiple list of index (one for each instance)... so far my vertex shader can work with each cube's matrix but can only work on 1 index array (the uniq GL_ELEMENT_ARRAY_BUFFER).

I've been googling a lot but could not find a solution. So I'm asking here: does anybody know how to implement Instanced Rendering with multiple indice lists? or does anybody know a better approach to render shadow volumes of multiple instances of the same object in one draw call?


texts: Rendering Texture Quad to Screen or FBO (OpenGL ES)

texts:
I need to render the texture on the iOS device's screen or a render-to-texture frame buffer object. But it does not show any texture. It's all black.

(I am loading texture with image myself for testing purpose)

//Load texture data

UIImage *image=[UIImage imageNamed:@"textureImage.png"];

    GLuint width = FRAME_WIDTH;
    GLuint height = FRAME_HEIGHT;

    //Create context
    void *imageData = malloc(height * width * 4);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(imageData, width, height, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGColorSpaceRelease(colorSpace);

    //Prepare image
    CGContextClearRect(context, CGRectMake(0, 0, width, height));
    CGContextDrawImage(context, CGRectMake(0, 0, width, height), image.CGImage);

    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

Simple Texture Quad drawing code mentioned here

//Bind Texture, Bind render-to-texture FBO and then draw the quad

const float quadPositions[] = {  1.0,  1.0, 0.0,
                                -1.0,  1.0, 0.0,
                                -1.0, -1.0, 0.0,
                                -1.0, -1.0, 0.0,
                                 1.0, -1.0, 0.0,
                                 1.0,  1.0, 0.0 };
const float quadTexcoords[] = { 1.0, 1.0,
                                0.0, 1.0,
                                0.0, 0.0,
                                0.0, 0.0,
                                1.0, 0.0,
                                1.0, 1.0 };

// stop using VBO
glBindBuffer(GL_ARRAY_BUFFER, 0);

// setup buffer offsets
glVertexAttribPointer(ATTRIB_VERTEX, 3, GL_FLOAT, GL_FALSE, 3*sizeof(float), quadPositions);
glVertexAttribPointer(ATTRIB_TEXCOORD0, 2, GL_FLOAT, GL_FALSE, 2*sizeof(float), quadTexcoords);

// ensure the proper arrays are enabled
glEnableVertexAttribArray(ATTRIB_VERTEX);
glEnableVertexAttribArray(ATTRIB_TEXCOORD0);

//Bind Texture and render-to-texture FBO.
glBindTexture(GL_TEXTURE_2D, GLid);

//Actually wanted to render it to render-to-texture FBO, but now testing directly on default FBO.
//glBindFramebuffer(GL_FRAMEBUFFER, textureFBO[pixelBuffernum]);

// draw
glDrawArrays(GL_TRIANGLES, 0, 2*3);

What am I doing wrong in this code?

P.S. I'm not familiar with shaders yet, so it is difficult for me to make use of them right now.


texts: Unity - How to make grass details look good from top-down

texts:
I have an issue with the terrain details. Since it only draws a single plane per texture, it looks quite crappy with a angled top-down camera, for example for an RTS camera.

Is there some way around this, I know one solution people use is to angle the grass towards the camera a bit, but that isnt possible with the terrain details painter.

The issue is circled in red:

If there is no solution to this, are there some techniques I can use to make some interesting-looking grass for an RTS camera?


texts: Drawing a texture of arbitrary size in XNA

texts: I wish to know if there is a way to load a texture which is not in powers of 2, for example 100 X 56 in dimension, in XNA 4.0 and draw it using VertexPositionColorTexture.


texts: How to swap out the visual mesh component of an actor at run-time

texts:
I am attempting to replace the visible component of a pawn with a different component at runtime (in my case a UCustomMeshComponent with randomly generated vertices) and running into problems.

I set up my pawn like this in its constructor (where OurMesh is a UCustomMeshComponent * member variable):

ATestGeomPawn::ATestGeomPawn() : OurMesh(NULL)
{

    PrimaryActorTick.bCanEverTick = false;
    AutoPossessPlayer = EAutoReceiveInput::Player0;

    // root is a scene component so this is placeable in the editor
    RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("RootComponent"));

    // camera attached to root
    UCameraComponent* Camera = CreateDefaultSubobject<UCameraComponent>(TEXT("OurCamera"));
    Camera->SetupAttachment(RootComponent);
    Camera->SetRelativeLocation(FVector(-250.0f, 0.0f, 250.0f));
    Camera->SetRelativeRotation(FRotator(-45.0f, 0.0f, 0.0f));

    // create an initial visible component
    RegenGeometry();

}

And RegenGeometry()'s intent is to set up the new component, destroying the old one if it exists (first time through it won't). RegenGeometry() may be called at any time (in my tests I have it bound to an action event):

void ATestGeomPawn::RegenGeometry() {

    // destroy old mesh
    if (OurMesh) {
        OurMesh->DestroyComponent();
        OurMesh = NULL;
    }

    TArray<FCustomMeshTriangle> tris;
    // code for setting up tris omitted for brevity

    // create and attach new mesh
    OurMesh = NewObject<UCustomMeshComponent>(this);
    OurMesh->SetCustomMeshTriangles(tris);
    OurMesh->SetupAttachment(RootComponent);

}

However, this leads to all sorts of bad results. I've tried various hand-wavey iterations of this:

The code as shown above just crashes the editor immediately, even if I don't actually have an ATestGeomPawn placed in the map.
If I use the now-deprecated NewNamedObject instead, with the same name every time, it works initially but subsequent calls to RegenGeometry() cause the mesh to disappear, with weird results shown in this video I made.
If I use NewNamedObject but generate a new name every time, it works initially but does not remove the initial component from the hierarchy, and has a similar visible outcome to the above, shown in this other video I made.
If I call RegenGeometry() in BeginPlay() instead of the constructor, it is never visible.

How do I do this properly?

I'm super new to the Unreal SDK, as in yesterday morning I was doing a crash course through tutorials and docs to try and get this done. I eventually arrived at the above. I have a feeling that my mistake here is some misunderstanding of life-cycles, replication, or maybe e.g. reference counting due to say player input on the pawn or something:

Update: The player input theory is eliminated. I tried the exact same thing as above but with a regular actor instead of a pawn (camera eliminated, no player input, just RegenGeometry() in constructor and nothing else), and the editor crashed in the same way. So it isn't related to this being a pawn.

I'm not sure which direction to head in next.

(Full source, if relevant: TestGeomPawn.h and TestGeomPawn.cpp; the "grow" stuff I just threw in from the tutorial to make sure player input was working)


texts: Multi-level 3D grid based pathfinding in Unity

texts:
I'm trying to come up with a way to pathfind on multiple levels. See image:

The orange walls would be considered a ladder, connecting you to the upper levels.

At first I thought of looking at it as though it were top down 2d, but I also need to be able to go under things at some point. How can I compute these paths?


texts:
I'm creating a fighting game where two opponents face off against each other in the ring. While I've been able to figure out the odds of a player winning based on previous wins/losses, I have yet to find a formula which modifies those odds based on opponent. For example:

Player 1: W:5 L:5 - 1/1 odds
Player 2: W:5 L:0 - 1/5 odds

I want to calculate the odds that Player 1 will wins against player 2. Compounding this the players could be of different levels: if the players are within a few levels of each other, the odds should map closely to wins/losses. However, as the levels diverge, the odds of the lower level player winning reduce. As a swag:

Player 1 - W:5 L:5  - 1:1 odds

Against a level  8 - 1:2
Against a level  9 - 2:3
Against a level 10 - 1:1
Against a level 11 - 3:2
Against a level 12 - 2:1

These are just estimates, my sense is that there is a math formula out there which will calculate that - can anyone out there point me to what this could be?

Thanks...Chris


texts: How to detect whether my Java application is active?

texts:
I want to pause my game (written in Java Swing), when the player switches to another application.

But I did not find a way to detect this switch. window.isActive() only works for multiple windows within one Java application. But it does return true, when a different application has the focus.

The same is true for the KeyboardFocusManager, it returns the window of my application that had the focus before the focus was given to another application.


texts:
I tried to move my obstacle with the event type KEYDOWN, but it seems it is not working.
This is my code.
import pygame
import time

pygame.init()
res=(500,500)
blue_color=(0,0,255)
black_color=(0,0,0)
red_color=(255,0,0)
title=pygame.display.set_caption("Pygame Game")
screen=pygame.display.set_mode(res,pygame.RESIZABLE)

coord_rec=pygame.Rect(250,2,20,20)
coord_obs=pygame.Rect(150,450,200,20)
rectangle=pygame.draw.rect(screen,blue_color,coord_rec)
obstacle= pygame.draw.rect(screen,red_color,coord_obs)

pygame.display.flip()
launched= True
while launched:
    for event in pygame.event.get():
        if event.type== pygame.QUIT:
            launched=False
        elif event.type==pygame.KEYDOWN:
            if event.key==pygame.K_LEFT:
                    coord_obs.x+=10
            elif  event.key==pygame.K_RIGHT:
                    coord_obs.x +=-10

    while not coord_rec.colliderect(coord_obs):
              time.sleep(0.0500)
              screen.fill(black_color)
              coord_rec.y+=10
              rectangle=pygame.draw.rect(screen, blue_color, coord_rec)
              obstacle=pygame.draw.rect(screen, red_color, coord_obs)
              pygame.display.flip()


texts: Identity the same component on all connected clients

texts:
I have a client-server architecture and a scene containing objects X, Y, Z, etc.

Each component needs to be identifiable so that messages sent from the server can be routed to the correct component it needs to. For example, I have 2 instances of Health component. Let's call them I1 and I2. I1 takes damage and the server updates its value and sends a message to all players to update the health of component I1 to 0.

For components that already exist in the scene when it is loaded, what I've done is assigned and serialized a unique ID at design time. But how can I handle components instantiated at runtime? For example, the same component could be instantiated on different clients but in different orders causing all the IDs to be out of whack.


texts: A* heuristic for use with Goal Oriented Action Planner

texts:
Many of the high-level descriptions I've found for GOAP and similar planners suggest using A* for their path-finding, but I'm struggling to implement it for my own planner. Specifically, I'm struggling with creating an admissible heuristic.

As a trite example, consider this set of nodes, expressed as a map of srcCoord -> dstCoord -> cost (cost is Euclidean distance with one exception):

{0, 0}:
  {-14, 0}: 14.0,
  {3, 3}: 4.242640687119285,
{-14, 0}:
  {10, 10}: 1.0, # exception here, call it a wormhole
{3, 3}:
  {6, 6}: 4.242640687119285,
{6, 6}:
  {9, 9}: 4.242640687119285,
{9, 9}:
  {10, 10}: 1.4142135623730951,

The shortest path from {0,0} to {10,10}, by 0.1421356237309501, is {0,0} -> {-14,0} -> {10,10}.

Euclidean distance is a reasonable heuristic without wormholes in the picture, but it's inadmissible here: It'd return 26 for {-14,0}->{10,10}, so it'll never expand the {-14,0} node and will end up incorrectly returning the path through {3,3}.

My planner has no connection to 2d-geometries, but it exhibits this "wormhole" behavior... an initial action doesn't appear to get us closer to our goal, but after expansion we see that it makes future actions less costly, or amplifies their effect in reaching the goal.

Here's a specific example I have in mind for amplifying the impact of future actions:

  If mid-fight a better weapon (let's assume it's better in all respects) appears on the ground than the one currently equipped (likely dropped by someone who died), and it won't take longer to pick it up + finish the enemy than to finish the enemy with the current weapon, then pick it up, equip it, and use it.

How can I avoid overestimating the remaining cost after picking up the weapon? It's tempting to say "let's assume the best possible outcome will come to pass", but if there're any further options after picking up the item than equipping and using it then calculating the best outcome would require its own planning exercise, turning my A* into a DFS.

Some plausible future actions that could lower our actual cost to lower the most obvious estimate:

wield the weapon with two hands, in order to do more damage
cast Haste on ourselves to double our attack speed
use a weapon-specific technique, e.g. sweeping our opponent's feet / tripping them using the haft of a polearm


texts: How to make multiple AI surround a player

texts:
I am working on a top-down RPG game and I have come across a problem. I am working on an AI system to allow the enemy AI to surround the player. I've been trying to keep my implementation really simple, however, I've been running into problems.

Here is what it currently looks like:

X represents the player and Y represents the friendly AI. There are 42 waypoints in total that the enemy can potentially occupy.

However, if any of the waypoints of the player object encounters an obstacle, or if another friendly AI is too close, it will disable those waypoints:

This poses a big problem because I do not have all 42 waypoints. From the looks of it, I might need something more dynamic in my case.

Are there any alternative ways to allow a large number of AI to surround the player or its allies?


texts:
I know Q3 + Q4 = 90

I searched internet and many physic topics, but not found how to calculate this values in Java?

(I found V3 and V4 but not found Q3 and Q4)

So how can i calculate V3, V4, Q3, Q4 values after the collision in Java?


texts: Intersecting Triangle and BoundingBox in 3D environment

texts:
I am trying to check if a triangle is intersecting a BoundingBox in a 3D space with libgdx, but I am unable to find anything that can help me with that.

I tried using a Plane but it is not precise enough and I would like to avoid using Bullet.

Is there any existing code that I can use to deal with this ?


texts: How do I convert the coordinates of a click to a tilemap position?

texts:
How do you turn a tilemap (produced by TileD) for cocos2d where I can click on individual items and get a callback?

Is it just a case of converting captured touch and finding out where it is on the tilemap and then converting that to pixels  -- but that doesn't say what item was clicked on.

I have a tilemap of a city with buildings on it, and I'd like to be able to click or press on a specific building, get a callback.

What would be the best way to accomplish this?


texts: Strategies for monster targeting AI in a turn-based combat system

texts:
I am making a Final Fantasy-style battle system.

I have a random generator that select the monsters move when it is their turn; different moves have different chances to be performed. I also have reactions and conditional actions for the monster to create simulated intelligence... but what I can't figure out is targeting.

I could just choose randomly between the five player characters, but I was looking for something that would make the game more challenging by adding some kind of strategy to the monsters' actions.

I code in C++.

Does anyone have an idea how to implement a system for the monster to choose who to attack besides completely random?


texts:
I want to start creating a very long project which i will work on and learn from. I've been making some basic games. Now i feel it's tine to step it up a notch.

My idéa is to create a 2.5d game such as Zelda. But i got stuck with viewport and world units. Since there is alot of viewports i can choose from and i've read what they offer.
So what is the preferred viewport, dimension and world unit for a 2.5d rpg mobile/desktop game?

Thanks


texts: What are the drawbacks of this messaging system implementation?

texts:
So I've just been thinking about component and messaging systems recently for simple C# XNA games and came up with this. How extensible would this implementation be and what are the drawbacks? Example below:

Score

class Score
{
    public int PlayerScore { get; set; }

    public Score()
    {
        EnemySpaceship.Death += new EventHandler<SpaceshipDeathEventArgs>(Spaceship_Death);
    }

    private void Spaceship_Death(object sender, SpaceshipDeathEventArgs e)
    {
        PlayerScore += e.Points;
    }
}

EnemySpaceship

class EnemySpaceship
{
    public static event EventHandler<SpaceshipDeathEventArgs> Death;

    public void Kill()
    {
        OnDeath();
    }

    protected virtual void OnDeath()
    {
        if (Death != null)
        {
            Death(this, new SpaceshipDeathEventArgs(50));
        }
    }
}

SpaceshipDeathEventArgs

class SpaceshipDeathEventArgs : EventArgs
{
    public int Points { get; private set; }

    internal SpaceshipDeathEventArgs(int points)
    {
        Points = points;
    }
}

Basically, the idea uses the built in events system in C#. When something interesting happens to an object, it raises a static event. Then, anything else in the game that wants to know when that happens subscribes to that static event and does something in response. In this case, the Score class subscribes to the static Death event of a Spaceship and when it dies, it uses the EventArgs to adjust the score accordingly.

Would this kind of architecture start to crumble and get quite confusing as the development of the game progressed? Thanks for reading.


texts: OpenGL: Shader using wrong layout location

texts:
It's actually taking the color vector instead of the vertex vector. I noticed because I set the colors to random(), and the triangle clusterfudge that is my cube keeps changing shape when I reload the program.

I'm in the process of updating my code to match OpenGL3/4 standards and use PyGLM instead of numpy. Unfortunately it looks like my pointers are getting scrambled by the VAO.

I checked my view, perspective, and model matricies and they appear to be correct. I have also tried transposing them to no avail. Here's the VBO:

   vector                               color (random)
 [[-0.25       -0.25        0.25        0.4582803   0.8329993   0.36713707]
 [-0.25        0.25        0.25        0.7530541   0.87386566  0.07133926]
 [ 0.25        0.25        0.25        0.2536045   0.34725097  0.5796058 ]
 [-0.25       -0.25        0.25        0.4582803   0.8329993   0.36713707]
 [ 0.25        0.25        0.25        0.2536045   0.34725097  0.5796058 ]
etc...

Here's my shader code:

#version 420
layout (location=0) in vec3 vertex_attrib;
// in vec3 texcoord_attrib;
// layout (location=1) in vec3 normal_attrib;
layout (location=2) in vec3 color_attrib;
out vec3 vertex;
// out vec3 normal;
out vec3 color;

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

void main() {
    gl_Position = projection * view * model * vec4(vertex_attrib, 1.0f);
    vertex = gl_Position.xyz;
    // normal = normal_attrib;
    color = color_attrib;
}

Commenting/uncommenting the normal location appears to do nothing.

VAO code where it binds the pointers for the VBO:

    self.VBOs.append(VBO)
    try:
        VBO.bind()
        for args in self.vptr_args:
            print(args)
            glEnableVertexAttribArray(args[0])
            glVertexAttribPointer(*args)
    finally:
        VBO.unbind()

# args for the two calls of glVertexAttribPointer: (result of the print)
# index=0, size=3, typ=GL_FLOAT, normalized=GL_FALSE, stride=0, pointer=None
# index=2, size=3, typ=GL_FLOAT, normalized=GL_FALSE, stride=0, pointer=c_void_p(12)

I'm terribly confused. The only thing I can think of is that PyGLM says it's using high-precision floats which is messing up the offset?

Edit: GLGets

VertexPointer 0
Enabled:  1
Size:  3
Type:  5126
Stride:  0
Buffer binding:  1
Ptr: 0
//
VertexPointer 1
Enabled:  1
Size:  3
Type:  5126
Stride:  0
Buffer binding:  1
Ptr: 12


texts: UI Dropdown - Is it possible to have a custom value type instead of an index?

texts:
I'm using the UI Dropdown component which lets you set the text of an option (OptionData) only.  The value of an option is the index position in the options list, so there is no way to set this.

My problem is that I have a dictionary<string, tile> that I use to populate the dropdown options, but I would like the value of the option to be the id of the tile class, not the index position.

Edit:

I know I can access elements from the list by using the value (index).

list[dropdown.value].id

But I wanted to see about extending the dropdown with this small change, as I have some other changes I would like to make, but wanted to start with something simple first just to get an idea of what is possile.

I do not want someone to post a full code solution.  Am mostly after some pointers.  Looking at the dropdown class, I don't see how I can extend it to modify some things (value in this case), it looks like I would have to implement by own version?

Some code will make this a little clearer I think:

// All tiles into list.
List<Tile> list = new List<Tile>(mydictionary.Values);

// Sort all tiles based on the tile name.
list.Sort((x,y) => x.name.CompareTo(y.name));

// Current way to add list to dropdown.
for(int i=0; i<list.Count; i++){
    dropdown.options.Add(new Dropdown.OptionData(){
        text = list[i].name // Tile name (string).
    });
});

// What I want to do.
for(int i=0; i<list.Count; i++){
    dropdown.options.Add(new Dropdown.OptionData(){
        text = list[i].name, // Tile name (string).
        value = list[i].id // Unqiue tile id (string).
    });
});

// Getting changed value
dropdown.onValueChanged.AddListener(delegate {
    Debug.Log(dropdown.value); // Instead of the index selected, I want the tile id
});

Or if the value is needed internally for some reason, then maybe an extra property that can be set and retrieved.

for(int i=0; i<list.Count; i++){
    dropdown.options.Add(new Dropdown.OptionData(){
        text = list[i].name, // Tile name (string).
        tile_id = list[i].id // Unqiue tile id (string).
    });
});

dropdown.onValueChanged.AddListener(delegate {
    Debug.Log(dropdown.tile_id);
});

I took a look at the DropDown class to see if I could extend it and add the "tile_id" option in, but I got completely lost on what to do, as I am still quite new to C#.

https://bitbucket.org/Unity-Technologies/ui/src/a3f89d5f7d145e4b6fa11cf9f2de768fea2c500f/UnityEngine.UI/UI/Core/Dropdown.cs

https://docs.unity3d.com/ScriptReference/UI.Dropdown.html


texts: (Unity) Drag and detect object below when dropping

texts:
I'm studying game development in Unity and I want to create a idle/clicker game like Cow Evolution.

I'm using OnMouseDown, OnMouseDrag and OnMouseUp to move the GameObject around the scene.

Now I want to detect the collision when dropping (OnMouseUp) a GameObject over another GameObject.

Like in this video:  https://www.youtube.com/watch?v=3OK77oVV_G0

Assuming there's more than one object below, I must detect which one is with most below the dropped object.

I apologize if it is difficult to understand my English.

Thank you.


texts: Is there a specific name for this type of concept art and the artist who does them?

texts:
Let's say you already have the fundamentals of your game: you created gameplay that you and your (possible) playtesters find enjoyable to play, and you think you can flesh out your game more. However, it's all just colorless blocks and cones at this stage. It's still just a prototype and you don't have a clear vision of how you want the game to actually look.

Before you try to glue together something compelling in your game engine, you want to create a mockup of how your game could possibly look like, just like how Bloodstained did on their Kickstarter page:

These aren't ingame screenshots, those were made before the game even started. How are these prototype images called and what are their artists called? What kind of "keywords" do I have to look for if I want to hire an artist to prototype one or multiple possible looks for my game?


texts: Proper indoor lighting without directional light

texts:
I would like to know how to properly handle indoor lighting without a directional light. My scene has a room( its some kind of shop), in which the player and ai-agents can move around. I can get good results by placing long area lights at the ceiling and baking the light, and placing light probes so the dynamic objects are also affected by the baked light.

The main problem is how can i get real-time shadows for the player and the ai-agents ?

You could position a few point lights roughly where the center of the area lights would be. But i don't know if i can or even should have so many shadow casting lights in one scene. I tried placing 6 or so and i think only 4 of them would actually cast shadows.

I would really appreciate some help. For this project, i've kind of given up on it but i really want to know. Thank you.


texts: How to highlight intersection between objects?

texts:
I'm new to Unity and I'm developing an augmented reality app.

My situation is as follows: I have two objects in the scene, a neighborhood model and a cube. The mockup will be the object I am going to enlarge and the cube will be like the acrylic box where the mockup is. The cube represents the viewing area and will be transparent. The model has an animation in which it moves and scales and the cube remains fixed.

I need something to assign to the cube so that when expanding the model, the parts that stick out of the cube will have 50% colorless transparency (all gray) and the part of the model that is inside the cube (in intersection) remains solid and with the colors and textures.

The idea is to present the mockup on an initial scale that is inside the cube (acrylic box) then the model's animation will zoom in on the mockup at certain points, the whole mockup will be much larger than the cube. the outside of the cube is transparent and colorless, and the inside remains coloured  to make it more prominent.

Can someone help me?


texts:
I have two completely white bitmaps here:

They're there, trust me.

When I put one on top of the other and scale them down with TextureFilter.Linear I get this:

How do I get rid of the dark pixels?


texts: I'm having trouble finding sprite sheets that have the characters turn in 8th movements, so that you can see back, front, left, right, and in between.  What would be a good term to search for when trying to find these kind of sprite sheets?


texts:
Basically what i wish to ask:
*A game is developed for android platform, is on google store and its leader board (scores etc.) are on Google server.

Can we display the top scores from there on a webpage/website which is on a different server? Yes or No!


texts: How tightly should I stick to entities in a component based game?

texts:
I apologize if the question is a little vague, It was hard to explain it in a short sentence.

I'm currently writing a component based game, it's getting along great but I'm starting to wonder how tightly I should stick to "the rules". Actually, I'm not even sure what the rules are!

It's clear that every interactive gameobject should be an entity. But what about the level elements? I'm using a tile based system, should every tile be an entity? I do have a GraphicsComponent ready with all it's displaying goodness that I need to display them. But coming from inherritance, it just feels strange threating a "gameobject" the same as a level element.

It also feels like I'm dumping everything in a big empty space right now, there is no dedicated environment for different game elements. Where a tile normally is part of a map, and an object normally is part of a world. The tiles and objects are now thrown in the same place.

Same goes for interface components, I was in need of animated button, and that GraphicsComponent looked very tempting again.

How is this usually handled in component based games?
Most articles online only mention the use of components for gameobjects, and looking into other component engine source code gives me a headache.


texts: How Many Entities can the Unity Game Engine Handle Before it Starts to Lag?

texts: I am building a player model for my game, the model is very complicated due to its ability to be customizable. A single player entity can have 70 + entities including the head, parts to the face, arms, legs, shoes, and the clothes and armor it wears, and the weapons it has equipped. I just need to know, at what point does the unity game engine start lagging due to too many entities? Also, the game is low poly, there are many entities, but each one is block based, or very simple in design.


texts: How do I do 3d collisions in isometric game?

texts:
I've wondered how to get basic collision detection working in an isometric game. I'm using panda3d which has very comfortable support for bullet, ode and a small builtin physics framework. The problem is that these naturally don't work with flat images. I'm using dynamically generated quads as canvases in the 3d coordinate system. Every image or texture is mapped on one of these. The idea is to create tiles with images and place them in 3 dimensions to let panda3d do the rendering.

In order to place a tree on the screen I would generate one of the dynamic flat quads and map a texture with an image of the tree on it. Then I would move the quad to the desired position and everything's fine. Panda3d manages the correct rendering order.

Up to now the player object simply walks through the environment. I need to implement basic collision detection in order to solidify the trees. Browsing through previous questions I've found this one How do I handle Isometric collision detection? Unfortunately the question only targeted collisions to prevent the player from falling through the ground and allowing him to jump on platforms. This can be done comfortably with panda3d's builtin physics.

Here's a picture to show you what I want:

The ground itself is composed of a 10x10 grid of tiles. I've used the same texture for all of them. The tree is not a sprite that's rendered in 2d. It's actually a flat rectangle with a partially transparent tree texture. The white rectangle is my player object. With the standard 3d physics I could prevent the player from walking through the quad but the tree would still be perfectly flat. I thought about adding a "dummy mesh" to have 3d collisions but that would surely come pricey in terms of performance and would spoil the neat implementation of my 3d canvases.

Is there a canonical way to get 3d collisions in an isometric game ?

How would you do this ? Please answer this second question on behalf of panda3d.

I know that this is probably rather complicated. A link to a good article would be perfect. If you want to have a look at my code, you might want to read this question: How do I use setFilmSize in panda3d to achieve the correct view?

UPDATE:

Here's another picture that might depict the problem better


texts: Using break statement in a GLSL compute shader

texts:
I'm writing a compute shader that is invoked once for each vertex of a geometry, and does a distance based search to find the the N closest vertices. To do this each invocation iterates over the position buffer and does a distance based check:
uniform float   uRadius;
uniform int     uMaxPoints;
void main()
{
    vec4 currentPoint = texelFetch(inputPosBuffer, ivec2(gl_GlobalInvocationID.xy), 0);

    if (currentPoint.w < 1.0f)
    {
        int pointsInRange = 0;
        uint rx; // inputPosBuffer width
        uint ry; // inputPosBuffer height

        // I also tried to add the uMaxPoints check to the for loop
        // as opposed to using a break
        // but the results also seems to be wrong
        for (uint i = 0; i < rx * ry, pointsInRange < uMaxPoints; i++)
        {
            uint x = i / rx;
            uint y = i % rx;
            vec4 p = texelFetch(inputPosBuffer, ivec2(x, y), 0);
            if (distance(currentPoint.xyz, p.xyz) <= uRadius)
            {
                pointsInRange++;
            }

            if (pointsInRange >= uMaxPoints)
                break;
        }
        currentPoint.w = float(pointsInRange);
    }
    imageStore(computeOutputBuffer, ivec2(gl_GlobalInvocationID.xy), currentPoint);
}

The issue is my break statement which I use to stop looping if uMaxPoints (max number of closest points to find) is reached, I'm not sure what happens but if I remove it the outcome is correct. I am assuming that my texelFetch should not be causing any problems as it is a read only.
So two questions:

Is it OK to use break in this context or does it maybe apply break to the whole work group?
Do I need a barrier somewhere or something similar?


texts: When is a quadtree preferable over spatial hashing?

texts:
I'm making a 2d platformer with lots of objects at the same time. They're all AABB collision detected. I first tried a quadtree to decrease the number of of objects to check, tried a few different configurations, but it didn't prove as effective as I needed. I implemented a spatial hash and it's way more efficient, the number of objects to check for each collision went down drastically.

Is there a case when doing 2d collision detection using a quadtree is preferable over spatial hashing? According to my tests, it seems spatial hashing always ends up with less objects to be tested for collision?

I haven't done timing over the algorithms, but is hashing simply very expensive or difficult to implement when you're, for example, coding in C?  Worth noting is that I'm writing the game in javascript, where you have hashing "for free".

Here's the comparison, did I overlook something? http://zufallsgenerator.github.io/2014/01/26/visually-comparing-algorithms/


texts: What is Clash of Clans projection called?

texts:
What is the Clash of Clans projection (it doesn't seem to be isometric Image )
Image from here


texts:
I am trying to implement shadow mapping into my project and am stuck at this problem: If I'm reading the shadow map values with glReadPixels and linearize those values, I am getting exactly the value I was looking for: ranging from 0 to 1. But when I am doing the exact same calculation in my shader, everything, where I rendered an object, is white.
Another thing I noticed(which i assume is directly linked to my problem) is that if I am changing glClearDepth to anything different than 1, the output of my shader is black and the output of glReadPixels after linearizing is not anymore the value I wanted but anything else.

Here is the code where I am creating the depth texture:

glBindTexture(GL_TEXTURE_2D, _textures[GBTEXTURE_DEPTH]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);

glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, _textures[GBTEXTURE_DEPTH], 0);

And here is the fragment shader:

in vec2 fragUV;
uniform sampler2D tex;

float zfar = 1000.0f;
float znear = 1.0f;

float linearize(float depth)
{
    return (-zfar * znear / (depth * (zfar - znear) - zfar)) / zfar;
}

out vec4 finalColor;
void main(void){
    float depth = texture2D(tex, fragUV).r;
    depth = linearize(depth);

    finalColor = vec4(depth);
}

I am doing the exact same calculation on the CPU, with correct values as a result.

I hope I described my problem with enough details for you to help me.