texts: Are there any resources for motion-planning puzzle design?

texts:
Some background: I'm poking at a set of puzzles along the lines of Rush Hour/Sokoban/etc; for want of a better description, call them 'motion planning' puzzles - the player has to figure out the correct sequence of moves to achieve a particular configuration.  (One characteristic of the sort of puzzle I'm thinking of is that they're generically PSPACE-complete; they're not necessarily in NP because the optimal sequence of moves isn't necessarily polynomial in the input size, so we can't guarantee that a solution can be verified in polynomial time).

While I have a few straightforward 'building blocks' that I can use for puzzle crafting and I have a few basic examples put together, I'm trying to figure out how to avoid too much sameness over a large swath of these kinds of puzzles, and I'm also trying to figure out how to make puzzles that have more of a feel of logical solution than trial-and-error.  Does anyone know of good resources out there for designing instances of this sort of puzzle once the core puzzle rules are in place?  Most of what I've found on puzzle design only covers creating the puzzle rules, not building interesting puzzles out of a set of rules.


texts:
Below is the code I'm using to check if the board state has a tic tac toe style victory state.
The board is always square and is made of an array of objects that keep track of their own completion state (the variable board[x,y].complete is a boolean on if that node is currently complete)
The current method is to see if the player can count to the width of the array in a single pass and if so use breaks to skip any future necessary checks.

But at the moment the code either ignores legitimate win states or falsely detects win states.

I'd be appreciative if anyone can give me pointers on what might improve the code or help solve for arbitrarily sized square boards.

///check to see if the player has bingo

var board = global.board;
var score_ = 0;
var row = 0;
var col = 0;
var victory = false;

//check horrozontal complete
for (col = 0; col < array_height_2d(board); col++)
{
    if victory == true
    {
        break;
    }
    for (row=0; row<array_height_2d(board); row++)
    {
        if board[row,col].complete == true
        {
            score_ += 1;
        }
    }
    if score_ == array_height_2d(board)
    {
        victory = true;
        break;
    }
    score_ = 0;
    score2 = 0;
}

//vertical checks
score_ = 0;
for (row = 0; row < array_height_2d(board); row++)
{
    if victory == true
    {
        break;
    }
    for (col=0; col<array_height_2d(board); col++)
    {
        if board[row,col].complete == true
        {
            score_ += 1;
        }
    }
    if score_ == array_height_2d(board)
    {
        victory = true;
        break;
    }
    score_ = 0;
}

//diagonal checks
score_ = 0;
var diag = 0;
for (diag = 0; diag< array_height_2d(board); diag++)
{
    if victory == true
    {
        break;
    }
    if board[diag,diag].complete == true
    {
        score_ += 1;
    }
    if score_ == array_height_2d(board)
    {
        victory = true;
        break;
    }
}
score_ = 0;
diag = array_height_2d(board);
while diag > -1
{
    if victory == true
    {
        break;
    }
    if board[diag,diag].complete == true
    {
        score_ += 1;
    }
    if score_ == array_height_2d(board)
    {
        victory = true;
        break;
    }
    diag -= 1;
}
score_ = 0;

return victory;

Examples of arrays that fail to detect a win state:


texts: How can I save and load an adventure game?

texts:
I'm using cocos2dx and sqlite to store datum. The table looks like this: x INT, y INT, className TEXT, properties TEXT. I use json to serialize terrains and sprites. But I don't know how to synchronise it. Below is how I'm doing:

//1: create a interface takes an range and returns data in it.
Data getData(Rect range);

//both are global objects.
cachedRange = [];
cachedData = [];

//2: while reading from sqlite, I scale the range and cached other data.
Data getData(Rect range){
    //if it has been cached.
    if(cachedRect.contains(range)){
        return retrieveDataFromCached(cachedData, range);
    }

    var scaledRange = scale(range, 10);
    var data = retrieveFromSqlite(scaledRange);
    var inRange = [];
    for(var d : data){
        if(range.contains(d)){
            inRange.append(d);
        }else{
            cached.append(d);
        }
    }
    cachedRange.append(range);
    return inRange;
}

However, these data will change. For example, some mobs are instantiated and then killed, and some are moved. When should I delete original records of the table.


texts: javascript game loop and game update design

texts:
There is a main game loop in my program, which calls game update every frame. However, to make better animation and better control, there is a need to implement a function like updateEveryNFrames(n, func).

I am considering implementing a counter for each update. The counter will be added by one each frame. The update function will be invoked according to the counter % n.

For example, in a sequence of sprites animation, I can use the above function to control the speed of the animation.

Can some give some advice or other solutions?


texts:
I am an iOS developer but I'm new to cocos2d. I'm working on new game, I use Kobold2D, have cocos2d installed too, and I want to make this effect:

I know how is done with Flash, but can't make it with Kobold2D. There's 2 images with the same size: one is a low-res image for the background and the second is a hi-res over the first one. When the "reticle" mask moves, it reveals the second image inside the circle and the background is visible outside only. I googled with no success, saw some Ray Wenderlich projects they weren't helpful.


texts:
Hi I’m working on turn based game development using turn based API from Apple’s GameKit framework. My game is 2 player strategy game.  Currently I’m facing the issue match data update on game play screen when the player complete their turn. I have more animation on game play, so the turn  data make impact both side.

and also we need reference or guidance for following questions:

1.when i get invite from the opponent player, the app will launch and authenticate on home screen but didn’t navigate to game play screen.

2.How the match data manage easily?

3.I have  3 primary leaderboard to play the game, Is this possible to update scoreboard for every turn?


texts: Fps shoots up when sdl2 window is not on top

texts:
I am learning sdl2 with C++ from Lazy Foo Productions' tutorials. I am using a 5 year old retina mac book pro and xcode.

When reading this entry on calculating frame rate I noticed that when runing the application it would tend to 60 fps and the cpu and energy impact were very low, 2% and Low respectively, but when placing another window over it the fps would shoot up to 5000 along with cpu and energy impact, to 93% and High respectively.

Why is this happening? Is it because sdl2 just stops rendering all together when it is not on top of other windows? Or is it because the OS stops it from rendering?


texts: How to make Unity NullReferenceExceptions more informative

texts:
Is there a way to modify the NullReferenceException for Unity gameObjects so that not only does it say "object reference not set to an instance of an object," but also says exactly what the name of the object in code that was null?

For example, if I write

GameObject myGameObj,

forget to assign myGameObj in the inspector, and then say

myGameObj.transform,

is there a  way to print to the Unity console something along the lines of

"Object reference not set to an instance of an object. The object that is null is {0}", $name_of_nullVariable_in_code$);

?

See:
https://docs.unity3d.com/Manual/NullReferenceException.html


texts: Why does Farseer 2.x store temporaries as members and not on the stack? (.NET)

texts:
UPDATE: This question refers to Farseer 2.x. The newer 3.x doesn't seem to do this.

I'm using Farseer Physics Engine quite extensively at the moment, and I've noticed that it seems to store a lot of temporary value types as members of the class, and not on the stack as one might expect.

Here is an example from the Body class:

private Vector2 _worldPositionTemp = Vector2.Zero;

private Matrix _bodyMatrixTemp = Matrix.Identity;
private Matrix _rotationMatrixTemp = Matrix.Identity;
private Matrix _translationMatrixTemp = Matrix.Identity;

public void GetBodyMatrix(out Matrix bodyMatrix)
{
    Matrix.CreateTranslation(position.X, position.Y, 0, out _translationMatrixTemp);
    Matrix.CreateRotationZ(rotation, out _rotationMatrixTemp);
    Matrix.Multiply(ref _rotationMatrixTemp, ref _translationMatrixTemp, out bodyMatrix);
}

public Vector2 GetWorldPosition(Vector2 localPosition)
{
    GetBodyMatrix(out _bodyMatrixTemp);
    Vector2.Transform(ref localPosition, ref _bodyMatrixTemp, out _worldPositionTemp);
    return _worldPositionTemp;
}

It looks like its a by-hand performance optimisation. But I don't see how this could possibly help performance? (If anything I think it would hurt by making objects much larger).


texts: The websocket messages in my online game are being served too slow

texts:
Im attempting to make a online game in python, though I have ran into a problem. Basically I want the game to be playable in many regions, but the websockets are to laggy to be played in farther regions. To get around this I have implemented a system on the client that extrapolates between two values to find the speed (x and y axis change). The player will continue to move to these speeds, so if there is a lag spike, it wont be as noticeable. the server is coded in python, I use a python web-framework called Quart (flask with asyncio functions) The websockets run asynchronously to the main loop. The main problem is when the x and y values are updated on the server, they might be updated multiple times before they get served by the websocket; The result of this is an inaccurate estimate on the client side, which cause jittery movement when the clients x and y values are updated to the proper values. I would appreciate advice for resolving this issue.

Things to note:

The python web-framework I use is documented here:  https://pgjones.gitlab.io/quart/

My method for extrapolating the values on the client-side is just recording the before and after x and y values, then subtracting the before from the after.


texts: Shader to see silhouette through alpha blended sprites

texts:
I want to achieve in Unity a see through effect like the one in these examples:

In my specific scenario there are a couple of requirements:

Sprites are using alpha blending, and sprites have transparent areas.
There are 2 kind of elements that occlude the character. One should create the silhouette effect, and the other one should behave like normal.

For occluding elements that create the silhouette I enable ZWrite, and disable it for elements that doesn't.

For the character I tried setting the queue of the shader to transparent+1, and added this pass:

Pass
{
    ZTest Greater
    Lighting Off
    Color [_Color]
}

And the effect works partially:

The silhouette is drawn all over the character, even the parts that are transparent. Transparent parts shouldn't create a silhouette.
The silhouette is created when the character is behind a sprite, even if that part of the sprite is transparent. Being behind a transparent part of the sprite shouldn't create the silhouette.
The character appears infront the rest of the elements, even if it is behind them. I guess this is because setting the queue to Transparent+1. But if I leave it as Transparent, the character is drawn in the correct order, but the silhouette is never seen.

I tried to follow these tips someone gave me, but I'm unable to get it to work:

  1) Leave the pass that renders the sprites as is.

  2) Add a pass that writes to the z-buffer, but has a shader that uses clip() to discard pixels based on alpha. You can't use the z-buffer to make soft z-tests without using MSAA and alpha-to coverage. The quality of that won't be great, but it's the best you can do. A faster alternative is a pattern or noise dither, or a good old fashioned threshold if your sprites all have fairly sharp edges.

  3) Add third pass to occludable objects that draws the occlusion color using the z-test and make sure it's drawn as a final pass.

I'm kind of new to shaders, specially in Unity, and I just can't figure out how to make it work properly.


texts:
I've got a really strange problem, that I can't solve whatever I try. So it's the following:
I have 2 body's in Box2D, one, the player is a dynamic body, the other one, an obstacle is a static one. Now everything is fine, I can move my player around and everything, however as soon as he touches the obstacle, my game instantly crashes, no errors or something. I don't add or destroy body's while the game is ticking, so there shouldn't be a problem here ...... has anyone experienced something comparable and got a solution for it ?

Sadly I can't upload code right now as I'm on my phone, but I'll try to add some later


texts: How to rotate a sprite on touch/drag done on the screen wih Andengine?

texts:
when I look at the andengine examples I saw an example about rotate a sprite with joystick. Here is the code;

    final float y2 = (this.mPlaceOnScreenControlsAtDifferentVerticalLocations) ? 0 : y1;
    final float x2 = CAMERA_WIDTH - this.mOnScreenControlBaseTextureRegion.getWidth();
    final float x1 = 0;
    final float y1 = CAMERA_HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight();
    final AnalogOnScreenControl rotationOnScreenControl = new AnalogOnScreenControl(x2, y2, this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, this.getVertexBufferObjectManager(), new IAnalogOnScreenControlListener() {
        @Override
        public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) {
            if(pValueX == x1 && pValueY == x1) {
                face.setRotation(x1);
            } else {
                face.setRotation(MathUtils.radToDeg((float)Math.atan2(pValueX, -pValueY)));
            }
        }

        @Override
        public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) {
            /* Nothing. */
        }
    });

That is okay for joystick BUT I want to implement this without joystick.. I mean when user drag/slip the screen with finger than sprite will also rotate according to finger movement. By the way I only want to rotate NOT move.. And here is code that I try to;

mScene.setOnAreaTouchListener(new IOnAreaTouchListener() {

        @Override
        public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
                ITouchArea pTouchArea,final float pTouchAreaLocalX,
                final float pTouchAreaLocalY) {
            if(pTouchAreaLocalX == x1 && pTouchAreaLocalY == x1) {
                face.setRotation(x1);
            } else {
                face.setRotation(MathUtils.radToDeg((float)Math.atan2(pSceneTouchEvent.getX(), -pSceneTouchEvent.getY())));
            }
            return false;
        }
    });

and my code didn't work.. Is there any suggestion ? Thanks...


texts: What is the difference between Pygames, Pyglet and Kivy and how each helps python game development?

texts:
I trying to figure out which options would be best to give a graphics to a UNIX based 2D game whose logical part was written in python. Which engine to use.

What is the difference between Pygames, Pyglet and Kivy and how each works in relating the logical part of the game with it's actual graphical display?


texts: How to make MathNet.Numerics work with Unity?

texts:
I have installed the latest version of MathNet on Visual Studio using the NuGet Package Manager. I've also, copied the MathNet.Numerics.dll to an Plugins folder in the Unity editor. Yet it still gives a compiler error: error CS0234: The type or namespace name 'Distributions' does not exist in the namespace 'MathNet.Numerics' (are you missing an assembly reference?)

Does anyone know how to solve this or knows a similar package that works with Unity?


texts: How to gain accurate results with Painter's algorithm?

texts:
A while ago I asked how to determine when a face is overlapping another. The advice was to use a Z-buffer.

However, I cannot use a Z-buffer in my current project and hence I would like to use the Painter's algorithm. I have no good clue as to when a surface is behind or in front of another, though. I've tried numerous methods but they all fail in edge cases, or they fail even in general cases.

This is a list of sorting methods I've tried so far:

Distance to midpoint of each face
Average distance to each vertex of each face
Average z value of each vertex
Higest z value of vertices of each face and draw those first
Lowest z value of vertices of each face and draw those last

The problem is that a face might have a closer distance but is still further away. All these methods seem unreliable.

Edit: For example, in the following image the surface with the blue point as midpoint is painted over the surface with the red point as midpoint, because the blue point is closer. However, this is because the surface of the red point is larger and the midpoint is further away. The surface with the red point should be painted over the blue one, because it is closer, whilst the midpoint distance says the opposite.

What exactly is used in the Painter's algorithm to determine the order in which objects should be drawn?


texts: How do you develop the model matrix for an object?

texts:
This might be a misunderstanding on my part but let me give you my superficial understanding of Model-View-Projection pipeline and different coordinate systems. Then I will ask a question.

As we know, we might have many models in our scene. You might load vertex attributes for each using a model loader etc. When you load the coordinates, these are in object space or model space. So they describe the object wrt a local frame. We use model matrix to transform this to world space shared by all models, a global frame let's say.

After this, we are in a huge world space. We might think this as an endless Euclidean 3D space. Here coordinates may have any value. Somewhere in the world, we have a camera and these objects in the world have different coordinates wrt. camera's frame. This is where view matrix comes into play. After applying this transformation, coordinates are in view space. In the OpenGl world, we think like the camera lies at the origin. We specify a view frustum and we do (actually delay) the clipping etc.

After this we apply projection matrix and transform this viewing pyramid into a cube that spans [-1, 1] in all the axes. This is homogeneous coordinates and we do perspective divide, clipping etc. This is my view of the whole thing, roughly.

The question is, we have routines to generate view and projection transformations given the required parameters. But how about the model matrix? For example, I load a bunny model stored in an OBJ file. It might have a coordinate value like (32.657, -12.545, 8.444). In which space are these coordinates? If it's in the model space, what is the best strategy to develop a model matrix to put this object into world space? Another OBJ model of same bunny might have coordinates all lying in [-1, 1] range for example. Does this mean this object is already transformed with an MVP? Are those model matrices related to only skeletal, hierarchical models?

I think this is a strange question so I don't see this really mentioned anywhere. But this bugs me, leaves me with a superficial understanding of whole matter. I want to truly understand.


texts:
I've been having a bit of trouble using OpenGL to make 2D games. I am using a traditional ortho perspective with just some sprites being rendered and moved around.

It all works perfectly but there is a little graphical artifact that I would like to get rid of. As the sprites move, their edges jitter a little bit; I assume this happens as the position of the sprite goes from a half-pixel coordinate to a nicely rounded up coordinate, and then back again, causing the artifact to intermittently show up.

I also had the exact same problem with text rendering (textured quads technique), when it was sitting at half-pixel coordinates, where it would get blurry and ugly, while at strict integer positions it would show immaculate.

I could force my sprites to integer positions before rendering, which would probably fix the artifact, but at the same time ruin the movement smoothness.

So, does anyone know what is the state of the art solution for this problem? How to handle sprite positioning without artifacts?


texts: Separating axis theorem implementation flaky minimum translation vector based on triangle orientation

texts:
I've implemented some collision detection using separating axis theorem. Works fine for axis-aligned rectangles and two out of four possible right triangle orientations. For some reason when the hypotenuse is oriented down left or up right, the minimum translation vector being calculated is that of the normal of the base or height of the triangle rather than the hypotenuse that is being collided with.

http://i.stack.imgur.com/W5WHH.png

I've got a jsfiddle demo of my implementation. The center box and right side triangles all show a correct MVT when the collision box collides with them. The ones on the left side do not. Move your mouse over the canvas to move the collision box.

http://jsfiddle.net/XLtdB/


texts:
I'm implementing a shadow map algorithm with a spotlight (a spotlight that always "looks" at a given object).

My issue is that for some configuration, part of the object the light is "looking at" is out of the light frustum. As a consequence everything that is not "seen" is shadowed.

To account for this I tried to increase the field of view of the "light camera", but as a result I get very blocky shadows.

Am I doing something wrong? Is there a more clever way to make sure the light can see the whole object? If not, how can I solve the above said artefact?


texts: Should clients in an online game access the database directly or through a game server?

texts:
first im total noob about c# and mysql. Just trying to find which way is better. i believe your answers prevents me from losing plenty of time.

Online game(not more than 50 users at pre-alpha. Not expecting than 500+ at the end.)
Text based game / console like ( minimum graphics )
PVP -> Players are able to destroy other players.
Simlpy a hacking simulation.
There will be some servers.(NPC servers and player made servers)
players can reach that servers made by other players.

Q: Which one is the good way to store that servers data?

game client --> Mysql server ?
or
game Client --> a Server Client(which is localy running a mysqL server)

If it's totaly wrong to use mysql server how can i make it?
Thank you...


texts: How can you meaningfully market test microtransactions?

texts:
For a number of reasons I have chosen to use Microtransactions to monetize my current project. However, like all make or break features I am concerned about how they are received in-game.

Microtransactions seem to present a unique problem in my mind though. I believe that just giving people currency will skew my results, and it wouldn't actually represent how people feel about how things are priced (in the same way that I am more apt to waste money when I didn't have to earn it).

With that in mind, how can I effectively, and meaningfully market test the implementation of Microtransactions in my game?


texts: Converging at position and angle using motor-based rigidbody movement

texts:
I am given a rigidbody positioned in \$\mathbb{R}^2\$. It is a box of length \$l\$ and height \$\epsilon\$. The position of the box's left center is described by \$\vec{p}\$, and its angle from the x-axis is \$\theta\$. The body is in a vacuum (no friction), and its mass is \$m\$ (uniformly distributed). Here's a quick diagram.

Next, I am given a target position and angle to reach. It is not guaranteed that the body will reach the target position and angle the next time frame.

I need to calculate the necessary force \$F\$ and torque \$T\$ that will push the body closest to the target. I am given constraints for max force and max torque.

To make things complicated, the body might be affected by external forces. One of them is gravity \$F_g\$, which will always remain constant. Sometimes, normal forces exist as well. The applied forces or the total force is unknown, but the velocity or the angular velocity is available.

I tried to solve this problem using steering behaviors. However, the angle seems to fluctuate constantly. Here's part of my code in C# (Unity).

\$\vec{p}_0=\$transform.position
\$\theta_0=\$transform.eulerAngles.z
\$\vec{p}_t=\$position
\$\theta_t=\$angle

private RigidBody _body;

public float SlowDownRadius = 2f;
public float MaxVelocity = 50f;
public float MaxForce = 10000f;

public float SlowDownDelta = 15f;
public float MaxAngVelocity = 180f;
public float MaxTorque = 10000f;

public void Next(Vector3 position, float angle) // angle in degrees
{
    // force
    Vector2 to = position;
    var from = (Vector2) transform.position;
    var desired = to - from;
    var dist = desired.sqrMagnitude;

    desired = desired.SetMagnitude(dist < SlowDownRadius * SlowDownRadius
        ? MaxVelocity * Mathf.Sqrt(dist) / SlowDownRadius
        : MaxVelocity);

    Vector2 vel = _body.velocity;
    var steering = desired - vel;

    var mass = _body.mass;
    Vector2 force = mass * UnityEngine.Physics.gravity;
    var time = Time.deltaTime;

    var newForce =
        (time <= 0 ? new Vector2() : (mass / time * steering)) - force;

    _body.AddForce(newForce.Clamp(MaxForce)); // limits magnitude of newForce to MaxForce

    // torque
    var toAngle = angle;
    var fromAngle = transform.eulerAngles.z;
    var desiredAngle = AngleDistance(fromAngle, toAngle);
    var distAngle = Mathf.Abs(desiredAngle);

    if (distAngle < 1f)
    {
        transform.eulerAngles = new Vector3(0, 0, angle);
        return;
    }

    desiredAngle = Mathf.Sign(desiredAngle) * (distAngle < SlowDownDelta
                  ? MaxAngVelocity * distAngle / SlowDownDelta
                  : MaxAngVelocity) * Mathf.Deg2Rad;

    var angVel = _body.angularVelocity.z; // in radians
    var steeringAngle = desiredAngle - angVel;

    var newTorque = (time <= 0 ? 0f : (mass / time * steeringAngle));

    _body.AddTorque(0, 0, Mathf.Sign(newTorque) * Mathf.Min(Mathf.Abs(newTorque), MaxTorque));
}

public static float AngleDistance(float from, float to)
{
    var dist = (to - from + 180f) % 360f - 180f;
    return dist <= -180f ? dist + 360 : dist;
}

If I made any errors, please let me know.
Thank you in advance!


texts: How to make an arrow land at a specific position in 3D world space

texts:
In my game when I click with the mouse on the terrain somewhere, I'd like the player to fire an arrow to that position in a parabolic fashion.

The arrow has a position, acceleration and velocity all using 3D vectors. I looked at the Trajectory of a projectile article on wikipedia, but I don't know how to apply it in my situation as it explains 2D mathematics. I was wondering if there's a solution for 3D vectors? Any good resources perhaps related to the 3D situation?


texts:
I try to add angular velocity to my GameObject with this command:

rigidbody2D.angularVelocity = Random.value * tumble;

All works, but I want center of velocity be in the center of my rigidbody, but center is outside my GameObject and looks like every time in different place. How can I set rotation center to the center of my rigidbody?

IMPORTANT: when my GameObject is stay on place (no movement) then all works fine, when I add linear movement it begin rotate around some outside center.

Thanks!


texts: How to handle animations for a turn based deterministic game?

texts:
I have a turn based combat system where all monsters act one turn, then all players, etc. The combat mechanics are completely deterministic - I can pre-calculate the outcome of a turn.

I'm interested if I should do all calculations ahead of time (monster A will be at X, monster B will be at Y), and then just play a bunch of animations based on these calculations:

(Calculate for A)
(Calculate for B)
(Animate A move to X)
(Animate B move to Y)

OR do one animation per calculation?

(Calculate for A)
(Animate A move to X)
(Calculate for B)
(Animate B move to Y)


texts: Maintain performance and precision with a large vertex buffer?

texts:
I have a world with 100s of simple objects on screen at once. Most objects don't have more than 40-50 vertices. The vertex coordinates for these objects are very large (planetary scale), so I use the 'floating origin' method to draw my data (actual coordinates are close to the origin and then you apply a translation out to where you want the object).

Based on the user's position, these objects are dynamically created and destroyed. Other than that, the objects are static. With my previous implementation, I was drawing these objects separately, and the result was significant slow down (I'm targeting mobile devices)... since the total number of triangles on screen is sort of trivial (even though there are many objects), I assume that the slow down is because of the multiple draw calls.

So I tried packing my objects into a single buffer to draw them all with a single call. This works, but I also use a 'floating origin' transform to position the geometry. The final transform matrix is calculated with the CPU to maintain precision and then sent to my vertex shader. The problem is applying the floating origin fix is CPU intensive:

If I use a single floating origin for the vertex buffer:

(good) only need to calculate one transform matrix
(bad) I need to perform an offset subtraction on every vertex in the buffer. The upper limits of scene complexity reaches 50k+ vertices, so this is expensive.

If I use multiple objects:

(sorta good) only need to compute as many matrices as there are objects (this is still really expensive though, since there are a ton of objects)
(bad) I need to pass the shader a large array of matrix uniforms

I feel like I'm stuck. Are there any other ways to maintain precision I could use? Or maybe a better way to use the floating origin method? The problem is basically "how do I draw a ton of simple geometry with really large numerical coordinates with OpenGL ES 2?"... I'd appreciate any advice.

EDIT

Just some clarification on the offset. The vertex should always be a valid float. The maximum distance a vertex can be from the origin is the maximum radius of the earth +/- few thousand meters. Assume 1 unit = 1 meter. The distances are never so large that they can't be represented by floats at all.

The objects themselves are things you find in a map on the surface of the earth: buildings/roads/etc. So relative to the coordinates being used, the objects are very small.

I'm not confident on the floating origin stuff, but here's my take...

When you calculate the MVP on the CPU where your vertex is offset, you're getting something you calculate with double precision that goes from an offset vertex position (say its 10.1,10.2,10.3) to the normalized opengl coordinates (I think thats +/- 1 in xy and 0-1 in z... I don't remember right now). You then pass the shader a vertex thats close to the origin, so no huge loss in precision, and a transform matrix that was calculated with double precision.

That's way better than sending the shader a vertex with much larger values since you lose a bunch of precision right away.


texts: How can I load all of my scenes at startup?

texts:
I want all of my scenes to load when the loading screen is shown (but only one
should be shown at a time) so I can switch between them quickly I have tried
this:

if (Application.GetStreamProgressForLevel (2) == 1) {
    Application.LoadLevel (2); Application.LoadLevelAdditive (1);

and:

(Application.GetStreamProgressForLevel (2) == 1) {
Application.LoadLevelAdditive (2);
Application.LoadLevelAdditive (1);
Application.LoadLevel (1)


texts: How can I fix my sprite being rotated 90 degrees more than toward the mouse?

texts:
I am trying to get a Sprite in LibGDX to look at the player's mouse. Here's the code I have (mind you, I am using JRuby):

target = mouse_position.sub(spatial.position)
rotation = MathUtils.atan2(target.y, target.x)
spatial.rotation = rotation * MathUtils.radiansToDegrees

This is definitely doing something, but it's not completely correct. Here's a GIF of what it looks like in action:

Where am I going wrong?


texts: Design patterns for effects between actors and technology

texts:
I'm working on my first game, and taking the opportunity to brush up my C++ (I want to make as much of it as portable as I can.)

Whilst working on the technology tree and how it affects actors (spaceships, planets, crew, buildings, etc) I can't find a pattern that decouples these entities enough to feel like a clean approach.

Just as an idea, here's the type of effects these actors can have on one another (and techs too)

An engineer inside a spaceship boosts its shield
A hero in a spaceship in a fleet increases morale
A technology improves spaceships' travel distance
A building in a planet improves its production

The best I can come up with is the Observer pattern, and basically manage it more or less manually (when a crew member enters a spaceship, fire the event; when a new building is built in a planet, fire the event, etc etc.) but it seems to be too tightly coupled to me.

I would love to get some ideas about how to approach this better.


texts: Roguelike corridor creation; Connecting rooms

texts:
I have a simple Tile[,] that I populate with Rooms. Now I need to connect the rooms with a single tile wide corridor. At first I used A* to hook up the rooms but that, of course, get's the best path from tile to tile, but that's a bit boring.

So I decided to roll my own path walker, which very inefficiently get's me the same paths currently as A* except for some reason it never reaches the end tile. I was planning to add a randomness to it by adding a random chance to go in a random direction for a few steps before going back to it's route.

public static List<Tile> GetPath( Room startRoom, Room endRoom, Tile[,] map, int drunkenStep )
{
    //Select random tile from the wall list
    Tile startTile = startRoom.wallTiles[ UnityEngine.Random.Range( 0, startRoom.wallTiles.Count) ];
    Tile endTile = endRoom.wallTiles[   UnityEngine.Random.Range( 0, endRoom.wallTiles.Count) ];
    startRoom.wallTiles.Remove( startTile );
    endRoom.wallTiles.Remove( endTile );

    //Make it a floor tile
    startTile.type = RoomType.FLOOR;
    endTile.type = RoomType.FLOOR;
    startRoom.floorTiles.Add( startTile );
    endRoom.floorTiles.Add( endTile);

    //Add the start tile to the list
    Tile selectedTile = startTile;
    List<Tile> path = new List<Tile>();
    path.Add( selectedTile );

    List<Tile> tilesToCheck = new List<Tile>();
    do
    {
        //loop four times for each adjascent tile
        for(int i = 0; i < 4; i++)
        {
            int x = selectedTile.x + Convert.ToInt32( selectedTile.adj[i].x );
            int y = selectedTile.z + Convert.ToInt32( selectedTile.adj[i].y ); //x/y because 2D map. Tile y is for height displacement
            //Check if we are within bounds
            if( x < 0 || x > map.GetLength(0) || y < 0 || y > map.GetLength(1) ) continue;
            //We cant back track through a room and only use tiles that aren't set yet
            if( map[x,y].type == RoomType.NONE || (map[x,y].type == RoomType.FLOOR && map[x,y].roomId == -1) ) tilesToCheck.Add( map[x,y] );
        }

        float minDist = Mathf.Infinity;
        Vector2 endPos = new Vector2( endTile.x, endTile.z );
        foreach (Tile t in tilesToCheck)
        {
            float dist = Vector2.Distance( new Vector2( t.x, t.z), endPos);
            if (dist < minDist)
            {
                selectedTile = t;
                minDist = dist;
            }
        }

        path.Add(selectedTile);
        tilesToCheck.Clear();

    } while( selectedTile != endTile );

    return path;
}

Right now this never resolves and i'm not entirely sure why it doesnt reach the end tile. So my question is:

What is going wrong and what should I do to get straighter corridors and maybe some drunken randomness; maybe have a path loop around a little bit

Thanks for your time!


texts: Is there any case to mix Android UI with LibGDX?

texts:
my question is about creating "non-playable" screens in games with the help of native android tools.

For example, I have an Android LibGDX game (singleplatform), what should I use to provide start screen, level selection screen etc?

Is it "right" to build all screens in LibGDX only (where I know nothing about UI) - skins, scene2d...?

Or is it ok to build all in Android UI (I'm pretty familiar with that, and it seems to me more easy and fast to develop), and only use separate LibGDX Activity/Fragment where the game actually begins?

What is the common approach?

Thank you in advance! :)


texts: What would a good hacking gameplay look/feel like?

texts:
In real life, 'hacking' (that is, using brute-force attacks to guess a password) is not very interactive. In fact, it works pretty much independent of any user from the moment you press Return until it finds the password. Now, I am making a home project game in Unity where you are a computer, and you can interact with everything from cameras to door to explodable gas pipes. Now for difficulty and fun, some things are secured with passwords of varying difficulties. The passwords are chosen for each camera by the basic formula of picking a random integer number between 1 and (10 to the power of x), where x is set in the editor under "security level".

Right now, for the purpose of creating other aspects of the game, hacking is simply pressing 'G' while pointing at a camera, letting the computer compare each number from 0 onwards until the guess matches the cameras passcode - then when it does, the camera becomes 'unsecured' and it can be switched to. Obviously, this is uber simplistic and is not the final gameplay. My problem is what would the final gameplay look like? I want it to be enjoyable and interactive (i.e. not just the computer randomly guessing upwards) but at the same time not corny and ridiculously unrealistic (i.e. not the absurd things seen in action movies which are nothing like actual hacking). I would prefer it somewhere in between, but I am stumped as to how it would look and feel. Any suggestions are welcome, and if there are any examples from a game that I can use for inspiration, that would be great too, thanks.

Criteria

Interactive
Not super unrealistic or absurd
Must guess passwords in a way which works with the (> 1, < 10x) formula


texts: pixel shader and vertex shader problem in visual studio 2008

texts:
I have just installed XNA for VB2008 professional, now i try to run my first game development and i get this error,

any way around this, am using windows xp sp3

my system configuration

Host Name:                 USER-PC
OS Name:                   Microsoft Windows XP Professional
OS Version:                5.1.2600 Service Pack 3 Build 2600
OS Manufacturer:           Microsoft Corporation
OS Configuration:          Standalone Workstation
OS Build Type:             Uniprocessor Free
Registered Owner:          user
Registered Organization:   user-pc
Product ID:                55274-640-1011873-23081
Original Install Date:     1/26/2011, 7:00:52 PM
System Up Time:            0 Days, 10 Hours, 31 Minutes, 22 Seconds
System Manufacturer:       Hewlett-Packard
System Model:              HP d330 uT(DC579AV)
System type:               X86-based PC
Processor(s):              1 Processor(s) Installed.
                           [01]: x86 Family 15 Model 2 Stepping 9 GenuineIntel ~
2593 Mhz
BIOS Version:              COMPAQ - 20031003
Windows Directory:         C:\WINDOWS
System Directory:          C:\WINDOWS\system32
Boot Device:               \Device\HarddiskVolume1
System Locale:             en-us;English (United States)
Input Locale:              en-us;English (United States)
Time Zone:                 N/A
Total Physical Memory:     1,527 MB
Available Physical Memory: 689 MB
Virtual Memory: Max Size:  2,048 MB
Virtual Memory: Available: 2,008 MB
Virtual Memory: In Use:    40 MB
Page File Location(s):     C:\pagefile.sys
Domain:                    WORKGROUP
Logon Server:              \\USER-PC
Hotfix(s):                 10 Hotfix(s) Installed.


texts: How can I let players "scrape away" one texture to reveal another?

texts:
In this game I'm making, I want my players to be able to remove rust from an object based on collisions from another object such as a wire brush.  Since it's a VR game, performance is key.

I've been having a hard time getting on the right track; I think I'm not asking the right questions.  The closest I've gotten was a video about making a scratch-off lotto ticket.  Someone in the comments to that video says:

  Good Idea. But, this isn't practical for any real world apps. It instantiates too many gameobjects. There are better more efficient ways of achieving this effect using shaders or render texture.

They don't really expand on that further, but I did do a little more searching to see how I might do this using shaders.  I found this video about using replacement shaders, but I'm still not sure if that's the right track.  I don't know If something like that is the smartest way to do it.

I'm basically a complete noob when it comes to shaders and textures so this is new territory for me.  I apologize if this is a duplicate question, I've tried searching but haven't found anything quite like what I'm looking for.  Please let me know if there's anything I can explain further, and any help that gets me pointed in the right direction would be greatly appreciated.


texts: How to calculate FOV with four-walled tiles?

texts:
I'm working on a 2D tile-based game. I'm trying to calculate FOV and I've implemented walls so they don't take up an entire tile. Instead, they just take up a side of each tile. Similar to:

class Tile {
    bool northWall;
    bool westWall;
}

Most of the algorithms I've been looking at expect walls to take up a full tile, and the check to see if a tile is blocking tiles behind it is trivial. I'm having trouble wrapping my head around this. I've got an implementation of Recursive Shadowcasting right now, but not sure how to write my is_blocked() function. Can anyone give me some advice?


texts: Find camera coordinate of vanishing point

texts: Given a vector and a camera (position, angle, up vector, field of view, etc), how would I find the vanishing point of the vector in camera space?


texts:
How do I create new entities (the collection of their components) in an entity system? I have space ships in my game, for example, they need a lot of information set in their components when I create them. For example I set the mass, size and a moment of inertia tensor in a physicscomponent of the ship. I also have a component that contains a list of engines on the ship (is that right by the way? My ES doesn't support multiple components of the same type, should it?), each engine has a position and a force.

Now when creating a basic ship I see a couple of options. I can just hard-code it in my game. This is the way I have it at the moment, and it doesn't feel too good, there will be a lot of code to create different kind of space ships that are very similar except for some properties which would create lots of code duplication.

I could also use a database, I've seen this used before and I can definitely see how it'd be a good fit. Although it's a pretty small hobby project that I'm working on and it seems like it would be a little overkill. I'm not sure though, maybe it's worth it?

So the only thing remaining I can think of is describing entities in a text file of some sort, which might work. I guess it would require writing lots of code to parse different kinds of values, and where would I put the code that actually sets the values on the components? I'm using C# so I guess I could use reflection on the properties but I fear it'd be slow? And I don't want to clutter up my component code.

Maybe I should mention that it's a multiplayer game. So some components are client-only which could easily be marked in some way.

So how do you create new entities, or their components, in an entity system?


texts: Unity2D: How to check for overlap using the job system

texts:
Currently, I have implemented a job in unity for performance reasons. In that job, I am checking if a game object overlaps with the "detection circle". The job looks like this:

[BurstCompile]
public struct CreateGridJob : IJob
{
    public float diameter, radius;
    public NativeArray<int2> positionsArray;
    public NativeArray<bool> isWallArray;
    public float3 bottomLeft;
    public int sizeX, sizeY;
    public float3 right, up;
    public LayerMask layer;

    public void Execute()
    {
        int x = 0, y = 0;
        for (int i = 0; i < positionsArray.Length; i++)
        {
            float3 point = bottomLeft + right * (x * diameter + radius) + up * (y * diameter + radius);
            bool wall = true;
            Vector3 worldPoint = point;
            if (Physics2D.OverlapCircle(worldPoint, radius, layer))
                wall = false;
            positionsArray[i] = new int2(x, y);
            isWallArray[i] = wall;

            if (x % sizeX == 0)
                x++;

            y++;
            if (y >= sizeY)
                y = 0;
        }
    }
}

The problem course when I have to call if (Physics2D.OverlapCircle(worldPoint, radius, layer))as it can only be called in the main thread thus throwing an exception.

The result of this job will be a grid to be used in pathfinding.

Am I going in the right direction or is there a different way of doing this?

Edit-1: Unfortunately no, not all are convex (can be changed if there's no other way).

Here is an example of a concave asteroid:

There are many of these asteroids scattered across the scene. First, they are grouped in sectors, and each sector has its own asteroids. Sectors are independent of each other and are only connected through portals. For the simulation purposes, all (at least for now) sectors are active and generate their grid. But a single sector can have for example 200 asteroids. They are placed at random.

Edit-2: Flow!
A script generates sectors and their children.
In this script on Update, I call the CreateGridJobHandle. which gets the Job handles and then I execute them.

    private void Update()
    {
        if (Helper.IsStatusGraterOrEqual(GameStatus.FirstSectorGridSet))
        {
            NativeArray<JobHandle> jobHandleList = new NativeArray<JobHandle>(Sectors.Count, Allocator.TempJob);
            for (int i = 0; i < Sectors.Count; i++)
            {
                JobHandle handle = Sectors[i].SectorGrid.CreateGridJobHandle();
                jobHandleList[i] = handle;
            }
            JobHandle.CompleteAll(jobHandleList);
            jobHandleList.Dispose();

            for (int i = 0; i < Sectors.Count; i++)
            {
                Sectors[i].SectorGrid.SetGridFromData();
            }
        }
    }

    public JobHandle CreateGridJobHandle()
    {
        CreateGridJob job = new CreateGridJob();
        jobPositionsArray = new NativeArray<int2>(gridSizeX * gridSizeY, Allocator.TempJob);
        jobWallsArray = new NativeArray<bool>(gridSizeX * gridSizeY, Allocator.TempJob);

        job.positionsArray = jobPositionsArray;
        job.isWallArray = jobWallsArray;
        job.diameter = nodeDiameter;
        job.bottomLeft = transform.position - Vector3.right * GridWorldSize.x * 0.5f - Vector3.up * GridWorldSize.y * 0.5f;
        job.sizeX = gridSizeX;
        job.sizeY = gridSizeY;
        job.right = Vector3.right;
        job.up = Vector3.up;
        job.radius = NodeRadius;
        job.layer = WallMask;

        return job.Schedule();
    }

After this, I just set the grid into 2d array and apply the isWall values.

    public void SetGridFromData()
    {
        for (int i = 0; i < jobPositionsArray.Length; i++)
        {
            if (jobWallsArray[i])
            {
                grid[jobPositionsArray[i].x, jobPositionsArray[i].y].IsWall = jobWallsArray[i];
            }

        }
        jobWallsArray.Dispose();
        jobPositionsArray.Dispose();
    }
```


texts:
I wrote an application that takes an obj file, parses all the vertices, UV coordinates and normals, loads them into an OpenGL VBO and presents the model on screen. It works, but I'm getting annoying aliasing artifacts.

Notice black edges popping in and out of existence:

This happens with every model I load. I have tried enabling antialiasing, but although edges appear less jagged, the black artifacts still appear, only smoother. I need them completely removed.

What's the best way to fix this?


texts: How can I apply a mesh distortion to walls like in Dungeon Keeper 2?

texts:
In Dungeon Keeper 2, the walls of the dungeon have different random shapes depending on its state (freshly dug or reinforced, and so on).

They look like they are cubes of 3x3 vertices that have a x-z planar jitter or distortion. However, the corner vertices are shared by adjacent cubes, so there must be some kind of algorithm rather than just a random jitter.

How could I achieve a similar effect?


texts: How to paint regions of a map with visually different colors

texts:
I'm learning some concepts of procedural content generation. Now I'm generating a map with regions and each region has a diferent colors generated in a pseudo-random way.

My problem right now is that most of times (more probably when more regions exists), some regions has colors that are visually similar.

I want to control that adjacent colors are visually different, but still with some random component. What make colors different?


texts: Combining several animations into a single FBX

texts:
I'm trying to figure out a workflow for preparing character animations for Unity so that they are all combined in a single FBX file. The advantage as far as I see it is that it then uses only a single skeleton where multiple animation files would each have their own skeleton (which I think is unnecessary and would increase size considerably).

I've tried using Maya for this but haven't been successful so far. Then I tried Motionbuilder and I can get the animations (takes) together into a single file but many of the animations don't look right afterwards.

So I was wondering does anyone know of a solid workflow to achieve this? I'm having a hard time finding information about what I'm trying to achieve. This is probably a piece of cake for experienced animators but I'm just starting with animation now.

So how do you combine several animation FBX files into single one (whith either Maya, Motionbuilder, or 3DSMax) and make sure that the animations are all properly retained like they should? I'm sure there are some additional things to take care of but I don't know exactly what they are.


texts: What is actually moving in an endless runner?

texts:
For example the famous Flappy Bird game, or anything that sort really,
is the player(in this case the bird, or the camera whichever you prefer) moving forward or is the whole world moving backwards(the bird only changes Y position and has a constant X position)?


texts: How to animate alpha channel of sprite color using Animator in code in Unity3D?

texts:
I tried Animator + AnimationClipPlayable, but failed. Sprite disappears completely after 1 second, without animation happening. If I set "1" instead of "0" for final point, then nothing happens.

Code:

    AnimationClip clip = new AnimationClip();
    AnimationClipPlayable playable = AnimationClipPlayable.Create(clip);

    gameObject.AddComponent<Animator>();

    AnimationCurve alpha = AnimationCurve.Linear(0, 255, 1, 0);
    clip.SetCurve("", typeof(SpriteRenderer), "m_Color.a", alpha);

    gameObject.GetComponent<Animator>().Play(playable);


texts: Is there a limit to Gametime.TotalMilliseconds?

texts:
Gametime should always be increasing, and totalmilliseconds is going to be the largest value. So if the game is hypothetically run for 1 day, this value should 86 400 000.

This probably isn't a problem for most games, but I'm curious if there's some sort of fail safe mechanism if it does get too large, or if a limit even exists.


texts: Calculating World Unit or Pixels Per Unit values

texts:
Is there a formula to calculate world unit or pixels per unit values in LibGdx?
 Most of my objects fit into a 32x32 or 16x16 frame. When the objects are close to 32x32, and I use 1f as the size or 16x16 and use .5f things seem to work out fine. What I try to do is use this:

// Create viewport that is used to as the game size
static final float VIEWPORT_WIDTH = 15f;
static final float VIEWPORT_HEIGHT = 7f;

viewport = new FitViewport(VIEWPORT_WIDTH, VIEWPORT_HEIGHT);

// Scale sizes
final float UNIT_PIXEL = 0.03125f;  // 1 / 32
float newSize = 32f * UNIT_PIXEL;

Which seems to work for 32x32 or 16x16. But size problems seem to happen when you try to use that to calculate other widths or heights. Like if I try to use:

float newSize = 24f * UNIT_PIXEL;

Using this the bounding rectangle becomes much larger than the object.


texts: Discovering path through unknown territory

texts:
Let's say all the AI knows about it's surroundings is a pixel-map that it has which clearly shows walkable terrain and obstacles. I want the AI to be able to traverse this terrain until it finds an exit point.

There are some restrictions:

There is always a way to the exit in the entire map that the AI walks around in, but there may be dead ends. The path to the exit is always pretty random, meaning that if you stand at crossroads, nothing indicates which direction would be the right one to go.
It doesn't matter if the AI reaches a dead end, but it has to be able walk back out of it to a previously not inspected location and continue its search there.
Initially, the AI starts out knowing only the starting area of the whole map. As it walks around, new points will be added to the pixel-map as the AI corresponding to the AIs range of sight (think of it like the AI is clearing the fog of war)
The problem is in 2D space. All I have is the pixel map.
There are no paths in the pixel map which are "too narrow". The AI fits through everything.
The AI does not know where the endpoint is (it is hidden in the map)
The AI traverses the terrain in real time
It shouldn't be a brute force solution. E.g. it would be possible to simply find a path to each pixel in the pixel map that is yet undiscovered (with A*, for example), which will lead to the AI discovering new pixels. This could be repeated until the end is reached.
The path doesn't have to be the shortest path (this is impossible without knowing the entire map beforehand), but when movements within the visible area are calculated, the shortest and from a human standpoint most logical path should be taken (e.g. if you can see a way out of your room into a hallway, you would obviously go there instead of exploring the corner of your current room).

What kind of approaches to solve this problem are there?


texts: Shader is distorting a Texture of a sprite it's working on

texts:
I've been testing out fragment shaders in SFML, trying to learn how to write and use them and I've run into a recurring problem. Every shader distorts the texture.
Top left is the distorted test texture, top right and bot left are there for comparison along the axis.

The texture is 512x512 pixels in size and the sprite has the same dimensions. I've narrowed down the problem to this line.

vec2 texCoord = (gl_FragCoord.xy / sourceSize.xy);

Where sourceSize is the resolution. The value I'm passing in being (512,512). I've tested around with different values, the closest to the correct output is when I pass in the values (512, 1086) giving this.

Top left is the distorted texture. The X axis is correct but the Y axis is stretched enough to hide the numbers and enlarge the border.

Currently the shader does nothing for testing purposes.

uniform sampler2D       source;
uniform vec2            sourceSize;
uniform float           time;

void main( void )
{
        vec2 texCoord = (gl_FragCoord.xy / sourceSize.xy); //Value between 0.0 and 1.0
        texCoord = vec2 (texCoord.x,1.0-texCoord.y);    //Inverts the y component. GLSL treats bot left corner as the origin, sfml treats top left as it.
        vec4 Color = texture2D(source, texCoord);

        gl_FragColor = Color;
}

I'm not sure how to fix this. What I'm trying to achieve is a shader that doesn't distort the base texture so I can build on from there. Thanks for any help you can give.


texts: What can cause ALT-TAB to be 'annoying'/slow/glitchy?

texts:
This is more of an open ended question, but I hope to get some good insight on how to avoid the issue.

When playing Games on Windows, I might want to ALT-TAB out of it. Some games have no problems, others are not so easy: They may take AGES to switch out and back in. Some are even prone to crashing or to weird behaviour like graphic distortion or stuttering sound.

I just wonder what causes this behavior? Is this more a DirectX or an OpenGL thing? Is it caused by Games being 'clever' and caching/wiping the cache whenever the screen settings change? (I assume they do get some sort of signal when I ALT-TAB?)

I don't have any problem of my own, but I'd like to know what to avoid and which 'clever' trick may cause this type of horrible customer experience?


texts: How to tile multiple procedurally generated textures?

texts:
I'm trying to develop a procedural tile generator for a game, mostly for the ground tiles, instead of using "hand-drawn" tiles.

To achieve this I'm using Perlin noise and a sine wave with multiple parameters, which already gives me pretty nice results. I don't want to generate 1 tile and repeat that one forever for one ground type, but I want to avoid recurrences, so I'm generating n different tiles.

The problem I'm having now is that I want to tile the generated textures (smooth transitions).

At the moment I have this:

4 256x256 textures.

I thought a simple method would be to just add the positions of the different tiles to the noise generation algorithm, so that, when creating the 4 256x256 textures, it would behave like it would create a 512x512 texture, but that somehow didn't work as intented.

So how can I tile those textures?


texts: How to set up a Quiz game with multiple types of questions? (Structs and DataTables)

texts:
I am looking to integrate a quiz mode into a game I am in the process of developing in Unreal Engine 4. I'm really just kind of stuck on how to set up my data structures and not really know the way to go about doing it. At least for now I want the quiz to contain two different types of questions but, it could possibly contain more types later on.

The first type of question is a simple multiple choice type of question that contains a string Question, a string array of answers, and an integer for the correct index of the answer.

The second type of question I have is basically a click on the correct component that is in the scene already and then click on a confirm button to submit the response. It contains a string question and an integer id and string name for the answer. I haven't decided yet on which route I want to go with regarding the item id vs. item name.

Basically, what I really want is a single data table for all of my questions that I can choose a question at random from. My main question is, is there a way to create a single data table with these requirements? I mean I know I could just kind of merge the two and have empty fields in my data table but, maybe is there a way to basically have an enum within the data table to choose between what type of question I want on this particular row?

I know I have stated a few possibilities on how I can set up the data table but, I would really like some feed back on if there are different ways other than what I have stated already. I mean it doesn't even have to be a data table, if there is a more efficient way to go about doing this I am all for it. The main goal is to only have one main data structure to pull my questions from.


texts: How to avoid circular dependencies between Player and World?

texts:
I'm working on a 2D game where you can move up, down, left and right. I have essentially two game logic objects:

Player: Has a position relative to the world
World: Draws the map and the player

So far, World depends on Player (i.e. has a reference to it), needing its position to figure out where to draw the player character, and which portion of the map to draw.

Now I want to add collision detection to make it impossible for the player to move through walls.

The simplest way I can think of is to have the Player ask the World if the intended movement is possible. But that would introduce a circular dependency between Player and World (i.e. each holds a reference to the other), which seems worth avoiding. The only way I came up with is to have the World move the Player, but I find that somewhat unintuitive.

What is my best option? Or is avoiding a circular dependency not worth it?


texts: Intersection between moving circle and some squares

texts:
I'm developing a 2D game made of squares.

What I need to do is check if a circle collides with any of the squares as it moves.

I have a raycast function to check the same idea, but using a point. I think the best idea would be to do a circle-raycast, but I have no idea how to do it.

The information I have:

Starting coordinates of the center of circle
Last coordinates of the center of the circle
Radius of the circle

Given some coordinates, I can check if there is a square in those coordinates.


texts:
I know that WebGL is based on OpenGL ES 2.0 and that glBegin and glEnd have been removed and replaced with vertex buffer objects. I understand that VBOs are faster and use less code but is there a library or add-on for JavaScript / WebGL that re-implements these functions?

After more research, I have discovered that this functionality is called immediate mode.


texts: How to make player walk through layers of 2d fog smoothly?

texts:
I'm trying to recreate the fog effect that Graveyard Keeper has, with several layers, so taller objects will get less fog. I'm using the approach described here:
the devs post on Gamasutra
The problem with this approach is when the player is walking through each layer, it comes in front of the fog, and the fog effect "pops away", as the fog is thicker on the bottom of the fog layer. See the image where the fog is a little exaggerated.
I'm using Unity and all layers are in the "Default" sorting layer, and Y as the custom sort axis, so sprites higher up are behind lower sprites.
The jarring effect is worse the thicker fog I have.
How can I solve this, so the player doesn't "blink" like this? Thanks!


texts: How to set shader global variable in sharpdx without using Effect class

texts:
I am working with SharpDX, i thinking to try using (uniform) global variables for HLSL constants instead of constant buffers.

But, in my code SharpDX's Effect class is not used: i use PixelShader and VertexShader classes instead - constructed directly from bytecode blobs (i just don't use techniques/passes, i compile shaders separately).

With Effect class, i can assign new value to any constant in HLSL program by its name, as DirectX allows that, in any time. Example (i haven't tested this; yes, its ugly here):

SharpDX.Direct3D11.Effect fx = //
fx.GetVariableByName("someOption").AsVector().Set<Vector3>(newVectorValue);//nice

But i don't use Effect class.
How can i set global HLSL variable using Vertex/PixelShader class instance?
If it is not possible, shame on SharpDX dev then, in native DirectX it is much easier.


texts: importing 3ds max ( .max) file into blender

texts:
I got couple of 2 .max files that were created on 2008 version of 3ds Max. The files are really very simple 3d models of room and furniture item.

I am using blender 2.53 beta.

I have 3ds Max 2011 version. Using this version I exported the model to Autodesk Collada (.dae file) and also to .OBJ files but neither work with blender 2.53. In blender I can import the files but most details are gone and wall edges look like annoying zig zag pattern and look worse than a silly cartoon.

Even tried exporting to old .3ds format but that gives more problems.

I looked at 3ds max collada plugin :
http://update.multiverse.net/wiki/in...COLLADA_Plugin
but it is not compatible with 3ds Max 2011 version.

So I am confused what to do as I am new to blender and 3d. What is the best way to export from 3ds max when opening exisitng 3ds max 2008 version models and importing to blender 2.53?

The models have simple lights and no animation is involved.


texts: SVD vs Normal decomposition for BRDF compression

texts: In the slides over here by NVidia, they describe methods for BRDF compression. They first create a BRDF matrix where each column(or row) corresponds to a single light direction (or outgoing view direction). This matrix is then compressed by decomposing it either by using SVD or Normalized decomposition. My question is that they claim SVD gives better results than Normalized decomposition for similar compression sizes. Does anyone know what could be the possible reason for this?


texts: What happens to a license if both the publisher and the developer are bankrupt?

texts: Is one allowed to make a similar game or even a sequel which would usually require obtaining a license? Who keeps the license in the end, i.e. who is to be asked for permission in such cases?


texts: How to organize timeline in a Flash project?

texts:
I am starting a new Flash game and I was wondering if there is a better way to organize the timeline of the project. In my previous games I define a keyframe for each possible status of the game (loading, sponsor, intro, menu, gameplay, etc...). This method works but has some problems... For instance, it is not easy to implement transitions between the different screens in the game.

How do you do this? Do you know of some better way?


texts: unity - get component variable from object in trigger

texts:
i want to get a component value from the game object which collides with my trigger's object script. this is my code on the trigger:

 void OnTriggerEnter (Collider obj){
     if(obj.GetComponent<motor>().enabled == true){
         passed = true;
     }
 }

and this is the error i get:

NullReferenceException: Object reference not set to an instance of an object
 cp.OnTriggerEnter (UnityEngine.Collider obj) (at Assets/Scripts/cp.cs:15)

also when changing the code on the trigger:

 motor mObj = obj.gameObject.GetComponent();
    if(mObj != null){
         //code here
         Debug.Log("mObj not null");
     }else{
             Debug.Log("mObj is null");
     }

it returns

  mObj is null

but the parent obj does have that 'motor' script, other scripts in the car which enter the trigger can access it


texts: Direct2d off-screen rendering and hardware acceleration

texts:
I'm trying to use direct2d to render images off-screen using WindowsAPICodePack. This is easily achieved using WicBitmapRenderTarget but sadly it's not hardware accelerated.

So I'm trying this route:

Create direct3d device
Create texture2d
Use texture surface to create render target using CreateDxgiSurfaceRenderTarget
Draw some shapes

While this renders the image it appears GPU isn't being used at all while CPU is used heavily.

Am I doing something wrong? Is there a way to check whether hardware or software rendering is used?

Code sample:

var device = D3DDevice1.CreateDevice1(null,
                DriverType.Hardware,
                null,
                CreateDeviceOptions.SupportBgra,
                FeatureLevel.Ten
                );

var txd = new Texture2DDescription();
txd.Width = 256;
txd.Height = 256;
txd.MipLevels = 1;
txd.ArraySize = 1;
txd.Format = Format.B8G8R8A8UNorm; //DXGI_FORMAT_R32G32B32A32_FLOAT;
txd.SampleDescription = new SampleDescription(1,0);
txd.Usage = Usage.Default;
txd.BindingOptions = BindingOptions.RenderTarget | BindingOptions.ShaderResource;
txd.MiscellaneousResourceOptions = MiscellaneousResourceOptions.None;
txd.CpuAccessOptions = CpuAccessOptions.None;

var tx = device.CreateTexture2D(txd);

var srfc = tx.GraphicsSurface;

var d2dFactory = D2DFactory.CreateFactory();

var renderTargetProperties = new RenderTargetProperties
{
    PixelFormat = new PixelFormat(Format.Unknown, AlphaMode.Premultiplied),
    DpiX = 96,
    DpiY = 96,
    RenderTargetType = RenderTargetType.Default,
};

using(var renderTarget = d2dFactory.CreateGraphicsSurfaceRenderTarget(srfc, renderTargetProperties))
{
    renderTarget.BeginDraw();
    var clearColor = new ColorF(1f,1f,1f,1f);
    renderTarget.Clear(clearColor);
    using (var strokeBrush = renderTarget.CreateSolidColorBrush(new ColorF(0.2f,0.2f,0.2f,1f)))
    {
        for (var i = 0; i < 100000; i++)
        {
            renderTarget.DrawEllipse(new Ellipse(new Point2F(i, i), 10, 10), strokeBrush, 2);
        }
    }

    var hr = renderTarget.EndDraw();
}


texts: How do I get access to the PS4 platform tools for Unity?

texts:
I know that you can go to the "Xbox ID" program to get all the resources you need for the Xbox platform (developer forums, Unity SDK, etc.). but there is not really information about how to get the PlayStation tools.

...Well other than the contact sales button in Unity which links to Unity and not Sony (oddly enough).

So where does someone who hopes to put their games onto one of the Sony platforms (PS4, Vita, PS3, etc) go to get the build tools (and other things) they need? Do Sony contact you about it if they're interested or is it really only for developers who are considered above Indy?


texts:
I have a bunch of images I'm using for a chess game in a canvas using wpf, xaml, and C#. I want to use

Canvas.SetTop(image, position);

to set the position of this image. However I am given the index of child in my canvas and that is it.

myCanvas.children[index]

I tried

Canvas.SetTop(myCanvas.children[index], position);

but that did not work. How can I change the position of the image given only the index of the image in the canvas?

Edit: Another option would be to change the position of the canvas child. But I couldn't find anything for that.


texts:
I'm trying to create a hybrid system for my Unity game. I want to use tilemap for collision and use sprites for the world.

I drew a sprite onto a 40x40 checkerboard grid as can be seen here. I wanted an easy way to create a collider for this without spending 30+ minutes hand placing box colliders and I decided to use a tilemap to place red tiles and use a tilemap collider for collision geometry and just hide the red tiles in-game.

Issue is, I have no clue how to align the checkerboard with the Unity tilemap grid.

Here's a screenshot of the sprite in the unity editor with the tilemap grid visible.

If it isn't obvious, then the white lines is the grid for the tilemaps. The cellsize for each cell on the grid isn't the same size as the cells on the checkerboard pattern and I have no idea how to fix it.

The PPU (pixels per unit) of the sprite is 140. The PPU for the tileset tile(singular since there is literally only 1 tile in the entire tileset) is also 140. The checkerboard in paint.net is 40x40 and so is the tile. How can I get the cellsize of the grid in unity to match the cell size of the checkerboard.


texts: How do you use your own tileset in Tiled?

texts:
I'd like to create a 2d platformer and I understand that using tiles helps you a lot.

I think many use the map editor "Tiled" but I can't find anywhere how do you make your own tileset from a given image that you created.

I spent most of today searching a reference for this on Google, without much luck..
The only hint comes from a couple of python scripts, but I didn't manage to make them work
Am I missing something?


texts: Are there any good engines for isometric collision detection and platforming?

texts:
I've decided to resurrect an old game idea I had years ago. I currently have zero experience with programming, but I'm going to begin studying either C#, Python or both in the near future.

The issue I'm currently facing is that what I plan on making is an isometric Metroidvania-type game, similar to that old GBA title Scurge: Hive on a very basic level. Naturally, this means that there will be some emphasis on platforming. The problem is, I hear that programming those kinds of physics into a 2D game is highly impractical. General consensus, from what I've seen, seems to be that it's easier to just make isometric games in 3D so that programming collision detection and the like is simpler.

I really want this to be a 2D game, as I have absolutely no experience with 3D modeling. Yet I also don't want to have to build the entire underlying physics engine from scratch. I've looked around a bit and there don't seem to be any engines for this type of game that are compatible with C# or Python. There are isometric engines, but most seemed to be geared toward 3D games and RPGs.

So I guess what I'm trying to ask is, are there any engines available that would make it easier to program an isometric 2D platformer? Or would I have to do the collision detection coding myself?

(As an aside, while I'm considering both #C and Python, I'm leaning toward Python due to the fact that it's multiplatform and apparently better for beginners. So please take that into consideration if possible.)

Edit: After some more research, I've chosen to go with Lua, but I may still study Python and C# as well if possible. Hopefully I'm not biting off more than I can chew.


texts:
I am trying to create a gui with nifty on top of lwjgl. I've already had some problems during the Nifty setup, however now Nifty is set up and running correctly but for text rendering.
Here is my xml file:

    <?xml version="1.0" encoding="UTF-8"?>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<nifty xmlns="http://nifty-gui.sourceforge.net/nifty-1.4.xsd" xmlns:xsi="http://
www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://niftygui.
sourceforge.net/nifty-1.4.xsd http://nifty-gui.sourceforge.net/nifty-1.4.xsd">
    <screen id="start">
        <layer childLayout="center">
            <panel id="panel" height="25%" width="35%" align="center" valign="center" backgroundColor="#f60f" childLayout="center" visibleToMouse="true">
                <text id="text" font="aurulent-sans-16.fnt" color="#ffff" text="Hello World!"/>
            </panel>
        </layer>
    </screen>
</nifty>

and here the respective java class:

package niftylwjgl;

import de.lessvoid.nifty.Nifty;
import de.lessvoid.nifty.nulldevice.NullSoundDevice;
import de.lessvoid.nifty.renderer.lwjgl.input.LwjglInputSystem;
import de.lessvoid.nifty.renderer.lwjgl.render.LwjglRenderDevice;
import de.lessvoid.nifty.tools.TimeProvider;
import org.lwjgl.LWJGLException;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;

public class NiftyLwjgl {

    private static Nifty nifty;
    private static boolean close;
    private static LwjglInputSystem inSys;

    public static void main(String[] args) throws LWJGLException, Exception {
        init();
        initNifty();
        while (!close) {
            update();
            preRender();
            render();
            postRender();
        }
        destroy();
    }

    private static void init() throws LWJGLException {
        Display.setDisplayMode(Display.getDesktopDisplayMode());
        Display.setFullscreen(true);
        Display.create();

        GL11.glOrtho(0, 1920, 0, 1080, 1, -1);
    }

    private static void initNifty() throws Exception {
        inSys = new LwjglInputSystem();
        inSys.startup();

        nifty = new Nifty(new LwjglRenderDevice(),
                new NullSoundDevice(),
                inSys,
                new TimeProvider());
        nifty.fromXml("xml/main.xml", "start");
        nifty.loadStyleFile("nifty-default-styles.xml");
        nifty.loadControlFile("nifty-default-controls.xml");
    }

    private static void preRender() {
        GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_STENCIL_BUFFER_BIT);

        GL11.glMatrixMode(GL11.GL_PROJECTION);
        GL11.glLoadIdentity();

        GL11.glMatrixMode(GL11.GL_MODELVIEW);

        GL11.glEnable(GL11.GL_TEXTURE_2D);
    }

    private static void postRender() {
        GL11.glDisable(GL11.GL_TEXTURE_2D);
    }

    private static void update() {
        if (Display.isCloseRequested()
                || Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)
                || nifty.update()) {
            close = true;
        }
    }

    private static void render() {
        nifty.render(false);
        Display.update();
    }

    private static void destroy() {
        inSys.shutdown();
        Display.destroy();
    }
}

Here is a screenshot of the application running:

I somehow feel like I'm missing something incredible simple but important, like an glXXXXX call.
Any help/suggestions are appreciated.


texts: Procedurally generate rivers for 2-d heightmap terrain

texts:
I created an algorithm to procedurally generate 2d worlds based on a heightmap grid.  (I used a 2d simplex noise algorithm mapped on the inverse of the distance of each pixel from the center, to "center" the island and keep it from running off the screen, if you're interested). See below.

Now, I want to create natural-looking rivers which flow "downhill" from random points or artificial lakes to the ocean.  I would like the rivers to generally travel downhill, but since you will only ever see then in a 2d view in a small window, they don't have to be 100% realistic.  Its ok if they flow uphill over small bumps.

The naive approach of just checking all adjacent squares for one of lower elevation, then moving there gets stuck very easily in small holes/valleys.

My next was to use an A* star algorithm to find paths from the start point to random points random points in the ocean, using the negative difference in height between too squares as the move cost.  This also seemed to get hung up and randomly fails a lot.  It's probably just an issue with my code, but I can't find the bug and its also really expensive, so I was wondering if there was any conventional wisdom about how to do this.


texts: I was wondering how to make a Sprite do an orbit on a determinated point in SpriteKit. I tried to set the anchorPoint of the Sprite orbiting with the center point but it doesn't work. Please can someone help me?


texts:
This question has come mainly out of sheer desperation, after spending several hours trying to figure out the problem.

If you cast your eyes to the picture above, you should see that my midpoint displacement algorithm algorithm is working (somewhat) successfully; in producing a somewhat coherent noise pattern.

However, it is leaving behind a black dotted grid on the image, and I have no idea why. I can foresee this being an issue in the math, but I just cannot see it; nor was this pointed out in any online resources as a possible issue; so any help will be appreciated as to hunting down this bug.

unsigned char** mdp(unsigned char** base, unsigned base_n, unsigned char r) {
    size_t n = (2 * base_n) - 1;

    unsigned char** map = new unsigned char*[n];
    for (unsigned i = 0; i < n; ++i) map[i] = new unsigned char[n];

    // Resize
    // 1 0 1
    // 0 0 0
    // 1 0 1
    for (size_t i = 0; i < n; i += 2) {
        for (size_t j = !(i % 2 == 0); j < n; j += 2) {
            map[i][j] = base[i / 2][j / 2];
        }
    }

    // Diamond algorithm
    // 0 0 0
    // 0 X 0
    // 0 0 0
    for (size_t i = 1; i < n; i += 2) {
        for (size_t j = 1; j < n; j += 2) {
            unsigned char& map_ij = map[i][j];

            unsigned char a = map[i - 1][j - 1];
            unsigned char b = map[i - 1][j + 1];
            unsigned char c = map[i + 1][j - 1];
            unsigned char d = map[i + 1][j + 1];
            map_ij = (a + b + c + d) / 4;

            unsigned char rv = std::rand() % r;
            if (map_ij + r < 255) map_ij += rv; // EDIT: <-- thanks! the bug! `map_ij + rv`, not `r`
            else map_ij = 255;
        }
    }

    // Square algorithm
    // 0 1 0
    // 1 0 1
    // 0 1 0
    for (size_t i = 0; i < n; ++i) {
        for (size_t j = (i % 2 == 0); j < n; j += 2) {
            unsigned char& map_ij = map[i][j];

            // get surrounding values
            unsigned char a = 0, b = a, c = a, d = a;
            if (i != 0) a = map[i - 1][j];
            if (j != 0) b = map[i][j - 1];
            if (j + 1 != n) c = map[i][j + 1];
            if (i + 1 != n) d = map[i + 1][j];

            // average calculation
            if (i == 0) map_ij = (b + c + d) / 3;
            else if (j == 0) map_ij = (a + c + d) / 3;
            else if (j + 1 == n) map_ij = (a + b + d) / 3;
            else if (i + 1 == n) map_ij = (a + b + c) / 3;
            else map_ij = (a + b + c + d) / 4;

            unsigned char rv = std::rand() % r;
            if (map_ij + r < 255) map_ij += rv;
            else map_ij = 255;
        }

    }

    return map;
}

If you have any tips or resources other than http://www.gameprogrammer.com/fractal.html and http://www.lighthouse3d.com/opengl/terrain/index.php?mpd2 for fractal based terrain generation, I would appreciate them as comments also.

Edit:

This is the new image, as per Fabians suggestion (ty), however it still has some strange quirks, which you should be able to see straight away (small 'dimples' everywhere).

What could be causing this strange behavior? Updated source code: http://www.pastie.org/1924223

Edit:

Many thanks to Fabian in finding the bounds check error, for those interested, here is the current solution as 512x512 png. And current source code (modified by Fabian).

Edit (years later):
Python version https://gist.github.com/dcousens/5573724#file-mdp-py


texts: How can I achieve smooth animation of sprites between discrete tiles?

texts:
I'm currently learning game development with C# and XNA and my current assignment is to create a Pac-Man clone.

The game is partially tile based, which means that the level itself is built out of an array of tiles, but Pac-Man and the ghost just have a position to be drawn at.
I've got the basic functionality down, such as building the level with a string and drawing Pac-Man and the ghost on the screen.

Pac-Man is currently represented by two positions: one is where he is in relation to the array of tiles (a Point, for example 9, 11), and one where the sprite is drawn (which is a Vector2).
However, when trying to make the player be able to move Pac-Man (and Pac-Man is supposed to "glide" between tiles, not jump between them) it seems that his graphical position can not keep up with his tile position. It sort of lags behind.

This is hard to describe but here's some code to look over:

public PacMan(): base()
    {
        texture = Game1.pacManTexture;
        tilePosition = new Point(9, 11);
        position = new Vector2(tilePosition.X * spriteSize.X, tilePosition.Y * spriteSize.Y);

That is the constructor for Pac-Man.

else if (tileManager.playArea[tilePosition.X, tilePosition.Y - 1] is Tile) // if the  tile above Pac-Man is of the type Tile...
                {
                    tilePosition.Y -= 1; // decrement tilePosition by 1
                }

That is what happens if the player presses the Up key.

Vector2 tilePos = new Vector2(tilePosition.X * spriteSize.X, tilePosition.Y * spriteSize.Y);
        Vector2 direction = tilePos - position;
        if (direction.Length() != 0)
            direction.Normalize();
        position += direction;

And that is where the faulty magic happens. The graphical position of Pac-Man (the sprite) is being updated.

Rectangle pacManRectangle = new Rectangle((int)position.X, (int)position.Y, spriteSize.X, spriteSize.Y);
        Game1.spriteBatch.Draw(texture, pacManRectangle, new Rectangle(currentFrame.X * spriteSize.X, currentFrame.Y * spriteSize.Y, spriteSize.X, spriteSize.Y), Color.White);

And lastly, that happens in the Draw method.

If you need more information, just say so.


texts:
I am new to game development and I was trying to build a turret model, and control it through lua script in shiva3d. I can rotate it around the y axis which is no problem, but when it comes to pitching, I am not sure how to do that in a way which is independent of the Y rotation, for example,

in the default position, rotating with a positive value around X aims upwards, which is what I expect.

when I rotate it by 180 degrees around Y, the positive rotation around X aims downwards towards the ground instead of upwards.

on the other hand, if I rotate by 90 degrees, the turret rotates around it self as if its rolling...

I am not sure what to look for in order to understand how rotation in a 3d world should happen, so any pointers on that would be much appreciated


texts: Ray tracing - texture and phong lighting

texts:
Other questione releated to my ray tracer implementation for iPad.

If I have a polygon that has a texture and a material, how do I calculate the color using Phong lighting model? Is the texture used in substitution of some of the component (diffuse?)? Or if there's a texture I need to just ignore the material and get only the texture color?


texts:
.
.
In my script, enemy goes to dead point and if player closet to him he attacking player. When I started making wave of enemies I notes that all of them goes to player. Now, I need to add something making enemy avoid player in case there are 4 enemy around him and goes to dead_point. What I did is, I attached every player script "enemyAround" to count any enemy around player.

    public int enemies = 0;

void OnTriggerEnter(Collider other)
{
    enemies++;
}

void OnTriggerExit(Collider other)
{
    enemies--;
}

But I couldn't figure how to make enemy read it ?. If Enemy select player to attack him, He reads or knows How many enemy around the selected player.

enemy script

private Animator enemy_anim;
private NavMeshAgent mAgent;
private GameObject[] player;
public GameObject[] dead_point;
public int farPoint, dead_point_number, player_number;
public float dist;
public bool enemt_run, enemy_atack = false;
public bool near;

private enemyAround arounds;
public int enemy_around_player;

// Use this for initialization
void Start()
{

    mAgent = GetComponent<NavMeshAgent>();
    enemy_anim = GetComponent<Animator>();
    player = GameObject.FindGameObjectsWithTag("Player");
    dead_point = GameObject.FindGameObjectsWithTag("dead_point"); // 3 points
    enemy_dirction();

}

void Update()
{

    // count enemies around player
    enemy_around_player = selected player

    for (int i = 1; i < player.Length; i++)
    {

        if (Vector3.Distance(transform.position, player[i].transform.position) <
            Vector3.Distance(transform.position, player[player_number].transform.position))
        {
            player_number = i;
        }
    }

    dead_point_number = dead_point.Length;
    dist = Vector3.Distance(transform.position, player[player_number].transform.position);

    if (dist <= 5)
    {
        near = true;
    }
    else
    {
        near = false;
    }

    if (player != null && dist <= 5.1f)
    {
        mAgent.destination = player[player_number].transform.position;
        if (dist < 1.2f)
        {
            enemy_atack = true;
        }
        else
        {
            enemy_atack = false;
        }
    }
    else
    {
        if (dead_point_number > 0)
        {
            mAgent.destination = dead_point[farPoint].transform.position;
        }
        else
        {
            mAgent.destination = player[player_number].transform.position;

        }
        if (mAgent.remainingDistance <= 1.5f)
        {
            enemy_atack = true;
        }
        else
        {
            enemy_atack = false;
            enemt_run = true;

        }
    }

    mAgent.speed = 1.0f;

    enemy_anim.SetBool("run", enemt_run);
    enemy_anim.SetBool("attack", enemy_atack);
}// end update

// choose any deat_point.
void enemy_dirction()
{
    if (dead_point_number > 0)
    {
        farPoint = Random.Range(0, dead_point.Length);
        mAgent.destination = dead_point[farPoint].transform.position;
    }
    else
    {

    }
}


texts:
Me and 3 other friends want to make an indie title together. We all have ideas for what game we want to make, but we are facing the dilemma of making a decision on which idea we choose to actually bring to life. Naturally, everyone feels his/her own idea is the best, lol.

Has anyone been in a similar situation? How did you resolve the issue? We though of perhaps starting a poll and having the public opinion make the decision for us, but that puts our ideas out for grabs (i.e. someone may steal them :P). If you haven't been in this situation but still have an opinion/suggestion, please voice it!


texts: Simple Motor Vehicle Acceleration Function

texts:
So I have a simple 1D "racing" game, with a single button the player can press to max the gas pedal and there is also some other stuff going on.

I think acceleration should be highest somewhere at medium velocity (or medium RPM for each gear), and taper off towards maximum velocity, no?
What is a good set of functions to model this?

Do I need to model RPM too? I'm not sure whether to model different gears too, but I thought they'd each follow more or less the same function.


texts:
I'm trying to implement multiplayer into my game using the server client model. What is the best method of synchronozing the game between the clients? What I'm thinking is that the game runs on the client, where the clients send the inputs (keyboard input for example) to the server, and the server then passes that on to the other clients, which then process that information. To make this system more robust the game would also run on the server, and the server would send synchronization packets to synchronize all the instances in the room. I can already see some potential flaws in this design, so that's why I'm asking for a better implementation. Both the server and client run in gamemaker.

To give you some context: my game is a relatively simple rpg platformer, where you have an inventory and items, player stats like armor and physical damage (the stats are almost identical to those of league of legends). You move with the arrow keys or wasd, like a regular platform game. For now I want to implement pvp, but would like to set up networking in a way that allows for npcs. I want to have a maximum of say 4 or 5 players connected at a time.

I have read up on client prediction, server reconciliation, entity interpolation and lag compensation, but it seems overkill for my application (it might not be I'm not sure).

I guess there it is somewhat acceptable to have a pure authoritative server, other than the fact that the player movement will become unresponsive, which is a big issue. Also using items and switching between then will become less responsive, which will make pvp less intense, but I can't think of a reasonable workaround for that.

Also, I am not worried about cheating as I am making this game just to have fun with friends.

Thanks.


texts: Massive CPU Usage by WaitForTargetFPS in the Profiler

texts:
So I was checking the Standard Assets Example Projects of Unity, and they all have high FPS numbers in the Profiler.

I started a little project myself, just a simple sprite with movement via rigidbody and a plane as a floor, and suddenly this:

I searched for what exactly does WaitForTargetFPS represents, but apparently there is not a general consensus about what can cause such high CPU usage. So why exactly such a little and simple project have this performance (in contrast with the more complex Unity Example Projects)?


texts: What is the correct way to seperate (react) view from state?

texts:
I would like to know the correct implementation to declare game logic and view logic:

I see 3 ways of implementing this:

1.Storing (eg writing preprocessing to store the change to a property) property changes to data entities that are dispatched to listener(s) of the data entity. The main listener being the view, where the view contains the declared rendering logic (ie changing the entities animation based on a property change, changing the entities render object position).

  State Model (x,y,z,state) -> View (listens to change in
  x,y,z,state)->Scene graph object (x,y,z,animation, gets set by the View)

The issue with this is that it becomes evident that game engines are executing a lot of char[] switch statements (eg the names of properties) in the View.

2.Declaring the view as updating to the entirety of the model. Eg, instead of saving the changes as specified in 1) the view updates the render objects on every tick by inspecting the entire model, as opposed to the provided changes of 1). The tradeoff between 1 and 2 is the necessity of the additional execution of storing the property changes on the state tick.

3.Declaring animation logic in the state logic. Eg, instantiated member render objects are dummy objects when rendering is not performed.

The questions:

As specified in the title, what is the correct implementation to reacting to the game state  in the sense of where should one declare display/rendering/animation (view) logic that reacts to the game state?
What is the implementation used in most game engines that facilitate large projects? (if possible, please specify for specific engines: SupremeCommander/clones, SC2, Unreal, ID, Frostbite, Anvil)
Which implementation do studios implement to architect projects using said engines? It's apparent that it is possible to not seperate model from view in the above engines. Eg, if you implement an entity, you would presumably want it to be viable in multiplayer, coop, and single player.

The questions regarding other engines deals with the fact that perhaps it has been evaluated that it is not a sufficiently optimized implementation to consume the state in a View as opposed to executing direct calls to render objects.

So, on tick we update the game data simulation. For example:

  The state of a unit's weapon is updated to firing. However, updating
  the view of the weapon to firing (by for example, setting the animation of the weapon and animating the hand) is not necessary in all
  instances of the simulation.


texts: Scale screen space quads (used in font rendering)

texts:
I have quads positioned in <0, 1> x <0, 1> coordinates. I use this system for font rendering.

In vertex shader I have:

gl_Position.xy = 2.0 * POSITION.xy - 1.0;

that brings the position to the screen space <-1, 1> x <-1, 1>.

My quads are created from two triangles ABD, BCD

D-C
|\|
A-B

Now, I want to scale the quad by a scale factor. Can I achieve this with this data?

I have tried to change geometry and store quad center and half-sizes, then calculate the final position as

gl_Position.xy = 2.0 * (CENTER_POSITION.xy + HALF_SIZE.xy) - 1.0;

This way, I can translate points to origin, scale them and translate them back. However, this scale single quad correctly, but the two closely neigboring quads are no longer closely neigboring, since the space between them is constant.

So the final question. How can I scale quads used for font rendering, so that the text is still readable without large gaps between glyphs?


texts:
I want to render a simple OpenGL scene as usual, but then I want to superimpose a small image of my own (such as from a bitmap file) on top of the render, such that this image always shows. For example, this could be thought of as showing a logo in the corner of the screen for a 3D game, where the logo is always displayed on top of the rendered scene.

Please could somebody start me off in the right direction? What should I be looking into? I am rather a novice at OpenGL...

Let us suppose that I have the following code:

#include <GL/glut.h>

void renderScene(void)
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glBegin(GL_TRIANGLES);
        glVertex3f(-0.5,-0.5,0.0);
        glVertex3f(0.5,0.0,0.0);
        glVertex3f(0.0,0.5,0.0);
    glEnd();

    glutSwapBuffers();
}

int main(int argc, char **argv)
{
    // init GLUT and create Window
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
    glutInitWindowPosition(100,100);
    glutInitWindowSize(320,320);
    glutCreateWindow("GLUT Triangles");

    // register callbacks
    glutDisplayFunc(renderScene);

    // enter GLUT event processing cycle
    glutMainLoop();

    return 1;
}

This renders a triangle on the screen. How, for example, would I now render a 10-by-10 bitmap from file, at location (100, 100) on the screen? If the viewpoint was static, I could just calculate its 3D location and render it. However, I want the bitmap image to always be displayed in this location, even when the viewpoint changes.

Thanks :)


texts: Why isn't my tilemap collider appearing?

texts:
I am trying to make a 2d game but my player falls through the tilemap every time.
My tilemap collider doesn't seem to show up.
What is going on and how do I fix this?
The first image is rigidbody currently falling through the tilemap and the tilemap. The second image is rigidbody currently falling through the tilemap and the rigidbody.


texts: How can I copy/move a file from a folder to another with RGSS?

texts: I've been trying to do this but I can only find Ruby answers. I'm trying to move or copy a file from, say, Game Directory/Graphics/Pictures/file.png to Game Directory/file.png. How can I do this in RGSS?


texts: What are the pros and cons of incorporating Lua into a C++ game?

texts:
I have a C++ game programming book and it has a Lua section in it. I've started to read the Lua section, and it sounds interesting, but I can't determine the pros and cons of using Lua in my C++ game. The only benefit I can currently think of is that you can make some coding updates, via Lua, without having to recompile. Other than that, I can't think of anything. So what are the pros and cons of adding Lua to a C++ game?

Examples would be appreciated.