texts: Alpha is not working in diffuse light shader

texts:
I am following this tutorials series on rastertek.com and I got a bit stuck on the Diffuse Lighting Tutorial. Particulary, the part that does not work for me is alpha channel of the light color. Here are the [I think they are] relevant code parts:

Light Shader:

cbuffer MatrixBuffer
{
    matrix worldMatrix;
    matrix viewMatrix;
    matrix projectionMatrix;
};

Texture2D shaderTexture;
SamplerState SampleType;

cbuffer LightBuffer
{
    float4 ambientColor;
    float4 diffuseColor;
    float3 lightDirection;
    float padding;
};

struct PixelInputType
{
    float4 position : SV_POSITION;
    float2 tex : TEXCOORD0;
    float3 normal : NORMAL;
};

float4 LightPixelShader(PixelInputType input) : SV_TARGET
{
    float4 textureColor;
    float3 lightDir;
    float lightIntensity;
    float4 color;

    textureColor = shaderTexture.Sample(SampleType, input.tex);

    lightDir = -lightDirection;

    lightIntensity = saturate(dot(input.normal, lightDir));

    color = saturate(diffuseColor * lightIntensity);

    color = color * textureColor;

    return color;
}

PixelInputType LightVertexShader(VertexInputType input)
{
    PixelInputType output;

    input.position.w = 1.0f;

    output.position = mul(input.position, worldMatrix);
    output.position = mul(output.position, viewMatrix);
    output.position = mul(output.position, projectionMatrix);

    output.tex = input.tex;

    output.normal = mul(input.normal, (float3x3)worldMatrix);

    output.normal = normalize(output.normal);

    return output;
}

The problem here is the shader completely ignores the alpha channel of the light. If I set the diffuse color to red, then the texture will be reddish no matter what alpha is supplied.

The only way I could make the alpha work is changing the line

color = color * textureColor;

to

color = color * color.w * textureColor;

in the pixel shader. This however gives overall wrong result.

Might it be the DirectX setup issue, here are some parts of the device initialization:

// Set regular 32-bit surface for the back buffer.
swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;

[...]

// Set up the description of the depth buffer.
depthBufferDesc.Width = screenWidth;
depthBufferDesc.Height = screenHeight;
depthBufferDesc.MipLevels = 1;
depthBufferDesc.ArraySize = 1;
depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthBufferDesc.SampleDesc.Count = 1;
depthBufferDesc.SampleDesc.Quality = swapChainDesc.SampleDesc.Quality;
depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
depthBufferDesc.CPUAccessFlags = 0;
depthBufferDesc.MiscFlags = 0;

[...]

// Setup the raster description which will determine how and what polygons will be drawn.
rasterDesc.AntialiasedLineEnable = false;
rasterDesc.CullMode = D3D11_CULL_BACK;
rasterDesc.DepthBias = 0;
rasterDesc.DepthBiasClamp = 0.0f;
rasterDesc.DepthClipEnable = true;
rasterDesc.FillMode = D3D11_FILL_SOLID;
rasterDesc.FrontCounterClockwise = false;
rasterDesc.MultisampleEnable = false;
rasterDesc.ScissorEnable = false;
rasterDesc.SlopeScaledDepthBias = 0.0f;

What's wrong with this shader?

I'm not sure what other code might be relevant, I will gladly add any at your request.


texts: Examples of TIN-based terrain formats in FPS games

texts:
Do you know of any terrain formats for FPS games that use a triangulated irregular network (TIN) instead of a grid for elevation representation? Or at least a game whose development tools accept a TIN as input for terrain elevation?

The only example I have is the ASCII Scene Export (ASE) format that can be used as input in the terrain editor for the Unreal engine (UnrealEd). I am mainly looking for formats that support terrain holes (both visually and in collision detection) and allow underground models. I want to avoid having to carve and cover gridded terrain elevation grids to place underground models.


texts: Collision detection for an arc of a circle

texts:
So how do I implement the collision detection for an arc of a circle? Will I have to use the Box 2D collision or can I do it some other way using Rectangle or stuff like that?

BTW I hate box2d because I don't understand most of the things in it, so if there is a solution that excludes the box2d, it will be very much appreciated.

The yellow arc keeps on rotating over the black circle. How do I implement collision detection in here?


texts:
I have almost finished my game; I want to upload it to Google Play and the App Store.  I will make it free but with Admob advertising.
What is the best way to market my app (without any app promotion companies)?
Please give me a detailed explanation.


texts: How to scale major and minor radius of a quarter torus

texts:
I am dealing with quarter tori as in the image below. My issue is that I need to be able to scale its major radius and minor radius separately using a scale matrix. However, when I use a regular transformation matrix like:
    scaleX, 0, 0, 0,
    0, scaleY, 0, 0,
    0, 0, scaleZ, 0,
    0, 0, 0, 1;

It scales both radiuses. Is there a way I can do this separately? I can't get my head around how this would be possible? Thank you in advance.


texts:
I'm looking at this three.js cubemap example, and it runs fine in my browser when loaded from that page.
After much strain to find and download the files - it does not run?
What am I doing wrong, with this "module" stuff?
I got it to work by changing:

<script type="module">
import * as THREE from 'three.module.js';
...

Into:
<script src="three.js"></script>
<script>
...

Can anyone explain how to properly import three.module.js? Why is this change necessary when I run the project on my machine?


texts: Are there any pitfalls with this approach to isometric map generation?

texts:
First of all, I don't have much experience on game development but I do have experience on development. I do know how to make a map, but I don't know if my solution is a normal or a hacky solution. I don't want to waste my time coding things, and realise they're utterly crap and lose my motivation.

Let's imagine the following map. (2D - top view - A square)

X: 0 to 500
Y: 0 to 500

My character currently stands at X:250,Y:400, somewhere near center of 100px above bottom and I can control him with my keyboard buttons. LEFT button does X--, UP button does Y-- etc.

This one is kid's play.

I'm asking this because I know there are some engines that automate this task. For example, games like Diablo 3 uses an engine. You can pretty much drag drop a rock to map, and it is automatically being placed here - making player unable to pass through/detect the collision. But what the engine exactly does in the background? Generates a map like mine, places a rock at the center, and checks it like:

unmovableObjects = array('50,50'); //we placed a rock at 50,50 location

if(Map.hasUnmovableObject(CurrentPlayerX, CurrentPlayerY))
{
     //unable to move
}
else
{
     //able to move
}

My question is: Is this how 2D/Isometric maps are being generated or there is a different and more complex logic behind them?


texts:
I have two different projects open in Unity. But my grass material appears different in each project, despite all the parameters being the same.

See this image:

On the left is the desired appearance. But on the right my material has a strange white-ish outline. How do I get rid of it?

I have tried copying the material between the projects, and the problem seems to be independent of the available lighting


texts: Is there any reason for doing back face culling in software?

texts: I, a newbie, have been doing back face culling in javascript for my WebGL app because I didn't know gl.cullFace() existed. Is there any reason to use software-based culling instead of just passing all faces to GPU and let it do the culling?


texts: Roughly how many rigid bodies can I expect to have interacting in Bullet?

texts:
On my Phenom II desktop machine (about 3 years old) with 8GB of RAM, it seems that I can only throw around a hundred or two boxes before it starts to go slow. I'm using the built-in DbvtBroadphase.

Is this about right, or am I missing something?

One thing that can't possibly be right though is that it takes several minutes to delete all the bodies (the RigidBodies, to be exact), spending nearly all of its time in HeapFree.

By the way I'm using BulletSharp, but I'm only making one call to the native API each frame -- which suggests that it's not the fault of the wrapper that it's so slow, unless there's something really weird going on with it.

Edit: It seems that there's a threshold point after which the program's memory consumption just starts skyrocketing. Something's leaking. Still, I'd be interested to know what to expect in a normal situation.


texts: Calculating bullet travel knowing coordinates and radian

texts:
I have a player sprite that has a x and y coordinate and also a radian. The radian determines which way the sprite faces in a top-down game interface. In this case, the radian points from the player sprite to the mouse cursor, so the player is always facing the mouse.

I'm calculating it like this:

this.radian = Math.atan2(inputs.mousey - this.ypos, inputs.mousex - this.xpos);

Now I want the player to be able to fire bullets. The bullet sprite is 5x5 pixels, and I want it to fire directly away from the player in the players direction (so it's basically firing in the direction of the mouse cursor). The bullets the player fires are held in an array called (conveniently) bullets. It's a 2-dimensional array that looks like this:

var bullets = [
    [xpos, ypos, radian], // first bullet
    [xpos, ypos, radian], // second bullet
    [xpos, ypos, radian]  // third bullet
]

The bullet is to travel 5 pixels on each game tick, in the direction determined by the radian. But I'm having trouble working out the math for this. I already have the bullet being drawn to the canvas, and I can make it move, but have no idea how to make it follow the direction the radian is pointing.

Could anyone lend a hand, perhaps a code sample? Thanks.


texts:
Im pretty new to game dev in Unity, and thought I'd start off with a relatively simple game:

Im planning to make a game where 3 cups are shown on a table, and a ball is placed beneath one, the cups go down (concealing the ball) and move around. If the player selects the right cup, they win.

Not sure if I'm jumping in the deep end, but I'd like to make this dynamic in the sense that the animation shouldn't dictate the place of the cup on the table, as I want to code it so that the amount of cups can be set (as a difficulty).

After looking into the state machine stuff behind Unity's AnimationController but not sure how I should go about it.

I've identified various states as below:

A cup can be down on the table
A cup can be lifted
A cup can be moved to a different position on the table (?)

You can see from the above that I dont know if I should include that as a state. When moving 2 cups, one cup should move forward to it's new position, and the other should move behind it as not to cause them to collide, but would also like to be able to code this in a way where cups on the far ends can be swapped as well.

Any advice?


texts: When updating a mesh, does 'glBufferSubdata' belong in the update or render function?

texts:
When updating a mesh, does the glBufferSubdata call belong in the update function, or the render function?

I'm trying to organize my game appropriately. and knowing this would help me.  This is my first game, and I want to structure it properly.


texts:
I'm trying to change the velocity of a character controller component on a Third Person Controller, but when I try to change it, the console says the velocity is read only. This is my code.

P.GetComponent(CharacterController).velocity = 0;

(P is my player GameObject variable)

So, any ideas on how to change this?

Thanks, Chris.


texts: Unity2D: Pressing my mute button twice in order for it to set music back to 1

texts:
So far my mute button works, its just that I have to press my button twice (when game is restarted) in order for it to put my volume back to 1. Does anyone knows the problem. Anyway this is my script:

public bool mute;

void Start()
{
    // check if the player has a music volume preference
    if (PlayerPrefs.HasKey("musicVolume"))
    {
        // if yes, apply it.
        GetComponent<AudioSource>().volume = PlayerPrefs.GetFloat("musicVolume");
    }
}

private void Muted ()
{
    AudioSource audioSource = gameObject.GetComponent<AudioSource>();

    mute = !mute;
    if (mute) {
        gameObject.GetComponent<AudioSource> ().volume = 0;
       // PlayerPrefs.SetFloat("mute", 0);
    }
    else
    {
        gameObject.GetComponent<AudioSource> ().volume = 1;
       // PlayerPrefs.SetFloat("mute", 1);
    }
    // write new music volume preference to persistent storage
    PlayerPrefs.SetFloat("musicVolume", audioSource.volume);
}

Thank you. :)


texts:
I'm trying to make a pong clone and am having trouble grasping ball deflection. The way I'm approaching it is to increase the angle by how far the ball collides from the middle of the paddle. However, I can't seem to get the math right and I've tried so many things that I'm beginning to doubt what I know.

The issue I'm running into is that I can get the angle I want in degrees, but I can't figure out the correct way to apply it to the velocity vector. Is there a way that I can take ANY angle and apply it evenly across the ball velocity?

For example, when the game starts I set the velocity to -5,5 so that it heads left. If I were to calculate the angle of deflection as 50 degrees, what operation am I looking at to apply that to the velocity? Converting degrees to radians won't work because that would create fractional numbers and my velocity and position are ints. I've considered just hardcoding ranges of distance from paddleY into different velocities, but I was hoping there might be a better way.


texts: How do you create a .XNB Font file for use with CocosSharp?

texts:
I know the .XNB file format is an XNA thing and that CocosSharp inherits this from its MonoGame roots. However there doesn't seem to be any information on how to create your own .XNB fonts to use with CocosSharp. I've tried searching but can find any information.

Could someone explain it here or point me to a tutorial on how to create .XNB font file for use with CocosSharp?

A site to download already compiled .XNB Fonts would also be acceptable.

Update: Another thing that makes this tricky is that I guess XNA Game Studio could be used, but it's not compatible with Windows 8.1; which is what I currently use for my dev machine...


texts: Is a mesh OK to use for grass if there will be 1000's of them across the terrain?

texts:
Am creating a low poly game in Unity 3D for PC.  The terrain is made in Blender, so it's a fixed size, but quite large for the player to explore.  I want to add things such as grass and flowers, but am not sure the best practices are for creating those types of assets.

Is using a mesh for small clumps of grass the wrong way to do this if there will be 1000's of them?

I will likely be using the occlusion culling system Unity provides, but I'm not sure if I still need to look at doing things such as grass in a different way for performance sake.


texts:
I have created a very short piece of code to make the camera look at a transform object. I locked the rotation of the x and z axis as it is only supposed to rotate on the y axis. I would like to add some damping to this and make it rotate slowly, thanks.
Here is my Code:

public Camera Camera;

public void lookAt (Transform target)   {
    Camera.main.transform.LookAt (target);
}


texts: Unity 3d Raycast from localspace to worldspace

texts:
I want a raycast direction not relative to the rotation, but what happens is that the raycast points to one place as if it was a transform.forward

Why is the happening help

if(Physics.Raycast(transform.position, vector3.forward, out hit, SupportedDistance, CanBeSupported))
{
     NotSupported = false;

    //
}


texts: GameObject.Find() can't find object after loading the scene

texts:
I have 2 scenes in my project, MainMenu and Game.

MainMenu scene contains 2 buttons, 'Hide Black' and 'Hide White'. Game scene contains 2 panels, 'Black' and 'White'. When the user clicks any of button from main menu, I wanna hide the corresponding panel in Game scene and also load the scene. This is the script for the same.
using UnityEngine;
using UnityEngine.SceneManagement;

public class MainMenu : MonoBehaviour {
    public void HideBlack() {
        SceneManager.LoadScene(1);
        GameObject black = GameObject.Find("Black");
        black.SetActive(false);
    }

    public void HideWhite() {
        SceneManager.LoadScene(1);
        GameObject white = GameObject.Find("White");
        white.SetActive(false);
    }
}

But it turns out that GameObject.Find can't find the panels in my Game scene. I looked my forums for help but I find them confusing. What's going on here?
EDIT - This is not from my actual project. I created these scenes just to explain the problem better. I must use 2 scenes in my actual project as I have 3D objects in Game scenes.


texts:
I'm trying to work with picking up and throwing objects. So far I've come up with a solution which does pick up the object but the same time disappears the object also. Please check to the functionality I've used.

public class pickupobject : MonoBehaviour {
     //GameObject mainCamera;
     bool carrying;
     GameObject carriedObject;
     Camera cam;
     public float distances;
     public float smooth;

     // Use this for initialization
     void Start()
     {
         cam = GameObject.Find("MainCamera").GetComponent<Camera>();
     }

     // Update is called once per frame
     void Update () {
         if(carrying)
         {
             carry(carriedObject);
         }
         else
         {
             pickup();
         }

     }

     private void pickup()
     {
         if(Input.GetKeyDown(KeyCode.E))
         {
             int x = Screen.width / 2;
             int y = Screen.height / 2;
             Ray ray = cam.ScreenPointToRay(new Vector3(x, y));
             RaycastHit hit;
             if(Physics.Raycast(ray, out hit))
             {
                 pickupable p = hit.collider.GetComponent<pickupable>();
                 if(p!=null)
                 {
                     carrying = true;
                     carriedObject = p.gameObject;
                 }
             }
         }
     }

     void carry(GameObject o)
     {
         o.GetComponent<Rigidbody>().isKinematic = true;
         o.transform.position = o.transform.position + cam.transform.position + cam.transform.forward * distances;
     }
 }


texts: Convert global 3d coordinate system to a local one with specific direction

texts:
Imagine a (x,y,z) coordinate system within a solar system, with (0,0,0) beeing the center of sun where Z axis goes thru both solar poles.

I'm standing on a planet inside a house within that solar system.

Now from my perspective Z axis is skewed in unknown direction depending on where exactly the planet is at this moment.

What would be the steps I should take to create a local coordinate system with (0,0,0) being the house and where Z axis is perpendicular to the ground/house, so that I would be able to convert coordinates from local to global.

I have the global coordinate of my house and directional vectors for where is up/forward/right for my house.

I have some limited knowledge of vector math and projecting vectors on other surfaces, but there is a gap in my understanding that keeps me from solving this.

local housePos = vec(getHouseWorldPosition())        -- (x,y,z) position of house in global cooridnates (housePos.x,housePos.y,housePos.z)

local vRight = vec(getHouseWorldOrientationRight())  -- X directional normalized vector
local vForw = vec(getHouseWorldOrientationForward()) -- Y directional normalized vector
local vUp = vec(getHouseWorldOrientationUp())        -- Z directional normalized vector

local playerPos = vec(getPlayerWorldPosition())      -- players position in global coordinates

--Now how to get players position in coordinate system relative to housePos, with Z axis going along vUp vector


texts:
Is there a way to render something custom inside some html element in Awesomium?

For example:
I have inventory screen (that can be moved around) that has 3D avatar playing some idle animation weilding all equipped items. The screen should be html but the avatar is rendered by the game (to some texture) and now i need to display it on html page.


texts: How to put trees on procedural generated world created using Perlin noise

texts:
I have been new to game programming but I knew little bit about Perlin noise.
So I have created a infinite world using Perlin noise but I don't be able to understand how I put trees in my world like it is put in game Factorio.
My game is a 2d top down.


texts: Understanding MotionEvent to implement a virtual DPad and Buttons on Android (Multitouch)

texts:
I'm trying to implement a virtual DPad in android, but I'm still very confused about how do I keep track of each trouch point, from the moment it is pressed, till it is released.

In my code, I test if there is a "DOWN" or "MOVED" event, then if one of this events collides with one of the 4 rectangles of my DPad, I set the pressedDirectin variable to the side of the DPad which the user pressed.

The thing I'm not sure, is how do I get track of the touch points, I want to store the ID of the touch point which collided with the DPad direction, so when this ID is moved I update the direction of the DPad and when it gets released I set the Direction to None.

I don't want my DPad to handle multiple directions, but I still didn't get how to handle the multiple touch points, so I can know exacly which touch point is touching the DPad and store it's ID so I know when it is released.

Is the onTouchEvent called for every touch point, or all touch points comes in a single call? I still don't get it.

Here is the code I wrote so far, it works, but guess that it will only handle one touch point.

public boolean onTouchEvent(MotionEvent event)
    {
        if (event.getPointerCount() == 0)
            return true;

        int touchX = -1;
        int touchY = -1;

        pressedDirection = DPadDirection.None;
        int actionCode = event.getAction() & MotionEvent.ACTION_MASK;
            if (actionCode == MotionEvent.ACTION_UP)
            {
                if (event.getPointerId(0) == idDPad)
                {
                    pressedDirection = DPadDirection.None;
                    idDPad = -1;
                }
            }
            else if (actionCode == MotionEvent.ACTION_DOWN || actionCode == MotionEvent.ACTION_MOVE)
            {
                touchX = (int)event.getX();
                touchY = (int)event.getY();

                if (rightRect.contains(touchX, touchY))
                    pressedDirection = DPadDirection.Right;
                else if (leftRect.contains(touchX, touchY))
                    pressedDirection = DPadDirection.Left;
                else if (upRect.contains(touchX, touchY))
                    pressedDirection = DPadDirection.Up;
                else if (downRect.contains(touchX, touchY))
                    pressedDirection = DPadDirection.Down;

                if (pressedDirection != DPadDirection.None)
                    idDPad = event.getPointerId(0);
            }

        return true;
    }


texts:
I have begun work on an OpenGL application (all on my own and with little knowledge) and started with FTGL, rendering true type fonts, which, with alot of text has a great impact on frames per second.

I believe that to overcome this limitation one needs to generate a font atlas and save glyphs to opengl textures which are then drawn by shaders.

I have done a search of github for such a library and found several, a few of which are incomplete (and by their own admission have memory leaks)

I am looking for, and hoping that one of you can recommend, the most stable opengl font library that you preffer and does the aforementioned. I also need unicode support.

Or a guide to help a noob like me achieve this

Thankyou for reading


texts: Why aren't subsequent glDrawArrays showing up?

texts:
I am attempting to redraw with the same arrays using glDrawArrays in a GLKView on iOS. When I comment out any two of these calls, the other draw call draws as I expect. My last hunch was that I was attempting to draw at the same depth, so I introduced a depth uniform and am setting the depth in the vertex shader like so:

gl_Position = vec4(position.xy, 0.1*depth, 1.0);

the depth coming in is a lowp vector with a value of 0, 1, or 2. This didn't have any effect.

Here is my drawRect: method

- (void)drawRect:(CGRect)rect
{
    glClearColor(0., 0.0, 0.0, 0.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // Render the object again with ES2
    glUseProgram(_program);

    // the colors
    glBindVertexArrayOES(_vertexArray);

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, _wheelMaskTexture);
    glUniform1i(uniforms[UNIFORM_TEXTURE], 0);

    glUniform1f(uniforms[UNIFORM_COLOR_DEPTH], COLOR_DRAW);
    glUniform1f(uniforms[UNIFORM_COLOR_ANGLE], _angle);

    glDrawArrays(GL_TRIANGLES, 0, 6);

    // the sat
    glBindVertexArrayOES(_vertexArray);

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, _satMaskTexture);
    glUniform1i(uniforms[UNIFORM_TEXTURE], 0);

    glUniform1i(uniforms[UNIFORM_COLOR_DEPTH], SATURATION_DRAW);
    glUniform1f(uniforms[UNIFORM_COLOR_ANGLE], _satAngle);

    glDrawArrays(GL_TRIANGLES, 0, 6);

    // the bright
    glBindVertexArrayOES(_vertexArray);

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, _brightMaskTexture);
    glUniform1i(uniforms[UNIFORM_TEXTURE], 0);

    glUniform1i(uniforms[UNIFORM_COLOR_DEPTH], BRIGHTNESS_DRAW);
    glUniform1f(uniforms[UNIFORM_COLOR_ANGLE], _brightnessAngle);

    glDrawArrays(GL_TRIANGLES, 0, 6);
}

My GLKView is set up with a drawableDepthFormat = GLKViewDrawableDepthFormat24. I haven't set up any transforms because what I'm drawing is basically a simple color wheel.

There is no world or model transform. I'm simply drawing the same square 3 times one on top of the other without transforming. There are 3 different mask images that are used to mask out the fragments that I care about in the fragment shader like so:

gl_FragColor = vec4(rgb, texture2D(wheelMask, texCoord).a);

Why wouldn't all three glDrawArrays calls draw as expected? As I mentioned early any one of them by themselves draws as expected. As it is, with all three, only the first glDrawArrays draws as expected.


texts: Faking 2d light using shader (Unity, Shaderlab)

texts:
Since the concept was difficult to explain in words for someone who's not quite familiar with shader, I described it in pictures.

I'm currently using Unity and it seems Shaderlab is the best choice to accomplish this.

To shader masters, this seems like quite a simple trick, but as beginner, I've been struggling to find right keywords and tutorials to accomplish this.

I wish someone could explain the concept behind this shader trick.

Thank you in advance.


texts: Preparing a 2D character to export from Blender to Unity?

texts:
I'm an animator for a game currently, and I don't have Unity (can't download due to too much gigs coupled with slow internet,) but the game designer told me I can use Blender to export animations into Unity.

I asked if I needed to prepare multiple files to export, and they told me that I could just have one file with all the animations in it. The game, as stated in the title, is 2D.

My problem now is, how do I turn a rig into an actual character with different animations under it? (Right now I only have an 'idle' animation, but need to make running, jumping, walking, etc.) I mean how do I save this 'idle' animation and work on another animation without overwriting the previously finished animation(s)?

Thank you much


texts:
I am developing a first-person shooter/strategy game using the Lightweight Java Game Library, which has support for OpenGL. I would like to create a sniper which I need to magnify the screen and project an image onto the back of the scope.
I have tried using gluPerspective() for zooming in and out, but it just makes the screen go black.
I am thinking about using glReadPixels for grabbing pixel data from the zoomed in image, but I'm not sure what to put in field 'data'. explanation of glreadpixels here I'm also not sure how to get the data from glReadPixels and put it back onto the back of the scope.

EDIT: I'm not doing full screen zooming, I'm showing the image on the back of the scope.

Anyone know how to do this?


texts: How does this hash function work in this perlin noise implementation?

texts:
In Perlin's implementation of his noise function, he uses an array to hash the input coordinates and later find the gradient vectors. But in Stefan Gustavson's implementation, a strange "permute" function is used:

vec4 permute(vec4 x)
{
  return mod289(((x*34.0)+1.0)*x);
}

vec4 mod289(vec4 x)
{
  return x - floor(x * (1.0 / 289.0)) * 289.0;
}

Then, it is used like this:

vec4 i = permute(permute(ix) + iy);

vec4 gx = fract(i * (1.0 / 41.0)) * 2.0 - 1.0 ;
vec4 gy = abs(gx) - 0.5 ;
vec4 tx = floor(gx + 0.5);
gx = gx - tx;

I understand that the "*2.0 - 1.0" is for getting gx to the range -1 to +1, but I do not understand the rest of the hashing.
How does this "permute" function work and why does it divided by 41.0?

Thanks.


texts:
For quite some time I've been working on my open 3D game engine, to learn how this stuff works. You can see the full codebase relating to my problem here on GitHub.

I'm using an OpenGL 3.3 Core Profile Context on Mac OS X 10.10.3 and a GeForce GTX 760, if this matters.

Everything seems to work fine when submitting my vertices and MVP matrix to the Pipeline. But at two different points I try to transform vertices on my CPU, which leads to problems.

To simplify rendering the debug bounding boxes in a single frame, I transform the vertices by their MVP matrix and later submit them all to OpenGL with an identity matrix as transformation matrix:

for (auto& c : corner) {
    glm::vec4 t = VP * glm::vec4(c, 1.0f);
    vertices.emplace_back(glm::vec3(t) / t.w);
}
// ...
Shader::drawGL(vertices, colorsLine, indicesLine, glm::mat4(1.0f), gl::GL_LINES);

Most of the time, this seems to work fine. But when some vertices of a bounding box lie behind the camera, they will be "mirrored" and extend into empty space, as you can see in this screenshot:

Something similar happens with my portal based rendering approach, as described in Portals and Mirrors: Simple, Fast Evaluation of Potentially Visible Sets. Basically, I'm looking for a visible portal, and then for more portals that are visible through the already found portal. The relevant code:

for (int c = 0; c < 4; c++) {
    glm::vec3 port = portal.getVertex(c);
    glm::vec4 result = VP * glm::vec4(port, 1.0f);
    glm::vec3 vert = glm::vec3(result) / result.w;
    // ...
}

This basically works as expected, as you can see in the following screenshot:

However, as before, there is a problem with vertices behind the camera. I would expect the transformed vertices Z axis to be in the range [0;1] and vertices behind the camera should be outside of that range. What I'm really seeing, however, is that the Z part is always 1, as you can see in this screenshot (the first line is the world vector, the second is the vector multiplied with the matrix, the third is the multiplied vector divided by w):

To give you the full picture, this is how I create my projection matrix:

projection = glm::perspective(45.0f, size.x / size.y, 0.1f, 75000.0f);

And my view matrix is created using the quaternion of my camera:

glm::mat4 translate = glm::translate(glm::mat4(1.0f), pos);
glm::mat4 rotate = glm::toMat4(quaternion);
view = glm::inverse(translate * rotate);

According to every description I've read of the OpenGL transformation pipeline, I've done everything to have my world coordinates now in clipping space. But, looking at the Z axis, this seems to be false. I'm sure I'm missing something obvious with my math here.

Please help me out :)

Best Regards,
Thomas

PS: English is not my native language, please excuse any mistakes.


texts: Arcade Flight Simulator - should I use a physics-based approach, or should I just use translation and rotation?

texts:
I'm currently working on a little project - making something like Ace Combat with Shiva3D. I think I understand the basics of arcade flight simulators - thrust, pitch, roll, and yaw. I'm using a physics-based approach by applying forces on a dynamics object, and I couldn't figure out how to make it work perfectly.

As of now I'm simulating lift by applying a force equal to the dynamic's mass times gravity upwards to the positive direction of the local Y axis and applying a yaw according to the horizontal component of the altered lift when it makes a banked turn, but I couldn't emulate the yaw completely.

Some time later I decided to look at one of the Vector Thrust's airplane objects and opened its .ini file. There are many variables concerning the mobility, including the acceleration rate at sea level, acceleration rate at the service ceiling (the service ceiling height itself is also depicted), maximum velocity at sea level and ceiling level, etc.

These variables make me wonder whether I should just change into the ordinary translation/rotation model.

So, which approach would be better? Should I stick to the physics-based approach with corrections, or should I use the normal translation/rotation model with complex variables?

EDIT: To clarify, I am aiming for a mostly arcade experience, but with plausible speed (both linear and angular) changes.


texts: Is it a good idea to use the RDM socket type for multiplayer games?

texts:
I am currently developing a MOBA/RTS style game with an authoritative networking structure. Of course, the server needs to send a big number of packets every second, answering requests from the clients. The packets are split into commands and states. Commands contain all the actions a unit has performed since the last send-procedure, and states include the position and rotation data about a unit.
Commands are sent over TCP because they need to be in the right order and reliable for synchronized gameplay, individually to every client, states over UDP through a multicast group that consists out of the player clients because I interpolate, and a lost packet will not create any damage then.

Today i came across the RDM socket type, selectable through the C# Socket constructor, and I thought that this maybe is what I really want? My TCP connections currently do not make use of the seamless streaming of bytes as I wrap my data into packets and send them in constant intervalls. is the RDM socket type what I want? Having reliable connection-less packets send over PGM sounds really promising to me.


texts: Possible to yield a coroutine when it is taking too long to run?

texts: Suppose I have a function that raycasts from (0,0,0) to every object in the scene.  Sometimes the scene contains just a couple objects and sometimes it contains several hundred.  Is it possible to setup the raycasting function in a way that  ensures a good framerate? For example, within the "for" loop that shoots the rays could I somehow evaluate how much time has passed since the loop started and "yield return null" if the time in seconds is greater than the target time of each frame?


texts: Difference between linear and logarithmic z-buffer

texts:
I've searched about this topic for awhile and i couldn't find it on google. I've come across several ways to avoid z-fighting which are linear z-buffer, logarithmic z-buffer and reversed z-buffer. I decided to leave reversed z-buffer for now as i'm not planning to use OpenGL 4.5. The thing is i don't know the difference between linear and logarithmic z-buffer.

By "linear" i mean this:

float fz = gl_Position.z * gl_Position.w;
gl_Position.z = (fz - near) * 2.0 / (far - near) - 1.0;

And by "logarithmic" i mean this:

float w = gl_Position[3];
float C = 0.001;
gl_Position.z = (2 * log(C * w + 1) / log(C * far + 1) - 1) * w;

If i understand those codes correctly, the linear try to map all of the z value evenly. So does the logarithmic one. Sure both of them are totally different but i have tried both and see no or if any minimal differences, both eliminate the z-fighting. So there must be something i missed or don't understand.

edit: As Jimmy said, logarithmic is better than linear. Please add why logarithmic is better than linear z-buffer as i want to know why it is better and not just which one is better.


texts: AndEngine - Dragging a sprite that has a path modifier registered to it

texts: I'm looking to be able to drag a sprite that is currently on a path from a path modifier.  Currently, I have sprites on a path, and I have stationary sprites that are draggable.  However, simply overriding the sprite's onAreaTouched doesn't work until the sprite completes its path.  How would I do this?


texts: I wonder why games need installation at all. I can understand that some software like a browser needs it so it can associate some file types with it and start an executable, or add the icon to the Programs/Features component on Windows. But what's the purpose of installing, say, a Steam game? The Steam itself handles installation/removal of a game, updating, starting etc. If I develop my own game launcher (which will use installation) what are the reasons for me to use also an installer for my games?


texts: Using polymorphism in an Entity-Component System without sacrificing data-oriented design

texts:
I've been planning out an Entity-Component System in C++. My idea of it is most in line with the one described on this page of the entity systems wiki. To summarize, components are just structs of data, all code is in systems, and entities are just IDs shared by components.
The issue I'm having is mostly to do with how components are stored and accessed. My intent was to have a vector for each component type (which inherit a base Component class). These vectors are then stored in an unordered map, with a ComponentType (an enum) as the key. An EntityManager handles interactions with the vector, with functions like removeComponent, which takes a ComponentType and ID as arguments (which would search the unordered map and then iterate over the matching vector until finding the correct component to remove).
I specifically liked this implementation because it meant I could add new component types without having to change the way the manager accesses the vectors.
I realized that this implementation only works when utilizing polymorphism (i.e., a bunch of vector<Component*>s), since this allows them to all be stored in a single container, and operated on the same way. Unfortunately, this design results in the actual object data being scattered all over memory (even though the pointers are contiguous).
An advantage of the original structure that I chose, in my mind, was the improved cache performance offered by accessing large contiguous structures of data. But storing components in vectors is a problem, because then each vector is of a different type (ex: vector<Position>vs vector<Velocity>). This means I can't store them in one container, or use the same interface for operations on all of them. I believe I'd have to add new code to handle each new type of vector every time one was added.
I've been wracking my mind for the last few hours trying to devise a compromise. I can't seem to think of a design that would both store each type of component contiguously in data as well as allow for generic operations on those collections (ex: functions like the aforementioned removeComponent that don't require edits with each new compent type). I'm also unsure if my desire to maintain contiguity is reasonable, or if the impact on performance would actually be quite minor.


texts: My game is pretty much just a game-builder, where you create your own levels, scripts, graphics, music etc. and the game just loads them from a file you tell it. But how would I make it so the user could generate an exe that would just load the game files and act like a standalone game but actually be made with the game-builder thing? I'm using C++.


texts:
I've been working with this for the entire week now, this is about a leveling system of my application. When a user gets the enough exp needed, it gets leveled up, everything works fine. But, when a user gets a bulk exp, it won't get a bulk level as well. The default for exp needed for every user is 1000. For example:

The user gets 1000 exp, for level 1, it gets leveled up to level 2. It works fine that way, but if it gets more than the exp needed the flow won't work the same way. Because the exp needed for level 2, is 1400. So the algorithm for this if the user gets enough or more than the exp needed, the current exp_needed for the next level is multiplied by 1.4.

if($user->level <= 19){
   while($user->curr_exp >= $user->exp_needed){
   $user->level += 1;
   $user->curr_exp -= $user->exp_needed;
   $user->prev_exp = $user->exp_needed;
   $user->exp_needed = $user->prev_exp * 1.4;
   $user->save();
  }
}
elseif($user->level >= 20){
 while($user->curr_exp >= $user->exp_needed){
 $user->level += 1;
 $user->curr_exp -= $user->exp_needed;
 $user->prev_exp = $user->exp_needed;
 $user->exp_needed = $user->prev_exp * 1.1;
 $user->save();
 }
}

Edit : The levels 1-20 and their exp_needed is working fine now, but when I'm at Level 21, I'm having troubles with the exp, because the exp_needed at level 21 should only be multiplied by 1.1,

For example,

Scenario 1:
The User will earn a curr_exp(current exp) of 2,100,000 the user will jump on to level 21 with an experience of 836,6825.55 which is wrong because the exp_needed at level 21 should be the sum of the prev_exp(level 20 = 597,630.40) multiplied by 1.1 which will be

(prev_exp of level 20) 597,630.40 * 1.1 =  657,393.44

Scenario 2:

The user gets an exp of 2,000,000 it will be on the level 20 with an exp of 508,424.01 with an exp_needed of 597,630.40 and when it gets another exp of 100,000 the user will be leveled up to 21 with an exp_needed of 657,393.44 which is correct.

So to summarize each scenarios results:

Scenario 1:

Level 21
Exp:10,793.61
Previous Exp: 597,630.44
Exp Needed for the next level: 836,682.55

Scenario 2:

Level 21
Exp: 10,793.61
Previous Exp: 597,630.40
Exp needed for the next level: 657,393.44

Scenario 2 should be the results I am seeking for but it doesn't work that way on my while loop. Any ideas how to deal with this? Thank you.


texts:
How can I do that? I can generate simple beziers, but how can I generate a closed curve like this:

http://www.youtube.com/watch?feature=endscreen&NR=1&v=hlDYJNEiYvU


texts:
I'm currently working on a 2D soft-body physics engine (since none exist right now -_-), but I'm worried that there's no point to spending what will most likely be years on it.

Although I love working on it, I doubt such an engine would get any income considering anyone willing to pay money for the library will likely to be working in 3D.

Do 2D games have any sort of future in the game industry?
Should I just drop my engine and find something meaningful to work on?

Bonus:

I've been trying to think of a unique way to implement my physics engine in a 2d game by looking at games that are multiple dimensions, but still in 2d perspective like Paper Mario. Any ideas?


texts: How to handle pathfinding on a non-grid/non-node terrain map

texts:
I'm not sure if this is even  path-finding. All I have is a 3D map that has hills, etc. I'd like the enemy to flock an object, but also walk around other objects. These blocking objects may be added after the path is calculated, which would cause a re-calculation of the path.

What algorithm am I looking at here?


texts: Get timing correct with client side prediction

texts:
I believe I've got my head round CSP after reading Gabriel Gambetta's blog, Valve article and buildnewgames.com but having an issue understanding the time execution of everything.

So if a player holds the right arrow key down. I move the sprite by (speed * deltaTime) where deltaTime is the time between frames so speed is the same on differing frame rates.

My questions are:

Do I send a command to move right every frame?
How does the server correctly calculate this movement as it does not know the deltaTime of the client?

Really appreciate some guidance on this one. I'm using HTML5, javascript, node.js with socket.io.


texts:
I am creating spells for my game.

The collision with a normal fireball works just fine, what I am trying to achieve is to have the player_2 getting hit when the green explosion happens.

How can I achieve that? I tried adding explosion force with very high values just for testing purposes, but I could not make it work.

Below you can check a demonstration of what I am trying to do, and a piece of the code I tried.

this.spellPrefab.GetComponent<Rigidbody>().AddExplosionForce
            (configuration.ExplosionForce,
            spellPrefab.transform.position,
            500,
            0f,
            ForceMode.Impulse);


texts:
I'm making a school-based sandbox adventure game in Unity. I need a lot of NPCs with different apperances. I dreaded this since I don't have fun doing art and it is usually the reason I end up becoming burnt out of projects.

My solution for this was to segregate parts of the characters by color. The skin being green, hair being blue, shirt being red and trousers/leg wear being yellow. Then, I would use a shader to change these colors to something else.

The result is this sprite sheet:

and the ability to easily change the apperance of my NPCs to make them look different from eachother but there's still an issue.

A lot of the characters have the same hair style etc. Not to mention when I make a new hair style for a female, I have to then draw that style 3-4 more times for the different combinations of clothes.

The solution for this that would work ideally would be a modular apporach. I would only need to draw the sprite once and just swap out different clothing combinations. I have attempted this before but the main issue that kept on coming up was the different sprites not lining up, especially when changing the different sprites.

The art style is pixel art so they have to line up perfectly to look nice. How should I go about doing this to ensure I can fit every sprite together perfectly, no matter the combinations I choose?


texts: What happens to my already-published game when I upgrade to Unity Pro?

texts: I made a game with Unity's Standard liscense, and published it (version 1.0) on Google Play. If I buy a Unity Pro license can I publish an update to my game (version 2.0) with it on Google Play, or must I create a new game on Google Play for the updated version?


texts: Are there any good html 5 mmo design tutorials?

texts:
Hey all. I got a rather inspired after playing gaia online's zOMG and wanted to revive an old project idea I've had laying around for a few years now.

I'm looking to work with html5 (ie canvas, svg based sprites, & WebGL) to build a graphical web based MUD/MMO. Obviously, this is a new take on an old idea and after searching google I haven't really turned up many good resources. But does anyone have any tutorials or other resources to point me in the right direction?


texts: Unity mailchimp / Klaviyo subscription form

texts:
Hey everyone so i want to add a subscription form on my game. so far i can send data to a database and display them on a leaderboard, i found a similar question here but its a bit outdated. Ideally i would like to use klaviyo but since this is the only lead i have i might want to get familiar with how it works!
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

public class MailingScript : MonoBehaviour
{

    public InputField emailField;
    public InputField nameField;

    public void onClick()
    {
        StartCoroutine(SendToMailChimp());
    }

    private IEnumerator SendToMailChimp()
    {
        WWWForm form = new WWWForm();
        form.AddField("EMAIL", emailField.text);
        form.AddField("b_0f079b7af1cef143021ff4236_6cd74c0a6a", nameField.text);
        //form.AddField("subscribe", "Subscribe");
        UnityWebRequest www = UnityWebRequest.Post("https://slaga-games.us1.list-manage.com/subscribe/post?u=0f079b7af1cef143021ff4236&amp;id=6cd74c0a6a", form);
        yield return www.SendWebRequest();

        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            Debug.Log("Registered");
        }
    }
}

this is my code so far but it wont do anything. i have a same code for the database which works!


texts: Rendering lighting only on specific objects

texts:
I have done something similar to this in monogame:

My question is, what would I have to do to draw that lighting effect only on the pillar and not the background ? Is there something like ignoring certain sprites when using BlendState.Additive ? How would that work ? Here is how i'm drawing it now.

//draw background
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Opaque);
spriteBatch.Draw(Background, Vector2.Zero, Color.White);
spriteBatch.End();

//draw pillar
spriteBatch.Begin(SpriteSortMode.Deferred);
spriteBatch.Draw(Texture, new Rectangle(PillarX, PillarY, Width, Height), Color.White);
spriteBatch.End();

//draw lighting sprite in additive mode
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Additive);
spriteBatch.Draw(LightTexture, pos, null, Color.OrangeRed, 0f, Vector2.Zero,
    scale, SpriteEffects.None, 0f);
spriteBatch.End();

Edit: Also, apart from the pillar I have as an example, I need to do that for 3D models as well, so would the Stencil Buffer work here ?


texts: Platforming - Hanging off of cliffs and edges?

texts:
Possible Duplicate:
  Programming a climbing system like tomb raider

I've been interested in platforming gameplay dynamics for a while now. What I'm trying to ask is how games like Assassin's Creed, Prince of Persia, or any platformer do the environment interactions like hanging off of and climbing edges, etc. I have no idea how this kind of gameplay can be programmed.

In 3D games, the character is usually a capsule, so when the character falls off of a ledge and the grab onto it, where would the capsule be ? I'm confused... How the heck is this done ?

Thanks in advance.


texts: Where have the cross and dot products gone in DirectX10?

texts:
In D3D9 there were functions to deal with D3DXVECTOR3's in order to calculate dot and cross products. However these have disappeared from the math library in D3D10.

I assume they must have gone somewhere? My question is where and why?


texts:
I am making a Atari Breakout game with unitys 2d tools and I need to get the ball to bounce of colliders in the scene. If you havent played the game before how it works is if the ball hits the wall at 45 degrees it will bounce of the wall at the same angle (diagram bellow)

How can I get the ball to move at a continues speed and when it hits a collider to bounce back the way the image shows?


texts: My perlin noise height map doesn't have smooth transitions and goes directly from black to white

texts:
I am using lua with the love2d engine to make infinite 2d tiled terrain with perlin noise.  This is just the first step and I want to fix the bugs early.
The problem is that there is no gradient between the black and white islands.  There should be a smooth transition all through the map.

Also there is a line between the two chunks that I can't get rid of.
I am completely lost and cannot figure these problems out.  Here is what I am going for:

Here is my code.

seed = 257
local canvas = love.graphics.newCanvas()

function Interpolate(a, b, x)
    ft = x * 3.1415927
    f = (1 - math.cos(ft)) * 0.5

    return  a*(1-f) + b*f
end

function Noise(x, y)
    n = x + y * seed
    n = bit.bxor((bit.lshift(n,13)),n)
    return ( 1.0 - ( bit.band((n * (n * n * 15731 + 789221) +
      1376312589), 0x7fffffff) / 1073741824.0))
end

function SmoothedNoise1(x, y)
    corners = ( Noise(x-1, y-1)+Noise(x+1, y-1)+Noise(x-1,
      y+1)+Noise(x+1, y+1) ) / 16
    sides   = ( Noise(x-1, y)  +Noise(x+1, y)  +Noise(x, y-1)  +Noise(x,
      y+1) ) /  8
    center  =  Noise(x, y) / 4
    return corners + sides + center
end

function InterpolatedNoise_1(x, y)
    integer_X, fractional_X = math.modf(x)
    integer_Y, fractional_Y = math.modf(y)

    v1 = SmoothedNoise1(integer_X,     integer_Y)
    v2 = SmoothedNoise1(integer_X + 1, integer_Y)
    v3 = SmoothedNoise1(integer_X,     integer_Y + 1)
    v4 = SmoothedNoise1(integer_X + 1, integer_Y + 1)

    i1 = Interpolate(v1 , v2 , fractional_X)
    i2 = Interpolate(v3 , v4 , fractional_X)

    return Interpolate(i1 , i2 , fractional_Y)
end

function getExampleMap()
    mapWidth = 400
    mapHeight = 400
    mapMin = InterpolatedNoise_1(0, 0)
    mapMax = mapMin
    map = {}
    amp = 128
    freq =32
    octaves = 6
    for x = 0, mapWidth - 1 do
        map[x] = {}
        for y = 0, mapHeight - 1 do
            map[x][y] = 0
            for i = 1, octaves do
                map[x][y] = map[x][y] + getNoiseValue(x, y, freq / i,
                  amp / i)
            end
            mapMin = math.min(mapMin, map[x][y])
            mapMax = math.max(mapMax, map[x][y])
        end
    end
    -- /*scale the values between 0 and 255 for rendering in grey
    scale.*/
    mapMultiplier = 255 / (mapMax - mapMin)
    for x = 0, mapWidth - 1 do
        for y = 0, mapHeight - 1 do
            map[x][y] = map[x][y] * mapMultiplier
        end
    end
end

function getExampleMap2()
    mapWidth = 400
    mapHeight = 400
    mapMin = InterpolatedNoise_1(0, 0)
    mapMax = mapMin
    map2 = {}
    amp = 128
    freq =32
    octaves = 6
    for x = 400, (mapWidth + 400) do
        map2[x] = {}
        for y = 0, mapHeight - 1 do
            map2[x][y] = 0
            for i = 1, octaves do
                map2[x][y] = map2[x][y] + getNoiseValue(x, y, freq / i,
                  amp / i)

            end
            mapMin = math.min(mapMin, map2[x][y])
            mapMax = math.max(mapMax, map2[x][y])
        end
    end
    -- /*scale the values between 0 and 255 for rendering in grey
      scale.*/
    mapMultiplier = 255 / (mapMax - mapMin)
    for x = 400, (mapWidth + 400) do
        for y = 0, mapHeight - 1 do
            map2[x][y] = map2[x][y] * mapMultiplier
        end
    end
end

function getNoiseValue(x, y, freq, amp)
    return InterpolatedNoise_1(x / freq, y / freq) * amp
end

function love.load()
    love.window.setMode( 1920, 1080, {fullscreen=false})
    getExampleMap()
    getExampleMap2()
end

function love.draw()

    for x = 0, mapWidth - 1 do
        for y = 0, mapHeight - 1 do
            love.graphics.setColor(map[x][y], map[x][y], map[x][y], 255)
            love.graphics.point(x,y)
        end
    end
    for x = 400, (mapWidth + 400) do
        for y = 0, mapHeight - 1 do
            love.graphics.setColor(map2[x][y], map2[x][y], map2[x][y],
              255)
            love.graphics.point(x,y)
        end
    end

end

function love.update()

end

function love.keyreleased(key)
    if key == "escape" then
        love.event.quit()
    end
end


texts:
I have a spherical world defined by simple trigonometric functions to create triangles that are relatively similar in size and shape throughout.

What I want to be able to do is use mouse input to target a range of vertices in the area around the mouse click in order to manipulate these vertices in real time.

I read a post on this forum regarding translating 3d world coordinates into the 2d viewport.. it recommended that you should multiply the world vector coordinates by the viewport and then the projection, but they didn't include any code examples, and suffice to say i couldn't get any good results.

Further information.. I am using a lookat method for the viewport.  Does this cause a problem, and if so is there a solution?  If this isn't the problem, does anyone have a simple code example illustrating translating one vertex in a 3d world into a 2d viewspace?

I am using XNA.


texts: Building an Octree for terrain generation

texts:
I've previously implemented marching cubes/tetrahedra to render an IsoSurface. It worked (YouTube), but the performance was dire as I never got around to implementing variable Level of Detail based on view distance (or even removing old, distant chunks).

I decided to have another go and do it properly this time.
I've started by creating an OctreeNode that works as follows when Build() is called.

If the chunk is too small to build, return immediately.
Work out if the surface passes through this chunk's volume.
If so, then decide if we want to raise the LOD (because the camera is close)
If so, then spawn 8 children and call the same process on them
If not, build the mesh using the current node's dimensions

Some PseudoCode:

OctNode Build() {
    if(this.ChunkSize < minChunkSize) {
        return null;
    }
    densityRange = densitySource¹.GetDensityRange(this.bounds);
    if(densityRange.min < surface < densityRange.max) {
        if(loDProvider.DesiredLod(bounds)² > currentLoD) {
            for(i 1 to 8) {
                if(children[i] == null) {
                    children[i] = new OctNode(...)
                }
                children[i] = children[i].Build();
            }
        } else {
            BuildMesh();
        }
        return this;
    }
}

¹ As well as returning density at a point, the density source can determine the possible density range for a given volume.

² The LoD provider takes a bounding box and returns the max desired LoD based on camera position/frustum, user settings, etc...

So... This all works fairly well. Using a simple sphere as the Density source, and showing all nodes:

And just the leaves:

However, there are a couple of issues:

I have to define the initial bounding volume (and the larger it is, the more processing I need to do)
At the root of the tree, I have no idea how deep the leaves will be, so my LoD numbering starts at lowest quality (root) and increases as chunks get smaller. Because LoD is now relative to initial volume, it's not much use when I want to do things at specific sizes / qualities.

I've thought of a couple of options but both seem flawed:

Maintain a collection of Octrees and add/remove depending on distance. Can't see how I'd mesh across nicely¹, plus I'd need a list of known-empty nodes, especially if I want arbitrary 3D surfaces (to avoid re-calculating empty volumes repeatedly)
Add a parent Node to the current root, then add seven siblings for the original node. This would work and be on-demand but it seems complex to shrink back down sensibly as the player moves through the landscape. It would also make LoD numbers even less meaningful.

¹ [In clarification to Q below] At present, if 2 physically adjacent nodes in the tree are at different LODs, I have some code to coerce the verts such that there's no seam when the meshes are generated. I'm able to do this by knowing the the density for multiple of surrounding nodes. In a scenario where I have 2 independent octrees side-by-side, I'd have no easy way to retrieve this information, resulting in seams.

What's an optimal way to approach this?


texts:
Sound and it's quality is something like religion. Never ending story.

People will say, that MP3 320kbps is lossless, while experts will say that any MP3 is crap, but in the end, no one will hear a difference in the result... unless they're in the music industry for 20 years+.

What would be the best format for video game, and what properties should be enough (Hertz, bitrate etc.), assuming that 320kbps MP3 is "heavy"?

Maybe an example or two, how some AAA titles work with their sounds.


texts: XNA Required information to represent 2D Sprite graphically

texts:
I was thinking about dividing my game engine into 2 threads: render thread and update thread (I can't come up on how to divide update thread from physic thread at the moment).

That said, I have to duplicate all Sprite informations, what do I really need to represents a 2D Sprite graphically?

Here are my ideas (I'll mark with ? things that I'm not sure):

Vector2 Position
float Rotation ?
Vector2 Pivot ?
Rectangle TextureRectangle
Texture2D Texture
Vector2 ImageOrigin ? (is it tracked somewhere else?)

If you have any suggestion about using different types for datas, it's appreciated

Last part of the question: isn't this a lot of data to copy in a buffer?what should I really copy in the buffer?I'm following this tutorial:

http://www.sgtconker.com/2009/11/article-multi-threading-your-xna/3/

Thanks

UPDATE 1:

Newer values at the moment:

Vector2 Position
float Rotation
Vector2 Pivot
Rectangle TextureRectangle
Texture2D Texture
Color Color
byte Facing (can be left or right, I'll do it with an enum)

I re-read the tutorial, what I was doing wrong is not that I need to pass all those values, I need to pass only changed values as messages.

UPDATE 2:

Vector2 Position
float Rotation
Vector2 Pivot
Rectangle TextureRectangle
Texture2D Texture
Color Color
bool Flip
uint DrawOrder
Vector2 Scale
bool Visible ?

Mhhh, should Visibile be included?


texts: How to detect whether or not a tile is occupied?

texts:
I'm using Python 2.7 on Win7x64 with PyGame

What is the best way to iterate over all the tiles in the game or screen, efficienty? Ideally I have about 800 tiles, but that is a dynamic number I've been playing around with.

The way I've got it is the logic is looking through all the tiles per frame (at 60fps, and I haven't yet got GFX and Logic decoupled):

for tile in TILES: #tiles is a simple list
  if player_pos is in tile.coords: #coords is a list filled with (x, y) tuples
     tile.color = RED #a simple attribute change, performance hit whether this line is 'pass' or not

but the list of TILES is huge enough that looking through 800 tiles, 60x a second obviously isn't efficient.

What is the best way to proceed from here? How do I find the occupied tiles, without iterating over them every frame? I could split the map up into quadrants or something similar, but maybe there's a fancy concept I'm not familiar with that would work better.

edit: Solved, for now: I added an attribute to the Tile class that has the lowest and highest two coordinates and then every frame, the logic looks to see of the player's pos is between the two ranges like so:

for tile in TILEs: #pos is player pos
    if tile.range_x[0] <= pos[0] <= tile.range_x[1]: #range_x is the lowest and highest
                                       # x coordinate within the tile in pixels
        if tile.range_y[0] <= pos[1] <= tile.range_y[1]: #low and high y here
                     pos_tiles.append(tile)

edit2; I should mention that a tile holds several coordinates, meaning a unit (or player) can move within a tile.


texts:
I am currently creating a 3D Camera on the Playstation Mobile SDK (which is basically openGL with just a little bit of abstraction).

The game I am trying to make is a 3D Tactical. That means my world is composed of 3D cubes, all of the same size (unit size) and placed at integer position.

I'd like to be able to detect on which block the player clicks. That means, some sort of raytracing from the camera to detect the nearest block. My problem is that I am new to all this maths/physics/3d stuff.
How could I implement this easily (and in a efficient enough way) ?

My camera currently have a position, and two modes : Target mode (it uses a LookAt on a point) and direction mode (it uses a lookAt on its position + the direction). That means I have access to the direction of the camera.


texts:
I am right now developing paint application in andengine because some features are only possible with andengine.

For this I have used color dialog box to use user selected color but that dialog box return int value.
But my sprite use Color class for setting color.

Reverse thing is possible using,

getColor().getABGRPackedInt()

Using this I provide source color but after choosing I can't able to receive chosen color.

At present I use following dialog box.

Android Color Picker

So I need to convert int value return by the dialog in Color class object. So members please help me in this.


texts: Java - Loading background music into memory

texts:
I am currently developing a game with Java, with a soundtrack consisting of ten tracks in .ogg format, 1-2 MB in size each. To be able to switch between these tracks quickly and easily in the game, before the game starts, I load all of them into memory by creating ten Clip classes. Unfortunately, but understandably, pre-loading these tracks increases the application's CPU usage from about 61 MB to 340 MB.

Since I'm only ever playing one track at a time, I could make it so that only one Clip is ever in memory, and is destroyed when the track needs to change. This means, though, that I'll have to hang the game up on loading the Clip when this happens, or do this on a different thread during a few seconds of undesirable silence.

Is there a smarter, more conventional way to handle large BGM files, or do I just have to pick my poison?


texts: Avoid object from bouncing non-stop after AddForce() is applied to it

texts:
I want to implement some sort of elastic field on my light blue magnetic field when a cylinder is colliding it, it worked except the lines won't stop bouncing. I am enabling the trigger collider on the cylinder since I want to be able to drag the cylinder up and down across the blue line, so I'm kinda stuck here..

Here's the demo, notice that the lines at the bottom of the cylinder is the effect that I wanted on the lines on top of the cylinder as well. I don't know why top lines behaving like that.

The curves that reacted to the cylinder is represented by the basic cube on each blue line which I added a collider and rigidbody to it.

And here is the code that I use to implement attract and repel effect like the first picture

private void Attract(Rigidbody rb)
{
    float Distance = Vector3.Distance(rb.transform.position, maxBounds.transform.position);
    float TDistance = Mathf.InverseLerp(MaxRange, 0f, Distance); // Give a decimal representing how far between 0 distance and max distance the object is.
    float strength = Mathf.Lerp(0f, MaxStrength, TDistance); // Use that decimal to work out how much strength the magnet should apply
    Vector3 FromObjectToMagnet = (maxBounds.transform.position - rb.transform.position).normalized; // Get the direction from the object to the magnet
    rb.AddForce(FromObjectToMagnet * strength, ForceMode.Force);// apply force to the object
}
private void Repulse(Rigidbody rb)
{   // This is exactly the same as Attract(), the direction is just reversed
    float Distance = Vector3.Distance(rb.transform.position, minBounds.transform.position);
    float TDistance = Mathf.InverseLerp(MaxRange, 0f, Distance); // Give a decimal representing how far between 0 distance and max distance the object is.
    float strength = Mathf.Lerp(0f, MaxStrength, TDistance); // Use that decimal to work out how much strength the magnet should apply
    Vector3 FromMagnetToObject = (rb.transform.position - minBounds.transform.position).normalized; // Get the direction from the object to the magnet
    rb.AddForce(FromMagnetToObject * strength, ForceMode.Force);// apply force to the object
}

I detect the colliders using OverlapCube method btw.

Any ideas? Thanks!

[Update]
[]3

The cube landed slowly to its original position, which is not the effect that I want.


texts: How to export Visual Studio game for mass distribution

texts: I've coded a Visual Studio 2015 game in SDL2 and ran some distribution tests, I gave a user the game's .exe (the raw game with no files) and they got the error SDL2.dll is missing. How would I export the game so it includes the least amount of rubbish (visual studio) files and doesn't produce these sdl errors.


texts: Problem setting up OpenGL dev environment in Ubuntu 14.04

texts:
Currently I'm using this tutorial to get started with opengl.So when I try to compile the example program :

#include <GLFW/glfw3.h>
#include <thread>

int main()
{
    glfwInit();
    std::this_thread::sleep_for(std::chrono::seconds(1));
    glfwTerminate();
}

using

  g++ test.cpp -o test  -lglfw3

to ensure that all is good with glfw I get this

  In file included from /usr/include/c++/4.8/thread:35:0,
                   from test.cpp:2: /usr/include/c++/4.8/bits/c++0x_warning.h:32:2: error: #error This
  file requires compiler and library support for the ISO C++ 2011
  standard. This support is currently experimental, and must be enabled
  with the -std=c++11 or -std=gnu++11 compiler options.  #error This
  file requires compiler and library support for the \   ^ test.cpp: In
  function ‘int main()’: test.cpp:7:10: error: ‘std::this_thread’ has
  not been declared
       std::this_thread::sleep_for(std::chrono::seconds(1));
            ^ test.cpp:7:38: error: ‘std::chrono’ has not been declared
       std::this_thread::sleep_for(std::chrono::seconds(1));

So then I guessed I could use the flag that g++ suggested and compile it using

  g++ -std=c++11 test.cpp -o test  -lglfw3

But then things get weirder and g++ comes with this error(I will post only a part of it since it's a huge output overall but you will probably get the idea) :

  x11_window.c:(.text+0x2d9): undefined reference to XSaveContext'
  x11_window.c:(.text+0x324): undefined reference to
  XChangeWindowAttributes' x11_window.c:(.text+0x3be): undefined
  reference to XSetWMProtocols' x11_window.c:(.text+0x417): undefined
  reference toXChangeProperty' x11_window.c:(.text+0x41c): undefined
  reference to XAllocWMHints' x11_window.c:(.text+0x48e): undefined
  reference toXSetWMHints' x11_window.c:(.text+0x49d): undefined
  reference to XFree' x11_window.c:(.text+0x4a2): undefined reference
  toXAllocSizeHints' x11_window.c:(.text+0x5ed): undefined reference
  to XSetWMNormalHints' x11_window.c:(.text+0x5fc): undefined reference
  toXFree' x11_window.c:(.text+0x613): undefined reference to
  XAllocClassHint' x11_window.c:(.text+0x66c): undefined reference to
  XSetClassHint' x11_window.c:(.text+0x67b): undefined reference to
  XFree' x11_window.c:(.text+0x6dc): undefined reference to
  XISelectEvents' x11_window.c:(.text+0x71e): undefined reference to
  XRRSelectInput' //usr/local/lib/libglfw3.a(x11_window.c.o): In
  functionhideCursor': x11_window.c:(.text+0x7bd): undefined reference
  to XUngrabPointer' x11_window.c:(.text+0x7fb): undefined reference to
  XDefineCursor' //usr/local/lib/libglfw3.a(x11_window.c.o): In
  function captureCursor': x11_window.c:(.text+0x880): undefined
  reference toXGrabPointer'
  //usr/local/lib/libglfw3.a(x11_window.c.o): In function `showCursor':

How could I fix this type of problem cause it really hurts my motivation to get into opengl. And please if you have in mind any better-hassle free guide for setting a proper opengl environment for deving with glfw and glew in linux/ubuntu , care to mention it.

UPDATE 1: http://pastebin.com/CPEwmbUZ <--- The whole output is here if anyone cares.


texts: glGetFloatv – should it be avoided? Can it be replaced?

texts:
Platform is OpenGL ES 1.x. I am using glGetFloatv() to get MODELVIEW matrix. This allows me to compute points, where I need to draw a shadow effect. This is very handy, as I can forget about complexity of scene (its translations, rotations, etc.) – and by simple 3x1 matrix multiplication get the points.

But here it is stated that the call should be avoided. Is it correct recommendation? Can be glGetFloatv() omitted?


texts: Need help transforming DirectX 9 skybox hlsl shader to DirectX 11

texts:
I am in the middle of implementing a skybox to my game. I have been following this tutorial http://rbwhitaker.wikidot.com/skyboxes-2. I am using MonoGame as a framework and in order to support both Windows and Windows 8 metro I need to compile the shader with pixel and vertex shader 4.

compile vs_4_0_level_9_1
compile ps_4_0_level_9_1

However some of the hlsl syntax has been updated with DX10 and DX11.

I need to update this hlsl code:

float4x4 World;
float4x4 View;
float4x4 Projection;

float3 CameraPosition;

Texture SkyBoxTexture;
samplerCUBE SkyBoxSampler = sampler_state
{
   texture = <SkyBoxTexture>;
   magfilter = LINEAR;
   minfilter = LINEAR;
   mipfilter = LINEAR;
   AddressU = Mirror;
   AddressV = Mirror;
};

struct VertexShaderInput
{
    float4 Position : POSITION0;
};

struct VertexShaderOutput
{
    float4 Position : POSITION0;
    float3 TextureCoordinate : TEXCOORD0;
};

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output;

    float4 worldPosition = mul(input.Position, World);
    float4 viewPosition = mul(worldPosition, View);
    output.Position = mul(viewPosition, Projection);

    float4 VertexPosition = mul(input.Position, World);
    output.TextureCoordinate = VertexPosition - CameraPosition;

    return output;
}

float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    return texCUBE(SkyBoxSampler, normalize(input.TextureCoordinate));
}

technique Skybox
{
    pass Pass1
    {
        VertexShader = compile vs_2_0 VertexShaderFunction();
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}

I quess I need to change Texture into TextureCube, change sampler, swap texCUBE() with TextureCube.Sample() and change PixelShader return semantic to SV_Target0.

I'm very new in shader languages and any help is appreciated!


texts: Animating 2d character which can wear items?

texts:
In my game the player can control a character which can wear items.
Now it is not visible but I would like to make it visible like for example in Terraria, Starbound, etc.

In my game a player can only face right or left. (right is the mirrored version of left) Only the character's feet and arms are moving during the game.

Is there a simple way in Unity to stick the sprite of the items to "bones"?
(like in 3d modelling)
Or how could I implement this "equipment on character" system?

I found some assets but I dont have much money.

Thanks in advance! :)


texts: A coroutine to rotate one point around another by a given angle without referring to game object

texts:
I need to rotate a point around another point (in 2D) by a given angle over a given duration, independent of game object (meaning that I've manually created the points and they're not positions from a game objects transform ) as shown in the image below where point B rotates to C by and angle e around A by with radius AB. Using a coroutine would be preferable.

UPDATE

Based on links provided by @MichaelHouse I wrote the following methods to rotate a control point over time by a certain angle but it rather moves to a point (which is not the desired point) immediately to another point, not by the right angle. I'm not sure what I've done wrong.

public static Vector3 RotatePointAroundPivot(Vector3 point, Vector3 pivot, Quaternion angle)
{
    return angle * (point - pivot) + pivot;
}

IEnumerator RotateControlPointWithDuration(Vector3 point, Vector3 pivot, float duration, float angle)  {
    float currentTime = 0.0f;
    float ourTimeDelta = 0;

    ourTimeDelta = Time.deltaTime;
    float angleDelta = angle / duration; //how many degress to rotate in one second

    while (currentTime < duration)
    {
        currentTime += Time.deltaTime;
        ourTimeDelta = Time.deltaTime;

        Vector3 newPos = RotatePointAroundPivot(point, pivot, Quaternion.Euler(0, 0, angleDelta * ourTimeDelta));
        points[0] = new Vector2(newPos.x, newPos.y);

        yield return null;
    }
}

IEnumerator runMovement()  {

    yield return new WaitForSeconds(2.0f);
    Vector3 point = new Vector3(points[0].x, points[0].y, 0);
    Vector3 pivot = new Vector3(points[3].x, points[3].y, 0);
    StartCoroutine(RotateControlPointWithDuration(point, pivot, 2.0f, 45.0f));
}

UPDATE 2

I've tried another approach using trig functions, but the point moves erratically before finally arriving at a point that seems to be the right point. Please see the code below:

 IEnumerator runMovement()  {

    yield return new WaitForSeconds(2.0f);
    Vector2 pivot = points[3];

    StartCoroutine(RotateControlPointWithDuration(pivot, 2.0f, 90.0f));

}

   IEnumerator RotateControlPointWithDuration(Vector2 pivot, float duration, float angle)
{
    float currentTime = 0.0f;
    float ourTimeDelta = 0;
    Vector2 startPos = points[0];

    ourTimeDelta = Time.deltaTime;
    float angleDelta = angle / duration; //how many degress to rotate in one second

    while (currentTime < duration)
    {
        currentTime += Time.deltaTime;
        ourTimeDelta = Time.deltaTime;

        points[0] = new Vector2(Mathf.Cos(angleDelta * ourTimeDelta) * (startPos.x - pivot.x) - Mathf.Sin(angleDelta * ourTimeDelta) * (startPos.y - pivot.y) + pivot.x,
                                                        Mathf.Sin(angleDelta * ourTimeDelta) * (startPos.x - pivot.x) + Mathf.Cos(angleDelta * ourTimeDelta) * (startPos.y - pivot.y) + pivot.y);

        yield return null;
    }
}


texts:
So I've been away from Unity and game development in general for a bit, so I'm working through Unity's UFO Tutorial and had a question about the camera set up. I don't understand why you need the offset for it? It follows the Player object directly it seems, and they use a Vector3? But it's a 2D game, so why not just use a Vector2? I was experimenting with the code just to see if I could figure it out, so I removed the offset variable completely but then when I ran the game it just showed a blank space in the game view. Any body who can help me understand this?

public class CompleteCameraController : MonoBehaviour
{
    public GameObject player; //Public variable to store a reference to the player game object
    private Vector3 offset; //Private variable to store the offset distance between the player and camera

    // Use this for initialization
    void Start ()
    {
        //Calculate and store the offset value by getting the distance between
        // the player's position and camera's position.
        offset = transform.position - player.transform.position;
    }

    // LateUpdate is called after Update each frame
    void LateUpdate ()
    {
        // Set the position of the camera's transform to be the same as
        // the player's, but offset by the calculated offset distance.
        transform.position = player.transform.position + offset;
    }
}


texts: How to generate random level from a seed?

texts:
How would I go about using a random seed to generate a game level? The same seed should always generate the exact same level.

For this example it would be a Worms style level. So each level would have a theme (grasslands, snow etc), base terrain, different objects such as trees.

So where would I start to create this kind of level generator? What would be involved? What concepts does it use?

Bonus points for any any good links (bonus bonus points for anything related to how it was done in worms or similar).

Thanks.


texts: I am currently thinking about porting a XNA game to other platforms using MonoGame. Do I understand this correctly that I can expect the game to render faster even under Windows 7 due to the use of SharpDX?


texts: How I can I prevent users from downloading games they're not authorized to?

texts:
I am building a platform like Steam and, like Steam, I'd like to prevent users from downloading games they have not purchased yet. For example I don't want users to be able to download a game just because they know the SFTP link to it on my servers.

How can I accomplish this?


texts:
I'm having an exam soon and got a problem with one alpha blending exercise:

BlendState BS3 {
    BlendEnable[0]     = TRUE;
    SrcBlend[0]        = ONE;
    SrcBlendAlpha[0]   = ZERO;
    DestBlend[0]       = ONE;
    DestBlendAlpha[0]  = ZERO;
    BlendOp[0]         = ADD;
};

There are 3 triangles overlapping #1, #2 and #3. Each one has it's own RGBA values. The background color is 0.0, 0.0, 0.0, 0.0.

My tries:

  SrcBlendAlpha and DestBlendAlpha are both 0.0. I can calculate all rgb values with

  1*rgb#3 + 1*rgb#2 + 1*rgb#3

  The alpha value is: 0 * alpha#3 + 0 * alpha#2 + 0 * alpha#1 = 0.0

  The resulting color then is: (0.0, 0.0, 0.0, 0.0)

Is my approach correct? Does this even make sense having a color with alpha value 0?


texts: Create a continuous flight path on a Bezier Curve in Unity3d

texts:
I am working on a game in which a butterfly is flying along some path.

What I am trying to do currently is create a Bezier curve starting from the butterfly's position(previous curves end point) and the rest of the points random for it to fly on. Once it has finished on the curve it needs to continue its path along the next curve that is generated. The problem I have is that the next curve sometimes starts in a direction that makes the transition look rugged and unrealistic. This is the code I have so far.

void updateDirection()
{
    if (!LeanTween.isTweening(this.gameObject))
    {
        Vector3 curveA = { transform.position, new Vector3(Random.Range(-5f, 0), 0, Random.Range(-3f, 0)), new Vector3(Random.Range(-5f, 0), 0, Random.Range(-3f, 0)), new Vector3(Random.Range(-5f, 0), 0, Random.Range(-3f, 0)) };
        LeanTween.move(this.gameObject, curveA, 3f);
    }
}

I am using the LeanTween API to create the movement method easier.

So basically I need to find a way to make a continuous bezier I guess and I am no mathematician so if it could be explained in easy to understand terms that would be amazing!


texts: Scene doesn't load in editor but loads perfectly fine in final build

texts:
When my character dies the game is supposed to load a new scene. The code is perfectly fine because it does this when I make a web build for it. But in the editor I get this:

I have no idea what the issue could be, everywhere I've looked online seems to have the opposite problem (IE: it works fine in the editor but not in the final build). Any help would be appreciated.


texts: How to fit a bitmap to a random size rect so it does not strech? (Android Studio)

texts:
I'm trying to fit a bitmap to a random size rect but I don't want the bitmap to be streched out. I've tried using BitmapShader and tile it but it become animated and not fixed.

Here is my code without BitmapShader.

 public void draw(Canvas canvas) {
      Paint paint = new Paint();
      canvas.drawBitmap(spike1, null, rectangle, paint);
      canvas.drawBitmap(spike1, null, rectangle2, paint);
 }

Here is my code with BitmapShader.

 public void draw(Canvas canvas) {
    Paint paint = new Paint();
    paint.setShader(new BitmapShader(spike1, Shader.TileMode.REPEAT, Shader.TileMode.REPEAT));
    canvas.drawRect(rectangle, paint);
    canvas.drawRect(rectangle2, paint);
}

Here is a picture of my problems

Can somebody tell what I need to do so the image is fix but not stretched?


texts:
Say you have two Bounding Box Objects each of them storing the current vertices of the box in a vector with all the vertices of the object rotated and translated relative to a common axis.

Here is an image to illustrate my problem:

How can I work out if the two OBB's are overlapping any links to help explain the solution to the problem would be welcome. Nothing too convoluted please...


texts: Creating proper jump mechanics in LibGDX with Box2D?

texts:
I'm trying to create a proper jumping system for a 2D platformer with box2D, however, I'm not exactly sure how to make a good jumping system. Right now, I'm just doing

public void jump(float delta) {
    body.applyLinearImpulse(new Vector2(0, 7), body.getWorldCenter(), true);
}

What I want to do, is have a system like Mario's or Sonic's, where the height jumped is determined by how long the player held the jump button. How do I do something like that? Also, what's better, a rectangular box2D fixture, or an oval one? I'm sorry for such a newb question, and thank you for the help!


texts: How to make rigid body move smoothly on uneven platform?

texts:
Right now I'm using Rigidbody2d for the game character along with polygon collider 2D(2d platform game).

I'm beginner hope I'm using correct components.

And transform to move character from left to right.

Character.transform.Translate(Vector2.right * speed * Time.deltaTime);

And upward(jump).

Character.transform.Translate(Vector2.up * speed * Time.deltaTime);

When the game character moves on slopes there's lot of friction and bounciness and rotation and its worse when jumping from slopes.


texts: How to convert from OpenGL to OpenGL ES?

texts: I need to convert code from OpenGL to OpenGL ES 1.1, I found that the GLUT library is missing in that. Can anyone tell me what do I do to replace glRasterPos3f in OpenGL?


texts: How can I set up an intuitive perspective projection/view matrix combination in OpenGL, using GLM?

texts:
Could anyone help me set up an intuitive perspective camera matrix using OpenGL and the GLM library?

By "intuitive" I mean that I want the camera to be looking at the middle of the screen down the -Z axis, but I want it to be positioned in front of the camera to the exact degree that would cause a vector placement at (0,0,0) and a vector placement of (screen_width, screen_height, 0) to show up in the bottom-left and top-right corners respectively.

Feel free to ask me to clarify, if need be. This is what I have currently:

 glm::mat4 Projection = glm::perspective(45.0f, (GLfloat) window_width / (GLfloat) window_height, 0.1f, #X#);

 glm::mat4 View = glm::lookAt(
     glm::vec3(window_width/2, window_height/2, #X#), // camera position
     glm::vec3(window_width/2, window_height/2, 0), // look at origin
     glm::vec3(0, 1, 0)  // Head is up
 );

  glm::mat4 Model = glm::mat4(1.0f);

  glm::mat4 MVP = Projection * View * Model;

The #X#s are the arguments that I'm not sure how to calculate.

I don't know how to calculate the correct Z position for the camera, and I also don't know how far out to put my far clipping plane. (Should it be a fixed(large) value, or should it be based on my width/height?)

Also, is 45 degrees what I should be using? I've seen some people use values like 60 or 70.

I'm sure whatever the calculation function is would work based off of the angle/window_width/window_height and I'm also sure its easy if you know trig.

EDIT

In response to user1118321

I tried to implement the solution provided, but it didn't quite give me what I'm looking for.

Here is the code I have now

float fov=45.0f;
glm::mat4 Projection = glm::perspective(fov, (GLfloat) window_width / (GLfloat) window_height, 0.1f, 10000.0f);

float angle1=fov/2.0;
float angle2=180 - (90 + angle1);
float Z = 0.5 * window_height * sin(glm::radians(angle2))/sin(glm::radians(angle1));
glm::mat4 View = glm::lookAt(
    glm::vec3(window_width/2, window_height/2, Z), // camera position
    glm::vec3(window_width/2, window_height/2, 0), // look at origin
    glm::vec3(0, 1, 0)  // Head is up
);

 glm::mat4 Model = glm::mat4(1.0f);

 glm::mat4 MVP = Projection * View * Model;

When I try to render a square, who's bottom left corner is at (0,0,0) and who's top right corner is at (window_width, window_height,0), it doesn't span the entire screen.

This is what I get instead:


texts: How to combine tiles in a procedurally generated level in 2D tile based maps?

texts:
I am developing a 2D tile-based top-down game. It is currently instantiating square objects with a sprite renderer to procedurally generate the map.

Each floor and wall is a 1-unit wide object.

I have two issues with that:

The memory usage is quite high and it is not efficient (generating
maps that are more than 300x300 become really slow)
There are lights glitches when I have multiple lights in the scene.
The borders of the squares become visible as seen in the picture:

Is it possible to combine all my static elements (floor and wall
tiles) in a Mesh object, or another adequate object for that?
The floors items do not have colliders, as the walls have a box
collider. Does it cause an issue?


texts: Making the camera look at the player while keeping another object in view

texts:
I'm working on a sorta football game where I need my player to always be at the center of the camera view while keeping the ball into view, without any vertical movement. The idea would be for the camera to act like the picture below.

What I came up with was the following code that I'm using in a LateUpdate. I'm computing a directional vector between the player and the ball and placing my camera behind the player using that data, and then I look at my player.

Vector3 ballPosition = ballTransform.position;
Vector3 playerPosition = playerTransform.position;

ballPosition.y = 0.0f;
playerPosition.y = 0.0f;

Vector3 directionVector = (ballPosition - playerPosition).normalized;
directionVector.y = 0.0f;

Vector3 newPosition = playerTransform.position - directionVector * 12.0f;
newPosition.y = 9.0f;

transform.position = newPosition;

transform.LookAt(playerTransform.position);

The code itself is working, but the camera movement is a bit nauseous, and when I'm trying to smooth it I end up with the ball leaving the camera field most of the time. Plus when I get too close from the ball I end up with some really quick camera movements which makes the whole thing kinda hard to follow. I tried to use a totally different technique by working with a Cinemachine Camera, but there doesn't seem to be an easy way to achieve such a view.

Does anyone have an idea of how to achieve such a thing?


texts:
I am implementing a deferred rendering framework, and I wanted to allow programmers to write custom materials.
However, I did not find yet how to handle different materials.
For now, a material is just a set of uniforms for me.

I wanted to write the material ID in the GBuffer, however, I don't see the point of doing it as the lightning pass is using the same shader for every fragment (obviously).

In the frosbite paper (page 15), they explain they use a Material ID and a MatDat parameter, but I did not really get what it can be and how they handle it during the lightning pass.

Is the material ID used in a simple branching condition? In this case, when a new material is created, do I have to rebuild the lightning pass uber shader by adding this branching and the code to execute?

UE4 seems to build GLSL code from the material editor, which is not something hard, but how do they handle it with the deferred renderer?
Do they only plug the GLSL code into the Uber Shader?


texts: Slow dictionary access with coordinates as keys

texts:
I am making a game server and currently I am experiencing a huge performance hit.

I have a class Map which holds a Dictionary of the class Tile with each tile having X, Y, and Z coords, some lists, etc. nothing fancy as it's a MMORPG.

Currently in the Map class I have this:

public Tile GetTile(Coordinate_t coordinate)
{
    if (Tiles.ContainsKey(coordinate))
    {
        return Tiles[coordinate];
    }
    return null;
}

Coordinate_t is a struct containing X, Y and Z as UInt32. the Dictionary is represented like this:

 Dictionary<Coordinate_t, Tile> Tiles;

Basically I need to hold over 7 million tiles in this list, but it's being really slow! Every time I try to get around 12 tiles in a function it increases the program CPU use to 1~3% which is a lot! Since the game server is supposed to hold over 100 players online at a time.

Any ideas why is it being so slow? Are there better ways to hold a huge amount of tiles of a game in a list to be accessed continuously without having such a huge performance hit?


texts: How to integrate Javascript into C# and run scriptcode step by step

texts:
We are currently working on a Pokemon MMO trying to figure out how to implement an asynchronous scripting language the best. We don't want to work with threads or tasks, but the goal was to wait for specific commands like the messageBox("Hello World")-Command and stuff like that.

Is there any general solution for our problem?


texts: Reducing adjacency bookkeeping work in constrained Delaunay triangulation

texts:
I'm using the Sloan algorithm for constraining a generated Delaunay triangulation. This primarily consists of edge flipping for the edges that overlap the constrained edges.
In order to flip an edge, I have to know what two triangles contain that edge, and so for every edge I currently maintain an index (into the triangle array) of the current and opposite triangles for that edge. This gets built from the triangle array, where each triangle maintains indices for all adjacent triangles.
While this works, I've found that the vast bulk of my code is dealing with the maintenance of these triangle adjacencies. Every time an edge gets flipped, I not only have to update the two triangles that share the edge, but also update all of the other neighboring triangles that may have adjacency to one of those triangles, as well as go through and update any adjacency indexes within my list of edges to be flipped.
And then again, after the edges are flipped and you get a list of final "good" edges to use, you have to go through them and make sure they still satisfy Delaunay circumcenter rules, and if not, flip them again. Which means repeating all of the same work to maintain adjacency indexes.
Is there an algorithm for efficiently maintaining triangle/edge adjacency without all of this work? Or, better, is there an efficient method of determining neighboring triangles that share a common edge without the need to maintain these links?
I feel like I'm doing more adjacency maintenance than actual triangulation...


texts: Help to Code Bowling Like Feature in Unity for Mobile

texts:
I need Code or Guidelines for Touch Feature. When We Drag ball back and Send it Forward.
I am Making feature like bowling, and I need Player to add force while dragging back and also curve the path of the Ball
Anybody, Please Help


texts: Efficient communication between entities using ECS via entt

texts:
To avoid confusion about the ECS terms I'll use, I explain them here quickly. I use entt terminology and set-up my architecture like this:

Entity: is only an id (entt::entity)
Component: is a struct holding plain data (int, floats, etc.)
System: is a function looping over a family of components (using entt::registry.view)

In my game, I model a space ship that can have multiple engines. The engines apply a force on the ship each frame so the ship accelerates. I implemented it like the following:
Ship is an entity, Engine is an entity. Ship has the components AppliedForces, Mass and Velocity. Engine has the components Parent and Thrust. Parent is a component containing the parent's id of the engine (in this case a ship entity).
I have two systems: ThrustSystem goes through all entities that have the components Thrust and Parent. It looks up the AppliedForces component of the parent and adds the thrust vector to it. Then the AccelerationSystem runs through all entities with the components AppliedForces, Mass and Velocity. It adds the applied forces to entity's velocity. In code, it looks like this:

void ThrustSystem::update(entt::registry& entities)
{
  auto view = entities.view<Thrust, Parent>();
  for (auto [thrust, parent]: view)
  {
    auto& applied_forces = entities.get<AppliedForces>(parent.id);
    applied_forces.vector += thrust.vector;
  }
}

void AccelerationSystem::update(entt::registry& entities, dt)
{
  auto view = entities.view<AppliedForces, Mass, Velocity>();
  for (auto [applied_forces, mass, velocity]: view)
  {
    velocity.vector += applied_forces.vector * mass * dt;
  }
}

This works perfectly for me, the systems are decoupled and work independently from each other and I don't experience any performance issues (I model max. 1000 ships with an average number of 4 engines each). So I will stick to this implementation in my current game.
But I am actually curious and I would like to learn more about the "correct" usage of ECS in game code: is this a recommended approach to gain high performances and avoid cache misses? This is my first project with ECS and I am not an expert in CPU stuff at all but naively-thinking I would say there are two "bottlenecks" in my code:

Look-up time for the AppliedForces component of the parent entity in ThrustSystem
The AppliedForces is probably further away from Thrust and Parent in memory. So I introduced a cache miss.

At first, are my assumptions correct? And if yes, how would one avoid these bottlenecks?


texts:
I want to combine the Android UI with libGDX. I want to have half of my screen drawing an animated sprite with the libGDX engine, and the other half of the screen drawing Android UI buttons.

How do I combine the Android UI buttons with libGDX?


texts: How to export character from Zbrush to Blender?

texts: Zbrush displays only 1 format (zpr), which Blender doesn’t accept((


texts: Do I need to create an HLSL in XNA to display textures without content pipeline

texts: I currently have a jpeg texture stored as a Color array in XNA as RGBA. I also have the vertices of a cube in OBJ format mapped to VertexPositionColor vertex buffer using the VertexBuffer and Indices of the GraphicsDevice class. The OBJ has my jpeg mapped as a UV texture. I think I have all the Texture Coordinates as well(not sure, the array has 24 Vector3D values). I'm not sure where to go from here. I'm not using the Content Pipeline for my cube model or its texture though I'm wiling to add a custom .fx file if i need to. I realize I will have to add info about texture coords and color to my VertexDeclaration but do i need to write a custom effects file in HLSL to display my textured cube model or is there another way?