texts: How to limit steering force at low velocities

texts:
Sorry if this is posted before, but I didn't find an answer for this. I've been banging my head on this for a day now and I seems to be stuck.

I've implemented (see below) the 2D steering arrival behaviour described in http://www.red3d.com/cwr/steer/ which all works fine until there is a characters which wants to turn 180°. The character simply slows down, flips 180° and starts accelerating. I tried to illustrate this in Figure 1 (a).

Figure 1 - where red is the velocity and green the desired direction

What I would ideal like is a smoother path as seen in Figure 1 (b). I was thinking of using the clipped_speed in combination with steering 'left' or 'right', however I can't seem to figure out how to do this with vectors. If anyone could point me in the right direction, that would be great.

The implementation (using libgdx)

Vector2 target_offset = target.sub(position);
float dist = target_offset.len();
float clipped_speed = Math.min(max_speed * (dist / (20 * mass)), max_speed);

desiredVelocity = target_offset.mul(clipped_speed / dist);
steeringForce = desiredVelocity.sub(this.velocity);

truncate(steeringForce, max_force);
Vector2 acceleration = steeringForce.mul(1 / mass * 60 * delta);

velocity.add(acceleration);
truncate(velocity, max_speed);

position.add(velocity.mul(60 * delta));

And the code for truncate:

public void truncate(Vector2 v, float max) {
    float i = v.len() != 0 ? max / v.len() : 0;

    if(i < 1) {
        v.mul(i);
    }
}

EDIT: Using bobobobo input I think I'm there. So for those interested:

Vector2 target_offset = target.position().sub(position);

float dist = target_offset.len();
float clipped_speed = Math.min(max_speed * (dist / break_dist * mass), max_speed);

desiredVelocity = target_offset.mul(clipped_speed / dist);
steeringForce = desiredVelocity.sub(velocity);

truncate(steeringForce, max_force);
forward = steeringForce.mul(1 / mass * 60 * delta);

float a = (float) (Math.acos(velocity.nor().dot(forward.nor())) * MathUtils.radDeg);
if(Float.isNaN(a)) a = 0;

if(a > max_rot) {
    if(velocity.nor().crs(forward.cpy().nor()) < 0) {
        forward.setAngle(velocity.angle() - max_rot);
    } else {
        forward.setAngle(velocity.angle() + max_rot);
    }
}

velocity.add(forward);
truncate(velocity, dist < break_dist * mass ? dist / (break_dist * mass) * max_speed : max_speed);

Breaking is done by just scaling the velocity linearly, which isn't really all that nice implementation wise, but it give better stopping results. So we don't overshoot.


texts: Unity Raycasting only hitting mesh colliders from particular directions

texts:
I have a game which involves clicking to select some objects. Each of the objects has a mesh collider attached to it so that objects can be clicked, handled by the following:

if (Input.GetMouseButtonDown(0)){ // if left button pressed...

    // Find hit object
    Ray ray = task_scene.main_camera.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;
    if (Physics.Raycast(ray, out hit)){
        execute_some_function();

    }
}

Now this works fine when I run the game in the editor. However, when I build and run in the browser some objects are not being selected when clicked, and it seems to be objects that are created from particular meshes.
I have tried:

changing the mesh import settings to generate colliders but this doesn't seem to do anything
changing Prebake Collision Meshes in build settings, which again doesn't solve the problem
Changing mesh collider cooking option to both 'everything' and 'none'
Setting 'Queries Hit Backfaces' to true in physicsmanager settings
making setting the meshes to convex, which does then work in the build but is not ideal.

EDIT: I've noticed that the raycasting is actually working for the problem objects but only from particular directions. Is this because, according to the manual: 'Faces in collision meshes are one-sided. This means objects can pass through them from one direction, but collide with them from the other.'

Any thoughts on what might be causing this?


texts:
I'm building my own game engine in C++ and I'm currently deciding on what user interface I should use.

Should I use a library? Should I make my own?


texts: Draw coloured transparent polygons on top of texture in modern opengl

texts:
I am trying to render an image in the viewPort using symmetry_create = 1
and binding texture to it.

 static const GLfloat vertices[] = {
//vertexdata
        -symmetry_create,
        symmetry_create,
        0.0f,
        //uv
        0.0f, 1.0f,
        symmetry_create,
        symmetry_create,
        0.0f,
        //uv
        1.0f, 1.0f,
        symmetry_create,
        -symmetry_create,
        0.0f,
        //uv
        1.0f, 0.0f,
        -symmetry_create,
        -symmetry_create,
        0.0f,
        //uv
        0.0f, 0.0f};

My vertex shader looks like

#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec2 texCoord;

out vec2 TexCoord;
void main()
{
    gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);
    TexCoord = texCoord;
}

And fragment shader looks like

#version 330 core

in vec2 TexCoord;
out vec4 frag_color;

uniform sampler2D myTexture;
void main()
{
    frag_color = texture(myTexture, TexCoord);
}

I have setup my vao, vbo and indices correctly and thus I am getting the result as expected (ie: A provided image on the display screen).

Now I would like to draw 'n' number of transparent polygons on the image generated.For each polygon, I have thought of achieving using mouse cursor positions and clicks and render using glDrawArrays(GL_TRIANGLE_FAN, 0, n);.

If I use the same vertex and fragment shaders my result now is black opaque polygons on top of the image.
How to achieve transparency and color in the polygons. Do I need to another set of shaders(vertex and frag)?


texts: Making the ball go faster makes collision detection impossible

texts:
I have a simple tennis game like Breakout. I have a ball, and a racquet made from a long rectangle. The ball bounces around the walls, and the game terminates when the ball hits the floor. To prevent this, I have a long racquet I can move horizontally that the ball can hit. Each time the ball hits the racquet, the speed of the ball increases.

The speed increases by adding to the number of pixels for each increment of the ball. This means that after a while (around 50 hits), the steps of the ball become quite long. The ball moves at 50 px per frame. With long steps, the ball might just jump over the racquet, and not detect collision.

To prevent this, I was thinking of incrementing the FPS, instead, and keeping the ball speed fixed. This would probably work, but I don't think changing the FPS is the right solution. How should I go about solving collision detection at higher speeds?


texts:
I'm trying to make a game which requires a random generation of sentence upon pressing spacebar. I've never done anything like this and wanted to give it a shot with whatever knowledge I had.

Whenever spacebar is pressed, "Be something in something." appears. I want the somethings to be randomized.

This what I wrote in the Create event -

global.profession = irandom(2);
global.situation = irandom(2);

And this in the Space event -

draw_set_colour($777777);
draw_set_font(fnt_rpl);

if global.profession = 0{
  global.profession = "a nurse"
}

if global.profession = 1{
  global.profession = "a driver"
}

if global.profession = 2{
  global.profession = "a police officer"
}

if global.situation = 0{
  global.situation = "in a hospital."
}

if global.situation = 1{
  global.situation = "in a car."
}

if global.situation = 2{
  global.situation = "in a police station."
}

draw_text_ext_transformed(200, 500, "Be" + global.profession + global.situation, 20, 800, 1, 1, image_angle);

Room is set to be 1920x1080 and I've added the object in the room. I'm getting no result, not even an error, when I press space.


texts:
So currently ive been using the physics.castSphere method with a small radius to find the closest of an object with a tag.

However this is pretty performance heavy so my question is, is there a way to optimize it?

i  have also been looking at keeping a list of gameobjects and just looping through those however doing that a few times a frame for each object searching also seems rather performance intensive.

Here is my case:

  50 individual characters on team 1

  50 individual characters on team 2

each character has to find the closest of the character from the other team.

What is the fastest and least performance heavy way of doing it?


texts:
I created a human model in Blender, exported the vertices and indices into a JSON file and render the model in a browser using WebGL. Now I created a walk and jump animation in Blender and would like to do the same with WebGL.

I saw examples that use a list of vertices for every frame of the animation. Is this the way to go? Do I need to export the vertices for every frame for every animation?


texts: Why is integer value not updating as a text?

texts:
I have a space shooter game and I am trying to create a shield power for the player ship. My mechanic for shield is working. When I press the shield power button(P), the shield power decreases from 100 to 0 at a certain pace.

Problem is that I am trying to draw this shield power value on screen but it's just showing the starting shield power value(which is 100) and not showing the decrease in shield power value when I press the shield button.

What am I missing?

Here's the relevant code:
Game.cpp

if (keyboard->IsKeyPressed('P'))
{
    if (player_->shield == true)
        player_->shield = false;
    else
        player_->shield = true;
}

if (player_->shield && player_->shieldPower > 0)
{
    if (keyboard->IsKeyPressed(VK_SPACE))
    {
        XMVECTOR playerForward = player_->GetForwardVector();
        XMVECTOR bulletPosition = player_->GetPosition() + playerForward * 10.0f;
        SpawnBullet(bulletPosition, playerForward);
    }

    player_->shieldActive = true;
    if (GetTickCount() - player_->time > 100)
    {
        player_->time = GetTickCount();
        player_->shieldPower--;
        if (player_->shieldPower <= 40)
        {
            player_->shieldPowerLow = true;
        }
        else
        {
            player_->shieldPowerLow = false;
        }
    }
}
else
    player_->shieldActive = false;

TextClass.cpp

void TextClass::OnRender(System *system)
{
Graphics *graphics = system->GetGraphics();
FontEngine *fontEngine = graphics->GetFontEngine();
Player *player = new Player();

Game *game = system->GetGame();
game->RenderEverything(system->GetGraphics());

std::stringstream buffer;
buffer << player->shieldPower;

fontEngine->DrawText(buffer.str().c_str(), 50, 100, 0xffffffff,
FontEngine::FONT_TYPE_SMALL);
}

Player.h

class Player
{
public:

int shootDelay;
int time;
int shieldPower;
bool shield;
bool shieldActive;
bool fullShield;
bool shieldPowerLow;
bool shoot;
}

Player.cpp

Player::Player() :
shootDelay(500),
shieldPower(100),
fullShield(true),
shieldPowerLow(false),
shield(false),
shieldActive(false),
shoot(false)
{
}


texts: I want the rotation of the sprite. So that I used RotationModifier, but in that I have to specify the time interval you want the rotation. But I want to create rotation which was infinite. So please help me.


texts: How can I model AI Interactions across the entire game world without computing them individually?

texts:
I'm making a 2D top-down tile-based game in C++ using SDL2. The game uses a very large world map (think Dwarf Fortress).

My world terrain is generated using a noise function, another function is then used to build towns, model NPCs, etc. which are then saved to a local SQLite database (I'm using a database because NPC states, for example, are quite complicated - the database models their relationships with other NPCs, changing personalities, goals etc., and can be affected by player interactions with them as well).

At any point in time during play, the player is in some 'sector' of the world map. Currently, only interactions in the player's current sector are modeled (e.g. NPCs talking to each other, NPCs fighting each other etc.).

How can I model interactions across the entire world map, without the obvious computational problems of modelling every single interaction that occurs?

Is there some pattern which can generalise interactions?

The game uses time heavily (where a minute of game-time is a second in real-time, and thus in-game minutes, hours, days, months and years can be used). Could I somehow compute large-scale estimations of changes overtime? Some of these changes could be computed on player entry into the sector, based on how long it has been since the player has been in that sector (e.g. NPC getting older, dying of age etc.), but some changes should occur as they actually 'happen' (e.g. cross-sector things like an army or a trader travelling across the map).


texts: 2D shader to draw representation of rotating sphere

texts:
I want to display a 3D textured sphere, and then rotate it in one direction. The direction will never change, and the camera will never move. One way is to actually create a spherical mesh, map a texture to it, rotate the sphere, and render in 3D.

My question is, is there a way to display a 2D circle, that looks like a rotating sphere, with just a 2D shader.

In other words, can someone think of a trick, like mapping a texture to the circle in a particular way, to give the appearance of an in-place rotating sphere, that is always viewed from the side?

I don't need exact shader code, I'm just looking for the right idea.


texts: Move enemies over the network without sending their positions

texts:
I am trying to move enemies on two clients without sharing their positions. I use this:
startingPosition + GetRandomDir() * Random.Range(1f, 10f)

To have the same movement on clients and server, I set the same seed to get the same directions with Unity Random.
I set it with the system datetime now ticks on server and clients:
Random.InitState(newTicks);

I am getting the same movements on the server and on the clients until a enemy starts looking for a player and chasing that player.
When this happens, the enemy on one client is not at the same position on the other client. One enemy is targeting a player on one client, but on the other client he hasn't targeted that player yet. The enemy keeps wandering creating a different position on one client than on the server or other clients for example.
Is there a better way to synchronize the enemy movement ?
My idea was not to send the positions of the enemies from the server to the clients but rather have the clients move their enemies themselves.
I would also like to know what to search for on Google to get help with this problem: networking ai movement doesn't help, synchronize movement over the network without sending position does not return the results I would like either.
What I think is strange and I don't understand is that the same code is executed on both the client and the server. The players and the enemies are at the same positions. Yet the enemy will choose to chase a player on the server and not to chase a player on the client. Resulting on the client to view the enemy at a different position than the position of the enemy on the server.


texts: Indirect indexing (uv coords read from texture)

texts:
In the vertex shader, I need to make a texture fetch, where the texture coordinate itself is read from some other texture.

vec2 uv = texture(someTexture,coords).xy;
vec4 val = texture(otherTexture,uv).xyzw;

As far as I know, the second sample has undefined results, because the value of uv is outside of uniform flow control.

Is there any way to efficiently (i.e., not copy back the contents of the texture and upload it as a uniform to the shader or something) do what I want to do?


texts: How to calculate the transformation such that two points with different position, orientation and origins line up?

texts:
Let's say you have two different 3D Objects which both contain a node that is off center (not at the origin) and have an orientation. How do you calculate the transform for one of the object so that both of these nodes line up? As in both nodes end up at the same position in space and the same orientation?

In gaming terms, both 3D objects have "snap" points and I'd like to calculate how to transform one of them so that they snap together at that specific node.

 The cubes are the 3D objects, the X/Y/Z axis represent the origin of each of these objects, and the arrow is the node. The goal would be in this case both arrows overlap and thus the cubes end up at the exact same place. Note the origin is NOT at the same spot for both objects.


texts: Positioning a sprite in XNA: Use ClientBounds or BackBuffer?

texts:
I'm reading a book called "Learning XNA 4.0" written by Aaron Reed. Throughout most of the chapters, whenever he calculates the position of a sprite to use in his call to SpriteBatch.Draw, he uses Window.ClientBounds.Width and Window.ClientBounds.Height. But then all of a sudden, on page 108, he uses PresentationParameters.BackBufferWidth and PresentationParameters.BackBufferHeight instead.

I think I understand what the Back Buffer and the Client Bounds are and the difference between those two (or perhaps not?). But I'm mighty confused about when I should use one or the other when it comes to positioning sprites. The author uses for the most part Client Bounds both for checking whenever a moving sprite is of the screen and to find a spawn point for new sprites. However, he seems to make two exceptions from this pattern in his book. The first time is when he wants some animated sprites to "move in" and cross the screen from one side to another (page 108 as mentioned). The second and last time is when he positions a texture to work as a button in the lower right corner of a Windows Phone 7 screen (page 379).

Anyone got an idea?

I shall provide some context if it is of any help. Here's how he usually calls SpriteBatch.Draw (code example from where he positions a sprite in the middle of the screen [page 35]):

spriteBatch.Draw(texture,
   new Vector2(
   (Window.ClientBounds.Width / 2) - (texture.Width / 2),
   (Window.ClientBounds.Height / 2) - (texture.Height / 2)),
   null,
   Color.White,
   0,
   Vector2.Zero,
   1,
   SpriteEffects.None,
   0);

And here is the first case of four possible in a switch statement that will set the position of soon to be spawned moving sprites, this position will later be used in the SpriteBatch.Draw call (page 108):

// Randomly choose which side of the screen to place enemy,
// then randomly create a position along that side of the screen
// and randomly choose a speed for the enemy
switch (((Game1)Game).rnd.Next(4))
{
   case 0: // LEFT to RIGHT
      position = new Vector2(
         -frameSize.X, ((Game1)Game).rnd.Next(0,
         Game.GraphicsDevice.PresentationParameters.BackBufferHeight
         - frameSize.Y));

      speed = new Vector2(((Game1)Game).rnd.Next(
         enemyMinSpeed,
         enemyMaxSpeed), 0);
   break;


texts: Performance of instantiating many prefabs as children of one prefab in unity

texts:
Is there any performance difference between [instantiate multiple prefabs] and [put all prefabs under a single parent prefab and then instantiate that parent prefab] in scene.
Hope you understand what i want to say.


texts: I am learning game design, and wanted to know how one can automatically generate spiky terrain (something like this: Cavernaut, notice, the terrain at the sides?). I have heard about midpoint displacement algorithm. But How can I apply that to my problem, given that I would also like to increase/decrease the randomness of the terrain. Also, Is there any helpful library for this in libgdx?


texts: Rescale pixel art scenery before rendering in SDL2

texts:
I looked at this page that mentions the SDL2_gfx library for rescaling SDL_Surfaces without the image getting blurry:
SDL zooming/upscaling without images becoming blurry?

I wanted to know if it was a good idea and if there was any way (instead of individually resizing each texture, all relationships of space, and fixing the proportions of the speed for each object) to take the tiny scene of little sprites and tiles and rescale it before the image blits on the screen.

If there's a more reasonable solution, someone tell me, but this seems to make the most sense to me.

Thanks for the help!


texts: Cant write/read to/from external storage with LibGDX

texts:
My create method looks like this:

@Override
public void create () {
    batch = new SpriteBatch();

    FileHandle file = Gdx.files.external("file.txt");
    file.writeString("My god, it's full of stars", false);
}

I allso included:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

The Exception i get is this:

02-13 14:45:51.858 12439-12466/com.snowdevs.tweetiebirds E/AndroidRuntime: FATAL EXCEPTION: GLThread 1120
Process: com.snowdevs.tweetiebirds, PID: 12439
com.badlogic.gdx.utils.GdxRuntimeException: Error writing file: file.txt (External)
   at com.badlogic.gdx.files.FileHandle.writeString(FileHandle.java:353)
   at com.badlogic.gdx.files.FileHandle.writeString(FileHandle.java:339)
   at com.snowdevs.tweetiebirds.TweetieBirdsGame.create(TweetieBirdsGame.java:22)
   at com.badlogic.gdx.backends.android.AndroidGraphics.onSurfaceChanged(AndroidGraphics.java:254)
   at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1519)
   at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1240)
Caused by: com.badlogic.gdx.utils.GdxRuntimeException: Error writing file: file.txt (External)
   at com.badlogic.gdx.files.FileHandle.writer(FileHandle.java:330)
   at com.badlogic.gdx.files.FileHandle.writeString(FileHandle.java:350)
   at com.badlogic.gdx.files.FileHandle.writeString(FileHandle.java:339)
   at com.snowdevs.tweetiebirds.TweetieBirdsGame.create(TweetieBirdsGame.java:22)
   at com.badlogic.gdx.backends.android.AndroidGraphics.onSurfaceChanged(AndroidGraphics.java:254)
   at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1519)
   at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1240)
Caused by: java.io.FileNotFoundException: /storage/emulated/0/file.txt: open failed: EACCES (Permission denied)
   at libcore.io.IoBridge.open(IoBridge.java:452)
   at java.io.FileOutputStream.<init>(FileOutputStream.java:87)
   at com.badlogic.gdx.files.FileHandle.writer(FileHandle.java:322)
   at com.badlogic.gdx.files.FileHandle.writeString(FileHandle.java:350)
   at com.badlogic.gdx.files.FileHandle.writeString(FileHandle.java:339)
   at com.snowdevs.tweetiebirds.TweetieBirdsGame.create(TweetieBirdsGame.java:22)
   at com.badlogic.gdx.backends.android.AndroidGraphics.onSurfaceChanged(AndroidGraphics.java:254)
   at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1519)
   at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1240)
Caused by: android.system.ErrnoException: open failed: EACCES (Permission denied)
   at libcore.io.Posix.open(Native Method)
   at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
   at libcore.io.IoBridge.open(IoBridge.java:438)
   at java.io.FileOutputStream.<init>(FileOutputStream.java:87)
   at com.badlogic.gdx.files.FileHandle.writer(FileHandle.java:322)
   at com.badlogic.gdx.files.FileHandle.writeString(FileHandle.java:350)
   at com.badlogic.gdx.files.FileHandle.writeString(FileHandle.java:339)
   at com.snowdevs.tweetiebirds.TweetieBirdsGame.create(TweetieBirdsGame.java:22)
   at com.badlogic.gdx.backends.android.AndroidGraphics.onSurfaceChanged(AndroidGraphics.java:254)
   at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1519)
   at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1240)

I use a Nexus 5 with Android 6 Marshmallow for testing.
I searched and found that Android 6 uses runtime permissions but the LibGDX guys says that it works even on Android 6... Is there a fix With or Without runtime permissions?


texts:
I am using Manjaro linux and SDL 2. However, when I build the application in debug mode and use gdb or something like qtcreator with gdb, to debug it, it gives me a segfault, when the function SDL_Init() is called.
The code I am trying this with:
#include <iostream>
#include <SDL2/SDL.h>

int main(int argc, char *argv[])
{
    if (SDL_Init(SDL_INIT_VIDEO) < 0)
    {
        printf("SDL Init error: %s", SDL_GetError());
        return -1;
    }

    SDL_Window *window = SDL_CreateWindow("window", 10, 120, 800, 640, 0);

    SDL_Renderer *ren = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

    bool running = true;
    while (running)
    {
        SDL_Event e;
        if (SDL_PollEvent(&e) != 0)
        {
            switch(e.type)
            {
                case(SDL_QUIT): running = false;
            }
        }

        SDL_RenderClear(ren);

        SDL_RenderPresent(ren);
    }

    SDL_DestroyRenderer(ren);
    SDL_DestroyWindow(window);
    SDL_Quit();
    return 0;
}

I then recompiled SDL for debugging and went into the source, to find out this function in SDL.c is actually the cause:
        if (SDL_PrivateShouldInitSubsystem(SDL_INIT_VIDEO)) {
            if (SDL_VideoInit(NULL) < 0) {             <- this here is causing the segfault
                return (-1);
            }
        }

I don't know what to even do with this. None of the SDL versions work anymore. I've tried installing older ones, compiling from source.


texts: Why did 320x240 become the famous Mode X, and not 400x300?

texts:
Mode X was hack invented during the good old days of DOS gaming, offering 320x240 resolution, 256 colors, square pixels, and page flipping.

VGA adapters had 256 KB of memory.

320 * 240 = 76800 bytes
262144 / 76800 = 3.413 pages

So you have lots of memory left over when you do page flipping with two pages (equivalent of double buffering).

400 * 300 = 120000 bytes
262144 / 120000 = 2.18453 pages

You get all the benefits of Mode X, but more resolution. So what is the reason 400x300 resolution didn't become the standard for DOS games? What were its drawbacks?


texts:
When I build my project, which references the System.IO.Compression namespace, the build succeeds without issue inside Visual Studio.

However, inside the Unity editor, I see the following error:

error CS1069: The type name 'ZipArchive' could not be found in the namespace 'System.IO.Compression'. This type has been forwarded to assembly 'System.IO.Compression, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' Consider adding a reference to that assembly.

I added a csc.rsp file inside my Assets folder, with the following line:

-r:System.IO.Compression.FileSystem.dll

Unfortunately, that did not resolve the issue.

Here are the properties of the System.IO.Compression DLL that I reference inside Visual Studio:

How can I fix this error?


texts:
I am new at OpenGL, I try this example:  https://stackoverflow.com/a/31524956/4564882

but I get only a black widget. The code is exactly the same. this is the code associated to the QopenGLWidget:

OGLWidget::OGLWidget(QWidget *parent)
: QOpenGLWidget(parent)
 {

 }

 OGLWidget::~OGLWidget()
{

}

 void OGLWidget::initializeGL()
 {
   glClearColor(0,0,0,1);
   glEnable(GL_DEPTH_TEST);
   glEnable(GL_LIGHT0);
   glEnable(GL_LIGHTING);
   glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
   glEnable(GL_COLOR_MATERIAL);
}

 void OGLWidget::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glBegin(GL_TRIANGLES);
    glColor3f(1.0, 0.0, 0.0);
    glVertex3f(-0.5, -0.5, 0);
    glColor3f(0.0, 1.0, 0.0);
    glVertex3f( 0.5, -0.5, 0);
    glColor3f(0.0, 0.0, 1.0);
    glVertex3f( 0.0,  0.5, 0);
glEnd();
 }

 void OGLWidget::resizeGL(int w, int h)
 {
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45, (float)w/h, 0.01, 100.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0,0,5,0,0,0,0,1,0);
  }

I tried the example here: https://doc.qt.io/archives/qt-5.3/qtopengl-2dpainting-example.html. It works fine (trying the both base class: QGLWidget and QOpenGLWidget. this is the code associated to the Widget:

  GLWidget::GLWidget(Helper *helper, QWidget *parent)
  : QGLWidget(QGLFormat(QGL::SampleBuffers), parent), helper(helper)
 {
 elapsed = 0;
setFixedSize(200, 200);
setAutoFillBackground(false);
}

void GLWidget::animate()
{
 elapsed = (elapsed + qobject_cast<QTimer*>(sender())->interval()) % 1000;
 repaint();
 }

void GLWidget::paintEvent(QPaintEvent *event)
{
QPainter painter;
painter.begin(this);
painter.setRenderHint(QPainter::Antialiasing);
helper->paint(&painter, event, elapsed);
painter.end();
}

I use  Qt 5.5.1 binairies built on my machine. I let the Build Configuration by default, so it is based on Qt ANGLE not Desktop OpenGL.
My Graphic card Driver is updated.
What is the problem of such a behaviour?


texts: Problem with Ogre::Camera lookAt function when target is directly below

texts:
I am trying to make a class which controls a camera. It's pretty basic right now, it looks like this:

class HoveringCameraController
{
public:

   void init(Ogre::Camera & camera, AnimatedBody & target, Ogre::Real height);
   void update(Ogre::Real time_delta);
private:
   Ogre::Camera * camera_;
   AnimatedBody * target_;
   Ogre::Real height_;
};

HoveringCameraController.cpp

void HoveringCameraController::init(Ogre::Camera & camera, AnimatedBody & target, Ogre::Real height)
{
   camera_ = &camera;
   target_ = &target;
   height_ = height;

   update(0.0);
}

void HoveringCameraController::update(Ogre::Real time_delta)
{
   auto position = target_->getPosition();
   position.y += height_;
   camera_->setPosition(position);
   camera_->lookAt(target_->getPosition());
}

AnimatedBody is just a class that encapsulates an entity, it's animations and a scene node. The getPosition function is simply forwarded to it's scene node.

What I want(for now) is for the camera to simply follow the AnimatedBody overhead at the distance given(the height parameter), and look down at it. It follows the object around, but it doesn't look straight down, it's tilted quite a bit in the positive Z direction. Does anybody have any idea why it would do that?

If I change this line:

position.y += height_;

to this:

position.x += height_;

or this:

position.z += height_;

it does exactly what I would expect. It follows the object from the side or front, and looks directly at it.


texts: Can you help me solve the paradox that has confused me about the glViewport and glOrtho functions?

texts:
suppose that I have an image that I want to apply as a texture on a geometry (at time we don't consider texture mapping but this image has a certain width and height here it is a 512x512 image)
I want the image be drawn at the center of the window so I have set the window coordinates as follows:

glOrtho(-oglWindowWidth/2, oglWindowWidth/2, oglWindowHeight/2,-oglWindowHeight/2, -1, 1);

and then drew the geometry:

float x0 = -ImageWidth/2; // top left corner of image
float y0 = -ImageHeight/2;
float x1 = x0 + ImageWidth; // bottom right corner of image
float y1 = y0 + ImageHeight;

glBegin(GL_TRIANGLE_STRIP);
{
    glVertex2f(x0, y1);
    glVertex2f(x0, y0);
    glVertex2f(x1, y1);
    glVertex2f(x1, y0);
}
glEnd();

It's true and what I reach as the result is:

Meaning that the coordinates of the center of both the image and window is (0,0) and the image will be drawn at the center of the window
But since I need the viewport, I used this code after drawing the geometry:

GLint iViewport[4];
glGetIntegerv(GL_VIEWPORT, iViewport);

and reached the result: (0,0,573,543)
now I think that the line of code: glOrtho(-oglWindowWidth/2, oglWindowWidth/2, oglWindowHeight/2,-oglWindowHeight/2, -1, 1); says that:
left of window : -573/2 = -286.5
right of window : 286.5
top of window : -543/2 = -271.5
bottom of window : 271.5
But the Viewport tells:
left of window : 0
right of window : 573
bottom of window : 0
top of window : 543
Note that if I set the Viewport by something like the following code:

glViewport(-oglWindowWidth/2, oglWindowHeight/2, oglWindowWidth, oglWindowHeight);

I won't get the true result. I mean the geometry will not be drawn at the center of window as shown in the photo?
How can I solve the paradox having two different coordinate values for the bottom left of the image by two different codes?


texts:
I'm new to using unity and came across a problem when I was following a tutorial. The game is in two dimensional space, and when my player walks over a certain tile the detection never goes off. Here's the code that I have,

function calculateWalk() {

    yield WaitForSeconds(0.3);

    var hit : RaycastHit;

    if(Physics.Raycast (transform.position, Vector3.down, 100.0)) { // Never evaluates to being true
        var distanceToGround = hit.distance;
        Debug.Log("Hit");

        if(hit.collider.gameObject.tag == "tallGrass") {
            walkCounter++;
            Debug.Log("Tall Grass");
        } // END if
    } // END if
} // END calculateWalk()

I've made sure to attach the script to my player, as well as tag the tiles that I want with "tallGrass". I've followed what was done in the tutorial, but for some reason it's not working out for me, not sure if this is all the code needed to help solve this problem, if more information is needed let me know, I also set my player 1 unit above the tiles.


texts:
I'm trying to implement a crouching system to my 2D platformer. The problem is, I don't want the character to be able to do anything else except jumping when it's crouching. I have many functions but I think posting the movement function here would be enough. When I gain velocity and then press crouch, I skid across the platform, and stop.
First, my crouch function:
private enum State { idle, running, jumping, falling, crouching}

    void Update()
{
    //crouch
    if(Input.GetButton("Crouch"))
        {
        animator.SetInteger("state", 4);
        Crouch();
        }
    else
    {
    boxCol.size = new Vector2(0.5454721f, 1.8065f);
    }
}

 void Crouch()
{
    boxCol.size = new Vector2 (0.6933689f,1.44953f);

}

And here is my movement function. I tried to fix it by adding the if condition on top of it, but when I run and crouch, it slides a lot before stopping. What can I do to fix that? The character already has a physics material with zero friction. I know I can make the velocity zero if the player is crouching but that would just kill the gameplay. I need to add a smooth stopper. I'm not sure how to make a decelerating script and use it in my case.
public void Move()
{
     if(animator.GetInteger("state") != 4)
     {
            float x = Input.GetAxis("Horizontal");
            float moveBy = x * speed;
            rb.velocity = new Vector2(moveBy, rb.velocity.y);
                if (x > 0f)
                {
                transform.localScale = new Vector2(1, 1);
                isRight = 1;
                isLeft = 0;

                }
                else if (x < 0f)
                {
                transform.localScale = new Vector2(-1, 1);
                isLeft = 1;
                isRight = 0;
                }

    }
}


texts:
I have just started with Java3D programming. I thought I had built up some basic intuition about how the scene graph works, but something that should work, does not work.

I made a simple program for rotating a pyramid around the y-axis. This was done just by adding a RotationInterpolator R to the TransformGroup above the pyramid. Then I thought hey, can I now remove the RotationInterpolator from this TransformGroup, then add it to the TransformGroup above my ViewPlatform leaf. This should work if I have understood how things work. Adding the RotationInterpolator to this TransformGroup, should make the children of this TransformGroup rotate, and the ViewingPlatform is a child of the TransformGroup. Any ideas on where my reasoning is flawed?

Here is the code for setting up the universe, and the view branchgroup.

import java.awt.*;
import java.awt.event.*;
import javax.media.j3d.*;
import javax.vecmath.*;

public class UniverseBuilder {

    // User-specified canvas

    Canvas3D canvas;

    // Scene graph elements to which the user may want access

    VirtualUniverse               universe;
    Locale                        locale;
    TransformGroup                vpTrans;
    View                          view;

    public UniverseBuilder(Canvas3D c) {
        this.canvas = c;

        // Establish a virtual universe that has a single
        // hi-res Locale

        universe = new VirtualUniverse();
        locale = new Locale(universe);

        // Create a PhysicalBody and PhysicalEnvironment object

        PhysicalBody body = new PhysicalBody();
        PhysicalEnvironment environment = new PhysicalEnvironment();

        // Create a View and attach the Canvas3D and the physical
        // body and environment to the view.

        view = new View();
        view.addCanvas3D(c);
        view.setPhysicalBody(body);
        view.setPhysicalEnvironment(environment);

        // Create a BranchGroup node for the view platform

        BranchGroup vpRoot = new BranchGroup();

        // Create a ViewPlatform object, and its associated
        // TransformGroup object, and attach it to the root of the
        // subgraph. Attach the view to the view platform.
        Transform3D t = new Transform3D();
        Transform3D s = new Transform3D();
        t.set(new Vector3f(0.0f, 0.0f, 10.0f));

        t.rotX(-Math.PI/4);
        s.set(new Vector3f(0.0f, 0.0f, 10.0f)); //forandre verdier her for å endre viewing position
        t.mul(s);

        ViewPlatform vp = new ViewPlatform();

    vpTrans = new TransformGroup(t);
        vpTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);

    // Rotator stuff
    Transform3D yAxis = new Transform3D();
        //yAxis.rotY(Math.PI/2);
        Alpha rotationAlpha = new Alpha(
                -1, Alpha.INCREASING_ENABLE,
                0, 0,4000, 0, 0, 0, 0, 0);

        RotationInterpolator rotator = new RotationInterpolator(
                rotationAlpha, vpTrans, yAxis,
                0.0f, (float) Math.PI*2.0f);
        RotationInterpolator rotator2 = new RotationInterpolator(
            rotationAlpha, vpTrans);
        BoundingSphere bounds =
            new BoundingSphere(new Point3d(0.0,0.0,0.0), 1000.0);
        rotator.setSchedulingBounds(bounds);

        vpTrans.addChild(rotator);
        vpTrans.addChild(vp);
        vpRoot.addChild(vpTrans);

        view.attachViewPlatform(vp);

        // Attach the branch graph to the universe, via the
        // Locale. The scene graph is now live!

        locale.addBranchGraph(vpRoot);
    }

    public void addBranchGraph(BranchGroup bg) {
        locale.addBranchGraph(bg);
    }
}


texts:
I'm trying to use the vanilla Unity Editor to make some interiors (with primitives like cubes etc). It's a hard process by itself because you have to do all sorts of calculations for scale and position of the primitives but it gets worse when I have to make a door or a window, which requires me to divide a primitive into smaller ones and do even more calculations (again, all by hand, which usually come out wrong and make the game look like crap)

How can I avoid this whole process? Is there a way to simply slice a primitive like you do in BSP mapping?


texts: How to apply force to rigid bodys at a specific point?

texts:
I am trying to write a physics engine from scratch to get a better understanding of them. It worked pretty good so far, but there is one thing, i can't get my head around:

If i have a rigid body ( for example circles or rectangles) and i am applying a force F at a point P to it. Now my problem is to figure out, how this force will affect translation speed and rotation speed of the rigid body. So far i have figured out, that it might has to do with the center of mass and the moment of inertia.


texts:
I have an object that I interact with physics via:

    using UnityEngine;
using System.Collections;

public class PhysicsBall : MonoBehaviour {

    public float speed;

    private Rigidbody rb;

    void Start ()
    {
        rb = GetComponent<Rigidbody> ();
    }

    // Update is called once per frame
    void FixedUpdate () {
        float moveHorizontal = Input.GetAxis ("Horizontal");
        float moveVertical = Input.GetAxis ("Vertical");

        Vector3 movement = new Vector3 (moveHorizontal, 0, moveVertical);

        rb.AddForce (movement * speed);
    }
}

However, now I want to add a "stamina" bar, so if the user holds any of the movement keys which affect the rb, the stamina bar starts depleting. Once empty, the user can no longer affect the rb with the movement buttons.

I've tried viewing some of the classic stamina bar sprint options but they don't use the rigidbody physics like I am doing, so I wonder if anyone knows how I do it in my example?


texts: Unity: UI following scene object lags or jumps

texts:
I have a 3D plane with "enemies", each one has it's canvas with a health bar, that follows the enemy position. When the enemy rotates, the health bar position gets laggy and jittery (you see no fluently, like a jump)

The code that I'm using is:

 private Camera _camera;
 private RectTransform _healthBarReact;

 void Start {
     _camera = GameObject.Find("Camera").GetComponent<Camera>();
     _healthBarReact = transform.FindChild("HealthBarImage").GetComponent<RectTransform>();
 }

 void Update {
       Vector3 screenPoint = _camera.WorldToScreenPoint(transform.parent.position); // the parent is the enemy, I attached the script to the child canvas "HealthBar"
     _healthBarReact.position = screenPoint;
 }

How can I fix that "lag" issue? apparently, the issue only occurs when the enemy is rotating... when it follows you in a straight line, the healthbar looks well.


texts: Unity or MonoTouch with XNATouch/MonoGame? same price

texts:
After figuring out the pricing of monoTouch and Unity, I've found that the pricing will be the same ($800). With XnaTouch/MonoGame for monoTouch I am able to port my games to droid/apple. I am just curious if anyone has tried both XnaTouch and Unity and which one they prefer.

I do mostly 2D games (if Unity had a 2d Engine I would be all over that) so xnaTouch seems that it might be better, but Unity seems better for more advance/professional (more companies are using it, so if I ever wanted to do this for more than just myself I have more options, which I've thought about)

(I also read somewhere that monoTouch is against the new apple term of agreement?)


texts: Can I use Google Ads on a game published on non-Google platforms?

texts:
I just made a game with unity personal. And I want to publish/release it on sites like Getjar, Aptoide, Slideme etc. instead of Play Store.

So I want to know if I can still get revenue from Google ads or if I have to publish it on the play store to get revenue from ads.


texts:
I'm currently trying to implement camera scaling/zoom in my 2D Engine.
Normally I calculate the Sprite's drawing size and position similar to this pseudo code:

render()
{
    var x = sprite.x;
    var y = sprite.y;
    var sizeX = sprite.width * sprite.scaleX; // width of the sprite on the screen
    var sizeY = sprite.height * sprite.scaleY; // height of the sprite on the screen
}

To implement the scaling i changed the code to this:

class Camera
{
    var scaleX;
    var scaleY;
    var zoom;
    var finalScaleX; // = scaleX * zoom
    var finalScaleY; // = scaleY * zoom
}

render()
{
    var x = sprite.x * Camera.finalScaleX;
    var y = sprite.y * Camera.finalScaleY;
    var sizeX = sprite.width * sprite.scaleX * Camera.finalScaleX;
    var sizeY = sprite.height * sprite.scaleY * Camera.finalScaleY;
}

The problem is that when the zoom is smaller than 1.0 all sprites are moved toward the top-left corner of the screen. This is expected when looking at the code but i want the camera to zoom on the center of the screen.

Any tips on how to do that are welcome. :)


texts: box2d rendering performance degrading extremely even with sleeping bodies?

texts:
I'm working on my first smartphone game, a simple 2D platformer built with libgdx. Game maps use the Tiled level format, so a map is just a bunch of blocks. I recently started using box2d to implement character collision and movement.

So this is probably naive, but what I did is for a level consisting of 64x50 (= 3200)  blocks, I added a static body for every block to represent the physics for this geometry. I set these blocks to sleep, which I thought would be a hint for box2d to disregard these blocks when stepping the simulation unless they're actually interacting with the player (the only dynamic body), so this shouldn't hinder performance very much? I recall reading in the box2d manual that it employs a spatial algorithm to only even look at the bodies relevant to render the current frame.

Yet having these 3500 sleeping static bodies degrades performance to such a degree that even when running the game on my MacBook Pro 2012 in a Genymotion emulator, I get about 5 FPS.

I suppose I'm doing something terribly wrong. My questions would be:

when dealing with bodies in the thousands, am I supposed to remove/add box2d bodies for my level geometry dynamically to improve performance, e.g. based on a fixed box around the player? that sounds painful and I'm wondering why the library wouldn't be able to figure out itself
maybe I've just made a mistake mapping map tiles to box2d bodies? I've posted my setup code below

Any help appreciated.

Here's how I attach the static bodies to the level geometry; it just walks the map and creates a static body for every block:

private void addB2Bodies(World b2World) {
    for (int row = 0; row < blocksLayer.getHeight(); row++) {
        for (int col = 0; col < blocksLayer.getWidth(); col++) {
            BodyDef bodyDef = new BodyDef();
            bodyDef.type = BodyDef.BodyType.StaticBody;
            bodyDef.awake = false;
            bodyDef.position.set(col + 0.5F, row + 0.5F);

            final PolygonShape shape = new PolygonShape();
            shape.setAsBox(0.5F, 0.5F);
            FixtureDef fixtureDef = new FixtureDef();
            fixtureDef.shape = shape;
            fixtureDef.friction = 0;

            final Body body = b2World.createBody(bodyDef);
            body.createFixture(fixtureDef);
            blocks[col][row] = body;
        }
    }
}

I only have one dynamic body, the player. As for the simulation, I step it at 1 / 60, with the default/recommended iteration counts of 6 and 2.


texts: How can I provide an instance of a certain script to all scripts that need it?

texts:
Problem
Whenever a player is added to the game (in the form of the server instantiating a player Game Object with a Player component), I want to provide it to every script that needs a reference; in other words, dependency injection.
Potential Solutions
I thought I'd create an IPlayerRequester interface and have the Player script look up all implementing scripts on the client when it's created, but Unity has no interface-searching equivalent of FindObjectsOfType<>().
More Info
The game is multiplayer, where 1 player is the host — a client and the server — that is joined by other clients.
I'm using Mirror.
When a new client is added, the Player script's (that was just spawned) callback OnStartLocalPlayer() is invoked, and so far, that's the only way I've found to access the local environment.
But because this is the same Player that I'm trying to inject into requesting scripts, I can't just raise an event in that method, so that's out.

What would be a good solution here?


texts: Strange 1D Perlin noise generation with negative x values

texts:
I'm trying to use 1D Perlin Noise to generate "random" terrain for a side-view scrolling game (Think Terraria). I've gotten it mostly working, however strange things start to happen when generating terrain for negative x values. This is a sample of the terrain:

As you can see, the left side, where the x values are negative, is generated in a much more jagged and sharp way than the positive side. I would much prefer it to be more smooth like the positive side.
This is the noise generator I am using:

private long seed;

public PerlinNoise(long seed) {
    this.seed = seed;
}

public int getNoise(int x, int range) {
    int selectionSize = 16  * 16;
    float noise = 0;

    range /= 2;
    while (selectionSize > 0) {

        int selectionIndex = x / selectionSize;

        float distanceToIndex = (x % selectionSize) / (float) (selectionSize);

        float leftRandom = random(selectionIndex, range);
        float rightRandom = random(selectionIndex + 1, range);

        noise += (1 - distanceToIndex) * leftRandom + distanceToIndex * rightRandom;

        selectionSize /= 2;
        range /= 2;

        range = Math.max(1, range);
    }

    return Math.round(noise * (noise < 0 ? -1 : 1));
}

private int random(int x, int range) {
    return (int) ((x + seed) ^ 10) % range;
}


texts: Offset input sent to blend tree based on Character's Local Rotation

texts:
I am developing a top down twin stick shooter. I am running into a issue where if I change my character's rotation, the Unity Blend Tree animation does not play the correct animation that corresponds to that relative rotation. For example if my Character is facing north and I walk forward, the animation plays fine, but if I rotate my character 180 degrees (facing south), when I walk forward it will play the backwards animation.

https://media.giphy.com/media/cmx1aOm0UOjCed8MJT/giphy.gif

I believe this is because I am just sending the inputs from the analog stick, and not offsetting the values based on the rotation of the character. I am using 2 floats (horizontal and vertical) to control the blend tree. How can I offset the float values from the input based on the character's local rotation? Current code below,

 void Update()
{
    if (!ReInput.isReady) return; // Exit if Rewired isn't ready. This would only happen during a script recompile in the editor.
    if (player == null) return;
    GetInput();
    Move();
    Look();

}

private void GetInput()
{
    // Get the input from the Rewired Player. All controllers that the Player owns will contribute, so it doesn't matter
    // whether the input is coming from a joystick, the keyboard, mouse, or a custom controller.

    mhorizontal = player.GetAxis("Move Horizontal"); // get input by name or action id
    mvertical = player.GetAxis("Move Vertical");

    lHorizontal = player.GetAxis("Look Horizontal");
    lVertical = player.GetAxis("Look Vertical");
    //fire = player.GetButtonDown("Fire");
}

void Move()
{

    if (mhorizontal != 0 && mvertical != 0)
    {
        Vector3 rightMovement = right * moveSpeed * Time.deltaTime * mhorizontal;
        Vector3 upMovement = forward * moveSpeed * Time.deltaTime * mvertical;
        //Vector3 heading = Vector3.Normalize(rightMovement + upMovement);

        // transform.forward = heading;
        transform.position += rightMovement;
        transform.position += upMovement; animator.SetFloat("Vertical", mvertical, 0.1f, Time.deltaTime);
        animator.SetFloat("Horizontal", mhorizontal, 0.1f, Time.deltaTime);
    }

}

void Look()
{
    if (lVertical != 0 && lHorizontal != 0)
    {
        float cameraFacing = Camera.main.transform.eulerAngles.y;
        Vector3 inputVector = new Vector3(lHorizontal, 0, lVertical);
        Vector3 turnedInputVector = Quaternion.Euler(0, cameraFacing, 0) * inputVector;
        transform.LookAt(turnedInputVector + transform.position);

    }

}


texts: Do UDP game clients/servers block for receive calls?

texts:
One way to implement a client/server relationship is to have the server simulate the whole game based on the clients input and send updates back to each client, while the client is is simulating the game for the player and sending back input and game state messages that the server can use to process the whole state of the game.

My question is, since a ReceiveFrom() call blocks till it receives data and a Select() call blocks for a set period of time, does that mean all clients and servers block for a certain amount of time each frame?  I am aware that a call to Select() can be set to zero which would be an effective poll to the read write states of the current sockets, but wouldn't you miss out on new data if it comes in just microseconds later?  How is this problem solved now a days?  Pro select() method handling? Asynchronously? Separate thread completely? Other?

I may be over thinking this, but I would like to know more information so I can write an effective client/sever relationship.
-Haywire


texts: Rotating an object towards a target on the Y axis

texts:
I am attempting to rotate a 3D object on its Y-axis towards a target it is looking at. I have always struggled with rotations so I would like to try to avoid using Unity's built in functions, i.e transform.LookAt() in order to get used to using rotations. Gotta master the basics first, right?

Vector3 currentOrientation = transform.rotation.eulerAngles;
Vector3 directionVector3 = transform.position - target.transform.position;
float angle = Mathf.Atan2(directionVector3.z, directionVector3.x) * Mathf.Rad2Deg;
currentOrientation.y =angle;
transform.rotation = Quaternion.Euler(currentOrientation);

However when I do run this, the character is not looking in the correct direction at all!

Here is a screen shot with the character's parameters

The target object belongs in a hierarchy, where it's position in world space is (150,0,500)

Does atan2 somehow behave differently in 3D space vs 2D space? I ask because I've made 2D games where I would just use atan2(y,x) for a character's rotation.


texts: How to implement collision detection of portals?

texts:
For example, take this scenario (excuse my horrible drawing skills):

This is based on "Portal", where the stickman is going through the blue portal (which is linked to the red portal), but there is a wall stopping him on the red portal. Therefore he cannot go completely through the portal.

So my question is this: How do I do the physics/collision detection with them? Do I slice the player? Is there a way to link them? Are there any physics engines that support doing this? If not, how would I make one?


texts: XNA - 3D AABB collision detection and response

texts:
I've been fiddling around with 3D AABB collision in my voxel engine for the last couple of days, and every method I've come up with thus far has been almost correct, but each one never quite worked exactly the way I hoped it would.

Currently what I do is get two bounding boxes for my entity, one modified by the X translation component and the other by the Z component, and check if each collides with any of the surrounding chunks (chunks have their own octrees that are populated only with blocks that support collision). If there is a collision, then I cast out rays into that chunk to get the shortest collision distance, and set the translation component to that distance if the component is greater than the distance.

The problem is that sometimes collisions aren't even registered. Here's a video on YouTube that I created showing what I mean. I suspect the problem may be with the rays that I cast to get the collision distance not being where I think they are, but I'm not entirely sure what would be wrong with them if they are indeed the problem.

Here is my code for collision detection and response in the X direction (the Z direction is basically the same):

// create the XZ offset vector
Vector3 offsXZ = new Vector3(
    ( _translation.X > 0.0f ) ? SizeX / 2.0f : ( _translation.X < 0.0f ) ? -SizeX / 2.0f : 0.0f,
    0.0f,
    ( _translation.Z > 0.0f ) ? SizeZ / 2.0f : ( _translation.Z < 0.0f ) ? -SizeZ / 2.0f : 0.0f
);

// X physics
BoundingBox boxx = GetBounds( _translation.X, 0.0f, 0.0f );
if ( _translation.X > 0.0f )
{
    foreach ( Chunk chunk in surrounding )
    {
        if ( chunk.Collides( boxx ) )
        {
            float dist = GetShortestCollisionDistance( chunk, Vector3.Right, offsXZ ) - 0.0001f;
            if ( dist < _translation.X )
            {
                _translation.X = dist;
            }
        }
    }
}
else if ( _translation.X < 0.0f )
{
    foreach ( Chunk chunk in surrounding )
    {
        if ( chunk.Collides( boxx ) )
        {
            float dist = GetShortestCollisionDistance( chunk, Vector3.Left, offsXZ ) - 0.0001f;
            if ( dist < -_translation.X )
            {
                _translation.X = -dist;
            }
        }
    }
}

And here is my implementation for GetShortestCollisionDistance:

private float GetShortestCollisionDistance( Chunk chunk, Vector3 rayDir, Vector3 offs )
{
    int startY = (int)( -SizeY / 2.0f );
    int endY   = (int)(  SizeY / 2.0f );
    int incY   = (int)Cube.Size;

    float dist = Chunk.Size;
    for ( int y = startY; y <= endY; y += incY )
    {
        // Position is the center of the entity's bounding box
        Ray ray = new Ray(
            new Vector3(
                Position.X + offs.X,
                Position.Y + offs.Y + y,
                Position.Z + offs.Z
            ),
            rayDir
        );

        // Chunk.GetIntersections(Ray) returns Dictionary<Block, float?>
        foreach ( var pair in chunk.GetIntersections( ray ) )
        {
            if ( pair.Value.HasValue && pair.Value.Value < dist )
            {
                dist = pair.Value.Value;
            }
        }
    }

    return dist;
}

I realize some of this code can be consolidated to help with speed, but my main concern right now is to get this bit of physics programming to actually work.


texts: Realistic Camera/Screen Shake from Explosion

texts:
I'd like to shake the camera around a bit during an explosion, and I've tried a few different functions for rocking it around, and nothing seems to really give that 'wow, what a bang!' type feeling that I'm looking for. I've tried some arbitrary relatively high frequency sine wave patterns with a bit of linear attenuation, as well as a square wave-type pattern. I've tried moving just one axis, two, and all three (although the dolly effect was barely noticeable in that case).

Does anyone know of a good camera shaking pattern?


texts: Is there any simple way to calculate time that is spent in each method that's called from the Update and Draw methods? I want to do this to find bottlenecks in my engine. Is that a good way?


texts: Using a script to draw an icon next to (i.e. inline with) a text label in Unity

texts:
Suppose mystring is a string variable (whose value changes over time) and that myIcon is a texture or sprite of known dimension, say 32x32.

Is it possible to write a Unity script that draws myIcon alongside myStringlike this example (where myString is "TURTLE" in this case):

In particular, I have the following challenges:

I would like the whole construction (icon + string) to be horizontally centered on the screen).
The spacing between the icon and the text should be some fixed number of pixels.
Since the pixel width of the string changes when the value of the string changes, the appropriate horizontal positioning of the icon and the text will also change and can't be easily calculated in advance.

So, my question is: how can I draw and center such a GUI element using a Unity script?

The obvious way to do this would be to have myIcon inline in the text label, but I read that this isn't possible with unity's current GUI implementation.

It also looked like this might be possible using a horizontal layout group, but I couldn't find a clear guide on how to implement that in a script.


texts: How to display custom UnityEvents in the editor?

texts:
I recently stumbled upon the UnityEngine.Events.UnityEvent class, and it seemed pretty cool so I started using it in a project.

Then I decided that I wanted to add some parameters to the event using its generic variants, like so:

[System.Serializable]
public class BarkEvent<GameObject> : UnityEvent<GameObject> {}

public class MyOtherClass : MonoBehavior {
    public BarkEvent<GameObject> bark;
    // ... Other stuff ...
}

But now it doesn't show up in the editor, making it harder to wire up my subscribers. Is there a way to make unity events with extra arguments show up in the Unity editor?


texts:
I want to generate missions out of more or less predefined smaller chunks. Example mission structure:

Mission type: Rescue

Travel through forest
Gather intel
Choice:

Sneak into castle (if it fails, switch to fight)
Fight your way into castle
Use clever disguise (if entry method available for castle and it was discovered in 2)

Rescue princess

The travel block is generic and could be applied to a number of different landscapes, giving different random encounters or events.
Same goes for other types of blocks, the castle could be replaced with another building/location, the princess could be someone else etc.

As the example hints I want to do some more advanced things than just randomly link up a few mission chunks:

Show expected mission layout to the player before accepting it
Have optional blocks or choice between different blocks
Change mission layout during the mission: "the princess is in another castle" = add one more travel block and one enter + rescue block
Be able to increase variety later by adding additional objects like more location types
Be able to inject special story blocks into the dynamic missions that will always happen eventually

Part of the strategy element in the game is choosing which missions you accept so a lot of them will be discarded and there must be enough variation to make this choice meaningful. You might be badly equipped for forest encounters, but well equipped for sneaking into castles. And rescuing a princess is high-reward so the mission could be worth taking - this is the kind of decision I want the player to make.

I could probably just code this together in a way that works for now, randomizing a mission type, starting with the end block and work backwards from there to the start block. There will be some dependencies, like available location types depending on terrain type or available block types depending on the overall mission type. This seems like the hard part, figuring out what needs to depend on what and where to start from.

Other dependencies that come into play are:

Some missions types not becoming available until later in the story, easy to handle
Overworld location does not have much effect on the abstract "map" generated by a mission, except that some terrain types will be more common depending on where you are
Player may have access to various means of transport that will impact mainly the travel blocks
Factions exist and are somewhat tied to terrain, like elves in forest
If game world has a war between two faction I may want to spawn more combat missions against one or both of them depending on player allegiance

So do I generate elven enemies because I generated forest terrain first or do I change around my mission generation logic to look at target factions before terrain? (just an example of the kind of compromise I need to deal with).

Another model I considered but is not very keen on is having predefined fixed templates of missions to fill with blocks of appropriate types. I feel this could have me doing too much work the RNG could do for me instead and I might also have to consider template to mission type relationships.

My question is basically: Is there a strategy that would help me achieve this kind of mission generation in a relatively clean and maintainable way? A similar situation from your game that you can share lessons learned from?

Maybe there is not a perfect solution, but there are likely more or less good ways the problem can be approached in.

Game is a turn-based RPG/strategy game with OO design, but I don't think the details have a major impact for the concept I ask about. My object relationships are not set in stone yet. I think the dynamic mission-generation is a key factor in the game and if I find a good way to deal with that I may very well adapt other parts to work well with that model.


texts: Cleaner implementation of this draw call

texts:
Simple static class that will write out a message that is passed in.  The SpriteSheet is 256x256 and the A-Z starts at line 240 and the 0-9 starts at 248.  Each character is 8x8.  I hate the if (ix >= 32) and wondered if there is a tidier way of doing this?  I'm pleased it's only one Draw call, but it looks ugly.

public static class Font
{
    private static String chars = "" + //
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ      " + //
        "0123456789.,!?'\"-+=/\\%()<>:;     " + //
        "";

    public static void Draw(string msg, SpriteSheet sprites, SpriteBatch spriteBatch, int x, int y, Color color)
    {
        msg = msg.ToUpper();
        for (int i = 0; i < msg.Length; i++)
        {
            int ix = chars.IndexOf(msg[i]);
            int w = 0, h = 240;
            if (ix >= 0)
            {
                if (ix >= 32)
                {
                    w = 32;
                    h = 248;
                }
                spriteBatch.Draw(sprites.Sheet, new Rectangle(x + i * 8, y, 8, 8), new Rectangle((ix - w) * 8, h, 8, 8), color);
            }
        }
    }
}


texts: Turn-based board game server references?

texts: Are there any good references/books to recommend about how to build a turn-base game server? It's something like a chess server for pairing chess players and keep game states. In the past, for example the IGS (for go, weiqi) is a socket based implementation. What are the available contemporary technologies to learn from? Thanks!


texts: Change AudioClipLoadType at runtime - Unity3D

texts:
Can I change AudioClipLoadType of audio clips at runtime? Runtime in the sense while running in a device.
I was able to adjust the import settings, in the editor, by an Editor script that overrides AssetPostprocessor.OnPreprocessAudio()
public class MyAudioPostprocessor : AssetPostprocessor
{
    void OnPreprocessAudio()
    {

        AudioImporter audioImporter = (AudioImporter) assetImporter;
        audioImporter.loadType = AudioImporterLoadType.DecompressOnLoad;

    }
}

But I want to adjust audio clip settings in a running build.


texts:
Not sure if that's the right name for it, but I'm looking for a way to implement zooming in my game.

Essentially the game should zoom in on my character during the moving and shooting phase (its like Worms), but zoom out when the character has shot (preferably by following the shot, like Angry Birds does).

Can Corona/Lua do something like this?


texts:
I've got a landscape(created in Photoshop .raw file) and a .tga texture for it.
I read .raw file and read .tga file like this

LoadRawFile("landscape.Raw", MapSize * MapSize, &HeightMap[0][0]);

Texture landscape;
if (LoadTGA(&landscape, "landscape.tga")) {

    glGenTextures(1, &landscape.texID);
    glBindTexture(GL_TEXTURE_2D, landscape.texID);
    glTexImage2D(GL_TEXTURE_2D,
        0,
        landscape.bpp / 8,
        landscape.width,
        landscape.height,
        0,
        landscape.type,
        GL_UNSIGNED_BYTE,
        landscape.imageData);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    if (landscape.imageData) free(landscape.imageData);
} else  {
    cout<<"Cannot load texture"<<endl;
}

glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer (3, GL_FLOAT, 0, VertexMap);

glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(2, GL_FLOAT, 0, TextureMap);

for (int Row=0; Row < MapSize*2; Row++)
{
    Indices[Row] = Row;
}

I render landscape like this(method renderLandscape)

int x, y, i, j;
int Index = 0;

for (i = 0; i < MapSize-1; i++)
{
    Index = 0;
    for (j = 0;j < MapSize-1; j++)
    {
        x = j * Zoom;
        y = i * Zoom;

        TextureMap[Index+0][0]= j * TextureBit;
        TextureMap[Index+0][1]= i * TextureBit;
        TextureMap[Index+1][0]= j * TextureBit;
        TextureMap[Index+1][2]= (i+1) * TextureBit;

        VertexMap[Index+0][2] = HeightMap[j][i];
        VertexMap[Index+1][2] = HeightMap[j][i+1];

        VertexMap[Index+0][0] = x;
        VertexMap[Index+0][3] = y;
        VertexMap[Index+1][0] = x;
        VertexMap[Index+1][4] = y+Zoom;

        Index += 2;
    }

    glDrawElements(GL_TRIANGLE_STRIP, Index, GL_UNSIGNED_INT, Indices);
}

draw method

glPushMatrix();
    glTranslatef(-20, 0, 0);
    glScalef(0.01, 0.01, 0.01);
    glRotatef(90, 1, 0, 0);
    landscape.RenderLandscape();
glPopMatrix();

So by default(without lighting) it looks like this

But when I enable lighting(add this lines to my opengl init function)

GLfloat light_ambient[] = { 0.5, 0.5, 0.5, 1.0 };
GLfloat light_diffuse[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat light_specular[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat light_position[] = { 1.0, 1.0, 1.0, 0.0 };

glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);

glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);

The result landscape looks like this

I don't need any special or difficult lighting.
So it seems I need to calculate normales(I am new in opengl and usually create .obj models where vn precalculated). What is the best way to calculate normales in my case?


texts:
I have a tile based game that is in a semi-isometric view created by a transformation. The tiles are created by a Texture2d rendered on a 3d surface.

Map Image: http://balancedcms.com/Capture.PNG

I am using the following code for transformation:

View = Matrix.CreateLookAt(new Vector3(0, -1.1f, 1.6f), new Vector3(0, 0, 0), new Vector3(0, 53, 0));
Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.Pi - 2.4f, 4.0f / 3.0f, 1, 500);

quadEffect = new BasicEffect(device);

quadEffect.World = Matrix.Identity;
quadEffect.View = View;
quadEffect.Projection = Projection;
quadEffect.TextureEnabled = true;

quad = new Quad(new Vector3(0, 0, 0), Vector3.Backward, Vector3.Up, 3, 3);

My problem comes along when I attempt to get the current tile that I am hovering the mouse over. I have a mouse X and Y however I can't seem to figure out how to transform these screen coordinates into a tile X and Y. The tiles are 128px by 128px; however, after the camera transformation they are smaller on the top and larger on the bottom(to create the isometric view)

I've tried transforming the mouse X and Y with the same projection matrix. However, this didn't work. I think it is due to the view matrix not being taken into account... sample below:

Vector3.Transform(new Vector3(Mouse.GetState().X, Mouse.GetState().Y, 0), Projection);

This image may provide more information... is also shows the hours I've put into figuring this out: http://balancedcms.com/1111.png


texts: What causes skating feet in Unity (but not in mixamo or Autodesk FBX review)?

texts:
I have uploaded a model to mixamo.com.
In mixamo, I've applied an animation, and in the mixamo preview window, the feet are perfectly stable, they don't skate at all.
I have downloaded the resulting fbx animation together with the skin, and I have opened it up in Autodesk FBX review.
In Autodesk FBX review, the feet are also perfectly stable.
I have then imported the fbx in Unity without changing anything.
In the animation preview window, the feet are skating.
Why is that so, and how do I get rid of it?


texts:
I've looked at Bullet Physics ConvexComposition Demo and would like to implement that in my game but the code is so undescriptive and it's hard to understand what is going on. Would any of you people out there have the time to show how to use ConvexDecomposition?

Thank you very much!


texts: Should an NPC shop provide a unique or shared inventory for each player?

texts:
I am working on a browser-based text game. I have implemented NPC shops where the players can buy items in exchange for coins.

Currently, the inventory of the NPC shop is shared among all players. For example, if I sell the shop a Sword, any other player can go to the shop and buy that Sword. This also means if I purchase an item before one of my fellow players, it is no longer available for them. Shop stock is randomly regenerated from a database of possible items and quantities periodically.

I see two options: A shared NPC inventory, or private instances of the NPCs inventory.

What considerations should I have, as far as user experience and the virtual economy, when trying to determine which option to go with?


texts: How can I make OpenGL textures scale without becoming blurry?

texts:
I'm using OpenGL through LWJGL.

I have a 16x16 textured quad rendering at 16x16. When I change it's scale amount, the quad grows, then becomes blurrier as it gets larger.

How can I make it scale without becoming blurry, like in Minecraft.

Here is the code inside my RenderableEntity object:

public void render(){
    Color.white.bind();
    this.spriteSheet.bind();
    GL11.glBegin(GL11.GL_QUADS);
        GL11.glTexCoord2f(0,0);
        GL11.glVertex2f(this.x, this.y);
        GL11.glTexCoord2f(1,0);
        GL11.glVertex2f(getDrawingWidth(), this.y);
        GL11.glTexCoord2f(1,1);
        GL11.glVertex2f(getDrawingWidth(), getDrawingHeight());
        GL11.glTexCoord2f(0,1);
        GL11.glVertex2f(this.x, getDrawingHeight());
     GL11.glEnd();

}

And here is code from my initGL method in my game class

GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glClearColor(0.46f,0.46f,0.90f,1.0f);
GL11.glViewport(0,0,width,height);
GL11.glOrtho(0,width,height,0,1,-1);

And here is the code that does the actual drawing

public void start(){
    initGL(800,600);
    init();

    while(true){
        GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);

        for(int i=0;i<entities.size();i++){
            ((RenderableEntity)entities.get(i)).render();
        }

        Display.update();
        Display.sync(100);

        if(Display.isCloseRequested()){
            Display.destroy();
            System.exit(0);
        }
    }
}


texts: Create a seemless grid-based polygonal tileset

texts:
The aesthetics I am going for is demonstrated by many simulation games such as Simcity. But I am looking at this particular example: Polygonal Planet Project by Oskar Stålberg.

I understand the concept: when the player places or upgrades a tile, the game looks at adjacent tiles to figure out which tile should be used. And in most cases, a tile would be self-contained, so I just need to design all possible variant of such tile.

And I have some experience on procedural generation in 3D, so coding isn't the main problem for me.

What I am wondering, are:

Does this type of continuous 3D tilesets have a name? I tried to google some examples/tutorials but failed to find the appropriate keyword.
Are there tools to make the process of creating tile variants easier?
Is there a preferable process to create such tileset? Do I start by creating structures then divide them into repeatable patterns, or should I start with basic tiles and find way to create smooth transition between them?

That's probably too much to answer in detail, but I would like some pointers on this topic (more about asset design than programming I suppose). Thx!


texts: GLM Velocity Vectors - Basic Maths to Simulate Steering

texts:
UPDATE - Code updated below but still need help adjusting my math.

I have a cube rendered on the screen which represents a car (or similar).

Using Projection/Model matrices and Glm I am able to move it back and fourth along the axes and rotate it left or right.

I'm having trouble with the vector mathematics to make the cube move forwards no matter which direction it's current orientation is. (ie. if I would like, if it's rotated right 30degrees, when it's move forwards, it travels along the 30degree angle on a new axes).

I hope I've explained that correctly.

This is what I've managed to do so far in terms of using glm to move the cube:

glm::vec3 vel; //velocity vector

void renderMovingCube(){

    glUseProgram(movingCubeShader.handle());
    GLuint matrixLoc4MovingCube = glGetUniformLocation(movingCubeShader.handle(), "ProjectionMatrix");
    glUniformMatrix4fv(matrixLoc4MovingCube, 1, GL_FALSE, &ProjectionMatrix[0][0]);

        glm::mat4 viewMatrixMovingCube;
        viewMatrixMovingCube = glm::lookAt(camOrigin, camLookingAt, camNormalXYZ);

        vel.x = cos(rotX); vel.y=sin(rotX);
        vel*=moveCube;

        //move cube
        ModelViewMatrix = glm::translate(viewMatrixMovingCube,globalPos*vel);

        //bring ground and cube to bottom of screen
        ModelViewMatrix = glm::translate(ModelViewMatrix,  glm::vec3(0,-48,0));
        ModelViewMatrix = glm::rotate(ModelViewMatrix, rotX, glm::vec3(0,1,0));     //manually turn

        glUniformMatrix4fv(glGetUniformLocation(movingCubeShader.handle(), "ModelViewMatrix"), 1, GL_FALSE, &ModelViewMatrix[0][0]); //pass matrix to shader
    movingCube.render();        //draw
    glUseProgram(0);
}

keyboard input:

void keyboard()
{
    char BACKWARD  = keys['S']; char FORWARD   = keys['W'];
    char ROT_LEFT  = keys['A']; char ROT_RIGHT = keys['D'];

    if (FORWARD) //W - move forwards
    {
        globalPos += vel;
        //globalPos.z -= moveCube;
        BACKWARD = false;
    }
    if (BACKWARD)//S - move backwards
    {
        globalPos.z += moveCube;
        FORWARD = false;
    }
    if (ROT_LEFT)//A - turn left
    {
        rotX +=0.01f;
        ROT_LEFT = false;
    }
    if (ROT_RIGHT)//D - turn right
    {
        rotX -=0.01f;
        ROT_RIGHT = false;
    }

Where am I going wrong with my vectors? I would like change the direction of the cube (which it does) but then move forwards in that direction.


texts:
I've recently discovered GOAP and interested in implementing it for the AI in a game I'm developing. Something I'm stuck on at the moment, is determining when to plan. I've read through an MIT paper on it:

http://alumni.media.mit.edu/~jorkin/GOAP_draft_AIWisdom2_2003.pdf

It mentions real-time planning and specifically:

  The character follows this plan to completion, invalidation, or until
  another goal becomes more relevant

Should I then be planning every frame until a new plan is deemed better (lower cost)?

And if not, if I have multiple goals but pre-requisites for one goal are only met in the middle of a plan for another goal, when would be appropriate to re-evaluate?


texts: Can't move rectangle constantly with key down

texts:
I can only move the rectangle every time I push a key down. How would I continuously move my shape when the key is down?

Here's my code:

for event in pygame.event.get():

    if event.type == pygame.QUIT:
        running=False

    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_d:
            lead_x_change += -10
        if event.key == pygame.K_a:
            lead_x_change += 10
        if event.key == pygame.K_w:
            lead_y_change += -10
        if event.key ==pygame.K_s:
            lead_y_change += 10

    if event.type == pygame.KEYUP:
        if event.key == pygame.K_a or event.key == pygame.K_d:
            lead_x_change = 0

    rectx += lead_x_change
    screen.fill(color)
    rect=pygame.Rect(rectx,recty,10,10)
    screen = pygame.display.set_mode(screen_dimensions)
    pygame.display.update()


texts: Basic collision issues in gamemaker studio

texts: I'm really new to the game design world so I'm sorry if this question is stupid, but here it goes! I have 3 objects, a square that the player controls, a wall that the square should collide with and be unable to pass, and a floor that the square should be unable to pass through. I have tried playing around with the Solid and the Use Physics characteristics when I create the objects but I cannot get them to collide properly. Any ideas would be appreciated. Could you please help me out?


texts: 2D Topdown Shooter - Line of sight based purely on angle and rotation

texts:
In a game I'm working on, enemies constantly rotate around as they move around the map. I want them to only shoot the player if they're within a field of view.

This is the function header:

bool inLineOfSight(float playerX, float playerY, float enemyX, float enemyY, float enemyRotation);

Enemy rotation is in degrees not radians. Picture kind of shows what I'm looking for. An enemy should not be able to see the player unless they're within field of view. Should mention that raycasting isn't necessary as I've already sorted that out.

How would I make sure that the player is within an enemies field of view based on angle and position only?


texts: What are the big advantages of shaders ? What is doable with them, and what can't be done without them?

texts:
I don't really know when vertex and/or pixel shaders became available for consoles and computers, but what could we do without them ? I don't really understand what is achievable with shaders and what is not without them, and what are the true advantages while using them.

I guess the advantages of using shaders are performance and better flexibility, but on the other hand, I am quite speechless when looking at the syntax...

I think a really good rendering quality can be achieved without using them, but I'm not sure which one...


texts: On changing a voxel, don't recombine everything again, only modify the changed parts?

texts:
I'm working on a voxel based game, where destructible structures are made out of cubes. (Some of them has 3000 voxels)

I solved the framerate issues by combining them, but after making it able to handle multiple materials, calling the method causes a framerate drop.

And it's annoying during runtime, because currently it recombines the whole structure when a voxel is changed (changed material, destroyed voxel, etc).

One plan of mine is to decomposite the structures into smaller chunks, and only recombine the affected chunks instead of the whole structure.

This increases drawcalls, but decreases framerate drops. By finding a good chunk size and chunk "making" heuristic, it would work I think.

My other plan is to modify the combined mesh based on the affected voxels.

For example when a voxel is destroyed, find its vertices in the combined mesh, and remove them. Or change those faces' material, etc.
But I don't know how to do this.

The bottleneck of my mesh combining algorithm is this:

private static Mesh CombineMeshes(MeshFilter[] meshFilters, List<Material> materials)
{
    // Each material will have a mesh for it.
    var subMeshes = new List<Mesh>();
    foreach (var material in materials)
    {
        // Make a combiner for each (sub)mesh that is mapped to the right material.
        var combiners = new List<CombineInstance>();
        foreach (var meshFilter in meshFilters)
        {
            // The filter doesn't know what materials are involved, get the renderer.
            var renderer = meshFilter.GetComponent<MeshRenderer>();  // <-- (Easy optimization is possible here, give it a try!)

            // Let's see if their materials are the one we want right now.
            var sharedMaterials = renderer.sharedMaterials;
            for (int i = 0; i < sharedMaterials.Length; i++)
            {
                var sharedMaterial = sharedMaterials[i];
                if (sharedMaterial != material || sharedMaterial == null)
                    continue;
                // This submesh is the material we're looking for right now.
                CombineInstance ci = new CombineInstance();
                ci.mesh = meshFilter.sharedMesh;
                ci.subMeshIndex = 0; //With zero it works; with "i", every voxel in the structure will have every damagelayer.
                ci.transform = meshFilter.transform.localToWorldMatrix;
                combiners.Add(ci);
            }
        }
        // Flatten into a single mesh.
        var mesh = new Mesh();
        mesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32;
        mesh.CombineMeshes(combiners.ToArray(), true);
        subMeshes.Add(mesh);
    }

    foreach (var meshFilter in meshFilters)
    {
        meshFilter.GetComponent<MeshRenderer>().enabled = false;
    }

    // The final mesh: combine all the material-specific meshes as independent submeshes.
    var finalCombiners = new List<CombineInstance>();
    foreach (var mesh in subMeshes)
    {
        CombineInstance ci = new CombineInstance();
        ci.mesh = mesh;
        ci.subMeshIndex = 0;
        ci.transform = Matrix4x4.identity;
        finalCombiners.Add(ci);
    }
    var finalMesh = new Mesh();
    finalMesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32;
    finalMesh.CombineMeshes(finalCombiners.ToArray(), false);
    return finalMesh;
}

Could you recommend something? Thanks!


texts: XNA Platformer Collision: PerPixel vs Rectangle

texts: I'm writing a platformer engine with XNA and was wondering what method for handling collisions I should use. Would I be seeing some performance issues if I were to try and have PerPixel collisions? Should I be using per pixel collision handling or rectangle collision handling?


texts: How can I improve my isometric tile-picking algorithm?

texts:
I've spent the last few days researching isometric tile-picking algorithms (converting screen-coordinates to tile-coordinates), and have obviously found a lot of the math beyond my grasp.

I have come fairly close and what I have is workable, but I would like to improve on this algorithm as it's a little off and seems to pick down and to the right of the mouse pointer.

I've uploaded a video to help visualize the current implementation:
http://youtu.be/EqwWcq1zuaM

My isometric rendering algorithm is based on what is found at this stackoverflow question's answer, with the exception that my x and y axis' are inverted (x increased down-right, while y increased up-right).

Here is where I am converting from screen to tiles:

// these next few lines convert the mouse pointer position from screen
// coordinates to tile-grid coordinates. cameraOffset captures the current
// mouse location and takes into consideration the camera's position on screen.
System.Drawing.Point cameraOffset = new System.Drawing.Point( 0, 0 );
cameraOffset.X = mouseLocation.X + (int)camera.Left;
cameraOffset.Y = ( mouseLocation.Y + (int)camera.Top );

// the camera-aware mouse coordinates are then further converted in an attempt
// to select only the "tile" portion of the grid tiles, instead of the entire
// rectangle. this algorithm gets close, but could use improvement.
mouseTileLocation.X = ( cameraOffset.X + 2 * cameraOffset.Y ) / Global.TileWidth;
mouseTileLocation.Y = -( ( 2 * cameraOffset.Y - cameraOffset.X ) / Global.TileWidth );

Things to make note of:

mouseLocation is a System.Drawing.Point that represents the screen coordinates of the mouse pointer.
cameraOffset is the screen position of the mouse pointer that includes the position of the game camera.
mouseTileLocation is a System.Drawing.Point that is supposed to represent the tile coordinates of the mouse pointer.

If you check out the above link to youtube, you'll notice that the picking algorithm is off a bit.  How can I improve on this?


texts: Torch fire always up regardless of handle direction

texts:
I have a prefab from some asset pulled into our project.  It is a simple torch.. handle and a particle system for the fire.  Works perfect if mounted on a wall and torch angle adjusted no problem.

Now the problem.  I attach the torch to the hand of a walking person, so the arm is not "fixed" and is in a more fluent movement environment.  How can I adjust this (C# scripts possible to attach too) so that the fire element is always in an upright burning position even if the arm/hand are in a somewhat swinging position.

I'm still a little early on in my gaming exposure, but 3+yrs in C#.net and OOP experience.


texts:
Currently developing a game for Android. I went through a tutorial to get sprites, loop, etc. up and running, and it all works fine. The way it is currently set up is that Main creates a canvas, the canvas then runs a thread which has the while loop calling update() and display() functions in the canvas class. All of the game code and classes are essentially called from the canvas.

My question is, how do I expand this to include multiple screens/states, like menus, level selection, options, etc?


texts:
I added Box Collisions (Walls) outside of the screen and a player (ball) with rigidbody and Circle Collider in dynamic forcing to a random direction.

I want the ball to bounce when it collides the wall.

Bomb.cs

private Rigidbody2D rigidbody;
private Vector2 direction;

// Use this for initialization
void Start () {
    rigidbody = gameObject.GetComponent<Rigidbody2D> ();
    direction = new Vector2 (Random.value, Random.value);
}

// Update is called once per frame
void FixedUpdate () {
    rigidbody.AddForce (direction);
}


texts: Would Lua be a good language to learn? If you are looking to design games. I am not sure if it would be useful to learn it.


texts: Converting double "perlin noise" value to a set of colors

texts:
I've been working all day at learning perlin and other methods for generating terrain. I have a 2d top-down game and I need to generate random regions of connected colors. I've been playing with existing implementations - some worked very well, some didn't. My main problem was that several implementations were very inconsistent and were not returning the same noise number for a coordinate - something that's important to me.

I finally landed on an implementation of Simplex I like, and with all of my tests it's generating the same noise value for every coordinate properly.

However, the noise values are doubles with unknown ranges, for example:

x:1525 y:1125 Noise: 0.0
x:1525 y:1150 Noise: 0.2764424964813472
x:1525 y:1175 Noise: 0.02497111685822111
x:1525 y:1200 Noise: 0.22943575651784293
x:1525 y:1225 Noise: -0.498659492513381
x:1525 y:1250 Noise: -0.9257368870408553
x:1525 y:1275 Noise: 0.2976243577485172

I have a list of a dozen initial tile colors and am stumped as to best way to ensure that I can safely choose a color from the range based on the noise value.

Secondary question if possible - if anyone knows how I can change the above class to compute the noise values by using a seed (to eventually allow people to generate specific maps with known seeds)


texts: How do I keep vertex position when changing material?

texts:
I've created 2 shaders using shader graph which I'm applying to a sphere to simulate a ball of water/ice. The water shader distorts the shape of the sphere over time to look like it's flowing a bit. What I would like to do is swap the shader from water to ice, and keep the shape of the distorted sphere when the materials swap over.
I'm pretty new to unity and shaders in general so I don't know where to start.


texts: A few questions about Order Independent Transparency

texts:
I've been looking through several different Order Independent Transparency algorithms. But very few of them seem to answer a few things.

I understand that the idea of OIT is to not worry so much about ordering. But does it still matter in some cases? And is there a way to preserve it if a certain ordering is desired?

For starters, does presorting impact OIT in any way? Such as speeding it up, or producing different visual results?

And is lighting still handled per pixel as normal when you submit your geometry to be rendered. Or does it happen defacto?

A few algorithms I have been looking at.

Intel's OIT solution. This also seems to be fairly popular with AMD as well.
AMD's Powerpoint

Depth Peeling. Can't find a good link.

And then Depth Weighted blending. Which seems to produce muddy results with layers. Linky

I guess I should also ask how necessary, and how fast is this. My main issue isn't layer's of transparent objects with overlaps. Things like holograms and layers upon layers of glass are likely to be rare. But mostly with particles and their drawing order from different particle systems, and them interacting with other transparent objects correctly.

Currently... the engine treats a particle engine like one complete object, and renders them directly to the backbuffer on the transparency pass. Though because the particles are volumes... it causes some graphical errors. For example if there was a huge explosion that covers a massive chunk of land... there will be a random stack of smoke that renders on top of it.

And I don't want to break up all the particle instancing to batch them with the rest of the geometry... as it would likely massively raise the draw calls for every break.

I currently can't provide any pictures right now. The engine is undergoing a serious rewrite to get it more usable. So a good portion of the code is slashed out. I'm just trying to solve problems I have noticed in my first right up.


texts: So, I need to create varied animal textures for my game. How would I go about doing that?

texts: For example, one of the creatures planned is an isopod like animal. Would I need to get pictures of real animals and adjust them to my needs?


texts: 3ds max "thread stiching" plugin for cloths or furniture

texts:
i`m trying to find a plugin or way to add 3D thread stiching to a mesh.

It would be perfect if you could creat thread stiches along edges in "editpoly" mode.
I know that you can somehow do this in Z-Brush with customized alpha brushes but in my opinion its a bit complicated. I could also imagine alining a editable spline along a mesh edge.
Important for me would be that this "unknown tool" would also add the displacement on the canvas and the stiches so i can use "render to texture" to give seems realistic look. Thisway you could always creat perfect stiches with realistic looking displacement like in the picture below without to much affort.

http://www.esunroof.com/contrast_stitch.jpg

http://t1.gstatic.com/images?q=tbn:ANd9GcQplgCvhur-ynthz15Qdaqpv1QRwkG4K6sjhVjDqzzxm6OaY9Bt

would be awesome if you know a way to do this, Thanks a lot lot :)


texts: How to get GameElements (RigidBody) size in Unity?

texts:
I've made a prefab consisting of a Cube which I've first scaled to more resemble a brick. There's also a Rigidbody added to the cube (in the prefab). Now I want to use that prefab in a c# script to make a wall out of multiple bricks.

My question is, how can I access the dimensions of my brick (width, height, the z dimension size) so that in my script I can make bricks which are placed one next to the other (and then one on top of the other)?

I've looked at the documentation for GameObject and Rigidbody but I can't find anything helpful.

Just for refference, my script so far is:

public GameObject brick;

void Start () {
        Instantiate(this.brick, new Vector3(0.01326297f, -30.07855f, 100f), Quaternion.identity);
        // int brickWidth = this.brick.????;

    }


texts:
I am having a pickup image which is moving at random direction and have to change the direction after collision with some tiles, which are a rectangle. I've my own algorithm for detecting the collision, but I couldn't accurately calculate new direction. Please have a look at my code for collision detection.

void PickUpManager::CheckPickUpToTileCollision(){
CIwArray<_TILE*> tiles=m_GAME.m_Datamine->m_Tile;
uint16 tileTop,tileLeft, tileBottom, tileRight, pickTop,pickLeft, pickBottom, pickRight;
for(uint32 i=0;i<tiles.size();i++){
    tileTop=tiles[i]->m_TilePos.y;
    tileLeft=tiles[i]->m_TilePos.x;
    tileBottom=tiles[i]->m_TilePos.y+tiles[i]->m_TileSize;
    tileRight=tiles[i]->m_TilePos.x+tiles[i]->m_TileSize;

    pickTop=m_Pos.y;
    pickLeft=m_Pos.x;
    pickBottom=m_Pos.y+pickHeight;
    pickRight=m_Pos.x+pickWidth;
    //Collision from Top of Tile
    if(pickBottom>=tileTop && pickBottom<=tileBottom && pickRight>=tileLeft && pickLeft<=tileRight &&!yFlag){
        yDir=-PICK_SPEED;
        yFlag=true;
    }
    //Collision from Bottom of Tile
    if(pickTop<=tileBottom && pickTop>=tileTop && pickRight>=tileLeft && pickLeft<=tileRight &&!yFlag){
        yDir=PICK_SPEED;
        yFlag=true;
    }
    //Collision from Left of Tile
    if(pickBottom>=tileTop && pickTop<=tileBottom && pickRight>=tileLeft && pickRight<=tileRight &&!xFlag){
        xDir=-PICK_SPEED;
        xFlag=true;
    }
    //Collision from Right of Tile
    if(pickBottom>=tileTop && pickTop<=tileBottom && pickLeft<=tileRight && pickLeft>=tileLeft &&!xFlag){
        xDir=PICK_SPEED;
        xFlag=true;
    }
    if(xFlag && yFlag)
        return;
}
}

void PickUpManager::Move(){
xFlag=false;
yFlag=false;
CheckPickUpToTileCollision();
    m_Pos.x+=xDir;
    m_Pos.y+=yDir;
}

The problem is the tiles are like bricks making a wall. So if the pickup hit the tile from top left, it changes it's x and y both direction, while the change of direction should be only in the x direction, as there's another tile which ended before this tile. I know it's some stupid problem, but still couldn't make it out.


texts:
I've been having problems building my game. I've built it successfully before, until I added the LuaJava.dll and LuaJava.jar files (so I can use Lua in my game).

Now, it just briefly opens with black screen and immediately closes. Even though it works just fine in Eclipse.

What I used to do before, was set my jar file in my assets and it would just work fine. But now, it refuses to work, and I have no idea what the error is.

Is there a function I can call to output the error into a log file?