texts: How can I efficiently implement a bitmask larger than 64-bits for component existence checks?

texts:
In my ECS implementation, I use bit-wise operations (as described and illustrated in this thread) to tell an entity what type of components it currently consists of. So my Entity class has the following member:

unsigned long m_CompMask;

The different component types are then defined as an enum, whose member values are all power of two:

enum ComponentType
{
    COMP_TYPE_UNKNOWN                   = 0,
    COMP_TYPE_PERSON                    = 1,
    COMP_TYPE_RENDERABLE                = 2,
    COMP_TYPE_MOVEABLE                  = 4,
    [...]
};

Each time a new component is added to my entity instance, I do the following bit operation to update the mask (where newType is a member of the enum mentioned above):

m_CompMask |= newType;

This approach enables me to efficiently check if a certain entity instance has a certain component (and hence might be relevant for a specific system), like so:

return (m_CompMask & type);

The limiting factor in this approach however is the m_CompMask variable since it won't be able to handle more than 64 component types (if I increase it to unsigned long long).

I don't expect to be needing more than that in my current project, but nonetheless I'd like to hear some ideas regarding alternatives that allow more than 64 types (as big games certainly need to) while still maintaining the ease and efficiently of those bit-wise operations as much as possible? Any ideas how this is handled in "proper big" projects?


texts: Reinterpreting point inside a distorted cube

texts:
Given a cube:

And a point anywhere inside that cube.
Could that point be reinterpreted given any kind of deformation applied to the cube?

I.e., where would that point be inside the deformed cube?
The cube could be deformed in any way, and we only know the location of the vertices.
Likewise, given a point in relation to the distorted cube, could we find where that point is in relation to the undistorted cube?
The vertices of the cube are indexed and stay the same between the undistorted and the distorted cube.


texts: Dealing with 2D pixel shaders and SpriteBatches in XNA 4.0 component-object game engine?

texts:
I've got a bit of experience with shaders in general, having implemented a couple, very simple, 3D fragment and vertex shaders in OpenGL/WebGL in the past. Currently, I'm working on a 2D game engine in XNA 4.0 and I'm struggling with the process of integrating per-object and full-scene shaders in my current architecture.

I'm using a component-entity design, wherein my "Entities" are merely collections of components that are acted upon by discreet system managers (SpatialProvider, SceneProvider, etc). In the context of this question, my draw call looks something like this:

SceneProvider::Draw(GameTime) calls...
ComponentManager::Draw(GameTime, SpriteBatch) which calls (on each drawable component)
DrawnComponent::Draw(GameTime, SpriteBatch)

The SpriteBatch is set up, with the default SpriteBatch shader, in the SceneProvider class just before it tells the ComponentManager to start rendering the scene. From my understanding, if a component needs to use a special shader to draw itself, it must do the following when it's Draw(GameTime, SpriteBatch) method is invoked:

public void Draw(GameTime gameTime, SpriteBatch spriteBatch)
{
    spriteBatch.End();
    spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, EffectShader, ViewMatrix);

    // Draw things here that are shaded by the "EffectShader."

    spriteBatch.End();
    spriteBatch.Begin(/* same settings that were set by SceneProvider to ensure the rest of the scene is rendered normally */);
}

My question is, having been told that numerous calls to SpriteBatch.Begin() and SpriteBatch.End() within a single frame is terrible for performance and creates a number of special cases for my drawing logic, is there a better way to do this? Is there a way to instruct the currently running SpriteBatch to simply change the Effect shader it is using for this particular draw call and then switch it back before the function ends?


texts: How to fake flipping a skeleton in Box2D?

texts:
Imagine I have a skeleton — that is a set of bodies held together through various constraints and joints — and I want to flip it. Bodies cannot be flipped in Box2D, so how can I fake that?

Here's an example: I have a humanoid skeleton, made out of different Box2D bodies: the head, torso, upper arm, lower leg, etc. These Box2D bodies are held together by joints. Some of the joints have angle constraints, like the ones between the upper and lower arm, which do not allow the 'elbow' to twist unnaturally.

When I turn my character the other way around, I should flip the skeleton and its joints should be flipped as well. How can I achieve that in Box2D?


texts: strange behavior in Box2D+LibGDX when applying impulse

texts:
I have been playing around with Box2D and LibGDX and have been using a sample code from DecisionTreeGames as the testing ground. Now I have a screen with four walls and a rectangle shape, lets call it a brick. When I use applyLinearImpulse to the brick, it starts bouncing right and left without any pattern and won't stop!

I tried adding friction and increasing the density, but the behavior still remains the same. Here are some of the code that might be useful:

method for applying the impulse:

center = brick.getWorldCenter();
brick.applyLinearImpulse(20, 0, center.x, center.y);

Defining the brick:

brick_bodyDef.type = BodyType.DynamicBody;
brick_bodyDef.position.set(pos); // brick is initially on the ground
brick_bodyDef.angle = 0;
brick_body = world.createBody(brick_bodyDef);
brick_body.setBullet(true);
brick_bodyShape.setAsBox(w,h);
brick_fixtureDef.density = 0.9f;
brick_fixtureDef.restitution = 1;
brick_fixtureDef.shape = brick_bodyShape;
brick_fixtureDef.friction=1;
brick_body.createFixture(fixtureDef);

Walls are defined the same only their bullet value is set to false

I would really appreciate it if you could help me have a change this code to have a realistic behavior (i.e. when I apply impulse to the brick it should trip a few times and then stop completely).

Further info:

At first, the brick is standing still.
With an impulse to its right side, it slowly leans rightward.
the moment it touches the ground wall, it jumps back with a high speed. It is like the ground is a trampoline!!
from here on, it bounces very quickly.
In these jumps it rarely touches other walls.


texts: Bad performance using VBO with OpenGL ES in Android

texts:
I'm making an Android app and I need to draw some polygons using OpenGL ES. I'm able to render them but I'm disappointed with performance. I updated the code to use VBO but I didn't notice any improvement. I want to render at 60 frames per second (16 ms per frame).

I have a test project where I render several triangles on the screen. When I render 1000 triangles it takes about 20 ms per frame (depending on the device).

I want to keep the rendering under 10 ms because I need the rest (6 ms) to perform other calculations (e.g. update positions, detect collisions, etc.).

Here is the code where I render a triangle:

public void render(int positionLocation, int colorLocation)
{
    GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, this.bufferIndex);
    GLES20.glVertexAttribPointer(positionLocation, Polygon.POSITION_COMPONENT_COUNT, GLES20.GL_FLOAT, false, Polygon.STRIDE, 0);
    GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, 0);

    GLES20.glUniform4f(colorLocation, this.red, this.green, this.blue, this.alpha);
    GLES20.glDrawArrays(this.mode, 0, this.length);
}

https://github.com/mauriciotogneri/test/blob/master/src/com/testopengl/Polygon.java#L51-66

Here is the code where iterate over the triangles:

private void renderTriangles()
{
    long start = System.nanoTime();

    for (int i = 0; i < COLUMNS; i++)
    {
        for (int j = 0; j < ROWS; j++)
        {
            float x = (i * TRIANGLE_SIZE) + (TRIANGLE_SIZE / 2);
            float y = (j * TRIANGLE_SIZE) + (TRIANGLE_SIZE / 2);

            moveTo(x, y);

            this.triangles[i][j].render(this.positionLocation, this.colorLocation);
        }
    }

    long stop = System.nanoTime();

    this.totalTime += stop - start;
    this.totalFrames++;

    Log.d("TEST", (this.totalTime / this.totalFrames) / 1000000 + " ms");
}

https://github.com/mauriciotogneri/test/blob/master/src/com/testopengl/MapRenderer.java#L117-139

(Change the value of NUMBER_OF_TRIANGLES to display more triangles)

For what I understand, the method GLES20.glDrawArrays(...) takes too much time if I need to call it 1000 times per frame (one per triangle).

Is there another way to render several polygons that doesn't take too much time?

Notes:

In the example all the triangles have a fixed position on the screen but in the real scenario they will move around
In the example I assign a random color to each triangle but in the real scenario each of them will have a fixed color


texts: libGDX upload z-axis of sprite to graphics card

texts:
Background:
I want to obtain each fragments position via vertex interpolation to then calculate the light vector for phong shading (L = [Fragment pos] - [light source pos]).

Problem:

At the moment I am using libGDX's com.badlogic.gdx.graphics.g2d.Sprites to upload my 2d sprites via the batch to the graphics card. However they only transport the x and y information for each vertex ( I think in the shader z is 0). I also want to upload the z axis of the sprite for use with normal map based pixel shading (calculate the vector of the incoming light).

Should I use a com.badlogic.gdx.graphics.Mesh for that or can I extend the Sprite class and somehow put the z axis in the vertices float[] array? If I should do that, how do I do this?


texts:
I was playing around with some isometric ideas, I want to create fairly large maps with a couple of Z levels, much like the older X-com games. I figured I am probably way better off to draw the quads however I need and just rotate the camera. So I started experimenting with this. I am currently creating a "chunk" like below and render it with a ModelBatch.

private Model floorChunk(int width, int height) {
        textureAttribute = new TextureAttribute(TextureAttribute.Diffuse, texture);
        Material mat = new Material(textureAttribute);

        ModelBuilder builder = new ModelBuilder();
        builder.begin();
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                builder.part("floor[" + x + "|" + y + "]",
                        GL20.GL_TRIANGLES,
                        VertexAttributes.Usage.Position | VertexAttributes.Usage.Normal | VertexAttributes.Usage.TextureCoordinates,
                        mat)
                        .rect(0 + x, 0, 0 + y, 0 + x, 0, 1 + y, 1 + x, 0 ,1 + y, 1 + x,0 ,0 + y,0, 1, 0);
            }
        }
        builder.manage(texture);

        return builder.end();
    }

I tried running it with 200 by 200 but thats running at around 20FPS. Now I don't need to zoom that far out but about 50 tiles across the screen is the bare minimum and need to take into account additional chunks. Then adding walls, objects, NPC and multiple layers this way will probably not work. I have not much experience with 3D rendering in LibGDX and neither with Open GL but I am open to suggestions, especially suggestions that show how to bind a specific texture to a specific mesh part.


texts: Where to store service urls for a Unity3D game

texts:
I have URL information for services (dozens of them) that I want to store in a Unity3D web player project.  What is a good practice for storing it.  (please don't say hard coding them)

I've recently joined a large scale Unity 3D project in the business world.  I've noticed that there is no configuration file of any type.  I.e. All URLs for service calls are hard coded.  (among other configuration settings that are not typical for player editing)

While looking for a good solution to store/load, I'm seeing that:
1) Unity does not appear to have any kind of AppSettings.  I.e. like Visual Studio dlls/exes/services might.  (PlayerPrefs expressed in #3)

2) Web Player (which the project uses) does not support File IO, to store my own config.xml/config.json type file.

3) PlayerPrefs appears that it will remain isolated to the local machine.  Updating the project does not replace the player prefs, and new variables are supposed to be hardcoded to populate the PlayerPrefs if those variables didn't already exist.

4) Hard Coding the values creates a hefty inconvenience, as we push our solutions from Dev to Test to Staging to Prod, we have to make sure to replace a code file.  (typically systems are designed to change config files.)  Additionally, once the code was built, we wouldn't be able to reasonably change the settings to experiment with different servers or other configuration changes.

What would you recommend?


texts: Why does PIX suggest my frames are rendering out of order?

texts:
When my application goes into a fullscreen state my movement is not smooth. It seems like frames are not rendered in the correct order, doing something like: 1, 3, 2, 4, 6, 5, ...
making the movement flicker.

For my PIX test, I draw really a low number of primitives (1140 triangle exactly) inside six vertex / index buffers. I clearly see a difference in the GPU frame "ordering" in PIX. Here is the result when in windowed mode:

PIX screenshot1 http://www.s33m3.be/PIX/PIX2.png

You can see that the GPU time needed for the frame is nearly in sync with the CPU time needed to generate it.

But in the fullscreen state here is what I got (same scene, without camera movement):

PIX screenshot2 http://www.s33m3.be/PIX/PIX.png

You can see that each GPU frame processing is split into at least two parts, and the GPU doesn't wait the end of a frame before starting another one.

What could cause this?


texts:
I would like to rotate the car so that the front wheels are touching the ground without using physics.

As you can see i want to rotate the car by angle a, but making sure that both tires are touching the floor. but it is kind of hard as the centre mass of the wheels is not the back of the car.


texts: Movement constrained to the faces of a cube

texts:
The basic setup I'm working with is a cube rendered in-Engine (Panda3d, although I only am looking for a generalized solution) as well as a 2d square on one face of the cube. The eventual outcome I'm looking for is for the player to control the 2d square with WASD as it moves on the faces of the cube (never anywhere else)

My current solution is to have the player object contain two unit vectors: forward and right. The forward vector controls with direction the player moves when W/S are pressed, and right controls the direction for A/D. So for example, the player starts out on the near Y face (y = -1), so the vectors are:

forward = {0, 0, 1}
right = {1, 0, 0}

When the player's position exceeds the a boundary of the cube (e.g. on a unit-cube, the Z coordinate is greater than 1), forward and right are recalculated for the new face the square should be on, and the square is appropriately rotated.

I've started to get this working, however, in this early implementation, there is a fixed camera. Eventually, the camera is planned to move to be orthogonal to the face the cursor is currently on, so I realized that what signifies "forward" is going to vary based on the path a player takes to get to a face. My struggle is to now find an appropriate movement method to the cube-face constrained motion, with a moving camera.


texts:
I have a global light in my scene. It casts shadows using shadow mapping and has an associated camera (for rendering to the shadow map). I'm going to refer to it as my "shadow camera" from now on.

I need to find a way to place my shadow camera's near plane as close as possible to my scene's bounding box (clip it to the scene bounds).
I need to do this so the shadow casters are never clipped by the shadow camera's near plane (otherwise I'd get holes inside of shadows) and to make sure I don't accidentally cull any shadow casters behind the camera. This would also allow me to increase the shadow mapping precision, because it lets me move the near and far planes closer together.

Example 1 (possible to do using a simple plane check):

Example 2 (NOT possible to do using a simple plane check):

The black box is the scene's AABB (but it would be nice if this would work for OBBs or other shapes too).
The yellow arrow represents the light direction.
The green box is the shadow camera's frustum without any modifications.
The red box is my desired result.

At the moment I'm constructing the red box by projecting the black box onto the global light's direction vector and use the closest vertex's distance to compute the shadow camera's near plane. But this makes it impossible to get something as seen in the 2nd image. Instead the red box starts above the scene's AABB.
I have thought of using SAT for this, but it doesn't seem to be the solution.


texts:
I have a 2D space shooter game. I looked up some questions from unity community and came across this solution. Below is the code for my player's movement:

//horizontal <- || -horizontal ->
//vertical down || -vertical up
float h = -Input.GetAxis ("Horizontal")*speed;
float v = -Input.GetAxis ("Vertical")*speed;

// do not let the ship get out of the camera
Vector3 viewPosition = Camera.main.WorldToViewportPoint(transform.position);
viewPosition.x = Mathf.Clamp01(viewPosition.x);
viewPosition.y = Mathf.Clamp01(viewPosition.y);
transform.position = Camera.main.ViewportToWorldPoint(viewPosition);

transform.Translate (h, v, 0);

I understand these functions as 0,0 being the left bottom of the camera and 1,1 being the right top. Therefore clamp01() is used. But with this code, half of my ship gets out of the screen, which is not what I want. How am I supposed to manipulate the clamp01 function so that the entire ship of the player stays in the camera scene?

Another workaround I thought was using the screen width and height and the regular clamp() function as follows:

transform.Translate (h, v, 0);

Vector3 tmpPos = transform.position;
tmpPos.x = Mathf.Clamp (tmpPos.x, -Screen.width / 2, Screen.width / 2);
tmpPos.y = Mathf.Clamp (tmpPos.y, -Screen.height / 2, Screen.height / 2);
transform.position = tmpPos;

However I get the Screen.height as 428, although the camera sees the interval of [-10, 10]. How am I supposed to clamp the movement independent of the game resolution, i.e. not using global positions but using relative positions so that I will be able to clamp correctly player's ship whatever the resolution of the game is?


texts:
I'm trying to add collider to the 3D scene. I have added mesh collider to the floor but I see the character is still floating up when I play.

How can I edit this collider. I don't see any edit collider option here(like we see in case of box collider & other one's)

Question has been updated with further details:

The floor is not perfectly plane. It's raised from some place and down from other. So, I don't see any problem with character properties. The problem with mesh collider is that it tries to join lower & upper parts of plain with a straight line. It doesn't exactly take the size of plane


texts:
Im trying to create a game on a 3d plane but with 2d objects. I have a perspective camera and the ground plane drawn. I can't seem to get sprites onto it.

I am trying to render the sprites, then to rotate over the x axis up into the 3d world. Is this even possible the way I'm trying it? If not how can I go about achieving this?

What I'm going for is almost like a Paper Mario look for the game objects, but on a larger 3d plane.


texts: Pickup another book or submerge into XNA

texts:
Completely read Head First C#.

Should I read something else or get personal with XNA from here on? Got links?

Edit: Hobby. Interested in 2D and 2.5D gamedev for personal fun, nothing serious. Multiplayer(in 2D/2.5D games) is also a very interesting topic for me. Basically not sure where to go now from here.


texts: Predicting circle-circle bounce vector when aiming one at another

texts:
I am making a game with libGDX (with box2d) in which you drag and aim one circle body at another then release to fire. I would like to be able to predict the path of the second circle based on the aim of the first. very like 8 ball pool when aiming your shot.

I have been playing around with various trig solutions but i just cant get it to work at all! I have also been reading about ray casting in which I would cast a ray from the center of the first circle body in the direction i am aiming. this would tell me where the ray intersects the second circle body (if it does so) but it would not be correct as the circle fixture would not actually collide where they ray does because it obviously has a radius.

Is the trig solution the correct path or is there a simpler way to do this?


texts: It is worth adding 'futuristic' features to our game, or should we put our focus elsewhere?

texts:
I'm lead programmer in a medium-sized indie game studio. This is our first game as a team. We're working on a futuristic FPS game, with a profit-sharing buisness plan.

Anyway, we have some very good programmers, who have the ability to create never-seen-before features (true realistic fluids, procedural mesh destruction, procedural skyboxes, etc.) And I'm wondering is there any point to implementing these things? They take a long time, but look brilliant. We're aiming for a 12 month development cycle. So should we do this, or just make a standard game.


texts: 2D Collision in tilemap - ArrayOutOfBounds

texts:
im trying to do collision detection with world based on tilemaps (two dimensional array)
array  -

private int WIDTH = 10;
private int HEIGHT = 6;
String[][] simplemap = new String[][]{

    { "0","1","2","3","4","5","6","7","8","g",},
    { "11","g","","","","","g","","","g",},
    { "22","g","","","","","g","","","g",},
    { "33","g","","","","","g","","","g",},
    { "44","g","","","","","g","","","g",},
    { "g","g","g","g","g","g","g","g","g","g",},
    { "g","g","g","g","g","g","g","g","g","g",},
};

than i create array from blocks and trying to show it

create blocks :

blocks = new Enemy[HEIGHT][WIDTH];
for(int i =0;i<HEIGHT;i++){
    for(int j=0;j<WIDTH;j++){
        blocks[i][j]= new Enemy(context,0,0);
        blocks[i][j].boxWidth=blockWidth;
        blocks[i][j].boxHeight=blockHeight;
        blocks[i][j].x=blockWidth*j;
        blocks[i][j].y=blockHeight*i;
        blocks[i][j].state = simplemap[i][j];
    }
}

im not sure about

blocks[i][j].x=blockWidth*j;
blocks[i][j].y=blockHeight*i;

but if write blockWidth*i (not j) than map building like rotated on 90 degree. Maybe error here in this code. Not sure
Than in glDraw i draw my map

for (int i = 0; i < HEIGHT; i++) {
    for (int j = 0; j < WIDTH; j++) {
        if ( blocks[i][j].state == "g") {
            blocks[i][j].draw(gl);
        }
    }
}

For collision i do a this code
(it's for Y collision detection) for X collision code similar

for(int i = (int)ball.y/tileSize; i<(ball.y+ball.boxWidth)/tileSize; i++) {
    for(int j = (int)ball.x/tileSize; j<(ball.x+ball.boxWidth)/tileSize;j++) {
        //System.out.print("  i = "+i+"j "+j);
        Log.e("ERROR ", " "+i+":"+j);
        Log.e("ERROR", "DY = "+dy);
        if (blocks[i][j].state=="g") {
                       //do what we need, check directions or something other
        }
    }
}

Problem
Map drawing ok with this code , and my object work only in small area like i =HEIGHT,
 In tests its like when i start moving from left to right side - i see 10 blocks(like road) app always crashed with nullpointerexception(from array out of bounds) after 4-5 blocks on road. I think i just not correct building my map and position . With this code i see on phone correct map, if change i and j when we set position for every blocks - than its rounded on 90 degree. Also exception on code if (blocks[i][j].state=="g") array out of bounds . Length 6 etc. I cant understand where my error, can any good guy help me ? please.

Regards, Peter.

Thank you all guys  Not sure if its right  - but in test its show all correct;
code for collision on Y

public void checkColisionY(){

        dy = dy + gravity * dt;
        ball.y = ball.y + dy * dt + 0.05f * gravity * dt * dt;
        for(int i = (int)ball.y/tileSize; i<(ball.y+ball.boxWidth)/tileSize; i++){
            for(int j = (int)ball.x/tileSize; j<(ball.x+ball.boxWidth)/tileSize;j++)
            {

                    if(dy>0){
                        if(ball.y+ball.boxWidth>=blocks[i+1][j].y && blocks[i+1][j].state =="g"){
                            ball.y = blocks[i+1][j].y-ball.boxWidth;
                            dy=dy*energyloss;
                            dy = dy * -1;
                        }
                    }
                }
            }
    }


texts:
I had some questions on geometry shaders.

Do directx geometry shaders offer anything over the opengl ones?

What advantages does the official geometry shader implementation on opengl 3.2 have over the plug-in for 2.0?  Is the official one faster?

What are the oldest cards which support opengl 3.2 and the geometry shaders on there?

What are the oldest cards which support opengl 2.0 and the geometry shader plugin?


texts: How do i eject bullet shells from a gun? Java/slick2d

texts:
So, here is my problem: I am working on a top down 2d shooter in Java and have a character, which can move and rotate/fire to the mouse direction.
Shooting guns etc. works fine but now i am trying to implement a shell ejection system, which "ejects" the shells next to the player. The problem is, that i can't just draw the shells next to the player since the player has an x and y position which are rotating. I want the shells to have a random radius in which they will be ejected. But i don't know how to implement something like this.
Any suggestions?

EDIT:
That's my shell-ejection method, which doesn't work(the angle represents the player angle):

    public void shellEjection(){
    x=(float) x*((float) (Math.cos(angle)));
    y=(float) y*((float) (Math.sin(angle)));

    double length = Math.sqrt((mouseX - x)*(mouseX - x) + (mouseY - y)*(mouseY - y));

    double xVel = (5 - x) /length * 5*bulletVelocity;
    double yVel = (5 - y) /length * 5*bulletVelocity;

    x+=xVel;
    y+=yVel;
}


texts:
I got this error message when trying to build and run on Android actual device.

UnityException: Unable to install APK!
Installation failed. See the Console for details.
UnityEditor.Android.PostProcessAndroidPlayer.ShowErrDlgAndThrow (System.String title, System.String message, System.Exception ex)
UnityEditor.Android.PostProcessAndroidPlayer.ShowErrDlgAndThrow (System.String title, System.String message)
UnityEditor.Android.PostProcessAndroidPlayer.UploadAndStartPlayer (System.String manifestName, System.String stagingArea, UnityEditor.Android.AndroidDevice device, System.String packageName, Boolean devPlayer, Boolean retryUpload)
UnityEditor.Android.PostProcessAndroidPlayer.PostProcessInternal (BuildTarget target, System.String stagingAreaData, System.String stagingArea, System.String playerPackage, System.String installPath, System.String companyName, System.String productName, BuildOptions options)
UnityEditor.Android.PostProcessAndroidPlayer.PostProcess (BuildTarget target, System.String stagingAreaData, System.String stagingArea, System.String playerPackage, System.String installPath, System.String companyName, System.String productName, BuildOptions options)
UnityEditor.Android.AndroidBuildPostprocessor.PostProcess (BuildPostProcessArgs args)
UnityEditor.PostprocessBuildPlayer.Postprocess (BuildTarget target, System.String installPath, System.String companyName, System.String productName, Int32 width, Int32 height, System.String downloadWebplayerUrl, System.String manualDownloadWebplayerUrl, BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry) (at /Users/builduser/buildslave/unity/build/Editor/Mono/BuildPipeline/PostprocessBuildPlayer.cs:316)
UnityEditor.HostView:OnGUI()

Why it happens? Please advice. Thank you.


texts: In a visual novel game with optional sidequests, how to encourage the sidequests without requiring them?

texts:
Context
I'm working on a small visual novel-style game, telling the story of a defense attorney and investigator. The story is split into chapters, with each chapter being a new case, and there are also recurring characters who develop throughout the story. It's a mini Phoenix Wright-style experience, with some point-and-click detective work mixed in.
As part of the game, you can embark on optional character-based sidequests, each of which focus on a different character and showcase some development between them and the protagonist. A few of these sidequests unlock after completing each case, and are usually related to the case that just happened. For example, after finishing a case involving a video game convention, you unlock an optional sidequest where you can take one of the supporting characters (the "tough guy who's secretly a dork on the inside", of course) to the convention before it leaves town.
I want to make these sidequests optional, and not force the player to do all of them or make them feel like they have to say "yes" to all of them - that is, I want to establish that they're free to decline an invitation if they don't like a particular character as much as the others and would rather not take them out for ice cream. However, I still want to make sure the player does some of them, because I feel many of them, if missed, would cause the player to miss out on really neat parts of the game. (If it helps, the game doesn't have a "completion percentage" or anything, just small achievements for doing certain things.)
My question
Given this design, I have a conundrum. I want the player to do at least some of the optional sidequests, but I don't want to force it or make them feel like it's necessary to see every single one of them. I don't want to place an arbitrary "you must do 3 sidequests to proceed" roadblock, but I also don't want the player to skip all of them and do the entire story without developing any of the characters. That obviously defeats the point of a heavily character-based visual novel! So, this is my dilemma:
What game mechanics in a visual novel are best to encourage optional sidequesting, but not require it for story progression or completion?
I have a couple ideas for this, since a lot of games have offered solid solutions for this problem already:

Making the sidequests optional, but having rewards for doing them. This is the approach that most games take nowadays. You don't have to do the sidequests, but maybe if you do one, it unlocks a palette swap, an item, or a hint coin.
Affinity mechanics. Maybe if you do enough sidequests for your prosecutor buddy, he gets closer to you and gives important hints in a later cases. This would work similarly to "friendship" in other games, where there's a number that keeps track of how good your relationships with different characters are and doing quests increases that number. At the same time, I think this encourages too much of a "metagame" approach, where players will just do every sidequest for a character all at once to unlock their bonus. It also makes the difficulty curve of the game wonky, since I want the cases to start easy and get progressively harder, and giving substantial bonuses in the late game might mess with that design.
Requiring the player to do at least X of them. This is the roadblock approach - blocking the progression of the story until the player does at least 1, 2, or 3 of the available sidequests. I dislike this because it feels like I'm being arbitrary and might frustrate the player if they don't like the current sidequest options and really want to do the next case.

Ideas and other suggestions are welcome!


texts: What would most games benefit from having?

texts:
I think I've seen "questions" like this on stackoverflow but sorry if I'm overstepping any bounds.

Inspired by my recent question and all the nice answers (Checklist for finished game?) I think every gamedev out there has something he/she thinks that almost every game should have. That knowledge is welcome here!

So this is probably going to be an inspirational subjective list of some sorts and the point is that anyone reading this question will see a point or two that they've overlooked in their own development and might benefit from adding.

I think a good example might be: "some sort of manual or help section. Of course it should be proportional to how advanced the game is. Some users won't need it and won't go looking for it but the other ones that do will become very frustrated if they can't remember how to do something specific that should be in the manual".

A bad example might be "good gameplay". Of course every game benefits from this but the answer is not very helpful.


texts: How can I make a spline that does not overshoot?

texts:
I have a list of line segments that run through a track model and I am looking to achieve two things:

smooth the overall shape of the path
being able to evaluate a position by querying from 0.0 to 1.0

I have implemented Catmull-Rom spline using the TreeSpline class from Unity (it's not explicitly in the docs but you can see it here), it does work except for one thing: some places have overshoot:

Legend

purple: original line segments
white: result of the TreeSpline evaluation

After searching for a bit, it appears that Monotone cubic interpolation would be a solution to my problem. However, the formulas only show on how to do with 2D points, not with 3D points which I'm using.

Question:

How can I adapt the formulas in the Wikipedia article to 3D points instead ?

(I am also open to alternative approaches)

Edit:

Thanks to @Jay it's better now:


texts: How do I ensure my custom TF2 model shows its texture?

texts:
I'm trying to make a new model for the Pyro's default Flamethrower, and I've run into a problem. When I load the new flamethrower model in HLMV or the game, I can't see the texture I made for it, all I see is the pink-and-black checkerboard.

I double-checked my QC, thinking I did something wrong, but the line that says where the texture is:
$CDMaterials "models\weapons\v_flamethrower"
is the same as the default (I even decompiled the default model and used its QC.)

The model is stored in the folder "[Path to TF2 folder]\tf\custom\newflamer\models\weapons\c_models\c_flamethrower\c_flamethrower.mdl", and the texture is stored in "[Path to TF2 folder]\tf\custom\newflamer\models\weapons\v_flamethrower\v_flamethrower.vtf".
Even still, all it gives me is the checkered texture.

I removed just the flamethrower model, and the texture still worked (although it was deformed because it was on the wrong model.) So the problem is in my QC. I'm not using a custom .vmt file, just a .vtf and .mdl.

Does anyone know what I did wrong, and how I can fix it?


texts: I'm currently wishing to draw up my UI for a 2d game, however I'm not so sure what the normal strategy is for creating the images for a UI. Are there any programmes which are specifically accurate for UI Design or is something like Photoshop perfectly fine?


texts:
I'm trying to set a realistic limit on the number of bonus objects that randomly show up during a wave of enemies in my game.

With each new wave I increase the number of enemies. During each wave I have bonus objects for the player to pick up that show up at random intervals anywhere from 5 to 25 seconds apart.

The problem I have is I want a limit on the number of bonuses so that the player can't just leave a few enemies and pick up an endless amount of bonuses to increase their score. Theoretically they could kill no enemies and continuously pick up bonuses so just checking the number of enemies left won't work for me.

I've thought about a hard limit per wave, and increasing that by a certain amount as the player progresses through waves. The problem I have with that is that the player could figure this out and always get the max number of bonuses before moving to the next wave...

Does anyone have any good ideas on how to calculate a good max bonus amount or determine when to show the bonuses better than just using randomly selected time intervals? I'm trying to come up with a good pattern that allows for moving the bonus count so that it's fair but doesn't allow cheating. Or maybe I'm just overthinking it too haha.


texts: Scrolling the camera when the mouse cursor gets to the edge of the screen

texts:
I was wondering if you could help me:

In XNA I have a hexagonal map, and the size of the map currently exceeds the size of the window. There is already code in place to move the 'camera' around the map using the directional keys, which is as follows:

if (ks.IsKeyDown(Keys.Left))
        {
            Camera.Location.X = MathHelper.Clamp(Camera.Location.X - 8, 0,
                (myMap.MapWidth - squaresAcross) * Tile.TileStepX);
        }

But I'd prefer using the mouse, like in good ol' Command and Conquer.

So basically: If mouse coords are within 5 pixels of game window edge, move map appropriately'. Any help would be greatly appreciated!


texts: Unity3D: Problems drawing on duplicated texture

texts:
I'm trying to:

load texture from assets folder
create a clone of said texture that will be manipulated during runtime
set pixels on cloned texture

I have successfully set pixels on the original texture (ie. discarding the code in the start function), but I cannot
seem to be able to draw to the duplicated version.

void Start () {

    canvas = gameObject.GetComponent(typeof(SpriteRenderer)) as SpriteRenderer;
    Sprite oldSprite = canvas.sprite;
    Texture2D oldTex = oldSprite.texture;
    Rect oldRect = oldSprite.textureRect;

    tex = new Texture2D(oldTex.width, oldTex.height, TextureFormat.RGB24, false);
    tex.SetPixels32(oldTex.GetPixels32());
    tex.Apply();

    Rect r = new Rect(oldRect.x, oldRect.y, oldRect.width, oldRect.height);
    Vector2 pivot = new Vector2(oldSprite.pivot.x, oldSprite.pivot.y);
    float pixelsPerUnit = oldSprite.pixelsPerUnit;
    Sprite sprite = Sprite.Create(tex, r, pivot, pixelsPerUnit, 0, SpriteMeshType.FullRect);

    canvas.sprite = sprite;
}

public void draw(Tool tool, Color32 color, List<Vector2> locations) {
    Color32[] pixels = tex.GetPixels32(0);

    for(int i = 0; i < pixels.Length; ++i) {
        pixels[i] = color;
    }
    tex.SetPixels32(pixels);
    tex.Apply();
}

Please ignore the unused vars, I'm just trying to set the whole texture's color for now.

Anyways, any help is always appreciated - thanks :)


texts: How to handle jumping up a slope in a runner game?

texts:
In an 2D endless runner, what should happen when the player is running "too fast" up a slope and jumps?

For example, in a "normal" case:

    .O.
   . __..O_____
  . /
 . /
 O/
_/

If he is moving to the right slowly enough, he will jump upwards and land on the flat part of the surface. However, if he is moving too fast, the jump will have no effect as his forward motion will bring him back in contact with the slope before he can get high enough to pass over it. When the speed is sufficiently high, there will effectively be no jump.

     _________
    /
 .O/
 O/
_/

Are there any known ways to solve this issue? I know it's physically correct*, but are there techniques that other games use to overcome this in a reasonable manner?

As a last resort I'll have to just remove all slopes that are too slanted.

*If you constrain the player to never jumping backwards.


texts: Position an object at the center of the screen

texts:
I need to create a grid of squares such as the grid is centered on the screen. Here is a schema:

I need the two green lengths to be equal, and the two red lengths to be equal.

Here is the method I am using right now to try to generate this pattern (slotGrid is a 2D array, but only its size is revelant right now).

void GenerateLevel(bool[,] slotGrid) {

    // The size of the grid, in the image above this is equal to 2 as it is a 2*2 grid
    // Note that I assume that the grid width and height are equal
    int slotGridSize = slotGrid.GetLength(0);

    // The size of one of the square
    float slotSizePixel = m_Slot.transform.lossyScale.x;

    // The size of the screen
    float screenWidthPixel = Screen.width;
    float screenHeightPixel = Screen.height;
    Debug.Log("Screen size: " + screenWidthPixel + "*" + screenHeightPixel);

    // Position of the upper left square
    float firstSlotX = (screenWidthPixel - (slotGridSize*slotSizePixel)) / 2;
    float firstSlotY = (screenHeightPixel - (slotGridSize*slotSizePixel)) / 2;
    Debug.Log("First slot position: " + firstSlotX + "," + firstSlotY);

    Vector3 newSlotPosition = new Vector3(firstSlotX, firstSlotY, 0);

    // Generate the grid starting from upper left corner
    for (int i = 0; i < slotGridSize; i++) {
        for (int j = 0; j < slotGridSize; j++) {
            Instantiate(m_Slot, newSlotPosition, Quaternion.identity);
            newSlotPosition = new Vector3(newSlotPosition.x + slotSizePixel,
                                          newSlotPosition.y,
                                          0);
        }
        newSlotPosition = new Vector3(firstSlotX, newSlotPosition.y, 0);
    }
}

However, this method is placing the squares in some weird position (i.e far off the screen). I realized this is because I mix pixel size (for the screen width and height) and... Unity scale size I guess (I don't know the proper name) for the square size.

How can I fix this?


texts: Recording the gameplay in the game itself?

texts:
I'm presently working on a 3D car racing game for the iOS platform. I had to implement a replay system and then record that replay in a video file to upload it to YouTube.

I'm only having issues with the recording part, the rest is done. What I'm doing is using the glReadPixels() command of OpenGL ES 1.1 to capture the framebuffer content and creating a video from these frames during runtime (using AVFoundation framework).

The problem I'm facing is that I have to call glReadPixels() in each update which is very slow . It decreases the FPS from around 30 to only 2-3...
Is there any alternative to the glReadPixels() command?
Or did anyone create a replay system and recorded to video?


texts: Simple heart container script for 2D game (Unity)?

texts:
I'm attempting to create a simple mobile game (C#) that involves a simple three-heart life system. After searching for hours online, many of the solutions use OnGUI (which is apparently horrible for performance) and the rest are too complicated for me to understand and add to my code. The other solutions involve using a single texture and just hiding part of it when damage is taken. In my game, however, the player should be able to go over three hearts (for example, every 100 points).

Sebastian Lague's Zelda-Style Health is what I'm looking for, but even though it's a tutorial there is way too much going on that I don't need or can't customize to fit in mine.

What I have so far is a script called HealthScript.cs which contains a variable lives. I have another script, PlayerPhysics.cs which calls HealthScript and subtracts a life when an enemy is hit. The part I don't get is actually drawing the hearts.

I think I understand what needs to happen, I just am not experienced enough with Unity to know how.

The Start function should draw three (or whatever lives is set to) hearts in the top right corner. Since the game should be resolution-independent to accommodate the various sizes of Android devices, I'd rather use scaling rather than PixelInset.
When the player hits an enemy as detected by PlayerPhysics.cs, it should subtract from lives. I think that I have this working using this.GetComponent<HealthScript>().lives -= 1 but I'm not sure if it actually works. This should trigger a redraw of the hearts so that there are now two hearts.
The same principle would apply for adding hearts when a score is reached, except when lives > maxHeartsPerRow, the new hearts should be drawn below the old ones.

I realise I don't have much code to show but believe me; I've tried for quite some time to figure this out and have little to show for it. Any help at all would be welcome; it seems like it shouldn't take that much code to put an image on the screen for each life there is, but I haven't found anything yet.

Thanks!


texts: LibGdx: How to check if VSync is enabled

texts:
I am just about finished my options screen, the only thing I need is some way of detecting if Vsync is enabled or not.

I'm using LibGdx 1.5. I have tried to find an access to wglSwapIntervals, but haven't found one. Libgdxs API only allows a setVsync options that accepts a Boolean.

If anyone could shed some light on this, it would be greatly appreciated!


texts: Why transform.Rotate(X,0,Z) rotates also Y?

texts:
In my game I'm trying to rotate a turret.
I'm using the classic pattern:

float h = Input.GetAxis ("Horizontal");
float v = Input.GetAxis ("Vertical");

if (h != 0 || v!=0)
    rb.transform.Rotate (new Vector3(v, 0, h));

The problem is that if I move in vertical axis also Y axis rotates. Why?

How can I achieve a rotation that rotates only the X and Z axis and not the Y axis?


texts: Box2D + Citrus Engine - Proper Pong Paddles

texts:
I am creating a pong clone for my first Citrus Engine project using Box2D. I've tried two types of paddles, both do not fully work.

1) Paddle is a dynamic body with a restitution of 1.0 and friction of 0.0.

Problem: The bouncing ball will move the paddle when it collides.

2) Paddle is a kinematic body type.

Problem: The paddle will not detect collision with the walls of the game screen.

Question: How can I create a paddle object that will not be affected by the collision of the ball while colliding normally with the game walls?


texts: Programmatically created instance does not execute any code

texts:
I've created a new instance, positioned it, and added it to the scene like this:

const Player = preload("res://player.tscn")

func _physics_process(delta):
    if <outside display>:
        var newplayer = Player.instance()
        newplayer.position.x = 200
        get_tree().get_root().add_child(newplayer)
        queue_free()

This works to the extent that the player is created in the right position and starts falling down with gravity. But the new player does not respond to any input, nor does it do anything if I print things in the _ready function or the _physics_process function. It seems its script is just never executed at all.

I've tried not queue_free()'ing the old one, in case removing it is like removing its parent, but that doesn't help.

I've tried calling the ._ready() function on it manually, but that doesn't work either.

I've tried calling request_ready() on the new player, but that doesn't run the _ready() function either.

In tutorials, this is usually all they do to get a new instance into the world, so I'm not sure what I'm missing here.


texts: Libgdx - GLSL shader which uses mod doesn't seem to work properly on android

texts:
Through trial and error I've managed to come up with a scanline-ish shader I'm satisfied with. On my desktop testbed it looks like this:

Basically, every 2nd(vertical) pixel is darkened.

However, when I add the same shader to my android sprite batch the darkened lines no longer show up. I've assumed it's due to use of mod and float comparison since GLES is lower precision than desktop GL and it probably never evaluates yPos == 0.5 to true. So to combat that I've created an EPSILON value to give a bit of leeway for float comparison but that didn't help either. However I'm certain that I've set up the shader program correctly since simple color manipulation shaders seem to work properly, only when mod gotten introduced into the mix things turned sour.

Here's the shader code:

scanline.vert

attribute vec4 a_position;
attribute vec4 a_color;
attribute vec2 a_texCoord0;

uniform mat4 u_projTrans;

varying vec4 vColor;
varying vec2 vTexCoord;

void main() {
    vColor = a_color;
    vTexCoord = a_texCoord0;
    gl_Position = u_projTrans * a_position;
}

scanline.frag

#ifdef GL_ES
    precision mediump float;
#endif

varying vec4 vColor;
varying vec2 vTexCoord;

uniform sampler2D u_texture;
uniform mat4 u_projTrans;

const float SCANLINE_INTENSITY = 0.7; // lower is stronger, probably should call this softness
const float SCANLINE_DENSITY = 2.0; // every 2nd pixel

const float EPSILON = 0.01;

void main() {

    vec4 texColor = texture2D(u_texture, vTexCoord);

    float yPos = mod(gl_FragCoord.y, SCANLINE_DENSITY);

    vec4 retColor = vColor;

    //if(yPos == 0.5) {
    if(abs(yPos - 0.5) < EPSILON) {
        retColor *= vec4(vec3(SCANLINE_INTENSITY), vColor.a);
    }

    gl_FragColor = texColor * retColor;
}

What am I doing wrong?


texts: How to show NGUI menu in the upper of a Game Scene?

texts:
I am new to Game Development. I made a menu with NGUI plugin. I have a background image in the behind of this menu. Now, I want to place my Game Scene in place of the background image. I have tried in several ways. But, Failed. Any suggestions will be highly appreciated.
Thanks


texts:
I am trying to write a perlin noise class with c++ and sfml, but I am experiencing unwanted visual artifacts in the output. In the image, there are obvious lines being drawn between the points of the lattice:

The class template representing the noise is a specialization of lattice noise for vectors. The important function, GetValue() expects values between 0.0-1.0, representing the coordinates at which to get the value of the noise, which should also return a value between 0.0-1.0. Calling the function at (0, 0) should return the value at the top left corner. NormX and normY are the distance between lattice points x0-x1 and y0-y1, again in the range 0.0-1.0.

Before calculating the dot product, the distance vector from each corner lattice point is calculated instead of only using the distance from the top left corner. Because the final value at any point may be negative (-1.0 - 1.0), it is mapped to the range 0.0-1.0 by adding 1 and dividing by two before being returned.

template<>
inline float LatticeNoise2D<sf::Vector2f>::GetValue(float u, float v)
{
    float normX = u * resX_;
    int x0 = normX;
    int x1 = x0 + 1;
    normX -= x0;

    float normY = v * resY_;
    int y0 = normY;
    int y1 = y0 + 1;
    normY -= y0;

    float fadeX = Fade(normX);
    float fadeY = Fade(normY);

    sf::Vector2f dist(normX, normY);
    float dot0 = Dot(At(x0, y0), dist);
    dist = sf::Vector2f(1 - normX, normY);
    float dot1 = Dot(At(x1, y0), dist);
    float lerp0 = Lerp(dot0, dot1, fadeX);

    dist = sf::Vector2f(normX, 1 - normY);
    dot0 = Dot(At(x0, y1), dist);
    dist = sf::Vector2f(1 - normX, 1 - normY);
    dot1 = Dot(At(x1, y1), dist);
    float lerp1 = Lerp(dot0, dot1, fadeX);

    float value = Lerp(lerp0, lerp1, fadeY);
    return (value + 1) / 2;
}

The At(x, y) function returns the pre-generated vector on the lattice (a 2d std::vector) at the given index. The dimensions of the lattice in each dimension are resX_ and resY_, respectivley.

template<typename value_type>
inline value_type LatticeNoise2D<value_type>::At(int x, int y)
{
    return lattice_[x % resX_][y % resY_];
}

The vectors at each point on the lattice are generated on the unit circle by randomly choosing an angle in radians (0-2pi) and then calculating the x & Y components given that the length of their hypotenuse is 1.0.

template<>
inline sf::Vector2f LatticeNoise2D<sf::Vector2f>::Random()
{
    float pi = 4 * atan(1);
    float theta = static_cast<float>(rand()) / RAND_MAX * 2 * pi;
    return sf::Vector2f(cos(theta), sin(theta));
}

The Lerp() function performs linear interpolation, and the Dot() function calculates the dot product of two vectors. The Fade(t) function maps a value from 0.0-0.1 to an S Curve to be used in the Lerp function instead of just the linear distance between lattice points.

Why am I getting these lines between the points of the lattice, and how can I fix them? My goal is to make noise like this example:


texts:
Are physics engine able to decrease that complexity, for example by grouping objects who are near each other and check for collisions inside this group instead of against all objects ? (for example, far objects can be removed from a group by looking at its velocity and distance from other objects).

If not, does that make collision trivial for spheres (in 3d) or disk (in 2d) ? Should I make a double loop, or create an array of pairs instead ?

EDIT:
For physics engine like bullet and box2d, is collision detection still O(N^2) ?


texts: How to place an object so that it does not overlap the objects in my scene?

texts: In my game, the user has to click at a point to place an object (mesh). I can cast a ray and find the horizontal point where the object can be translated and then attached to rootNode to display it. However, the problem is that if the user click too near to another object/scene_wall the object to be placed, runs into it. How can I prevent that?


texts: Why does my collision implementation cause my player to "bounce" when a collision occurs?

texts:
I have a player polygon and I check to see if it's colliding with my tiled map with this method:

public static boolean playerCollisionWith() {
    for(int i = 0; i < Blockmap.entities.size(); i++) {
        Block entity1 = (Block) Blockmap.entities.get(i);
        if(playerPoly.intersects(entity1.poly)) {
            return true;
        }
    }
    return false;
}

This would work normally but I'm using a different method for movement.  Instead of just adding a speed variable to the player's X axis.  I move like this:

if(Keyboard.isKeyDown(Keyboard.KEY_RIGHT)) {
        speedX = Math.min(5, speedX + 1);
        moving = true;

        playerPoly.setX(x);
        if(playerCollisionWith()) {
            speedX = -5;

            playerPoly.setX(x);
        }
    }

That Math.min call is what is messing me up.  I can't just call speedX = -5, because when I do the player "bounces" when the right mouse button is down and it's colliding.  Bounces as in flashes back and forth really quickly.  But I don't really know how I would make it so that collisions on the Y axis would work either, whether the player is jumping or not.  So if I could get some help with how to fix this problem that would be great.

EDIT: I just realized something, I have these lines of code which I'm pretty sure has a big effect on my collision problems.

if(!Keyboard.isKeyDown(Keyboard.KEY_LEFT) && speedX < 0 && !playerCollisionWith()) {
            speedX = 0f;

            playerPoly.setX(x);
        }
        if(!Keyboard.isKeyDown(Keyboard.KEY_RIGHT) && speedX > 0 && !playerCollisionWith()) {
            speedX = 0f;

            playerPoly.setX(x);
        }

So when I collide with a wall and I'm no longer pressing the arrow key, than the player drifts into the wall and is all glitchy.  Sorry I didn't say that earlier, I just did some more testing. Thanks again!


texts: Is it ok to commit to git while my Unity project is still open?

texts:
I tend to have big commits and it is related to me being tool lazy to close Rider and Unity, commit changes and then start both programms back up to make changes and repeat. I just assumed that this is the correct way of doing it, but is this even the case?

Thanks in advance!


texts:
I am new to OpenGL, I am able to render a model object (a human model) that is using .obj and .mtl file in iOS.

Now I want to make a modification to the loaded model. For example, I want to change the height, or change the shoulder width, stomach size, et cetera.

Is this possible ? If so, how do I go about it?


texts: What is the best way to check lists of objects that collide

texts:
I am making a top down shooter in XNA. I have a player, a list of enemies, a list of world objects like crates, trash cans, etc. and the map which has walls.  Is there a better way to check for collisions than,

for (all enemies)
  for (all world objects)
    check for collision between enemies and world objects
for (all players bullets)
  for (all enemies)
    check for collisions between players bullets and enemies
and so forth.

What I mean is, I have a few lists of a bunch of objects and they all need to be checked for collisions.  What is the most resourceful way to do this?
Thanks for your help in advance.


texts: Make camera follow and rotate with player without childing it

texts:
I want to have a camera, that follow the player, without childing it to the player object. So far I have this one line, that follows the player, but does not rotate with it (meaning the camera should look where the player's front is looking, how can I do it?

transform.position = player.transform.position + offset;


texts: How do you publish a Xbox Live game on Windows Phone?

texts: Curious if any of you have gone through the process? How did you kick it off? Is there anything in particular that we should be aware of when trying to make a Live game?


texts: Fixing error(23, 2) Error parsing expression, misplaced: func

texts:
When I try to use the GDScript code below, Godot gives me the error:

  error(23, 2) Error parsing expression, misplaced: func

Why am I getting this error, and how can I fix it? Is there another input node that could give the same results without the error?

func _ready():
 position = get_viewport_rect().size / 2
 direction.x = rand_range(-1, 1)
 direction.y = rand_range(-1, 1)
 direction = direction.normalized()
 width = get_viewport_rect().size.x
 height = get_viewport_rect().size.y

func _process(delta):
    position += direction * speed * delta
 if position.x < 0 or position.x > width:
  direction.x = -direction.x
 if position.y < 0 or position.y > height:
  direction.y = -direction.y

 func _on_UFO_input_event( viewport, event, shape_idx ):
 if event is InputEvenMouseButton and event.button_index ==
 BUTTON_LEFT and event.pressed:
 direction.x = rand_range(-1, 1)
 direction.y = rand_range(-1, 1)
 direction = direction.normalized()
 position.x = rand_range(1, width -1)
 position.y = rand_range(1, height -1)
 speed += 5


texts: Collision detection implementation suggestions

texts:
I'm working on a simple 2D game involving a rotating octagonal ring where a sphere sprite moves up/down avoiding objects as the ring rotates faster and faster. I'm having a difficult time with the collision between the sphere and the sides of the walls.

The ring is made up of 8 instances a primitive called a straightSection object. The camera is also zoomed in along the z-axis and positioned along the x and y to give the appears of a track. I've attempted to have 2 collision rectangles as part of the straightSection constructor. The rectangles would rotate with of the straightSection but what was happening was that the rectangles were aligning themselves with the axis and not rotating. I've then attempted to simply draw a vector across the top and bottom and use a BoundingSphere over the sprite and use the BoundingSphere.Intersect() method to determine but it was only working on vertices of the vector and not across the whole top.

I've tried attaching vectors and boxes to the vertices after they are transformed but also have used Viewport.Project() to obtain the coordinates for the box in the space as the sprite but it's the same thing

I've attached an illustration:

What I think is going wrong... well I'm not sure entirely. I've read so many tutorials and feel that I'm doing the same thing as them and it should be simple. My guess is that it has to do with the camera location, the ring location and the sphere location not being where I think they are.

If anyone needs to see the code, I can post that as well. I've been at this for weeks and I think I'm looking at the problem the same way over and over...

Adding some code

What I thought would be the simplest and most intuitive way to go about it was to have a ray traces starting from the top right of the primitive to the top left of the primitive. In the drawing above it would be the narrow red box (but in this case an attempt at a ray).

BoundingSphere bs = new BoundingSphere(new
Vector3(spriteManager.getPlayer.collisionRect.Center.X,
SpriteManager.getPlayer.collisionRect.Center.Y, 1) 25.0f)

Ray intersectRay = new Ray(section1.CoordTopR, section1.CoordTopL)
intersectRay.Direction.Normalize()

if (bs.Intersects(intersectRay) < 25.0f)
{
///

}

I've tried this with the View.Project coordinates of the vertices, or just using the transformed coordinates CoordTopR and CoordTopL and it doesn't work.  It either always collides or only does over a small point. I've tried to change the intersect float value but that doesn't help. I'd like it to stretch over the whole top of the shape.


texts: How would you generate details like trees, water or caves in a 2D terrain?

texts:
Yesterday I made a post about generating a 2D planet, which resulted in this:

I did it by subtracting a radial gradient from simplex noise (explained in my other post).

Now of course thats a bit boring, what technique should I use to add details like trees, lakes or caves? Would be able to do something like this (but of course across the whole planet):

I know doing it on a planet would make it a bit harder, because you would have to know if f.E. the tree is on the north of the planet or the south. To make it easier, if you want, just assume a flat 2D surface like this:


texts: Architecture of an action multiplayer game from scratch

texts:
Not sure whether it's a good place to ask (do point me to a better one if it's not), but since what we're developing is a game - here it goes.

So this is a "real-time" action multiplayer game. I have familiarized myself with concepts like lag compensation, view interpolation, input prediction and pretty much everything that I need for this. I have also prepared a set of prototypes to confirm that I understood everything correctly.

My question is about the situation when game engine must be rewind to the past to find out whether there was a "hit" (sometimes it may involve the whole 'recomputation' of the world from that moment in the past up to the present moment. I already have a piece of code that does it, but it's not as neat as I need it to be. The domain logic of the app (the physics of the game) must be separated from the presentation (render) and infrastructure tools (e.g. the remote server interaction specifics).

How do I organize all this? :) Is there any worthy implementation with open sources I can take a look at?

What I'm thinking is something like this:

-> Render / User Input
    -> Game Engine (this is the so called service layer)
        -> Processing User Commands & Remote Server
        -> Domain (Physics)

How would you add into this scheme the concept of "ticks" or "interactions" with the possibility to rewind and recalculate "the game"? Remember, I cannot change the Domain/Physics but only the Game Engine. Should I store an array of "World's States"? Should they be just some representations of the world, optimized for this purpose somehow  (how?) or should they be actual instances of the world (i.e. including behavior and all that).

Has anybody had similar experience?

(never worked on a game before if that matters)


texts: C++ SFML: Keypressed Event not registering half the time?

texts:
I have a very simple event handeling system at the moment.

void LevelScreen::PollInput()
{
    sf::Event event;

    while (pWindow->pollEvent(event))
    {
        if (event.type == sf::Event::KeyPressed)
        {
            int x = 0;
            int y = 0;

            if (event.key.code == sf::Keyboard::Left)
            {
                x = -1;
            }
            else if (event.key.code == sf::Keyboard::Right)
            {
                x = 1;
            }
            else if (event.key.code == sf::Keyboard::Up)
            {
                y = -1;
            }
            else if (event.key.code == sf::Keyboard::Down)
            {
                y = 1;
            }

            pCursor->Move(x, y);
        }
    }
}

The system gets updated every single cycle, yet many keypresses are not even registered eventhough there is no lag. Mouse movement is always registered, but when I press, for example, Down alot it fails to register from 30% to 50% of the time. Same counts for the mouse button, if I hold it down I can see that it registers it for 6 times in a row, then stops for about 5 seconds, continues, etc.

Putting it in the main loop doesn't change anything. I cannot find any reason for this input lag.


texts:
In my cbuffer in DirectX, I send 2 variables over to my HLSL shader called Light & Roughness. If I remove the Roughness variable my program compiles fine but as soon as I introduce Roughness I get the error:
Exception thrown at 0x00007FFDDEFA0030 (d3d11.dll) in Eagle Engine.exe: 0xC0000005: Access violation reading location 0x00000000000000C0.

On the HLSL side the light variable contains it's defined value that was set in C++ and works fine without Roughness. If anyone could help me that would be great, I've included the necessary code below.

effects.fx

#include "Common.hlsl"

struct Light
{
    float3 dir;
    float4 ambient;
    float4 diffuse;
};

cbuffer cbPerFrame
{
    Light light;
    float Roughness;
};

cbuffer cbPerObject
{
    float4x4 WVP;
    float4x4 World;
};

Texture2D ObjTexture;
SamplerState ObjSamplerState
{
    Filter = ANISOTROPIC;
    MaxAnisotropy = 16;
    AddressU = Wrap;
    AddressV = Wrap;
};

struct VS_OUTPUT
{
    float4 Pos : SV_POSITION;
    float2 TexCoord : TEXCOORD;
    float3 normal : NORMAL;
};

float3 DirectDiffuseBRDF(float3 diffuseAlbedo, float nDotL)
{
    return (diffuseAlbedo * nDotL);
}

VS_OUTPUT VS(float4 inPos : POSITION, float2 inTexCoord : TEXCOORD, float3 normal : NORMAL)
{
    VS_OUTPUT output;

    output.Pos = mul(inPos, WVP);

    output.normal = mul(normal, World);

    output.TexCoord = inTexCoord;

    return output;
}

float4 PS(VS_OUTPUT input) : SV_TARGET
{
    input.normal = normalize(input.normal);

    float4 textureColor = ObjTexture.Sample(ObjSamplerState, input.TexCoord);

    float nDotL = saturate(dot(input.normal, light.dir));

    float3 diffuseLighting = textureColor * light.ambient * light.diffuse * Roughness;
    diffuseLighting += saturate(DirectDiffuseBRDF(textureColor, nDotL));

    return float4(diffuseLighting, textureColor.a);
}

In my Main.cpp

constbuffPerFrame.light = light;
constbuffPerFrame.Roughness = 1.0f;

devcon->UpdateSubresource(cbPerFrameBuffer, 0, NULL, &constbuffPerFrame, 0, 0);
devcon->PSSetConstantBuffers(0, 1, &cbPerFrameBuffer);

Header.h

struct Light
{
    Light()
    {
        ZeroMemory(this, sizeof(Light));
    }
    XMFLOAT3 dir;
    float pad;
    XMFLOAT4 ambient;
    XMFLOAT4 diffuse;
    XMFLOAT4 specular;
};

struct cbPerFrame
{
    Light  light;
    float Roughness;
};

Light light;
cbPerFrame constbuffPerFrame;


texts: How can I create a set of collision points for an arbitrary mesh?

texts:
In my project I am working on automatically deforming an arbitrary mesh with respect to another arbitrary mesh, within the context of user generated content, similar to this deformer being developed for Second Life.

In order to preserve the features of a deformed mesh, which may consist of things such as 'folds' for the edge of the mesh, I would like to deform my target with a set of deformers, however defining an appropriate set of deformers has given me trouble and I think now the best way to do it is to create a 'collision mesh'/set of 'control points'. These points will proxy for the target mesh in collision detection and define the deformers used to deform the main mesh. Since I generate it its structure can be more tightly controlled.

I want to create a 'grid' of points which approximate the surface of my mesh, like the control points on a NURBS surface. I was thinking of a technique with principles like those used in the layered depth image technique here, but wondered if there was already a good existing solution for what I want to do?

What is the most effective way to create something that approximates a collision mesh for an arbitrary mesh automatically?


texts: How can I better implement A star algorithm with a very large set of nodes?

texts:
I'm making a game with nodejs in which many enemies must converge on the player as the player moves around a relatively open space (right now it is an open field with few obstacles, but eventually there may be some small buildings in the field with 1 or 2 rooms).  It's a multiplayer game using websockets, so the server needs to keep track of enemies and players.

I found this javascript A* library which I've modified to be used on the server as a nodejs module.  The library utilizes a Binary Heap to track the nodes for the algorithm, so it should be pretty fast (and indeed, with a small grid, say 100x100 it is lightning fast).

The problem is that my game is not really tile-based.  As the player moves around the map, he is moving on a more or less 1-to-1 per-pixel coordinate system (the player can move in 8 directions, 1 or 2 pixels at a time).

In preliminary tests, on an 800x600 field, the path-finding can take anywhere from 400 to 1000 ms.  Multiply that by 10 enemies and the game starts to get pretty choppy.

I have already set it up so that each enemy will only do a path-finding call once per second or even as slow as once every 2 seconds (they have to keep updating their path because the players can move freely).  But even with this long interval, there are noticeable lag spikes or chops every couple of seconds as the enemies update their paths.

I'm willing to approach the problem of path-finding differently, if there's another option.  I'm assuming that the real problem is the enormous grid (800x600).  It also occurs to me that maybe the large arrays are to blame, as I've read that V8 has trouble with large arrays.


texts: What is ramp shading or lighting and how does it work? Is it different than toon shading or is it the same concept? How is specularity calculated differently for ramp shading versus blinn-phong or lambert?


texts: Resizing the window moves and stretches the texture

texts:
I have a basic screen with 3 TextureRegions rendered on the screen rendered with this code(Ignore the hardcoded numbers, bad decision I know will be replaced later):

Gdx.gl.glClearColor(0, 0, 0, 0);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.draw(btnIdle, (Gdx.graphics.getWidth() / 2) - (169 / 2), 225);
batch.draw(btnIdle, (Gdx.graphics.getWidth() / 2) - (169 / 2), 150);
batch.draw(btnIdle, (Gdx.graphics.getWidth() / 2) - (169 / 2), 75);
batch.end();

and it renders like this:

But if I resize the window it becomes like this:

Why does the texture become like that when the window is resized and what are the solutions?

P.S. I am aware of this question and it does not solve my problem


texts:
I'm working on collision detection for a pong clone. I've calculated the angle of incidence but I can't find any information on how to specular reflect the angle I found.

The code for calculating the angle of incidence is below

 if (ballPosition.Y >= height - 6)
  {
    Vector2 bottomNormal = new Vector2(400, 460) - new Vector2(400, 480);
    Vector2 ballNormal = ballPosition - new Vector2(400, 480);
    ballNormal.Normalize();
    bottomNormal.Normalize();

    float angle = Vector2.Dot(bottomNormal, ballNormal);
 }


texts:
I currently have some 2D terrain in my game defined by 2D coordinates with lines drawn in between them (linear interpolation too keep it simple).

Now I want to cast a ray from anywhere above the terrain and see if it collides with the terrain for drawing bullet tracers.

Here is a quickly drawn example:


texts: How can I use tilt sensor in iOS iPad to steering a car

texts:
I am absolute beginner with unreal engine , I am working in car race project

here is my situation : I need to navigate my car in left and right direction using tilt

Here is what I do  I read tilt sensor value then break vector to (X,Y,Z)

as appear in image I need to read Y value , I call set steering input passing Y value.

I hope my question be clear  , I appreciate any help


texts: Where can I modify the default damage system on UDK

texts:
I want to make a custom damage system on my game but I can't find the function that handles it...

I looked on Actor.uc but the only thing I've found is the event TakeDamage, but there's nothing on it that actually deals the damage.

Thanks in advance.


texts: For games that time stamp a saved game (think Half-Life), is the entire game state really being saved every time?

texts: It seems to me if that were the case that your directory of saved binaries or serialized objects could get massive real quick. Is there some sort of strategy being employed on top of the State pattern that is optimizing each time stamped saved game so that it isn't saving the entire game "context" all the time?


texts:
While using spine in unity 2D with a spot light, the light from the spot light will shine on the character if he's facing right but only when the light is in front (in the Z direction) of the character. If the character turns left the light will not have any affect. But, if you turn left and move the light behind (in the Z direction) of the character, then the light will shine on the character. I'm using the Spine/Skeleton Lit or Spine/SkeletonGraphic material with spine 3.6 runtime. I've tried adjusting the alpha and other random settings, but im not sure where to begin.

The Z direction of the character doesn't change when turning left or right in unity, but the spot light only affects in a certain direction.

The environmental light affects the character, but the spot light only affects the character based on the rotation. I want the spot light to affect the character regardless of their X scale or rotation. Culling is off....


texts: How to create a Spawn Area that can be visualized in the Unity Scene Editor?

texts:
Consider a Spawn Area for GameObjects. We define a Spawn Area to be a boundary consisting of 3 or more points such that an object can spawn at any coordinate that is within the boundary of the Spawn Area. Contrast this with a Spawn Point, where objects can only be spawned at that specific coordinate.

In Unity, one method of creating such a Spawn Area is to place an Empty Game Object at a point, and then use Random.Range around that point.

Vector3 emptyGameObjectCoordinate = emptyGameObject.transform.position;
Vector3 randomSpawn = emptyGameObjectCoordinate + new Vector3(Random.Range(-1, 2), 0, 0);

My issue with this approach is that it is very difficult to visualize this area through the scene editor. It would look like a simple cube no matter what the area actually is.

I have considered possibly using a box collider as the area. This is can easily be visualized.

However, Unity Lacks a method to select points within a collider.

It would be ideal if we had a method such as Random.insideCollider.

BoxCollider collider = GetComponent<BoxCollider>();

// Ideally. But sadly, does not exist.
Vector3 randomSpawn = Random.insideCollider(collider);

So my question is, what is the Unity way of creating a Spawn Area such that it can be visualized through the scene editor?

As a bonus, how can we create areas that consists of arbitrary points, as opposed to just being rectangles or cubes? It would still need to be possible to visualize it, and it should be easy to select random points within it.


texts:
I have a basic entity system in place. Now I want to add audio. I want to make a database class that watches over entities, pulls data out of them, and creates audio streams whenever necessary.

I'm using C++ and SDL2. What is a simple approach to this?


texts: Unity: I need to edit my prefab but I can't move anything inside it!

texts:
I imported a character into Unity and turned him into a prefab. I couldn't get my custom "Look-At" script to work for the eyes, which are children of the prefab I imported. So I opened the prefab and discovered (to my HORROR) that I am unable to transform his eyes AT ALL, even in the prefab-view. It's like his body parts are made of stone, or something! I checked his eyes in the Blender scene and don't see any animation data attached to them. So how could this happen? How can I fix it?

The eyes ARE children of a bone called "root", which I don't think has any keyframes in any animation. Further, all my bones imported as empties.


texts:
I am attempting to add volumetric shadowing to an application I am working on to test some things. For this effect I wrote the following fragment

shader:#version 450

in float visible;
in vec3 normal;//Normal to the vertex
in vec3 vertexPos;//True position of the vertex (i.e it's location in space)

in vec2 texture_coord;

out vec4 outColor;//Final color of the pixel

uniform sampler2D text;

uniform vec4 color = vec4(1);//Default color
uniform vec3 lum = vec3(80,70,0.1);//A unique light position
uniform vec3 cameraPos = vec3(0);//The position of the camera in the world
uniform vec3 cameraDir = vec3(0);

float sphereIntersection(vec3 ray, vec3 origin, vec3 center, float radius)
{

    float a = dot(ray,ray);
    float b = -2*dot(center, ray)+2*dot(ray,origin);
    float c = -2*dot(origin,center)+dot(center,center)
              -radius*radius+dot(origin,origin);

    float discriminant =b*b - 4*a*c;

    float t, t1, t2;
    if(discriminant < 0)
    {
        return -1;
    }

    else
    {
        t1=(-b-sqrt(discriminant))/(2*a);
        t2=(-b+sqrt(discriminant))/(2*a);
    }

    if(t1<0 && t2>=0)
        t1=t2;
    else if (t1>=0 && t2<0)
        t2=t1;

    return min(t1,t2);
}

void main()
{
  vec3 l = vec3(lum-vertexPos);
  if(length(l)>0)
    l = normalize(l);
  vec3 c = vec3(texture(text,abs(texture_coord)));
  vec3 n = normalize(normal);
  vec3 e = cameraPos-vertexPos;
  e = normalize(e);
  vec3 h = normalize(e+l);

  outColor = vec4(c*(vec3(0.5)+0.5*max(0,dot(n,l))) + vec3(0.1)*max(0,pow(dot(h,n), 100)), 1);

  float t = sphereIntersection(vec3(90,70,1)-vertexPos, vertexPos, vec3(80,80,3), 6);

  if(t>0.01)
  {
    outColor = vec4(t/100,0,0,0);
  }
}

The issue is as follows, in the next image there's 2 shadows:

However as you can see, there's only one sphere and only one source of light and they are both hard coded, so I do not understand where the second shadow comes from (the one that does not have the circle).


texts: Abstraction for dialogue and quests in web game

texts:
I'm not very experienced with web languages, but I know a little bit of JavaScript. I'm working on creating a text-based rpg in HTML and need a way to modify dialogues for main story or quest dialogues and events without editing the code every time.

I know that if it's just to work with plain text, it wouldn't be too difficult. But I want to include a way to associate what type of monster to fight with specific quests or have specific rewards for them.

Is there a way to do this with JavaScript? What is the best way to approach this problem?


texts:
I'm moving from an old game dev tool to Unity, and wondering how to go about handling external data files.
In my previous program I'd set up external (txt/ini) files like this:
[Group1]
Count=1
1=Hello

[Group2]
Count=2
1=lol
2=end

Then I would simply reference which group name and line I wanted to pull.
What's the equivalent to this in unity? I see I can import TextAssets but I can't find functions to pull select data from it. Do these exist?
Do I have to split by lines, loop through them all and convert it into groups (lists) manually? What is the standard method for doing this? Is it moving to xml files?


texts: Why does my PBR material appear grey in game?

texts:
I am playing around with PBR materials and I cant get them to work correctly. When I create a material using PBR the model appears gray in game. Any ideas on why I’m not getting the same result?
val floorMaterial = Material(assetManager, "Common/MatDefs/Light/PBRLighting.j3md")
floorMaterial.setTexture("BaseColorMap", assetManager.loadTexture("Textures/Floor_Diffuse.png"))
floorMaterial.setTexture("NormalMap", assetManager.loadTexture("Textures/Floor_Normal.png"))
floorMaterial.setTexture("SpecularMap", assetManager.loadTexture("Textures/Floor_Specular.png"))
val sun = DirectionalLight()
sun.color = ColorRGBA.White.mult(1.3f)
sun.direction = Vector3f(-.5f, -.5f, -.5f).normalizeLocal()
main.rootNode.addLight(sun)
val lightProbe = LightProbe()
lightProbe.position = Vector3f(0f, 10f, 0f)
addLight(lightProbe)

For comparison when I use regular lighting this is the result
val floorMaterial = Material(assetManager, "Common/MatDefs/Light/Lighting.j3md")
floorMaterial.setTexture("DiffuseMap", assetManager.loadTexture("Textures/Floor_Diffuse.png"))
floorMaterial.setTexture("NormalMap", assetManager.loadTexture("Textures/Floor_Normal.png"))
val sun = DirectionalLight()
sun.color = ColorRGBA.White.mult(1.3f)
sun.direction = Vector3f(-.5f, -.5f, -.5f).normalizeLocal()
main.rootNode.addLight(sun)
val lightProbe = LightProbe()
lightProbe.position = Vector3f(0f, 10f, 0f)
addLight(lightProbe)


texts: Print string letter by letter in UI Text

texts:
i'm trying to print a string letter by letter for UI Text of Unity.
With each click of a button, the Stampa function, must print a letter. Up to this point everything is working perfectly.
But if I try to print a newline "\n" the function ignores him and continues to print on the same line.
This is my code:

using UnityEngine;
using UnityEngine.UI;

public class Click : MonoBehaviour {

    public static Text txt;
    public static int indice = 0;
    public string asd = "String1 \nStriga2";

    void Awake() {
        txt = GameObject.Find("Cmd").GetComponentInChildren<Text>();
    }

    public void Clicked() {
        Stampa(asd ,indice);
        indice++;
    }

    void Stampa(string stringa, int i) {
        txt.text += stringa[i];
    }

}

That produces this result(unwanted):

I also tried to print the entire string at the same time (not a letter at a time) as follows:

txt.text = "String1 \nStriga2";

That produces this result(wanted):
How can I get this second result by printing letter by letter?


texts: How do I determine that the edge of the camera intersects the edge of the background sprite? UE4

texts:
I'm trying to make sure that when the camera reaches the border (left or right) of the sprite's background, a copy of it is spawned from the corresponding side. But I seem to be missing something in the Unreal Engine.
Now I define the intersection of the camera and the sprite boundary as follows:

I take the X coordinate of the sprite and subtract half of its size. (Get it's left border)
I also take the camera coordinate and subtract half of the orthographic length (Left border of a screen?)

    ParallaxItems[Index]->GetActorBounds(false, ActorOrigin, BoxExtent, false);

    FVector ActorOrigin, BoxExtent;
    if ((NewBackgroundPos - BoxExtent.X) >
        CamManager->GetCameraLocation().X - (CamManager->GetOrthoWidth() / 2)) {

      UE_LOG(LogParallax, Warning, TEXT("Background %d LeftBorder! need spawning"), Index);
    }

This seems to be true, but I'm missing something else, perhaps a scale. (But box extent changes correctly) For some reason, the condition is triggered already on the blue line. And this is true for all backgrounds. Somewhere earlier, somewhere later, but player can always see that the background is over. Maybe it's the orthographic width of the camera? Now it's 2048.
If I am wrong, please tell me how to do it correctly? Thank you.


texts:
I'm working on a 3D space simulation game in C++.

I've read that in many cases games use spatial indexing (hashing) that allows to quickly detect collisions, find out what entities to draw and so forth.

Is this really necessary for my game, considering that collisions between entities can happen, but are very rare? Is there any viable (and simpler) alternative?


texts: Is it easy to use Sun Burn engine for WP7 game development?

texts:
I was wondering if anyone has tried to develop a game using the SunBurn game engine for the Windows Phone 7 platform.

How good is documentation, examples, etc?
Is it easy in use and implementation?

Any feedback would be greatly welcome.


texts:
I'm not a dev noob, but definitely never done anything in game dev. There is a trump based card game we play in town that I plan on coding. I'll be either using python/ajax/pyqt or c++/qt.

My question is as follow, what kind of advice would you give to writing card based games?


texts: Random Ghost Behavior in PacMan Clone Not Random?

texts:
I'm currently programming a PacMan clone as my first ever game with the XNA Game Studio before eventually going to DirectX.

As a first ever game, lots of things have given me great headaches, especially collision detection with the walls.

The problem I have now is the "AI" I have implemented for the ghosts. It's wish-wash, really. The basic method is that, if the Ghost runs into a corner, it will change its speed vector, and ultimately its direction.

However, the seed seems to be giving me the same pattern. If I launch them from the same corner multiple times, they keep taking the same direction. They have only rarely ever not taken the same route before getting stuck.

I'm not sure how much code can be posted here, but this is my current algorithm. Beware, it's not very pretty at the moment. It was implemented just to see if it's viable. Now I just want it to work properly before refactoring it and making it more intelligent.

        // OMG! Is the ghost trying to hit a wall? Ha! No wall-hacking for you!
        if (!wall_.Collides(frameSize_, pos_, direction_))
            pos_ += direction_;
        else
        {
            // a and b will change speed.
            // if a and b are both 1 (diagonal vector), then c will determine
            // which value a or b shall be taken.
            // d negates the values for reversed direction.
            Random rand = new Random();
            int a, b, c, d;
            a = b = 0;
            while (0 == a && 0 == b)
            {
                a = rand.Next(2);
                b = rand.Next(2);
            }

            if (1 == a && 1 == b)
            {
                c = rand.Next(2);
                if (0 == c)
                    spd_ = new Vector2(a * 2, 0);
                else
                    spd_ = new Vector2(0, b * 2);
            }
            else
            {
                d = rand.Next(2);
                if (1 == d)
                {
                    if (1 == a)
                        spd_ = new Vector2(a * 2, 0);
                    else
                        spd_ = new Vector2(0, b * 2);
                }
                else
                {
                    if (1 == a)
                        spd_ = new Vector2(-a * 2, 0);
                    else
                        spd_ = new Vector2(-b * 2, 0);
                }
            }
        }

Addendum: What I also meant to add is that the ghosts get stuck eventually. They stop taking corner with a different direction. I've waited for about 20-40 tries, but they simply reversed direction. This happened repeatedly with several restarts of the game.


texts:
I'm designing a simple 2 player RTS with Stencyl, a program that uses blocks for coding. The current code updates lists whenever an actor moves (new X and Y), and I'd want the server to update the game state with each change to the list. However, to start off: I don't even know how to set up a socket server. Stencyl has taught me the basics of logic, but I've yet to learn any programming languages.

I've downloaded a Smartfox 2X socket server that I'm intending to use. Right now I'm only looking to make baby steps; I want to do something to this effect: "When someone connects to the server, open insert file here". How can I do this? My intention is to have this file be the game client. Is this "open file when connected" method the best way to go about this? When answering: assume that I know nothing, because really, though I have done research (I know that UDP>TCP for real time), implementation-wise I know nothing.


texts:
As I understand for a client server model, it's common practise to send input to the server and then the server applies the input to update the state of the game. The server then sends updates to clients regularly. The client in the meantime does prediction, before it receives the "true" state.

My question is how often to send input. Surely it should be sent every frame otherwise some input (during frames which are not sent) will not be processed by the server. Will this be too heavy for the network. What is common practise?


texts: Unity WebGL Canvas only loads on select machines

texts:
https://herbertjoseph.com

There is a WebGL build in the background of this site, and it doesn't seem to laod on my iPad. I've asked a few people to visit and check it out, and some have said that the scene doesn't load on their workstations either...

I've checked the console of the builds, and found no egregious errors. Most browsers, even mobile, support webgl now...

How can I ensure it'll work across most/all devices?


texts: I have a player wich is a png image and I want a part of him to be able to go behind things, so I need to know how to hide pixels that are inside of a shape


texts:
I'm working on an idea for a trading game. Players would be traders buying in place A and selling in place B, hopefully for a profit.

I want prices to be dynamic, based on demand and supply. So if place A produces less food than it consumes, prices for food would he high and getting higher the closer they get to running out, while in place B, which has much more production than supply, prices would be near the production cost (minimum price). But if someone buys up a lot of the supply in B, prices would rise, and if someone sells a lot in place A, prices would drop.

Obviously, there are many ways to game such a system if it's not well-designed. The most easy is to empty the market, wait for the price to adjust, then sell everything back.

How could I design this system? I mean the actual math and functions, not philosophical musings. I searched a lot and haven't found anything specific.

I found this question but it and its answers are a lot more specific to the specific formula the guy uses in his game. I'm looking for a more generic approach (I want different price elasticity for different goods, maybe non-linear price curves, etc.)


texts:
I'm trying to build a simple world editor and I would like to implement a camera similar to what's used in 3ds Max, Maya or even Unity.

From what I can figure out from Unity, the panning behavior seems to be relatively simple : the camera is moving on the plane defined by the camera position and direction. However, rotation is more complex. Most of the time, the camera is looking at a fixed point on the xz plane and rotating around it. I'm not entirely sure how this point is determined and this is what I'm trying to find out. Also, I've noticed that, after a certain height, the camera fall back to a rotation-only control.

Does anybody implemented something similar to this?


texts:
I have a hover craft and I would like to implement it but I don't know what the algorithm or equation of how the physics work is. The variables I think would be the falling speed, the aircraft position and the distance from the ground. Based on that I need it to return the velocity. What makes it so hard is that it needs to work regardless of the situation like falling off a big cliff. Lets say it falls from a very high altitude. Once the craft is at a certain position from the ground the jets should gradually bring the craft down to speed and shoot it up from the ground a little depending on the height. Here is a picture illustrating what I'm talking about.

Could I get some help on what the algorithm would be determining the hover craft's vertical velocity?

Thanks.


texts: How can I enable/disable a script that is attached to a character, only once?

texts:
With only once, I mean once false and once true. The reason I want to enable and disable the script is that I don't want to disable the player controller and then after some point re-enable that controller again.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.Characters.FirstPerson;

public class FadeScript : MonoBehaviour
{
    public FirstPersonController fpc;
    public float fadeDuration = 5;
    public float speed;

    private Material material;
    private float targetAlpha = 0;
    private float lerpParam;
    private float startAlpha = 1;

    void Start()
    {
        material = GetComponent<Renderer>().material;
        SetMaterialAlpha(1);

        fpc.enabled = false;
    }

    void Update()
    {
        lerpParam += Time.deltaTime;

        float alpha = Mathf.Lerp(startAlpha, targetAlpha, lerpParam / fadeDuration);
        SetMaterialAlpha(alpha);

        if (alpha == 0)
        {
            fpc.enabled = true;
            var firstpc = fpc.GetComponent<FirstPersonController>();

            if (fpc.transform.rotation != Quaternion.Euler(0, 0, 0))
            {
                firstpc.enabled = false;
                fpc.transform.rotation = Quaternion.Slerp(fpc.transform.rotation, Quaternion.Euler(0, 0, 0), speed * Time.deltaTime);
            }
            if (fpc.transform.rotation == Quaternion.Euler(0,0,0))
            {
                firstpc.enabled = true;
            }
        }
    }

    public void FadeTo(float alpha, float duration)
    {
        startAlpha = material.color.a;
        targetAlpha = alpha;
        fadeDuration = duration;
        lerpParam = 0;
    }

    private void SetMaterialAlpha(float alpha)
    {
        Color color = material.color;
        color.a = alpha;
        material.color = color;
    }
}

This script is not attached to the FirstPersonController. That is why I added the global variable fpc.

I'm getting the script that is already attached to the fpc. I called it firstpc and the script name is: FirstPersonController

FirstPersonController gives the player a control over the fpc with the mouse camera. I want to disable the script until fpc.transform.rotation == Quaternion.Euler(0,0,0) and then enabled the script again to use.

The problem is that it's all the time getting over and over again to the line:

firstpc.enabled = false;

Then it's getting also to the line:

firstpc.enabled = true;

But since it's getting to the false all the time it's stuck between both states.

The script here in my question is attached to the Plane in the hierarchy.
And the script I want to enable/disable is attached to the FPSController.

In my script that is attached to the Plane, fpc is the FPSController and firstpc is the script FirstPersonController that attached to the fpc.


texts: How to stop jumping again when 3D character is in air (double jump)?

texts:
I'm working on simple rpg and having some trouble with player jumping. I'm trying to use unity's raycast to check colliders under the player before jumping again. The problem appears that no matter how many tweaks I make to the distance or the validation of the canJump function, the raycast the player seems to at max jump twice. At lower levels the player can even hover if timed correctly. Could someone overlook my code since it appears that I might have a noob glitch somewhere?

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

public class Player : MonoBehaviour
{

    public float speed;
    public float jumpForce;
    public float turningSpeed;

    private bool canJump;

    void Start()
    {

    }

    void Update()
    {

        RaycastHit hit;
        if (Physics.Raycast(transform.position, Vector3.down, out hit, 1.01f))
        {
            canJump = true;
        }

        ProcessInput();

    }

    void ProcessInput()
    {
        if (Input.GetKey("right") || Input.GetKey("d"))
        {
            transform.position += Vector3.right * speed * Time.deltaTime;

        }

        if (Input.GetKey("left") || Input.GetKey("a"))
        {
            transform.position += Vector3.left * speed * Time.deltaTime;

        }

        if (Input.GetKey("up") || Input.GetKey("w"))
        {
            transform.position += Vector3.forward * speed * Time.deltaTime;
        }

        if (Input.GetKey("down") || Input.GetKey("s"))
        {
            transform.position += Vector3.back * speed * Time.deltaTime;
        }

        if (Input.GetKeyDown("space") && canJump)
        {
            canJump = false;
            GetComponent<Rigidbody>().AddForce(0, jumpForce, 0);
        }

    }
}


texts: How to fuse 2 sprites as they approach each other in Unity2D?

texts:
Hi i seen this video by Sebastian Lague on ray marching. Link: https://www.youtube.com/watch?v=Cp5WWtMoeKg&t=204s At 3:19 mins.

I want this merging effect but for 2D sprites. Please can someone instruct me on how it can be made or the steps to make it.


texts:
I know that for Box2d I need to translate pixels to meters which is easy peasy. However my problem is what is the orientation of Box2D coordinates system? Is this the same as screen one (right += x, bottom += y) or it is like cartesian (right +=x, bottom -= y) ?

Also, does Box2D coordination system use negative values?

Thank you.


texts: How do I render a 2D overlay with DirectX 9?

texts:
I'm working in C++ with DirectX 9 on a 3D game, but I want a 2D overlay for rendering a HUD.

I've heard that I could use D3DXMatrixOrthoLH, but I'm very confused on how to use it. I'm more familiar with OpenGL, where I could simply switch between 3D and 2D by initiating the view.

How can I do this in DirectX 9?

EDIT:

I was able to achieve this like (partial psudocode):

But I have a good feeling this is not the right way to do it.

void render()
{
    beginscene();

    D3DXMATRIX matrix;
    D3DXMatrixIdentity(&matrix);

    D3DXMatrixTranslation(&matrix, 0, 0, 0);
    device->SetTransform(D3DTS_WORLD, &matrix);

    // Render 3D.

    D3DXMatrixIdentity(&matrix);

    device->SetTransform(D3DTS_WORLD, &matrix);
    device->SetTransform(D3DTS_VIEW, &matrix);

    D3DXMatrixOrthoOffCenterRH();
    device->SetTransform(D3DTS_PROJECTION, &matrix);

    // Render 2D.

    endscene();
}


texts: Is there a way to hardcode a JSON file into a Unity build?

texts:
I'm currently creating an external tool to generate dialogues that are exported as JSON files.

The idea is that after you create a dialogue (as a JSON), my main Unity project reads that file and generates a dialogue.

Right now it works just fine, but the JSON is an external file that you can modify even after compiling the game (of course).

Is there a way to actually "hardcode" that JSON file so that the game doesn't need to find and read the file every single time it plays?