texts: (Quaternion based) Trouble moving foward based on model rotation

texts:
Using quaternions, I'm having trouble moving my model in its facing direction. Currently the model moves can move in all cardinal directions with no problems. The problem comes when I rotate the move as it still travelling in the direction of world space. Meaning, if I'm moving forward, backward or any other direction while rotating the model, the model acts like its a figure skater spinning while traveling in the same direction.

How do I update the direction of travel proper with the facing direction of the model?

Rotates model on Y-axis:

        Yaw = pController.ThumbSticks.Right.X * MathHelper.ToRadians(speedAngleMAX);
        AddRotation = Quaternion.CreateFromYawPitchRoll(yaw, 0, 0);
        ModelLoad.MRotation *= AddRotation;
        MOrientation = Matrix.CreateFromQuaternion(ModelLoad.MRotation);

Moves model forward:

        // Move Forward
        if (pController.IsButtonDown(Buttons.LeftThumbstickUp))
        {
            SpeedX = (float)(Math.Sin(ModelLoad.ModelRotation)) * FWDSpeedMax * pController.ThumbSticks.Left.Y * (float)gameTime.ElapsedGameTime.TotalSeconds;
            SpeedZ = (float)(Math.Cos(ModelLoad.ModelRotation)) * FWDSpeedMax * pController.ThumbSticks.Left.Y * (float)gameTime.ElapsedGameTime.TotalSeconds;
            // Update model position
            ModelLoad._modelPos += Vector3.Forward * SpeedZ;
            ModelLoad._modelPos += Vector3.Left * SpeedX;
        }


texts: How can I render a font in C with OpenGL?

texts:
What I tried:
I was testing some things in order to render text with stb_truetype.h and OpenGL in C.
I took as a reference the example that appears here.
Basically, this example, loads a .ttf file and returns the raw information in bytes, that can be used to generate a texture in OpenGL.
I adapted the example, mentioned before, into modern OpenGL, because, the example uses OpenGL deprecated functions, like glVertex2f. The only thing I get to output on screen was this kind of noise of strange colors:

The code I use:
texture_t fnt_texture;
GLuint fnt_shader;

unsigned char ttf_buffer[1 << 20];
unsigned char temp_bitmap[512 * 512];

stbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs

#define FONT_VS\
    "#version 330 core\n"\
    "layout(location = 0) in vec3 m_Position;"\
    "layout(location = 1) in vec2 m_TexCoords;"\
    "out vec2 TexCoords;\n"\
    "void main() {\n"\
    "TexCoords = m_TexCoords;\n"\
    "gl_Position = vec4(m_Position, 1.0);\n"\
    "}\n"\

#define FONT_FS\
    "#version 330 core\n"\
    "in vec2 TexCoords;\n"\
    "uniform sampler2D Texture;\n"\
    "void main() {\n"\
    "gl_FragColor = texture(Texture, TexCoords);\n"\
    "}\n"\

void font_init(void)
{
    fread(ttf_buffer, 1, 1<<20, fopen("c:/windows/fonts/times.ttf", "rb"));
    stbtt_BakeFontBitmap(ttf_buffer, 0, 32.0, temp_bitmap, 512, 512, 32, 96, cdata); // no guarantee this fits!

    glGenTextures(1, &fnt_texture[3]); // My texture type, is an array that saves the texture on the 3rd position.
    glBindTexture(GL_TEXTURE_2D, fnt_texture[3]);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 512, 512, 0, GL_RGBA, GL_UNSIGNED_BYTE, temp_bitmap);
    glGenerateMipmap(GL_TEXTURE_2D);

    // can free temp_bitmap at this point
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    glBindTexture(GL_TEXTURE_2D, 0);

    fnt_shader = shader_init(FONT_VS, FONT_FS);
}

void font_render(model_t model)
{
    shader_bind(fnt_shader);
    texture_bind(fnt_texture, 0);

    model_begin(model);
    model_draw(model, GL_TRIANGLES); // The model (vao, vbo, ibo) is rendering the whole buffer, not individual glyphs
    model_end();

    texture_unbind();
    shader_unbind();
}

Can someone tell me what I'm doing wrong, and, how I'm suposed to render correctly text, with modern OpenGL, with textures and buffers, in order to read the .ttf file and create the necessary information with stb_truetype.h and, then, render the text?


texts: How to add material to a blueprint created?

texts:
My project has a cube and a capsule.

Below you can see an inserted cube of the modes tab. Beside a capsule inserted from a blueprint created by me:

I can drag the material I created and use it in the cube, but not in the capsule:

Note that the cube has a tab to insert the material:

But the capsule I created does not have that same tab:

I would like to know what components I would have to add to the capsule so that the capsule could have a material.


texts:
This might seem obvious to many, but I'm stuck and I cannot find any tutorial which helped me, so it would be great to find the answer here.

I tried to make a rectangle like you have in RTS games, so to speak a dynamic select box, but it does not work correctly.
It would also be enough is someone lists up bullet points which each step for creating a box like this.

(Don't wonder I'm really new to c++)

Mouse.h :

#ifndef MOUSE_H_
#define MOUSE_H_

class Mouse {

public:
    bool leftButtonDown = false;
    bool mouseMoves = false;

    struct MouseCoords {
        int x = -1;
        int y = -1;
    };

    MouseCoords start_coords;
    MouseCoords move_coords;
    Mouse(){}

    void setState(Uint32 eventType, SDL_Event event){

        if ( eventType == SDL_MOUSEBUTTONDOWN) {
            this->leftButtonDown = true;
            SDL_GetMouseState( &this->start_coords.x, &this->start_coords.y );
        }

        if ( eventType == SDL_MOUSEBUTTONUP ) {
            this->leftButtonDown = false;
        }

        if ( eventType == SDL_MOUSEMOTION ) {
            this->mouseMoves = true;
            this->move_coords.x = event.motion.x;
            this->move_coords.y = event.motion.y;
        } else {
            this->mouseMoves = false;
        }
    }

    /**
     * Provides coordinates when mousebutton down
     */
    MouseCoords getCoordinates(){
        return move_coords;
    }

    /**
     * Refresh the coordinates. MUST be called after Mouse::clearCoordinates();
     */
    void clearCoordinates(){
        this->move_coords.x = -1;
        this->move_coords.y = -1;

    }

    /**
     * Creates selector rect, call this in the render loop
     */
     void createSelectBox(SDL_Renderer *renderer){
         if(this->leftButtonDown) {
            Block rect(
                       this->start_coords.x,
                       this->move_coords.y,
                       this->start_coords.y -this->move_coords.y ,
                       this->move_coords.x - this->start_coords.x
                       );
             rect.draw( renderer );
             this->clearCoordinates();
         }
     }
};

#endif

Block.h

#ifndef BLOCK_H_
#define BLOCK_H_
/**
 * Standard Class which can be used to build a player, enemy, or something similar
 */

class Block{
    SDL_Rect rect;
public:
    Block(int x=10, int y=10, int w=10, int h=10, int filled=true){
        rect.x = x;
        rect.y = y;
        rect.w = w;
        rect.h = h;
    }

    /**
     * draw with the given rendererer
     */
    void draw(SDL_Renderer *renderer){
        SDL_SetRenderDrawColor( renderer , 200 , 155 , 255 , 255);
        SDL_RenderDrawRect( renderer, &rect );
        SDL_RenderPresent( renderer );
    }

    bool framed(){
        return 0;
    }

};
#endif

Then in my main.cpp

SDL_Window *window;
SDL_Renderer *renderer;
Mouse mouse;
Block rect;

void renderWindow(){
    window = SDL_CreateWindow("commanding rects", 100, 100, 700, 600, 0);
    renderer = SDL_CreateRenderer(window, -1, 0);
}

void renderGame(Mouse mouse){
    SDL_RenderSetLogicalSize( renderer, 400, 300 );
    SDL_SetRenderDrawColor( renderer, 0, 0, 0, 0);
    SDL_RenderClear( renderer );
    SDL_RenderPresent( renderer );
    mouse.createSelectBox( renderer );

}

void gameLoop(){
    bool game_run = true;
    while (game_run) {
        SDL_Event event;
        while( SDL_PollEvent(&event)){
            if ( event.type == SDL_QUIT ) {
                game_run = false;
            }
            mouse.setState(event.type, event);
        }
        renderGame(mouse);
        SDL_Delay( 15 );
    }

}

int main(){
    renderWindow();
    gameLoop();
    return 0;
}


texts:
My entity/component/system engine is coming along quite nicely; I have two very different apps working on the same executable. (One 2-d scroller, one 3D Asteroids-type game).

In the interest of getting something working, I've been creating XML definitions of the games, and editing them using a small custom tool that does little more than ensure that I don't add components that don't exist, and that the files are valid XML.

I'm at something of an apex or flection point in that the tools and process I'm using really aren't suitable for production.

Hand-editing large XML files is an error-prone, painful process. (JSON is well supported and pithy, but still requires visual syntax checking.) I could switch to a database such as SQLite, but I have yet to find a good graphical interface (something along the lines of SQL Server Management Studio would be nice).

Are there any COTS tools that can ease this process? I found a C# SQLite implementation with a basic ORM, but it doesn't support complex types like Vector3 or Rectangle. I can serialize these into strings or edit the ORM code to support those types, but then I wind up with my own branch of an OSS component which invites maintenance headaches further down the road.

Another thought was to just do everything in SQL Server and generate the XML from there, and have a tool that keeps the DB schema in sync with the component types in my engine, which is similar to using an ORM.

What's a good solution for this problem? I've read that bigger studios (as in, more than one guy) build their own tools for this kind of thing. I can do that, but I'd really rather be writing my game than building a tool set that only I will ever see.

To clarify: how do those that use entity/component/system engines create and maintain their data that defines the game?


texts: Store custom data against XboxLIVE Gamer in XNA?

texts: If I am using Xbox LIVE Gamer Services for a networked XNA game, is there anyway to store custom data against the Gamer or GamerProfile so should they sign-in again even on a different machine I can access it? For example if I want to store their colour choice.


texts: Unity UI Input Field suddenly malfunctioned

texts:
I'm using Unity 5.0.1f1, and my UI Input Fields are not working as they are supposed to.

I have an Input Field that is placed in a Panel and inside a Canvas.
It has a Text component in which I can set text that the Input Field will display.
When I change value of this Text component, the changes are not reflected on the Input Field, it seems to be reset to the value of Input Field (Script) \ Text of the Input Field.

If I enter Play mode, I can input text normally but when I build and run on my Android phone, I cannot input anything.

Has anyone encountered this problem? How can I solve this?


texts: How to dispose in Newest Java/LibGDX ApplicationListener?

texts:
What I'm wondering:

How do you dispose of textures / spritebatches and the things you normally need to dispose of now?

Why I'm asking:

Because theirs no automatic dispose() function upon creation of the Main libGDX class. I don't remember details but there used to of been an @override dispose

I don't want a memory leak or whatever it's called when you don't dispose.


texts: How to project a foam trail on dynamically changing mesh

texts:
I am trying to create water, and right now I got it through dynamically generating waves on a mesh. But now I want to make my boat manipulate these waves, and cause a Kelvin Wake on top of this.

Fact is I generate the water using different tiles, repeating the same pattern dynamically. So How would I generate this on top of a dynamically generated mesh(plane)? Without also manipulating the other tiles (planes)?


texts: How can I support scrolling when using batched rendering for my tiles?

texts:
I have tiled map 100*75 and tiles are 32*32 pixel.I want to use batching for performance .I don't figure it out , because of my game needs scrolling and every frame i draw 22*16 tiles (my screen is 20*16 tile) .I thought that batching tiles for every frame .Is it good or any suggestion?

edit :to more clarify
I want to use occlusion culling and batching at the same time.I thought that drawing only visible areas and batching them together .But there is a something i couldn't figure out .When scrolling screen with translate matrix , if one row become invisible , I bind new row and batch them again.Every batched objects needs to buffer again.So I batch tiles  and buffer to VBO every time when one row become invisible .I don't know these way is efficient or not .This is my question .And i am open to any suggestions.


texts: How do we export blender material with shaders and blender texture to unity?

texts:
I've blender model, it has noise texture and glossy shaders, when I import it to unity, they are not the same.
I tried both cycle and Eevee render and was looking for different ways to export the fbx file, but nothing seems to work.

I am not sure, if it is even possible to export to shaders and noise texture from blender to unity or do I have to create material from scratch in unity?

This seems to be very common problem while importing material from blender to unity.
I am able to find way to get UV color mapped material, I did it by creating new material in unity and add same texture image file that I used in blender.

Her is the my material in blender.

I tried using copy path option while exporting, but no luck

When I imported the file in blender,I've extracted the material like this

After extracting a .mat file appeared, but it doesn't have information related to noise texture or any blender shaders.
this is the only file I can see after extracting the material.


texts: How do I prevent reimport when switching between computers using Unity3D Portable?

texts: I use Unity Portable on a passport drive where my projects are also stored.  How can I prevent Unity Portable reimport all assets from a project stored on the same passport drive when I change the PC I'm running both on?


texts:
I have a template SVG file for an articulated doll and it looks something like this:

I can manually rotate and pose it in Adobe illustrator, but is there a better workflow to rig 2D segmented assets?


texts:
I'm trying to make a game boy emulator, and I'm using Windows for the graphics (StretchDIBits).
I'm getting screen tearing like this. I tried enabling vsync in graphic settings but nothing changed.

This is how I'm doing my timing in the end of my main loop.

if (cpu.T >= CLOCKSPEED / 40)
{
    if (MSpassed < 25)
        Sleep(25 - (int)MSpassed);
    MSpassed = 0;
    cpu.T -= CLOCKSPEED/40;
}

CLOCKSPEED is the number of emulated CPU cycles per second.
cpu.T is how many cpu cycles passed until now. MSpassed is in milliseconds. I'm measuring it with QueryPerformanceCounter.

Is the problem in the timing, the way I'm doing my graphics, or somewhere in the GB specific code?


texts: how to use .getTransform to get the current coordinates of translated/rotating object

texts:
I’m stuck trying to figure out how to use .getTransform to determine what pointA (x1,y1) and pointB (x2,y2) of each of my lines would be after translate and rotate. I've found other answers but they don't seem to target exactly what I need nor do I fully understand the matrix that gets returned.
From the snippet provided you can see that my lines always return their original values. I know there's a formula for this, or a way to use the matrix, I just don't know it or how I would implement it.
What I need is the start and end points of every line. The plan will be to rotate (animated spinning) them to any angle and have those coordinates get used for ray casting. I've previously done this from a center point out or one direction to another but not with so many lines using the rotate method.
I have tried the same thing with boxes and just can't seem to grasp how I can get the rotated coordinates.
Here's the snippet

let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d")
canvas.width = 200;
canvas.height = 180;

class Rays {
  constructor(x1, y1, x2, y2) {
    this.x1 = x1;
    this.y1 = y1;
    this.x2 = x2;
    this.y2 = y2;
  }
  draw() {
    ctx.save();
    ctx.translate(canvas.width/2,canvas.height/2);
    ctx.rotate(45 * (Math.PI/180))
    ctx.beginPath();
    ctx.strokeStyle = 'black';
    ctx.moveTo(this.x1, this.y1)
    ctx.lineTo(this.x2, this.y2)
    ctx.stroke();
    ctx.closePath();
    ctx.restore();
  }
}

let rays = [];
function createRays() {
  //due to translate i have to push some lines in the negative and some positive  this causes an overlap of one line in the center.
  for (let i=0; i < 26; i++) {
    let x1 =  i < 13 ? -10 * i : i * 10 - canvas.width/2 - 20;
    let y1 =  -canvas.height;
    let x2 =  i < 13 ? -10 * i : i * 10 - canvas.width/2 - 20;
    let y2 =  canvas.height;
    rays.push(new Rays(x1, y1, x2, y2));
  }
}
//enter angle here
createRays();

let count = 0; //just used to stop it from constantly console logging rays.x1

function drawRays() {
  for (let i=0;i<rays.length; i++) {
    rays[i].draw();
    count < 1 ? console.log(rays[i].x1) : false;
  }
  count++
}
drawRays();

console.log(ctx.getTransform())

function animate() {
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    ctx.fillStyle = "lightgrey";
    ctx.fillRect(0,0,canvas.width,canvas.height)
    drawRays();
    requestAnimationFrame(animate)
}
animate()
<canvas id="canvas"></canvas>


texts: Designing a "Grid" like object that contains game objects

texts:
I am working on a 2D game, where there's a game "board" on which other game objects are placed.

This this is 2D, my starting point was to design a class that will internally use a 2d array for the actual stored game objects.

This class could be simply accessed by 2 indices: (i, j) to get game objects on it.

My problem is that i have no idea how to make the game "board" "propagate" its data onto its children.

Design questions i ran into are:

Should the children placed on the board have display properties such as size, screen position?
Should the board itself dictate this information?
How to update children in case the board changes some of its properties? (position, etc).
Should the board be aware of the types of objects stored in it ?

I have no idea how similar things such as WPF or other UI frameworks go about organizing a "container like" object that can arrange or apply certain UI properties to its children.


texts: Networking for RTS games with lockstep using UDP

texts:
Apparently from what I can gather Starcraft 2 moved to UDP in a patch. Now obviously with fps games there is no dispute that UDP is the only way to go. But with RTS games what benefits does UDP give over TCP given that the network model is lockstep?

I suppose another way to phrase this is: what features of TCP make TCP inferior compared to UDP with resend, etc. implemented in the context of rts lockstep networking model?


texts: How to draw a rectangle with a border pixel over a camera/viewport?

texts:
With this code I intended to visually delimit the complete view of the circuit and the two controlled cars:

draw_rectangle(0,0,1279,719,true);
draw_rectangle(0,720,639,1079,true);
draw_rectangle(640,720,1279,1079,true);

It turns out that only the complete view of the circuit that is drawn directly in the room is correctly delimited (observe the black line of a thick pixel):

Where there should be the rectangle strokes (red line, not necessarily at this thickness):

This happens because of this camera/viewport:

I believe the rectangle is being drawn under the camera/viewport.

What do I need to do to make this rectangle draw over the camera/viewport?


texts: Scalability of multi-threading in game server

texts:
What is a reasonable number of threads for a simple 2D mmo in Java? Is it reasonable to have two threads per connection, one for the input stream and one for the output stream?

The reason I ask is because I use a blocking method on the input stream, and a workaround seems unnecessarily complex if I were to try to get around it without adding threads.

This is mostly for my own edification; I don't expect to have 5 million people playing it ever, or even 5, but I'm wondering what a good scalable solution is, and if this is reasonable for a small server (<30 connections).


texts: What is causing this problem with my object rotation?

texts:
I'm having an issue here with rotation in OpenGL. Before I changed my rendering function the rotation I had for my object worked fine, but now it seems to be messed up.

I changed my rendering function because I wanted to be able to clip the image (render frames of the image), whereas before I was just rendering things on a 1 object, 1 image basis.

The rendering is fine, just the rotation to clarify that. Here's my current rendering code:

void DrawRotateAdv(int x, int y, int width, int height, float sourceX, float sourceY, float imageWidth, float imageHeight,
    GLuint texture, float angle, bool blendFlag)
{
    glTranslatef((GLfloat) x + (width / 2),  (GLfloat) y + (height / 2), 0.0);
    glRotatef(angle, 0.0, 0.0, 1.0);

    if (blendFlag)
    {
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    }

    glBindTexture(GL_TEXTURE_2D, texture);
    float texscaleX = 1.0f / (float)(imageWidth / width);
    float texscaleY = 1.0f / (float)(imageHeight / height);
    sourceX = sourceX / (float)imageWidth;
    sourceY = sourceY / (float)imageHeight;

    glBegin(GL_QUADS);

    // Top-left vertex (corner)
    glTexCoord2f(sourceX, sourceY);
    glVertex2i( (-width / 2), (-height / 2));

    //Bottom-left vertex (corner)
    glTexCoord2f(sourceX, sourceY + texscaleY);
    glVertex2i( (width / 2), (-height / 2));

    //Bottom-right vertex (corner)
    glTexCoord2f(sourceX + texscaleX, sourceY + texscaleY);
    glVertex2i( (width / 2), (height / 2));

    //Top-right vertex (corner)
    glTexCoord2f( sourceX + texscaleX, sourceY);
    glVertex2i( (-width / 2) , (height / 2));

    glEnd();
    glLoadIdentity();
}

I think that perhaps my translation is wrong? Unsure though, guess that's a stab in the dark on my part. As for the getting the angle:

     angle = atan2((cEnemy->position.y - (float)position.y), cEnemy->position.x -        (float)position.x) / 3.14159265f * 180;

But I don't think that's the issue, like I said it worked before-hand perfectly. Screenshot of the output:


texts: Will Frame Independant Movement break collision

texts:
Using my game loop to give my game movement which is independant from the framerate, has been working fine for me but, I've started to consider my games running on machines which cannot keep up with my expected frame limit of 60fps, I've tried manually setting it to a lower cap and noticed that my collision detection starts to go off and objects on screen overlap because of this.

How can I make collision detection occur on movements which are too great and overshoot boundary checks?

Below is my loop for running my game

  while (g_Window.isOpen()){

    sf::Time dt = clock.restart();
    timeSinceLastUpdate += dt;
    while(timeSinceLastUpdate > TIME_PER_FRAME){

         timeSinceLastUpdate -= TIME_PER_FRAME;
         processEvents();
         update(TIME_PER_FRAME);
}
   updateFPSCounter(dt);
   render();
}


texts: How do I calculate paths for objects with limited acceleration?

texts:
For example, say I have a car and a car has a specific minimum turning radius and I want to drive that car from point a to point b, but the car isn't facing point b.   How do I compute a path to point b?  Being able to specify the orientation at the point b would also be good (say you want to drive to your driveway and then pull in to your garage -- it doesn't do much good if you got to your driveway by driving over your lawn and are facing sideways :)

A pointer to documentation (or even just a name) would be perfectly fine -- I'm having trouble finding anything at all.

In my attempts, they work in simple cases, but fail miserably in situations such as when point b is closer to a than the minimum turning radius.

For example, how would you determine a path similar to this (the bold path):

edit: In my actual problem, there are some simple pathing constraints, but I already have an A* algorithm in place that works, but it allows things to make instantaneous heading changes, so it looks silly seeing a car suddenly make a 90˚ turn on a dime when they get to a turn point.


texts: Is there a Box2d b2World::ShiftOrigin function in Libgdx?

texts: Is there an equivalent Box2d b2World::ShiftOrigin function in Libgdx? I can't seem to find it.


texts: Applicability of Business Architectures in XNA 4

texts:
I've done a lot of C# programming and the architecture we use of late is a MVC => PresentationService => Domain Service And/OR DataService => Repository with a UnitOfWork and a messaging bus.  In web applications this gives a pretty clean and flexible design that's extensible but is also stateless.

I've been working on a 2D starter project in XNA and I find these layers are still useful until I get to the interface and start trying to deal with knowing the states of everything, keeping the sprites and bounding rectangles and detecting clicks and drags.

What patterns should I be looking at that maybe I just wasn't exposed to doing enterprise architecture but are clearly needed in a game.

Which concepts might I need to let go of when doing a game because they are not applicable.


texts: Prevent Unity optimizing local variables out

texts:
Is there a way to instruct Unity compiler not optimize (best only for builds run from Unity editor)? More precisely, I would like it to stop removing local variables, because it complicates debugging. For example, inspecting node

void Generate() {
   var node = new Node();
   node = node; //breakpoint here, node cannot be inspected
   var x_nearest = Nearest(new_node);
   Debug.Log(new_node);//new_node still cannot be inspected, but x_nearest can
}
Node Nearest(Node node)
{
   //node is an argument here and can be inspected
}

in Visual Studio produces error rather than displaying its value.

  The identifier node is not in the scope

A solution would be make every local variable a private member instead:

private Node node;
void Generate() {
   node = new Node();
   node = node; //breakpoint here, node can be inspected
}

this would, however require frequent back and forth refactoring. I am using Unity 5.6.0f3 with C# 6.0 support and Visual Studio 2017.
note: provided code is for illustration only and the question is not about debugging said code because reproducing specific compiler behavior is not trivial


texts: Getting location / bounds of centered text

texts:
I want to show a dialog box where the user should answer a question.
It would look like this:

The question is aligned horizontally.

I don't show the entire question text right away, but it builds up character by character like this:

To do that, I store the text string in a variable at the script start, then I set the text to "", and in a coroutine I add character after character to the text component.

My problem is that (because of the horizontal alignment) Unity wants to build it up starting from the center like this:

Since this is not what I want, I was thinking that I should perhaps measure the bounds of the entire text while it is horizontally aligned, then I would turn off the horizontal alignment and make it left-aligned instead and set its position according to the measure bounds.

However, I don't know if I can measure the bounds of the text anyways.

Can anybody suggest how to handle this problem?


texts: Mouse click rectangle doesn't update to actual mouse position

texts:
I'm making a menu in XNA; and to solve clunky input via arrow keys, I thought I would use mouse input. I got everything to work perfectly, then I tried to click on something specific and nothing happened. To troubleshoot, I drew an image where the cursor rectangle is supposed to be. As you can see in the image below it's nowhere near my mouse.

One image of the cursors lag

Another image of the cursors lag

Note how they are in two different places.

How do I fix this horrible lag?

The menu update calls a mouse class to update the mouse position and place it within bounds of the screen. The mouse class also has a rectangle that updates based on the mouse position, but it updates almost 200 pixels away. The mouse moves fine in game, it's just the rectangle is in a weird position

   //This is located in the Mouse Class
    public void Update(GameTime gameTime)
    {
        oldmouse = currentmouse;
        currentmouse = Mouse.GetState();
        Position.X = currentmouse.X;
        Position.Y = currentmouse.Y;
        //Some other boundary code that's not essential
        clickRectangle.X = (int)Position.X;
        clickRectangle.Y = (int)Position.Y;
    }

    // this is located in the menu class

    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(ArrowTexture, mouseInput.clickRectangle, Color.White);
        //draw other arrows and text
    }

I don't see a problem with the code. Is there something else I have to do?

I should also mention it sometimes draw nearer to the actual cursor and sometimes farther away. The cursor only drew to my actual cursor once before it stopped working.

EDIT: I updated the question with more relevant information. I apologize for not including it earlier.


texts: How to render thin glass with proper refraction?

texts:
I want to render thin bumpy glass with refraction. But it offsets too much(look at the black frame of the glass). Looks thick.
How to do thin glass refraction properly? Or is it possible to exclude object(e.g. the black frame) from refraction?


texts:
I'm learning OpenGL and have a question. I read about Texturing and found border param in glCopyTexImage and glCompressedTexImage functions. In book: "OpenGL Programming Guide" wrote that border is reserved and must be zero? If it reserved why they place it into parameter?

P.S.: I have one idea, is it used for border texture? Like don't read data below that border, isn't it?


texts: Plotting 2D map coordinates to OpenGL 3D projection

texts:
I’m trying to convert a 2D map created in my map editor to a 3D plotting with OpenGL. This is my map generated in my map editor:

Those vertices are relative to my Cartesian origin world coordinate (top up of the picture) and I’m applying this formula to convert it to an OpenGL object coordinate:

World size: 800x600

x = (X / 800) -0.5
y = (Y / 600) -0.5

Getting this result:

(First object face)

−0.48625, 0.068333333
0.12625, 0.07
0.12875, −0.481666667
−0.4875, −0.486666667

Plotting this vertex buffer in OpenGL, I got a very weird result. So how can I get a 3D model from those vertex positions? Like this picture:

I’m rendering OpenGL in triangles mode and using this example as the start point: https://github.com/JoeyDeVries/LearnOpenGL/blob/master/src/1.getting_started/7.4.camera_class/camera_class.cpp

Edit:

Using the conversion formula + the Earcut tessellation (https://github.com/mapbox/earcut.hpp), I've finally got this rectangle rendering correctly inside OpenGL. With two planes with just the Z-axis different, now the problem is how to render its laterals since Earcut just works with 2D coordinates...


texts: Interactive texture modification (such as fluid mixing) in Unity

texts:
I am working on a game where I want to allow users to mix multiple colors (similar to shown in this video): https://youtu.be/11UFYyv8hjs?t=316.
I have the following questions:

I am expecting that this is done using shaders. What kind of shader I have to use for such implementation? What will be the logic to create this type of shader?

Are there any other ways using which this feature can be implemented?

Are there any open source tutorials or examples?

I would appreciate any suggestions and thoughts on this topic. Thank you.


texts: Unity's 'Ambient' Occlusion occludes everything. How to do it better?

texts:
I'm experimenting with custom AO solutions for Unity. While looking at the source for their built-in SSAO effect, I noticed the shader is doing this:

half ao = tex2D (_SSAO, i.uv[1]).r;
ao = pow (ao, _Params.w);
c.rgb *= ao;

So basically it's darkening the whole image as a post-process where the AO term is <1, specular and diffuse components included. I'd like my version to only attenuate the ambient component while leaving the direct lighting untouched.

So how to go about this? One option would be to go to the full on deferred renderer (not legacy light pre-pass), compute the AO texture after the G-buffer pass, and incorporate it into a custom shader to do the final lighting pass. But are there simpler options that would work with light pre-pass or even forward rendering?


texts: How to convert a SDL window to a SDL surface? SDL 2

texts: I am trying to make a paint program and there is a sdl function called IMG_SavePNG() which requires a surface and destination file. How can I turn what I see in the window to a surface?


texts: Is it possible to edit a Vector3 in the inspector by clicking on the scene?

texts:
I have a component that represents an NPC that patrols between several waypoints.

Initially I represented each waypoint as a simple Vector3, so the component had a serialized field of type Vector3[]. However, it required me to edit the x, y and z values of each waypoint manually.

Alternatively, I could represent each waypoint as a Transform, so the component had a serialized field of type Transform[]. Then, I could create an object for each waypoint, place it wherever I want on the scene, and then drag it into the waypoints array of the component. However, this requires me to create many game objects - one for each waypoint of each patroller - where I do not really need the objects, I only need the position.

Is there another way to edit a Vector3 field by clicking on the scene view?


texts:
I'm writing a Software Renderer for fun/learning. Basically, it's just a giant array of integers which contain hexadecimal values (representing colour) that are rendered to the screen....

int screenWidth = 16;
int screenHeight = 16;
int[] pixels = new int[screenWidth * screenHeight];
Arrays.fill(pixels, 0xffff00ff);

Something like that, the above should render a pink screen (255, 0, 255). So my problem is I've written a method that will fill a rectangle...

public void fillRect(int x0, int y0, int x1, int y1) {
    x0 += xOffs; // apply offset to each vertex
    y0 += yOffs;
    x1 += xOffs;
    y1 += yOffs;

    if (x0 < 0) x0 = 0;
    if (y0 < 0) y0 = 0;
    if (x1 >= width) x1 = width - 1;
    if (y1 >= height) y1 = height - 1;
    for (int y = y0; y <= y1; y++) {
        for (int x = x0; x <= x1; x++) {
            components[x + y * width] = 0xDEADBEEF;
        }
    }
}

And it works fine, although I want to try and rotate the quad by 90 degrees, then render it to the bitmap. So I tried this....

public void fill(int x0, int y0, int x1, int y1) {
    final int theta = 90;
    x0 = (int) (x0 * Math.cos(theta) - x0 * Math.sin(theta));
    x1 = (int) (x1 * Math.cos(theta) - x1 * Math.sin(theta));
    y0 = (int) (y0 * Math.sin(theta) + y0 * Math.cos(theta));
    y1 = (int) (y1 * Math.sin(theta) + y1 * Math.cos(theta));

    x0 += xOffs; // apply offset to each vertex
    y0 += yOffs;
    x1 += xOffs;
    y1 += yOffs;

    if (x0 < 0) x0 = 0;
    if (y0 < 0) y0 = 0;
    if (x1 >= width) x1 = width - 1;
    if (y1 >= height) y1 = height - 1;
    for (int y = y0; y <= y1; y++) {
        for (int x = x0; x <= x1; x++) {
            components[x + y * width] = hex;
        }
    }
}

Although it doesn't work, nothing is shown on the Window. Any ideas? I have a feeling after the rotation, the entire method is wrong. Any help would be great :)


texts:
I'm currently developing a test project to explore OpenGL 3 texturing abilities. I have a simple cube, made of 8 vertices and 36 indices. I want each of the cubes faces to have a different texture, so I devised this texture:

I made it obvious which sections I want visible (I hope...). In Direct3D, I once made a skybox, and I used a cubemap. However, I had to split it into 6 different textures. This is annoying and hard to manage, it would be nice to have just one texture. Is this even possible? I read somewhere that I could do this by duplicating vertices, is that a good idea? Someone else said I could do it in the shader, but that also baffles me...


texts: get access to Transform of a Clone in Unity

texts:
In my game when you lose, A panel with a button on it appears and if you don't have enough coins, You may be directed to shop by hitting shop button. when buying is completed you can return to the scene from where you left it and resume the game. I'm using PlayerPrefs to save properties like slider.value my player position timescale etc, But I can't access to Transform of an Instantiated GameObject (Clone). it acts like obstacle and is Instantiated continuously. Here is my script;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using CodeStage.AntiCheat.ObscuredTypes;
using CodeStage.AntiCheat.Detectors;

public class Spawner5 : MonoBehaviour {

    public float maxTime=1;
    public float Timer = 0;
    public GameObject pipe;
    public float height;

    // Use this for initialization
    void Start () {

        pipe = GameObject.FindGameObjectWithTag ("Gear");
    }

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

        if (Timer > maxTime) {

            GameObject newpipe = Instantiate (pipe);

            newpipe.transform.position = transform.position + new Vector3(4, Random.Range (-height, height) ,0);

            Destroy (newpipe, 15);
            Timer = 0;

        }

        Timer += Time.deltaTime;
    }
}


texts: Unity - Play animation based on horizontal drag position

texts:
So, what i want to do is some what complected, but I'll try to explain it to the best of my ability. I am using Unity's EventSystems events to detect a drag. When the user drags the object horizontally, I want to play the animation relative to the position of the object.

For example: If the user drags object to position 0.5, I want the animation to only play to time 0.5, and if the user drags back to 0.2, I want the animation to play back to time 0.2

Currently, I do not have any code because I do not know where to begin.


texts: Property replication vs RPC notifications

texts:
I'm not talking about something such as an object position, which changes very often. I'm talking about some object state that may be changed infrequently, such as a door opening and closing.

Would it be better to send an RPC to saying "The door is opening/closing" or would it be better to replicated a property that tells us the objects state? Obviously this can be done both ways, but what are the advantages/disadvantages of each?

As far as I know any competent implementation will only consider replication for properties that have changed. This means when the property does actually change, it should have the same cost( assuming it must be reliably replicated ) as sending an RPC. The other advantage to doing this would be removing the need for more complex RPC buffering. If a client connects, they get sent the state, no need to buffer/unbuffer things.

All I can see is advantages for replicating over RPCs in this case. However, I always see suggestions to have as few replicating properties as possible.


texts: How to add user created data to drop down menu options

texts:
So I'm trying to make it that I can have a dropdown that will have user created info appear in it.

List<engines> engineList = new List<engines>();
public Dropdown engineSelect;

public class engines
{
    public string engineName;
    public int featureNumber;
    public int totalDevPoints;
    public string optimizedGenre;
    public engines(string name, int feature, int totalPoints, string opt)
    {
        engineName = name;
        featureNumber = feature;
        totalDevPoints = totalPoints;
        optimizedGenre = opt;

    }
}
engines playerEngine = new engines(engineName, numFeature, 0, whatGenre);

Pretend player set engineName, numFeature, and whatGenre with text fields.
I wanted to have it that the drop down would add in whatever new engines the player makes. How would I do that? I want to have it say select engine: and then the player would pick from dropdown from engines they made(only saying engine names).


texts: Heightmap, Voxel, Polygon (geometry) terrains

texts:
In relation to Heightmap, Voxel and Polygon (geometry) terrains:

What are the main differences between all these three?
Can you form a "smooth" terrain with Voxels, I mean, can you for example get a smooth mountain with Voxels, or Voxels are limited to cubes?
Performance wise, a world 2000x2000 units, what would be faster Heightmap terrain, Voxel terrain or Polygon based, geometry terrain? (Assuming that there is "reasonable" performance gains/optimization done for rendering for every of possibilities)
Are there any more techniques used for terrain creation?
Any good titles representing each of types?

P.S. Polygon based terrain should be fully traingulated, no squareish stuff.


texts: Moving an object (pong paddle) along the x,y axis in 3d-space with mouse/touch

texts:
First of all: Sorry, my English isn't quiet good, I'm very new in 3D and I'am using JMonkeyEngine.

What I would like to do?:

A 3d pong game and I want to control the paddle with the mousecursor and/or touchscreen.

What I have done so far:

placed some boxes as floor and walls and the paddle with a coloured material(not included in the example code), put them in a geometry and then in a node an attach it to the root node to make it visible.

Box a = new Box(Vector3f.ZERO, 2, 0.01F, 5);
Box b = new Box(Vector3f.ZERO, 2,0.01F, 5);
Box c = new Box(Vector3f.ZERO, 0.01F, 1F, 5);
Box d = new Box(Vector3f.ZERO, 0.01F, 1F, 5);
Box e = new Box(Vector3f.ZERO, 4, 2, 0.01F);
Box paddle1 = new Box(Vector3f.ZERO,0.25F,0.15F,0.02F);

geomPaddle1 = new Geometry("paddle1", paddle1);
Geometry geomBottom = new Geometry("bottom", a);
Geometry geomTop = new Geometry("top", b);
Geometry geomLeft = new Geometry("left", c);
Geometry geomRight = new Geometry("right", d);
Geometry geomWall = new Geometry("Wall", e);

geomBottom.move(0, 0, 0);
geomTop.move(0, 2, 0);
geomLeft.move(-2,1,0);
geomRight.move(2,1,0);
geomWall.move(0,0,-5);
geomPaddle1.move(0,1,5);

nodePaddle1 = new Node("PaddleNode");
nodePaddle1.attachChild(geomPaddle1);

Node walls= new Node("walls");
walls.attachChild(geomBottom);
walls.attachChild(geomTop);
walls.attachChild(geomLeft);
walls.attachChild(geomRight);
walls.attachChild(geomWall);
rootNode.attachChild(nodePaddle1);
rootNode.attachChild(walls);

The camera is set in z-axis "-1" direction in front of the paddle and the flying cam is disabled

cam.setLocation(new Vector3f(0,1,8));
flyCam.setEnabled(false);

So, where is my problem?

I would like to attach the middle of the paddle to the mousecursor(mouseposition). I have read around and I think I have to translate the 2d mousecoordinates to 3d worldcoordinates. I found some code to do that:

Vector3f origin = cam.getWorldCoordinates(inputManager.getCursorPosition(), 0.0f);

Then I thought I only have to adjust or fix the z-axis in the simpleUpdate loop, because I only want the x,y-movement.

 Vector3f origin = cam.getWorldCoordinates(inputManager.getCursorPosition(), 0f);
 Vector3f dir2 = new Vector3f(origin.getX(), origin.getY(), 5F);
 geomPaddle1.setLocalTranslation(dir2);

but it doesn't worked as I thought:

mousecursor at paddle-origin

mousecursor right from paddle

The paddle move in the correct direction but not to the mousecoordinates.

Well.. I'm very new at this things, I dont know wheter I'am completely wrong or how I can implement the mousecontrol in another way. It would be wonderful if you can help me.

Best regards


texts: Texturing a PyOpenGL 3D Cube with PySDL2

texts:
So, I've just started learning OpenGL with PySDL2, and I've created a class that will create a cube to the window that I've created with PySDL2. What I'd like to do now, is to figure out a way to texture the cube. I don't believe that the actual texturing part is the problem, but actually loading the image. I've tried to do this with PySDL's image loader, but this causes an error from the OpenGL texture creator. Here is my code to load an texture and bind it to OpenGL:

def LoadTexture(self, filename):
    """Loads a texture for the cube"""
    surface = SDL_LoadBMP(filename)
    #Checks if the loading succeeded
    if surface:
        #Translate the LP_SDL_Surface-pointer got from SDL_LoadBMP() to a real SDL_Surface
        texture_surface = surface.contents
        texture_format = GL.GL_RGBA
        GL_TEXTURE_ID = GL.glGenTextures(1)
        GL.glBindTexture(GL.GL_TEXTURE_2D, GL_TEXTURE_ID)
        GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1)
        GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, 3, texture_surface.w, texture_surface.h, 0, texture_format, GL.GL_UNSIGNED_BYTE, texture_surface)
        return GL_TEXTURE_ID
    return None

And the error that gives looks like this:

TypeError: ("No array-type handler for type <class 'sdl2.surface.SDL_Surface'> (value: <sdl2.surface.SDL_Surface object at 0x030762B0>) registered", <OpenGL.GL.images.ImageInputConverter object at 0x02EC49F0>)

I'm using Python 3 so using something like PIL won't work for me. Any ideas how to get the texture loaded, preferably with PySDL2?


texts: Perlin Noise for generating terrain in a 2D side-scrolling game. Is there a way to make variations in noise's amplitude?

texts:
For example if my generated levels look roughly like this:

But once in a while I would like to have the "amplitude" rise say 10 times than the rest of the level, so that it would look something like:

That is, once in a while there are deep "trenches" in the level. Now I know that my terrain's Y values are always between for example 200 and 1000 pixels. I there a way for them to mostly be in that range, but once in a while there is a drop to for example 10000 pixels?


texts:
I'm trying to find a way to make an object inflated/deflated in Unity,
So I can change parameters via script and control a range of 0-100% inflation.

I have seen that there is a way to get this exact effect on Blender (it's in the pressure module), but as far as I understand, there is no option to get the same parameters in Unity and actually make them scriptable.
My whole game is based on this feature and I must find a way to achieve that effect.
Any help would be appreciated!
Thank you in advance,
Omer


texts: Replacement for glMatrixMode() in OpenGL 4?

texts:
In OpenGL version 3.x the function glMatrixMode() specifies which matrix is the current matrix, i.e., which matrix stack is currently the target of all matrix operations based on the parameter, the choices being GL_MODELVIEW, GL_PROJECTION, and GL_TEXTURE.

glMatrixMode() had been deprecated in OpenGL version 4.x.

I have tried to find the equivalent way of performing the same effect in 4.x without success.

I suspect there has been a change in philosophy in OpenGL 4 which I am overlooking.

How is the glMatrixMode() equivalent performed in OpenGL version 4.x?


texts: Unity: Increase animation speed of individual component in a blend tree?

texts:
I have blend tree with four different turns: a sprinting turn, running turn, walking turn, and standing turn.

I need to somehow make the angular velocity increase from sprinting down to standing, so that as the character gets slower he turns faster (otherwise it is basically unplayable).

How do I increase the angular velocity of an individual animation in the blend tree?  The usual "speed" attribute disappears when I put the animation in the blend tree...and I have not figured out how to access the blend tree substate from code yet.

Here is an image of the blend tree, and the inspector:


texts: I'm trying to create a click to move snake game on mobile but I'm having problems with the whole click to move functions and adding a body part every time my snake eats an apple. I want to make the click to move smooth you know like an actual snake is slithering around and when the snake eats an apple, I want to add another body part to my snake (maximum of body parts should be 5). Can anyone point me into the right direction or give me an example of what to do, thank you!


texts: Allowing one sprite to move through another in Quintus

texts:
I have a Bumper class extended from Sprite:

Q.Sprite.extend("Bumper", {

    init: function(p) {
        this._super(p, {gravity: 0});
        this.add("2d, ... //etc.
}

I have an Enemy class that should trigger a function when the center of the Bumper and of the Enemy collide.

I was thinking about doing something like this in my Enemy class :

this.on("bump.top, bump.bottom, bump.left, bump.right", function(collision) {
    if(collision.obj.isA("Bumper")) {
        if (this.p.x == collision.obj.p.x && this.p.y == collision.obj.p.y) {
        //Do something
        }
    }
});

But for that I need the two sprites to move through one another. Is there a way to do that while still checking for collision ?


texts: Cube worlds, instancing vs mesh generation

texts:
For a Minecraft type game, what are the pros and cons of hardware instancing the terrain vs generating a mesh of vertices based on what's visible?

The terrain is dynamic so cubes will be added/removed frequently. Also each side of a cube is the same texture.


texts: SharpDX/D3D: How to implement and draw fonts/text

texts:
I am playing with SharpDX (Direct3D for .NET) without using "Toolkit", already finished with basic rendering 3D models.
But now i am wondering how to program/create fonts for game (2D), or how to simple draw variable text to output with Direct3D? (it is not as SharpDX question as common Direct3D question, how to start with game GUIs?
And what should i do to program simple GUI's like menu for a game (generally i understand that it's shaders).


texts: Projectile immediately intersecting with target

texts:
I have a fairly simple and somewhat cookie cutter method for testCollisions: (FYI: BasicProjectile is a CCNode with a CCSprite member).

    for (BasicProjectile * basicProjectile in self.projectiles) {

        NSLog(@"projectile sprite %@",NSStringFromCGRect(basicProjectile.sprite.boundingBox));
        NSLog(@"destination sprite %@",NSStringFromCGRect(basicProjectile.destination.sprite.boundingBox));

            if (CGRectIntersectsRect(basicProjectile.sprite.boundingBox, basicProjectile.destination.sprite.boundingBox)) {

                [basicProjectile.destination setHealth:(basicProjectile.destination.hp - basicProjectile.damage)];

                [self.projectiles removeObject:basicProjectile];
                [self removeChild:basicProjectile cleanup:YES];
                }
        }

    }

Those NSLog statements output:

  2013-03-23 10:02:59.124 GridWars[25268:c07] projectile sprite {{-10,
  -10}, {20, 20}}

  2013-03-23 10:02:59.124 GridWars[25268:c07] destination sprite
  {{-13.5, -34}, {27, 68}}

The main problem is that the collision immediately happens.  It should take a few frames to travel from the source to the destination.  So although the logic of setting the health works fine the sprite itself is never seen on the screen because the very second its fired it is removed.
From what I understand about CGRectIntersectsRect those 2 points listed above do not intersect.  Am I wrong are they intersecting?  What can be causing these projectiles to immediately intersect with their target?

BasicProjectile class (CCNODE superclass)

-(id)initWithSourceAndDestination:(GameCharacters*)Source destination:(GameCharacters*)Destination
{
    if (self = [super init]) {
        self.damage = 25;
        self.sprite = [CCSprite spriteWithFile:@"Projectile.png"];
        [self addChild:self.sprite z:1000 ];
        self.source = Source;
        self.destination = Destination;
    }
    return self;
}

GameCharacters would look similar to this except have health and mana properties.

WizardHero Class, Method Fire:

basicProjectile.position = self.position;
    [self.hostLayer addChild:basicProjectile z:2021];

// Determine where we wish to shoot the projectile to
int realX;

// Are we shooting to the left or right?
CGPoint diff = ccpSub(basicProjectile.destination.position, basicProjectile.source.position);
if (diff.x > 0)
{
    realX = (self.hostLayer.tileMap.mapSize.width * self.hostLayer.tileMap.tileSize.width) +
    (basicProjectile.contentSize.width/2);
} else {
    realX = -(self.hostLayer.tileMap.mapSize.width * self.hostLayer.tileMap.tileSize.width) -
    (basicProjectile.contentSize.width/2);
}
float ratio = (float) diff.y / (float) diff.x;
int realY = ((realX - basicProjectile.position.x) * ratio) + basicProjectile.position.y;
CGPoint realDest = ccp(realX, realY);

// Determine the length of how far we're shooting
int offRealX = realX - basicProjectile.position.x;
int offRealY = realY - basicProjectile.position.y;
float length = sqrtf((offRealX*offRealX) + (offRealY*offRealY));
float velocity = 380/1; // 380pixels/1sec
float realMoveDuration = length/velocity;

// Move projectile to actual endpoint
id actionMoveDone = [CCCallFuncN actionWithTarget:self.hostLayer
                                         selector:@selector(projectileMoveFinished:)];
[basicProjectile runAction:
 [CCSequence actionOne:
  [CCMoveTo actionWithDuration: realMoveDuration
                      position: realDest]
                   two: actionMoveDone]];

[self.hostLayer.projectiles addObject:basicProjectile];

Basically here is the class structure

Three main superclasses

  GameProjectiles:CCNodes

  GameLevels:CCNodes

  GameChars:CCNodes

Then the actual more specific classes (used on the GameLevels)

  BasicProjectile:GameProjectiles

  Level1Layer:GameLevels

  WizardHero:GameCharacters

  RedEnemy:GameCharacters


texts:
I am pretty new to using physics engine and would like to know what is best practice for movement of playercharacters.

Currently I have a class called Hero that has a CircleShape and when the user presses left/right/up/down it gets an linear impulse in the appropiate direction. All this works fine. The problem happens when the player does not produce any input, the shape is going further in the last direction for a long time, but I would like it if the shape stops faster.
The players sees the world top down, so the worlds gravity is set to (0;0).

Maybe the whole idea of using impulses to move the character around is flawed, I would just like to know what works.


texts: Generating texture coordinates autmatically with Cube Mapping for an object that is not a skybox in OpenGL

texts:
I am wondering whether its possible to automatically generate texture coordinates for custom obj models to work with cubemaps. Every tutorial I see online is about environment mapping. Is it possible to write a shader that allows me to generate UV's like in this image:
http://i.imgur.com/NyWqcRC.jpg

So far I've loaded cubemap texture:

bool Texture::LoadCubicTexture(vector<string> filenameTable)
{
  glGenTextures(1,&texID);
  glBindTexture(GL_TEXTURE_CUBE_MAP,texID);

  glTexParameteri(GL_TEXTURE_CUBE_MAP,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
  glTexParameteri(GL_TEXTURE_CUBE_MAP,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
  glTexParameteri(GL_TEXTURE_CUBE_MAP,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_CUBE_MAP,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_CUBE_MAP,GL_TEXTURE_WRAP_R,GL_CLAMP_TO_EDGE);

  int i = 0;
  vector<string>::iterator vsit;

  // There is always six filenames
  for(vsit=filenameTable.begin();vsit!=filenameTable.end();++vsit)
  {
    string filename = *vsit;
    BMPData* bmpData = LoadTextureBMPData_custom(filename);
    glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X+i,0,GL_RGB,bmpData->width,bmpData->height,0,GL_BGR,GL_UNSIGNED_BYTE,&(bmpData->data[0]));
    i++;
    delete daneObrazu;
  }
  glGenerateMipmap(GL_TEXTURE_CUBE_MAP);

  return true;
}

I've also have my custom .obj posted online here:
https://pastebin.com/NVKgrGGZ


texts: What game mechanic can I use to show that the player character is bored?

texts:
I'm designing a part in my game where the player must notice that his character feels bored about a certain mundane task he is doing, without being boring for the player.

By observing the game mechanic, the player should understand that his character is bored or fatigued. To keep the player interested in playing though, the mechanic has to gamify that mundane process into something interesting or challenging.

How could this be done?


texts: XNA and HLSL shaders - Instancing using World Matrix array

texts:
I have posted this question on StackOverflow and was directed here, so I'll just copy the question:

I am attempting to improvise some sort of hardware instancing in my game. I wish to draw multiple trees with only one Draw Call.

So far, I have set up a class which holds the model, texture, and an array of Matrices. Each matrix corresponds to a location of one tree in the game world.

I have determined to use 50 copies of object as hard coded limit within my class and my shader.

I am sure that the matrices generated are correct ones. Using Basic effect with multiple draw calls and switching out World matrices between them does yield in correct number of trees on their correct locations.

I have tried a shot-in-the dark approach:

float4x4 View;
float4x4 Projection;
float4x4 World[50];

...

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output[50];

    for (int i=0; i<50; i++)
    {
        float4 worldPosition = mul(input.Position, World[i]);
        float4 viewPosition = mul(worldPosition, View);
        output[i].Position = mul(viewPosition, Projection);
        output[i].texCoord = input.texCoord;

        return output[i];
    }

}

To my surprise, this actually did compile, and to even greater surprise, didn't melt my GPU.

To not so big of a surprise, this draws only one tree, the first one, as the loop ends as soon as it hits the "return" keyword as any sane mind would expect it to.

I have tried my google-fu skills with googling this kind of problem, but majority of the results deal with C++ code (I'm using C# + XNA), and their approach to the problem is basically to collect all needed model's vertices and forward all that, as one huge model drawn with one World matrix position.

Is there a reliable way to draw one model using an array of World matrices on a shader, or must I collect all vertex data and batch it that way?

P.S. I am attempting to toy around with nested structures, like these:

struct VertexShaderOutput
{
    float4 Position : POSITION0;
    float2 texCoord : TEXCOORD0;
};

struct VSOUT
{
    VertexShaderOutput output[50];
};

VSOUT VertexShaderFunction(VertexShaderInput input)
{
    VSOUT output;

    for (int i=0; i<50; i++)
    {
        float4 worldPosition = mul(input.Position, World[i]);
        float4 viewPosition = mul(worldPosition, View);
        output.output[i].Position = mul(viewPosition, Projection);
        output.output[i].texCoord = input.texCoord;

    }

    return output;
}

But, of course, as the loop gets unrolled, the very next instance of Output gives an overlapping semantic error. I am pretty sure there are no POSITION50 and TEXCOORD50 semantics :p So, how would I go about solving this problem?

Thank you in advance!


texts: How to fix lag in 64 bit Android devices

texts:
My game's FPS drops to 30 - 8 FPS on any 64 bit Android device but is at 59 - 60 FPS on an even lesser 32 bit Android device.
I've tried unchecking Development Build on Build settings and I've tried disabling debug calls on my game by using:
void Update ()
{
#if UNITY_EDITOR
if(!Debug.unityLogger.logEnabled)
    Debug.unityLogger.logEnabled = true;
#else
if(Debug.unityLogger.logEnabled)
    Debug.unityLogger.logEnabled = false;
#endif
}

But there wasn't any change. And I tried setting all Stack Trace Log type to None(Edit > Project Settings > Player). Also no change.
PS: I used that update call because there are other imported assets that call the Debug class and I wouldn't want to mess around with their classes.
EDIT: As you can see in the screenshots below, the device that runs the game at less than 30 FPS(every 64 bit device) has Gfx.WaitForPresentOnGfxThread take 71.6% of the frames and RenderPipelineManager.DoRenderLoop_Internal() takes up 51.1%. While the device that ran the game at 60FPS(every 32 bit device) has RenderPipelineManager.DoRenderLoop_Internal() take up the most frames with 35.7% of the frame.
How should I fix the frame rate drop on the 64 bit device?

EDIT:
The 32 bit Android device is an Infinix Hot 4, 2GB RAM, 1.3GHz quad-core MediaTek MT6580 CPU, OpenGLES2, Android 7.0, 1280x720. - This reaches a maximum of 62FPS(Average 59FPS).
The 64 bit Android devices are:

Cubot X19 - 4GB RAM, [8 core CPU: 4x 2.3 GHz ARM Cortex-A53, 4x 1.65 GHz ARM Cortex-A53], OpenGLES3, Vulkan supported, Android 9.0, 2160x1080. - This reaches a maximum of 30 FPS(Average 25FPS).
Qubo P19 - 3GB RAM, 1.5GHz Quad-Core MT6739WA CPU, OpenGLES2, OpenGLES3 supported, Android 9.0, 1280x640. - This reaches a maximum of 25FPS(Average 19FPS).

I'm using Unity 2019.3.1f for my project.


texts: How do I convert 3D vertices and faces to 2D shapes?

texts:
I'm assuming all the math is done with projection matrices from linear algebra, but I don't yet understand how they work, and haven't found much information on them.

What I'm mainly curious about is how after you convert the 3D stuff to 2D, how do you attribute the vision through a portal (like in game Portal)? How is that math done?


texts: How to design a game's software such that it is easy to unit test?

texts:
Is it practical to use a testing framework like JUnit in a game development situation? What sort of design considerations can you follow in order to make your game more testable? What parts of a game can/should be tested and what parts should/must be left to human testing?

For example, if the game loop is encapsulated in one function, it seems like it would be terribly hard to test. I like to refactor out an "update" function that takes a time delta and moves forward the game logic; this allows some interesting tricks like the ability to slow the game down by feeding it fake, slower time deltas.


texts: How does skin width work in Unity's CharacterController?

texts:
I'm trying to write my own character controller and I want to understand how Unity's works. I think what it does is this: at each fixed update it takes the smaller collider reduced by the skin width, casts it forward to see where it hits something, then moves the character forward so that the full size collider touches that point. So my first question is is that right, am I missing an important step?
My next question is how does Physics.SphereCast work? What subroutines and geometric algorithms are involved? Every Collider has the methods Raycast, ClosestPoint, and ClosestPointOnBounds, so does Physics.SphereCast just use some combination of those functions for each Collider, or is there more math involved on top of that? And are sphere casting and capsule casting the main geometric algorithms used by the character controller, or are there others I should be aware of?


texts: How to implement server side auto attack?

texts:
I'm writing a basic MMORPG and im trying to implement auto attack.

At client side I send an AutoAttackMessage to the server.

Should I send this message every X ms to the server, or juste one time and then server handle this himself ?

How to handle delay between 2 auto attack at server side ? (timer, special thread)...


texts:
I seem to keep reading it's a bad idea to use XxxManager style classes in game engine programming, yet even when I try to avoid their use I always end up with something that holds all the actors/entities/game world locations and acts upon them, which ends up being a Manager if by another name.

Is this really a bad pattern to follow? If so, what are the alternatives?


texts: PBR How to correcly use standard lighting and IBL

texts:
I'm creating a physically based renderer but I am a bit confused on how to put together standard lighting with IBL, since like I'm doing now I think it's wrong.

Right now, for each light, I evaluate it's contribution to the scene lighting combined with IBL lighting (I use both the light contribution and diffuse and specular coming from the IBL) but like this I sum the IBL contribution for each light, and I don't think it's right.

To put together standard lighting with IBL, do I need to process all the lights alone and then, in another step, bake into the scene the IBL? I think this would be more correct.


texts: How do I procedurally create a directional light cone with an HTML canvas?

texts:
To create a directional light effect, I want to draw this kind of transparency mask on an HTML canvas (using context2d):

I also want to be able to generate such a mask dynamically. I've tried using arc to create this kind of light cone, but I'm not able to draw nice, smooth and naturally looking light.

How can I do this?


texts: What do I need to do legally to protect my game with copyright?

texts:
I am in the process of writing a game and I'm wondering what the copyright laws about publishing this game are.

I do not (for now) intend to make money from this. The beginning of my code contains a comment with # Copyright 2013, Collin Norwood, but is that legally valid? Do I have to apply with some government for a trademark or such?


texts: How can I select an audio output device in directshow

texts:
I was wondering how I can select the output device for audio in directshow. I am able to get available audio output devices in directshow. But how can I make one of these to be audio output device. Its always going for the default audio device. I want to be able to output audio on my choice of device. I have been struggling through google but couldn't find anything useful. All I could get was this link but it doesn't really solve my problem.

Any help will be really helpful for me.


texts:
I'm trying to view 3D objects in a terminal. Everything was looking good until I implemented lighting. I'm using shadow rays to determine where the object should be lit. Although it's working I don't know how to make it smooth, I haven't tried anything since I don't actually know what to do.
Here's how a sphere is looking (light is coming from above):

As you can see it's either really dark (.) or light (@) so it's hard to determine the object.


texts:
I am writing an Oculus Rift application, I am rendering a very high poly mesh that I wish to be able to perform picking on using the Oculus Touch. Ideally, I want to be able to get the "triangle" id and other information attached to it.

Currently, I am using an OBB Tree and ray casting to perform picking on the CPU, It works perfectly, the problem is that even with OBB tree the picking process is slow. I thought I'd perform picking on the GPU by rendering the view (from the point of view of the Oculus Touch) to an FBO using a custom shader that outputs "triangle information" to the buffer and then use glReadPixels to  read the central pixel data. The problem I am facing is that the Oculus does distortion to  my on-screen scene but there is no way to apply it to the off-screen buffer, so there is significant difference between the on-screen buffer and the off-screen buffer.

My question is, Is ray casting the only feasible way to do picking in Oculus Apps or is there a way to perform the faster FBO picking even when the view distorted?


texts: [JOGL] My program is too slow, how can I profile with Eclipse?

texts:
My simple opengl program is really toooo slow and not fluid.
I'm rendering 30 sphere with simple illumination and simple materials.
The only complex computing stuff I do is a collision detection between ray-mouse and spheres (that works ok and i do it only in mouseMoved)
I'm not using any threads, just an animator to move spheres.

How can I profile my jogl project?

Or maybe (most probable...) I have some opengl instructions that I don't understand and make render particular accurate (or back face rendering that I don't need or whatever I don't know exactly I'm just entering the opengl world)


texts:
My tanks working  good except one thing, they not avoid each other in good way. they not generate the path to find new good position. My tank follow it own agent position and direction. I add NavMeshObstacle fit the tank size. After all this, still I get some bad things. tanks hit each other, tank moving above other tank, some time get stuck between two tanks which lead to strange movement(shaking). example this tank on the middle.

what can I do to improve tank avoiding ?


texts: Calculate velocity to hit the target on flat 2d surface

texts:
I am creating a game using Python and Pygame.

I have used this function before (with JS with p5.js and Java with libwjgl, but for some reason it does not work with pygame (I am not sure if it matters here).

I'm trying to hit a static target shot from a moving object.

This is how I am doing this:

def shoot(self):
  posX, posY = 100, 100 # Static target coordinates

  diffX = self.player.x - posX
  diffY = self.player.y - posY

  distance = math.sqrt((diffX * diffX) + (diffY * diffY)) # Calculate the distance

  velX = float((-1 / distance * diffX * 6))
  velY = float((-1 / distance * diffY * 6))

  # Bullet(x, y, width, height, velocityX, velocityY)
  # Will be rendered on the screen
  self.bullets.append(Bullet(self.player.x, self.player.y, 10, 10,  velX, velY))

Updating bullet location:

  def update(self):
    self.bullet.x += self.velX
    self.bullet.y += self.velY

This works perfectly with other languages I have mentioned, but in Python the launched projectile is off...

Here is how it looks. The red square is the target.

THANK YOU, EVERYONE, FOR THE HELP. I really appreciate it :)


texts: Attaching two objects and changing their world matrices accordingly

texts:
I'm having a hard time wrapping my head around the transformations required to bind two objects together in either a two-way or one-way relationship. I will need to implement both types.

For the first case, I want to be able to 'couple' two ships together in space. The ships have different mass, of course. Forces applied to either ship will use combined mass and moment of inertia to calculate and move both ships. The trick is, being sure that the point at which they are coupled remains the same, and they don't move at all relative to each other.

The second case is similar: I want a ship to be able to enter the atmosphere of a planet and move relative to the planet. The planet will be orbiting the sun, which is fixed at 0,0,0. Essentially, when the ship is sitting still outside of the atmosphere, the planet will move past it on its course-- but when the ship is sitting still inside the atmosphere, it moves and rotates with the planet, so that it is always relative to the horizon. Essentially, the vertices which make up the ship are now transformed just like the ones that make up the planet, except that the ship can move itself around relative to the planet.

I get the feeling I can implement both of these with the same code. Essentially, I am thinking of giving each object (which I call Fixtures) a list of "slave" Fixtures onto which that Fixture's world matrix is imposed. So, this would be the planet imposing its world on any contained ships. In the case of coupling, I would simply make each ship a slave of the other, somehow.

Obviously I can't just multiply the ship's world matrix by the planet's, or each ship by the others. What I'd like some help with is what calculations to make in order to get a nice, seamless relative world to the other object. I was thinking maybe I could just multiply the world of the slave by the inverse of the master, but then when you couple two ships you would lose all that world data. So, perhaps I need an intermediate "world" which is the absolute world, but use a secondary "final world" to actually transform the objects?


texts:
I'm making a mobile game for Android and iOS on Unity. At the moment I am researching and designing the technical aspects of the game. Since it is not plausible to use highly detailed models for mobile platforms, should normal mapped models be used instead?

Thus I have couple of questions about normal mapping. Are normal mapped models much more costly to make, in other words, do they take a lot longer to create? And are they much more expensive to render? At least there are no additional draw calls, but of course the shader is more complex.


texts: Space Shooter: Multiple weapons approach

texts:
I'm building a small space shooter and want my player to have multiple weapons available.
I'm using an array and a vector for the weapons (both initialized when the player is initialized).  Both the weapon array and vector are members of the player.

    CWeapon     m_aWeapons[3];  // Array for unlockable weapons
    vector<CWeapon> m_vWeapons; // Vector for unlocked weapons

The weapons that can be unlocked are initialized in an array at the beginning.

// Set unlockable weapons
m_aWeapons[0].Init("LaserOrange.bmp", 0.2f, 400.0f, 20.0f);
m_aWeapons[1].Init("LaserBlue.bmp", 0.2f, 600.0f, 20.0f);
m_aWeapons[2].Init("LaserRed.bmp", 0.2f, 800.0f, 20.0f);

I save the weapons the player has available at current in the vector.

After each level the next weapon is unlocked, if possible, by pushing the next element of the array into the vector with the public method CPlayer::UnlockWeapon ().

// Unlock
//
// Task: Unlock next weapon
//
bool CPlayer::UnlockWeapon()
{
// Unlocked new weapon?
bool bUnlocked = false;

// Temp for size of weapon vector and array
int VectorSize = static_cast<int> (m_vWeapons.size ());
int ArraySize = sizeof(m_aWeapons) / sizeof(CWeapon);

// Not unlocked every weapon?
if (VectorSize < ArraySize)
{
    // Yes, then unlock next
    m_vWeapons.push_back(m_aWeapons[VectorSize]);

    // Unlocked new weapon
    bUnlocked = true;
}

return (bUnlocked);

} // UnlockWeapon

I save the index of the currently selected weapon in a variable and when the player shoots, I create a shot and initialize it with the speed and shotsprite of the vector element at the index of the currently selected weapon variable.

// ProcessShooting
//
// Aufgabe: Shoot weapon
//
void CPlayer::ProcessShooting ()
{
// Hasn't shot until now
m_bHasShot = false;

// Pressed "Space" and can shoot?
if (g_pFramework->KeyDown (SDL_SCANCODE_SPACE) && m_bShotLock == false)
{
    // Has shot
    m_bHasShot = true;

    // Create and initialize new shot
    CShot Shot;

    // Temp for ease
    CWeapon Temp = m_vWeapons.at(m_CurrentWeapon);

    Shot.Init(Temp.GetSprite(), m_fXPos, m_fYPos, Temp.GetSpeed ());

    // Insert shot into shotlist
    m_ShotList.push_back (Shot);

    // Shoot again, when space released
    m_bShotLock = true;

}

// Released space, so allow shooting
if (g_pFramework->KeyDown (SDL_SCANCODE_SPACE) == false)
    m_bShotLock = false;

} // ProcessShooting

Is that a strange approach or can I stick with it?


texts: What book/guide should I follow for GLSL

texts:
I searched a lot on the web without coming to a real solution and if I ask this it's because I really have difficulties getting an answer. I need to learn well GLSL 1.20 with OpenGL 2.1.

I have bought beginning OpenGL game programming, 2nd edition, but it talk too little about GLSL. So I'm following some tutorials like this one, but it just makes a lot of examples without explaining the theory.

The problem is that if I want to know something, I have to search a lot, and often the thing that I'm searching doesn't come straightforward. For example I didn't know how to compute the direction between two points, I looked into some example codes and I discovered that it was done with the dot product just by seeing the example code. But with this approach I waste a lot of time. I need a book/guide which tells me how to do basilar stuff and also explains the theory. I just feel like I'm travelling into the fog. What book/guide would you suggest?


texts: OpenGL camera translate and rotate on cameras local axis

texts:
How can I make rotation and translation on a local camera axis in OpenGL?
I want to make camera like "aeroplane" camera with a pitch yaw and roll.
I want to have good explanation on everything!

Can the solution be with gluLookAt maybe and be without gimbal lock?


texts: I want to delay 3 sec to load next level after the collision in C#

texts:
I need to delay the load new level by a few second. Please help.This is the script I need to use:

void OnCollisionEnter2D(Collision2D col)
{
    if (col.gameObject.tag == "Enemy")
    {
         score = score + 50;
         Destroy (gameObject);
         /*Here I need to wait for 3 sec then it should load the next level*/
         SceneManager.LoadScene(nextLevel);
    }
}

I have tried this code but this doesn't update my score and don't wait and don't even load the next level:

void OnCollisionEnter2D(Collision2D col)
{
    Debug.Log ("Collision");
    if (col.gameObject.tag == "Enemy")
    {
        score = score + 50;
        Destroy (gameObject);
        StartCoroutine (WaitForIt (3.0F));
    }
}

IEnumerator WaitForIt(float waitTime)
{
    yield return new WaitForSeconds(waitTime);
    SceneManager.LoadScene(nextLevel);
}


texts:
I am trying to Rotate a textured quad in directX however I think i am missing something. I am pretty sure it is because i am applying transformations to the WorldMatrix instead of the ObjectWorld, however i do not have an object world matrix so i am unsure how i would get that since i am not storing much except the texture and the position of 4 vertices directly to the buffer and only updated when it is needed.

here is what i have tried

bool GraphicsClass::Render(float deltatime)
{
D3DXMATRIX worldMatrix, viewMatrix, projectionMatrix, orthoMatrix, rotationZ;
bool result;

// Clear the buffers to begin the scene.
m_D3D->BeginScene(0.0f, 0.0f, 0.0f, 0.0f);

// Generate the view matrix based on the camera's position.
m_Camera->Render();
//DrawingStuff
// Get the world, view, projection, and ortho matrices from the camera and d3d objects.
m_Camera->GetViewMatrix(viewMatrix);
m_D3D->GetWorldMatrix(worldMatrix);
m_D3D->GetProjectionMatrix(projectionMatrix);
m_D3D->GetOrthoMatrix(orthoMatrix);
//Transform World Matrix with a rotation matrix
D3DXMatrixRotationZ(&rotationZ, 90.0f);
D3DXMatrixMultiply(&worldMatrix, &worldMatrix, &rotationZ);
// Turn off the Z buffer to begin all 2D rendering.
m_D3D->TurnZBufferOff();
// Put the bitmap vertex and index buffers on the graphics pipeline to prepare them for drawing.
result = m_Bitmap->Render(m_D3D->GetDeviceContext(), 124, 124);
if(!result)
{
    return false;
}

// Render the bitmap with the texture shader.
result = m_TextureShader->Render(m_D3D->GetDeviceContext(), m_Bitmap->GetIndexCount(), worldMatrix, viewMatrix, orthoMatrix, m_Bitmap->GetTexture());
if(!result)
{
    return false;
}

// Turn the Z buffer back on now that all 2D rendering has completed.
m_D3D->TurnZBufferOn();

// Present the rendered scene to the screen.
m_D3D->EndScene();

return true;
}

the full code can actually be downloaded from http://www.rastertek.com/dx11tut05.html with the minor difference that render takes in delta-time since last frame using a custom timer class which is not provided by them as well as a few minor tweaks but it is mostly the same.

i did find this http://www.rastertek.com/dx11tut25.html which i may try to implement however that is not really what i want, i want to rotate the actual quad, not the texture.


texts: AI: dealing with movement driving the same inputs as the player

texts:
My AI design is pretty simple. I have different entities that can be possessed either by the player or the AI.
Those entities have an "Input" component that holds the states of the actual inputs, like right, left, up, down, fire. (and wasRight, wasLeft, wasUp, wasDown, wasFire to perform checks on whether the input was just triggered or not).

My PlayerController class is driving that component by reading inputs from either the keyboard or the gamepad.

In a similar way, my AIController comes up with that same input through logic functions.

Now I've hit a wall with this kind of approach when dealing with movement.

Let's say that I'm in 2D space and that I'm moving the AI horizontally. I am moving from (0, 0) to (10, 0) so I'm activating the "right" input all the way until I reach the (10, 0) position.

But if the speed of my entity is high, I might actually go over the position and trigger a movement back, and then again forward and so on as it can't actually settle.
I know that I could just check if the previous movement was in the same direction and that if I went through the target I could just force the position to be in the exact spot that I want to reach. But it doesn't really look like a clean solution.

Is this approach completely wrong? I would like to try and keep it simple and modular at the same time.


texts: Is it possible to push real-world, real-time data into Unity?

texts:
I'm pretty new to this, and I'm having trouble figuring out where to even look.  If there's relevant terminology that'll be google-able, that would be a great help.

Suppose I want to have a monitor in-game that displays the output from a camera that's in the same room as the player.  Are there libraries for grabbing and rendering that data?


texts: Unwanted blendspace bone displacement in UE4

texts:
My characters hands "fall off" in the blendspace between the animations.
Looking for a way to fix it, if anyone has any ideas.


texts:
I was trying following things.
GameManager :
bool gameHasEnded = false;
public GameObject completeLevelUI;

public void CompleteLevel(){
    completeLevelUI.SetActive(true);
}

public void EndGame(){
    if(gameHasEnded == false){
        gameHasEnded = true;
        Invoke("Restart",2f);
    }
}

void Restart(){
    SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}

EndTrigger :
public GameManager gameManager;

void OnTriggerEnter(){
    gameManager.CompleteLevel();
}

I get a log in the console "END". Earlier I was using Console.Log("END"); on CompleteLevel(), but I changed that source code. The old code seems to be working and not the new one. It's like Unity couldn't refresh that source code. (And I am sure that I have successfully saved the C# file.)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerCollision : MonoBehaviour
{

    public PlayerMovement movement;

    void OnCollisionEnter(Collision collisionInfo)
    {
        Debug.Log(collisionInfo.collider.name);
        if (collisionInfo.collider.tag == "obstacle")
        {
            movement.enabled = false;
            FindObjectOfType<GameManager>().EndGame();
        }
    }

}
```


texts: Reading messages from a certain client in Lidgren

texts:
I'm setting up a game with Lidgren, and I was wondering if there was a way to read a message from a certain client instead of just from the server as a whole, such as-

//Why doesn't this exist?
NetIncomingMessage message = server.Connections[0].ReadMessage();

This way I would be able to split up reading data from each client into it's own thread and have a separate thread for sending data to each client. Currently there is only one loop in my server, which reads packets and I fear is favoring one client more than others, as some movements made by players take a while to be received by other players. I believe reading messages separately from each client would solve this issue. With simple TcpClients, you can read from each client's stream instead of the server as a whole, and I like this functionality but also rely on the simplicity of sending packets through Lidgren and was wondering if there was a similar functionality with Lidgren.


texts: Collision Between SKSpriteNode and SKShapeNode

texts:
I'm trying to create a collision between two objects. One is a SKSpriteNode and the other is a SKShapeNode. The code I have so far for determining contact is:

 func didBeginContact( contact: SKPhysicsContact) {
        let firstBody  : SKPhysicsBody = contact.bodyA
        let SecondBody : SKPhysicsBody = contact.bodyB

        if ((firstBody.categoryBitMask == PhysicsCatagory.Orange) && (SecondBody.categoryBitMask == PhysicsCatagory.Red)) || (firstBody.categoryBitMask == PhysicsCatagory.Red) && (SecondBody.categoryBitMask == PhysicsCatagory.Orange) {

            CollisionWithRed(firstBody.node as! SKSpriteNode, Red: SecondBody.node as! SKShapeNode)
        }

    }

    func CollisionWithRed (Orange: SKSpriteNode, Red:SKShapeNode){
       Orange.removeAllChildren()
       Red.removeAllChildren()
    }

The problem is that after the collision, the Orange and Red are not removed from the screen. They are still there.

The code for Orange is :

 func SpawnOranges () {
        let Orange = SKSpriteNode(imageNamed: "Orange.png")
        Orange.size = CGSize (width: 80, height: 80)
        let MinValue = self.size.width / 8
        let MaxValue = self.size.width - 20
        Orange.zPosition = 7
        let SpawnPoint = UInt32 (MaxValue - MinValue)
        Orange.position = CGPoint (x: CGFloat(arc4random_uniform(SpawnPoint)), y: self.size.height)
        Orange.physicsBody = SKPhysicsBody(rectangleOfSize:Orange.size)
        Orange.physicsBody?.categoryBitMask = PhysicsCatagory.Orange
        Orange.physicsBody?.affectedByGravity = false
        Orange.physicsBody?.dynamic = true
        Orange.physicsBody?.contactTestBitMask = PhysicsCatagory.red
        let action = SKAction.moveToY(-150, duration: 2.0)
        let actionDone = SKAction.removeFromParent()
        Orange.runAction(SKAction.sequence([action, actionDone]))

        addChild(Orange)

The code for Red is :

class Red: SKShapeNode{
    convenience init(path: UIBezierPath, color: UIColor, borderColor:UIColor) {
        self.init()
        self.path = path.CGPath
        self.fillColor = color
        self.strokeColor = borderColor

        Red = Red(path: projectilePath, color: UIColor.redColor(),
          borderColor: UIColor.blackColor())
        Red.position = Settings.Metrics.projectileRestPosition
        Red.zPosition = 7
        Red.name = "Square"
        Red.physicsBody = SKPhysicsBody()
        Red.physicsBody?.categoryBitMask = PhysicsCatagory.Orange
        Red.physicsBody?.affectedByGravity = false
        Red.physicsBody?.contactTestBitMask = PhysicsCatagory.Orange
        Red.physicsBody?.collisionBitMask = PhysicsCatagory.Orange
        Red.physicsBody?.dynamic = true
        Red.physicsBody?.affectedByGravity = false
        addChild(Red)

Any help would be extremely appreciated!


texts:
I have search with every word of my limited English for this question, and I think it's is not appropriate for this site but I just got to try.

I implemented Google IAP for Android. In all the tutorials I have read not one tells where I can check how much money I'm making, or specify where I get paid. I guess what I'm trying to ask is how Google is gonna pay me if I have not specified anything?


texts: How do developers implement custom systems (lighting, physics, etc.) in premade game engines that already have these systems, like Unreal or Unity?

texts: Unreal has built in systems for stuff like lighting, for example. If a developer wanted to create and use their own lighting system in Unreal, how do they go about doing that? Or are these systems already so customizable that creating a custom system isn't necessary?


texts: Is it efficient to use colliders on UI canvas in Unity?

texts:
Basically I have a task where the player will be able to drag an object (as UI Image), and place it inside a bag (another UI image).

What's the best optimized way to do so? As I researched, I do not think that using colliders for images is the "best" way to do it.
Additionally, I was thinking about  checking if the position of the image while dragging overlaps an element; however, I do think that would be performant as that would require checking the position on each frame instead of "OnTriggerEnter".

What would be the best way to implement such function?

Thanks & Regards,
HurpaDerpa


texts:
In Gamemaker, I have a main menu room, and hitting start takes you to the gameplay room. When testing it, it did not take me to the gameplay room. I made it load into the problem room first, and all it loaded was a black screen. I also noticed when I looked in the console it was said:

  RequestStats - failed: 2

What's causing this and how do I fix it?

Here is my game:
https://drive.google.com/open?id=1xWota0WfzcwvYGHY4zFVwS0vXDwNQfDp


texts: Poor text rendering quality with freetype

texts:
This is my first time that I use freetype library and I think I've got some problems. Right now, I draw the bitmap generated by freetype, but the generated image is really low quality. I've been reading about hinting and anti-aliasing, but the thing is none of them helped me and the problem is still here.

Take a look at my picture:

You can actually see what I mean.

I have applied a vertical hinting before rendering in my font class:

float scale = 100.0f;
FT_Matrix transform =
{
    (int)((1.0 / scale) * 0x10000L),
    (int)((0.0) * 0x10000L),
    (int)((0.0) * 0x10000L),
    (int)((1.0) * 0x10000L)
};

FT_Set_Char_Size(this->mFace, 0, (int)(this->mSize * 64), (FT_UInt)(72 * scale), 72);
FT_Set_Transform(this->mFace, &transform, NULL);

I'm loading the character with:

FT_Load_Char(this->mpFont->Face(), this->mText[i], FT_LOAD_RENDER);

which is supposed to make the generated bitmap anti-aliased immediately as documentation has stated.

The part which I translate the buffer is here:

...
    BYTE intensity = bitmap->buffer[q * bitmap->pitch + p];
    D3DXCOLOR pixel(this->mColor.r * intensity,
    this->mColor.g * intensity,
    this->mColor.b * intensity,
    this->mColor.a * intensity);

    this->mpTexture->SetPixel(i, j, pixel);
...

My texture format is A8R8G8B8 and I don't think I have anything wrong with my texture rendering part. The only thing that I'm not sure this is related to is the resolution. Currently I'm using the window size (640x480) which turns to lower resolution for device because of borders. By the way, this is a regular Tahoma font that I've used.


texts: Line plane intersection: what is this variable?

texts:
I'm doing line plane intersection, and have come across an un-referenced variable or constant in the tutorial I'm following.
One of the formulae given is this:
t = N dot (p2 – p0)
     N dot V
The variable I'm stuck with is V. Can someone tell me what V is and how I'd go about finding it?
For more info on that formula, please see the link given in the first para.
Thanks,
James


texts:
I remember visiting a webpage some time ago (1 year ago maybe)

It contained many java applets, describing how certain mathematical functions like sin, cos, arcsin, exp would make an object move, with an example of  animated ball next to it, with its curve and the function name.

It was quite exhaustive, and was quite handy to simulate physical behaviors, like bouncing ball, smoothing cameras...

I can't find it on google, Anybody remembering this page ?


texts:
I'm practicing the Phong lighting model with glsl, and here's my shaders:
vertex shader:

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

out vec2 TexCoord;
out vec3 LightColor;
uniform mat4 model;
layout (std140) uniform coord_mats {
    mat4 view;
    mat4 projection;
    vec3 lightPos;
    vec3 lightColor;
};

void main()
{
    vec3 vertex_position = vec3(model * vec4(aPos, 1.0));
//    vec3 vertex_position = vec3(view * model * vec4(aPos, 1.0));
    vec3 vertex_normal = normalize(vec3(model * vec4 (aNormal, 1.0)));
//    vec3 vertex_normal = normalize(vec3(view * model * vec4 (aNormal, 1.0)));
    vec3 light_position = vec3(vec4(lightPos, 1.0));
//    vec3 light_position = vec3(view * vec4(lightPos, 1.0));
    vec3 light_dir = normalize(light_position - vertex_position);
    float diff = max(dot( light_dir,vertex_normal), 0.0);
    vec3 diffuse = diff * lightColor;
    vec3 ambient = 0.1 * lightColor;
    LightColor = diffuse + ambient;

    gl_Position = projection * view * model * vec4(aPos, 1.0);
    TexCoord = vec2(aTexCoord.x, aTexCoord.y);
}

fragment shader:

#version 330 core
out vec4 FragColor;

in vec2 TexCoord;
in vec3 LightColor;
// texture sampler
uniform sampler2D texture1;

void main()
{
    FragColor = vec4(LightColor,1.0) * texture(texture1, TexCoord);
}

The diffuse light works right, that is, faces which are facing to the light source, are bright, when backing the light source, they are dark(basically ambient color).

Now I want to calculate the specular light, in order to get the camera position for free, I changes the coordinate to camera view coordinate(using the commented code, just multiply the view matrix to the vertex position, normal and light position), but weird things happened: all faces which are facing the light is dark, all faces which are backing to the light is bright.

How could this happened?


texts: Picking a suitable resolution for a modern low-res game?

texts:
I'm working on a 2D game project right now (using SFML+OpenGL and C++) and I'm trying to figure out how to go about choosing a resolution. I want my game to have a pixel resolution that is around that of classic '16bit' era consoles like the Super Nintendo or Neo Geo. However, I'd also like to have my game fit the 16:9 aspect ratio that most modern PC monitors use. Finally I'd like to be able to include an option for running full screen.

I know that I could create my own low-res 16:9 resolution that is more-or-less around the size of SNES or NeoGeo games. However, the problem seems to be that doing so would leave me with a non-standard resolution that my monitor would not be able to support in fullscreen mode.

For example, if i divide the common 16:9 resolution 1920x1080 by 4, I would get a 16:9 resolution that is relatively close to the resolution used by 16bit era games; 480x270.
That would be fine in a windowed mode, but I don't think that it would be supported in fullscreen mode.

How can I choose a resolution that suits my needs? Can I use something like 480x270? If so, how would I go about getting fullscreen mode to work with such a non-standard resolution? (I'm guessing OpenGL/SFML might have a way of up-scaling...but..)


texts: Moving from HeroEngine to Unity/Torque 3D

texts:
Short background: small team with some financial back-up from investors, yet no multi-billion-$ enterprise, working on an MMORPG for PC.

HeroEngine looks like the perfect solution. Everything included that's needed to get started, programming languages also include C++/C#. Sounds perfect.

However, once the money's rolling in, a company might prefer work on its own, including its own server park, etc.

Does anyone have experience in using HeroEngine? Is it possible to migrate projects from it to Unity/Torque 3D or the like? Are there legal restrictions (I had a look into the license agreements yet was unable to find an answer to this)?

Should they get started with HeroEngine and the migrate later or is it wiser to choose an engine like Unity/Torque 3D from the get-go?


texts: How can I make my C++ game which installs its own DLL files?

texts:
Example: Minecraft is the same single .exe from the moment it's downloaded. Installations occur fairly quickly (very painless) for the selected version.

My case: I have a C++ game which uses the following libraries:
- SFML
- GLAD
- GLEW
- GLM
- ASSIMP

How can I make my game a single .exe which installs these libraries in the directory I want, if they're not there on execution, and also executes the game? (presumably that's how I imagine it should work).

I think I already made my point, but in essence I want the game to be a single .exe managing all external dependencies.


texts:
Coming from XNA, I would use the content pipeline and create XML files for game objects.  However, if I changed something in the XML, I would need to do a rebuild of the project so it will create the XNB file.

Do I need to create XML files on my own and create* encrypt/decrypt process and XML parser?  Or should I simply hard code (since any changes would need a rebuild anyway)?

Most of the things in my game project will be random.  However, the base types (like Armor types) will be static.  Meaning one type of armor will give 20% armor.  And another type of armor will give 50% armor.

I do not want to use any third party solutions.  I want to do everything myself so I can learn how to handle these situations.


texts: Where is ID3D10EffectShaderResourceVariable::SetResourceArray in SlimDX?

texts:
I don't know if I'm just not looking in the right place, but I can't find ID3D10EffectShaderResourceVariable::SetResourceArray anywhere in SlimDX.

Anyone have any idea how I should be calling this?


texts: How to do score systems, combos, multipliers, chains, etc

texts:
I am designing a game, but I am having some trouble implementing a decent score system. Basically I have nodes with two different possible characteristics: color and shape. Since the player click from node to node, I want to award more points to the players which hit the same shape, same color or both, like: (SAME SHAPE x 3! AWESOME!, SAME SHAPE AND COLOR x 5! ARE YOU A WIZARD?!).

However I am having a lot of trouble implementing this. Can someone point me in the right direction or show me algorithms that can do this?