texts: Reducing texture bindings in LibGDX when drawing text

texts:
I'm making custom menus and buttons (I don't want to use scene2D) and I have everything in atlases, but when I draw a button, if it has text, the texture binding is always x2 because of the switching back and forth between the texture in the atlas and the bitmapfont.

(example of drawing order)

public void draw(SpriteBatch b){
   if(texture != null)
      texture.draw(b);

   if(text != null && !text.isEmpty())
      font.draw(b, "TEXT", x, y);
}

So as you see, if I have 3 buttons, each button will increase the texture binding x2. When using several buttons, texture draw/bind is maybe around the number 24. This hasn't cause noticeable performance issues yet (FPS stay at 60~61) but I want to know how I can reduce the number of bindings when drawing textures and fonts at the same time.


texts:
How can I draw many different objects on screen at once, with multiple vertex buffers, using DrawIndexed()? (Drawing the same object is simple, and I'm not looking to instance)

...but I am looking to transform two different vertex buffers. (Yes I am using indexed vertices)


texts: Android - Canvas.drawBitmap gives an awful performance

texts:
I am using SurfaceView for my game and I am loading all of the bitmaps that are the right size for the screen (pre-scaled in mipmap folder) into a class when the game starts. And I am drawing the bitmaps to the canvas using the drawBitmap method.
Though all of the bitmaps are compressed in 8 bit PNG format and scaled for the screen size, I am getting an awful FPS rate (around 40 FPS)
Things I have tried:
Made sure drawBitmap is the cause of the issue by recording the performance via performance monitor and examining the results. Basically, that is the only method that is causing an overhead.
Trimmed all of the transparent bits that are on the sides and used the fill canvas method for the background.
Scaled and compressed the bitmaps properly
Made sure nothing above or below the screen gets rendered
So this left me wondering; is a modern phone equipped with who knows how many times more powerful CPU and GPU than the computers in the early 2000s unable to utilize its hardware and thus unable to perform such a simple rendering request that those computers that are 2 decades old managed to do? I know drawBitmap uses CPU but nonetheless...
I am only drawing a bitmap that is 1/3 of the size of the screen and 2-3 small bitmaps on top of it (1/6 of the screen size) seeing as low as 30 FPS in such a simple task after all those optimizations is simply disappointing. Migrating to OpenGL will break so many parts of the code and obviously will be more challenging. And as far as I know, there isn't a library that simplifies drawing bitmaps by handling the OpenGL side and only exposes the canvas-like API.
So is there anything else I can do to increase the performance?


texts: Turning the camera when the player turns

texts:
I have a 3rd person view of the player character, and I wish my camera to follow the player both when he moves and when he rotates.

So far I have the movement correct:

    public class CameraController : MonoBehaviour {

    public GameObject player;
    private Vector3 offset;
    // Use this for initialization
    void Start()
    {
        offset = transform.position - player.transform.position;
    }

    // Update is called once per frame
    void LateUpdate()
    {
        transform.position = player.transform.position + offset;
    }
}

However the rotation of the camera does not change when the player looks in either direction. How can this be done?


texts: How do you make a Pong slider using touch events for mobiles?

texts:
I am stuck with an issue of moving the slider on android mobiles with finger touch event while developing pong game in unity 3D, though its working fine for pc.

This game is developed in 2D environment... please help me if anyone have available solution to this issue

Actually I have developed this game for pc so I have code for the movement of slider accordingly as below:

var keyup:KeyCode;
var keydown:KeyCode;
var speed:float=1;

function Update () {
    if(Input.GetKey(keyup))
        rigidbody2D.velocity.y=speed;
    else if(Input.GetKey(keydown))
        rigidbody2D.velocity.y=speed*-1;
    else
        rigidbody2D.velocity.y=0;
}

But now i want to use this game for android mobiles.


texts: New Vector Calculation for Elastic Collision of Circle and Fixed Rectangle

texts:
I am writing a fairly simple breakout-style game for Android phones. I have successfully detected the collisions between the ball(s) and bricks. The problem that I am having is in calculating the new vector for the ball. Even though the bricks are rectangular, I want to treat them as circles for the purpose of introducing more uniqueness to the ball directions.

I have the center point and vector of the ball and the center point of the brick which it has collided with and need to determine the new vector. The speed of the ball is always constant so the vector will be adjusted to that length but the direction is where I am having issues calculating. I've given it a few shots but they always end up being wildly incorrect.

The following is the code which I wrote but it has unpredictable results. All of the calculations must be done directly or using any of the methods in the Android SDK without a physics library of any sort.

float collisionUnitVectorX = ball.getLocation().x - blockCenterX;
float collisionUnitVectorY = ball.getLocation().y - blockCenterY;
final double collisionVectorLength = Math.sqrt(Math.pow(collisionUnitVectorX, 2) + Math.pow(collisionUnitVectorY, 2));
collisionUnitVectorX /= collisionVectorLength;
collisionUnitVectorY /= collisionVectorLength;

final double ballVectorLength = Math.sqrt(Math.pow(ball.getVectorX(), 2) + Math.pow(ball.getVectorY(), 2));
final float ballUnitVectorX = (float)(ball.getVectorX() / ballVectorLength);
final float ballUnitVectorY = (float)(ball.getVectorY() / ballVectorLength);

ball.setVectorX((float)(collisionUnitVectorX + ballUnitVectorX));
ball.setVectorY((float)(collisionUnitVectorY + ballUnitVectorY));

Here is a list of the information that I have for calculation:

ball center (x,y)
ball radius
ball vector (x,y)
block center (x,y)

The calculation should result in a new vector x and y values which has a length equal to the constant BALL_SPEED.

Remember, collision has already been determined, I am only looking for the new vector calculation. Thank you in advance.

(accepted answer author will be attributed in game credits)


texts: "_SRGB" suffix for BC texture format doesn't result in sRGB-to-linear correction at sampling

texts:
I am working on a 3D engine as a hobby (Direct3D 11). Currently I am trying to implement sRGB -> linear -> sRGB color space conversions via texture formats with "_SRGB" suffix. So, my textures are supposed to be sRGB images (for example, DDS-files compressed in BC1_UNORM_SRGB format), output is also gamma-corrected (thanks to R8G8B8A8_UNORM_SRGB frame buffer) and all shader calculations are made in linear color space.
The problem is, whether I use sRGB or non-sRGB format for the DDS-file, after sampling the texture I get exactly the same color values inside the shader that are stored in original image. But if I get it correctly, sampler should apply implicit gamma correction (pow(color, 2.2f)) for the input values. So, for example, if I want to output the same color as is in the map (lets say, 0.5f for R channel), I sample it from the texture (0.5f becomes 0.218f after transferring to linear color space by sampler), then I do nothing with it inside the shader and send to output. As the frame buffer has sRGB format, merger (or some other part of pipeline, that does it) will apply gamma re-correction to our value (pow(color, 1.0f / 2.2f)), and 0.218f will become 0.5f again. I will get the same image as I had on the input.
The output colors are definitely gamma corrected, as I see clear difference when I change frame buffer format from sRGB to non-sRGB. But as no input correction is applied, the final image looks brightened comparing to the input one. As I said, I checked the value in pixel shader after texture.Sample() call, and it is exactly the same as colorpicker shows for the source texture. When I swap the texture format to non-sRGB, nothing changes (I use Visual Studio 2013 Update 4 for format changing).
To load DDS files I use DDSTextureLoader. I also called Direct3D methods directly to create resource and view from the file, but nothing changed. Both resource and shader resource view have "_SRGB" format, as I can see in Graphics Debugger, so they are definitely sRGB ones.
I've read at MSDN that in Direct3D 11 setting texture format is enough for sampler to recognize sRGB image. Is there something I am doing wrong or missing, or understand incorrectly? Maybe someone had similar issues? Any advice would be highly appreciated!


texts: Point System For Answering Categorized Questions

texts:
We are currently developing a gamified e-learning website.

The website will have a point system where the users can gain points by doing either asking or posting questions. Questions are grouped by categories. Every time they answer/post a question, they get points for it.

The problem is students can easily gain points by repeatedly posting questions and get a lot of points. In order to prevent this we decided to implement a point system where posting questions will garner less points than answering questions. The point system will also follow the law of supply and demand.

When the amount of unanswered questions for a category is greater than the median of the total questions, the amount of points you will gain from asking a question on that category decreases while the amount of points gained from answering increases vice versa.

Our initial plan was to set a range for points with 1 point being our minimum and 8 being the max. By following the rule above we labeled each category with "Lower points" being the categories less than the median, and "Higher points" for the categories higher than the median. "Higher points" will have points ranging from 5-8 while "Lower points" will have a range of 1-4.

The points shown here are for answering questions

The problem is if there is an outlier the points given is not justifiable

We believe that points from category 7 should garner smaller points because of the huge difference of questions from category 8.

We also want to limit the maximum points from answering to 8

Is there any other better point system if this does not seem fit?


texts:
I'm writing a script (in C#) which, on mouse down, will spawn a gun and parent it to a game object. But for some reason the gun is instantiated just fine, but it doesn't parent. I have an empty game object called "Hands" and I'm trying to have the gun become a child and be moved to the position of "Hands".

To test what was going on I made two scripts, one which would parent the object upon pressing P, while the other script would just instantiate the item on mouse down. It worked, I first spawned the gun with mouse down, and then pressed P and it was parented. So my only guess is that you can't instantiate and parent in the same script all at the same time.

I have absolutely no clue what's going on, so I really appreciate any help I can get.

This is my code:

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

public class GiveWeapon : MonoBehaviour {

  public GameObject Weapon;
  public GameObject Hands;

  void OnMouseDown ()
  {
    Instantiate(Weapon);
    Hands = GameObject.Find ("Hands");
    Weapon.transform.parent = Hands.transform;
    Weapon.transform.position = Hands.transform.position;
  }
}


texts: How can I make that when the first animation end the next animation will start but from the same position?

texts:
I have two animations.
The first animation I downloaded from the Mixamo site.  The game start when the player is on his back on the ground and then slowly stand up. When the animation end the player is standing : Look at the player legs :

Then it's starting playing the next animation idle animation : Look at the player legs now when the idle animation start :

There is no problems with the animations.  It's just when the first animation end the player legs move close to each other because the legs position in the start of the second animation is not the same position when the first animation end.
I need somehow to make if it's possible that the first animation legs will end at the position of the second animation start. Now the legs are moving to each other and it looks funny. If I was showing a gameplay you will see the legs moving to each other like the player is closing his legs.
This screenshot is of the Animator controller where the left New State is the first animation and the Grounded is a blend tree with the idle animation inside :

And this is a screenshot of the blend tree and the first top state is the idle animation :

The transition between the two animations looks bad/funny. The player is closing his legs. Instead I wish there was a way to make the first animation to end with the legs close like in the second animation start.


texts:
I've recently modeled my character inside Maya; here's an image. The first thing I noticed whilst creating my model is that the models could be seen through source 1, after doing a little research people stated that it was a graphical bug in Maya. However, once imported into Unity the same effect occurs.

Therefore, my Question is: How can I fix this inside Maya or Unity?

To prove that my UV map doesn't contain a low opacity texture see the second image below:


texts: Move an enemy towards the player in pygame

texts: I set variables for the distance between the enemy and the player along the x-axis and y-axis. My plan is to move the enemy along the hypotenuse formed by y and x-axis line at a constant speed. The thing is I'm not sure how to set x and y speed of the enemy so that it will adjust dynamically to the changing position of the player and still maintain a constant speed. I thought that maybe I could find the angle at which enemy approaches the player and do something with that, but I couldn't think of anything.


texts:
I'm planning to make a long highway for a Racer game. What is the best way to do it ?

Do you make it in a single scene which I think is difficult to manage ? Or do you make multiple scenes or anything else ?


texts:
how can i look at a target on 2 axis but clamp the the object's rotation ,to only rotate from -45 to 45 on x and from -60 to 60 on y axis. i used this script to look at target and clamp the rotation, but it's not working right ): there is no problem with maximum value but whenever the rotation is about to become zero or a negative value the wired problem will show up. i made a gif here (http://www.mediafire.com/view/55phgr5qrhy8fk1/record.gif)

public Transform target;
public float speed;

public float minimumX;
public float maximumX;

public float minimumY;
public float maximumY;
// Start is called before the first frame update
void Start()
{

}

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

    Quaternion OriginalRot = transform.rotation;
    transform.LookAt(target);
    Quaternion NewRot = transform.rotation;
    transform.rotation = OriginalRot;
    transform.rotation = Quaternion.Lerp(transform.rotation, NewRot, speed * Time.deltaTime);

    transform.eulerAngles = new Vector3(Mathf.Clamp(transform.eulerAngles.x, minimumX, maximumX), Mathf.Clamp(transform.eulerAngles.y, minimumY, maximumY), 0);

}

}


texts:
Implementing a viewport is just a rectangular space on the back buffer usually a 2d texture set to the size of the client window that we render to.

However in direct3d when we describe the viewport it asks for the window width and heights and the top left X,Y position

From what I understand normalized device coordinates for the top left would be represented by 1,-1 and if I chose another type of device coordinate would be represented by 0 , 0.

How does this translate To a coordinate system for primitives I draw on screen from some file formats like wavefronts OBJ format their are coordinates that are out of range from -1 to 1.


texts: How should I handle exceptions in libGDX?

texts:
I want to keep my game running as much as possible for the user, obviously. They would be dissapointed if the game suddenly quits without leaving any notice behind, and it would be difficult for them to reproduce the error so I can fix it.

So when an exception is thrown, say, an ArrayIndexOutOfBoundsException, how should I handle it?

My current flow goes: DesktopLauncher > MyGame > Menu Screen / Game Screen / other screens


texts:
First off, I am making a game similar to SSB, which relies heavily on physics, even though it is a sidescroller. I am currently using Unity.
In Unity there are "character controllers" which are used for characters that move, but they don't interact with other physics objects. There are also rigid bodies, which are completely realistic physics components. I can't figure out how to use rigid bodies for human/humanoid characters. Here's some questions I have:

How should I move the character? Applying forces is not the way to do it, right? Would you set velocities or pixel-by-pixel movement, perhaps?

What kind of collider should I use? I've been using a capsule collider. But is that the best way?

How do you make him not fall down!? After some experimenting, I discovered that the character falls over (from applying force/velocity and from the capsule collider tipping it over). Would you constrain the rotation in the Z-axis?

What do you do when he gets hit? If you've ever played SSBB you'll be familiar with this topic. I'm thinking that applying a force would be best in this condition? If you did constrain the rotation, would you un-constrain it?


texts: what is the very last element of a 4x4 transformation matrix for?

texts:
while its a similar value to its neighbour - Z translation (and I wont say if thats above or to the left for fear of sparking a religious war!) and it only seems to change when the Z translation value changes, however the value is not quite the same

Normally I just see either this value ignored or just a 1 in all the tutorials I've seen

Can someone explain exactly what this last element does ?


texts: Game Engine Entity/Component with Services Architecture

texts:
I'm currently working on my first game engine and decided to use the entity/component model with services.

Background:
My GameEngine class is an Entity and has multiple services that are Components, like the RenderService and the PhysicsService. Other Entities in my game have components that communicate with services, like the RenderComponent and the PhysicsComponent.

Question: How do I get these components to communicate with their respective services?

Note: I have thought about having a call to the respective service create the components, but I would like to hear about other solutions you guys have. I'm open to adding/removing classes and changing my whole architecture. It is my first attempt, so I'm willing to take advice and learn. Time is not the concern.

Let me know if you need more information.

Thank you in advance.


texts:
I am trying to make a reload mechanism in Unity, but the function is in a scriptable object. This means I cannot use Coroutine as it is in MonoBehaviour. I could think of solving with a simple timer with Time.time and Time.deltaTime but for that, I should call the function every frame which seems not too right for me, I'd like to avoid this solution.
I thought about using C#'s built-in Async Await functions but I never used it before and it's quite confusing, I have no idea how to implement it after looking at Microsoft's documentation. I've tried implementing it but I always get an error saying
The body of 'Weapon.Reload()' cannot be an iterator block because 'void' is not an iterator interface type
I've done a coroutine implementation so it's easier to see what I want to achieve using Async/Await.
public virtual IEnumerator Reload()
{
    if (currentMagazine == magazineSize)
        yield break;

    if (!reloading)
    {
        Debug.Log("Started reloading");
        reloading = true;
    }
    else
    {
        yield return new WaitForSeconds(reloadTime);
        currentMagazine = magazineSize;
        reloading = false;
        Debug.Log("Reload time over");
    }

    Debug.Log("Finished reloading");
    yield break;
}

I want to be able to call this function and just let it do its job over time, without stopping code execution. At first, I tried the simple timer solution with a while loop then realized that just stops code execution so it's not working properly.
How could I do this using C#'s Async/Await?


texts: Unity equivalent of glDepthMask or alternative

texts:
I'm trying to achieve the following setup:

2 cubes. In the image attached they are the green and pink cube. They are both rendered culling their front faces, so that they are visible if a camera stands inside of them.
The 2 cubes intersect, as show in the image.
The pink cube has an opening (door, window, portal, whathaveyou) thru which a camea facing in the direction of the opening, can see the green cube.
Here is the interesting part: if the camera is not looking thru the opening however, I want the green cube face on the right side of the image to not be visible.

The culling is easy: just say Cull Front in a surface shader.
The part that I'm not sure how to pull of in Unity is the last point.

The way I would solve this in OpenGL, in a forward rendering pipeline, would be by turning on depth testing glEnable(GL_DEPTH_TEST) and, when rendering  the green box, I'd disable depth writing to the z buffer but keep testing on. i.e. glDepthMask(GL_FALSE) then render the cube and then re-enable writes to the z buffer. Essentially treating the green cube as if it were a skybox.

But I have not found anywhere in the ShaderLab documentation an equivalent of glDepthMask. there is ZWrite and ZTest but these just are equivalent to glEnable(GL_DEPTH_TEST) and glDepthFunc, not to the mask.

Any thoughts?

Alternatively, I was thinking of using clipping planes . In GL this would be using gl_ClipDistance in the shaders. I would render the green cube with a clipping distance equal to the intersection point of both cubes - 1, so it chops off that face. And the render the other cube without the clipping plane. But this would require updating the shader each time the clipping plane (intersection between the cubes) changes.

UPDATE:

I actually think that ShaderLab's ZWrite <On|Off> is the equivalent of glDepthMask. The issue is that I don't seem to be able to control rendering the green cube after Unity's skybox. If I were, the approach I'd take would be:

Unity renders it's skybox.
I render my green cube with ZWrite Off. This implies z testing takes place against the fragments of the cube, but the buffer won't be updated with the z values of the cube after this pass.
Render the rest of the geometry as usual.

Since step 2 did not write to the z buffer, the geometry should cover everything as it normally does with respect to the engine's skybox. This means it would cover the green cube too. But, if the geometry (pink cube) had any openings, the pink cube would not write  to the z-buffer since there is nothing there. The buffer in those areas should be 1 (the default for infinitely away).

I tried the above, which just meant creating a new surface shader with ZWrite Off and a tag "Queue" = "Background+1", hoping it would mean "render after the skybox". But while it does prevent the green cube rendering on top of the pink cube, it also makes Unity's skybox render on top of the green cube. So not sure how to tell it to render after the skybox.


texts: How can I fine-tune my movement values in a 2D block-based platformer?

texts:
I'm wondering how I can refine player movement/physics values, such as speed and jump height, to make it all work, while allowing the games to be fair and challenging. Is it simply trial and error, or is there a more standardized solution?

The levels in games like Super Mario or Geometry Dash are built on uniformly sized blocks, so the movement values need to work with these blocks. For example, if Mario can only jump 5 blocks high, the developers need to ensure that no obstacle is greater than 5 blocks tall (unless Mario has some special ability, but I'm not talking about that), or the player will be stuck.

Similarly, if the developers know that Mario can only jump 6.5 blocks horizontally, a blockless pit should be, at most, 6 blocks long. Knowing these relationships would allow one to create beatable levels, and even dynamically generate obstacles for the player to traverse.

I already have a character controller that can set my movement values easily, but I'm struggling to figure out a good way to make my movement and block sizes work together. Specifically, I'm concerned about making my game too easy or hard. How do I know when I've struck a proper balance?


texts: Infinite Seamless Background HLSL Shader in Monogame doesn't work with non square textures

texts:
I'm trying to write a shader that draws a seamless background infinitely in Monogame.

sampler TextureSampler : register(s0);
float2 ViewportSize;
float4x4 ScrollMatrix;
struct VertexToPixel {
    float4 Position : SV_Position0;
    float4 TexCoord : TEXCOORD0;
    float4 Color : COLOR0;
};
VertexToPixel SpriteVertexShader(float4 color : COLOR0, float4 texCoord : TEXCOORD0, float4 position : POSITION0) {
    VertexToPixel Output = (VertexToPixel)0;

    // Half pixel offset for correct texel centering.
    position.xy -= 0.5;

    // Viewport adjustment.
    position.xy = position.xy / ViewportSize;
    position.xy *= float2(2, -2);
    position.xy -= float2(1, -1);

    // Transform our texture coordinates to account for camera
    texCoord = mul(texCoord, ScrollMatrix);

    //pass position and color to PS
    Output.Color = color;
    Output.Position = position;
    Output.TexCoord = texCoord;

    return Output;
}

technique SpriteBatch {
    pass {
        VertexShader = compile vs_2_0 SpriteVertexShader();
    }
}

I'm using Monogame.Extended so I can use their Camera2D class. I have this function to draw my texture:

public static void drawSeamlessBackground(SpriteBatch s, Texture2D t, GraphicsDevice gd, float parallax, Camera2D cam) {
    //TODO: Make this work with non square textures.
    Vector2 textureSize = new Vector2(t.Width, t.Height);
    Rectangle view = gd.Viewport.Bounds;
    Matrix m = Matrix.CreateTranslation(new Vector3(-cam.Origin / textureSize, 0.0f)) *
                Matrix.CreateScale(1f / cam.Zoom) *
                Matrix.CreateRotationZ(-cam.Rotation) *
                Matrix.CreateTranslation(new Vector3(cam.Origin / textureSize, 0.0f)) *
                Matrix.CreateTranslation(new Vector3((cam.Position * parallax) / textureSize, 0.0f));

    infiniteShader.Parameters["ScrollMatrix"].SetValue(m);
    //Normally this next line would not be here since the viewport doesn't usually change.
    infiniteShader.Parameters["ViewportSize"].SetValue(new Vector2(view.Width, view.Height));

    s.Begin(samplerState: SamplerState.LinearWrap, effect: infiniteShader);
    s.Draw(t, new Vector2(0, 0), view, Color.White);
    s.End();
}

This whole thing works fine for square textures, but when the width and the height are different, there's distortion that happens when I rotate my camera.

In the next image, there are two textures, one that is square and one that is a rectangle.

Here is what it looks like with no rotation:

Here is what it looks like with some rotation:

The red texture has square dimensions (500x500). The white texture has rectangular dimensions (1280x720).

I'm sure this is a simple fix, but I can't figure it out.


texts:
I have a simple realisation of entity/component game engine.
Transform component have methods to set local position, local rotation, global position and global rotation.

If transform is being set new global position, then local position also changes, to update local position in such case I'm just applying current transform local matrix to parent's transform world matrix.

Until then I have no problems, I can get updated local transform matrix.
But I'm struggling on how to update local position and rotation value in transform.
Only solution I have in mind is to extract translation & rotation values from localMatrix of transform.

For translation it's quite easy - I just take 4th column values.
but what's about rotation?
How to extract euler angles from transformation matrix?

Is such solution right?:
To find rotation around Z axis, we can find difference between X axis vector of localTransform and X axis vector of parent.localTransform and store result in Delta, then:
localRotation.z = atan2(Delta.y, Delta.x);

Same for rotation around X & Y, just need to swap axis.


texts:
I'm trying to make a 2 dimensional grand strategy type of map, similar to Stronghold Kingdoms:

I've never dealt with these kinds of map before, but I assume this is a vector map (in svg format).
I have some GIS experience, specifically openLayers and I know it uses tiles for it's map rendering.
Is that an option for me too?
Maybe I could use tiles on the most zoomed out levels to make the map look pretty and overlay the vector map with transparency on top.

Sorry for badly written question, I'm really bad at this, if you could point me to some resources to writing better, I'd take those too.


texts: How to store tiles with different sizes?

texts:
in a tilegame, how can we use several tiles for 1 object?

I thought I could add each tile in a json file, with the type and its coordinates, like :

"line1: type1_xTile1_yTile1, etc."

"line2: type1_xTile1_yTile1, etc."

but in case when an object is bigger than the others, i don't see how to store this information. Is there another common way to store the tiles with different sizes?

Here is an example : the pond is bigger than the other tiles :

Thanks!


texts:
Can someone please give me any tips/ guides on how to create hologram, disintegration & freeze effects in Unity game?
I have a sci-fi shooter game in mind, and I would like to incorporate the above mentioned effects in it.

I would like to achieve something like these:

Holographic effect - 1,  2
Disintegration effect - 1
Freezing effect - 1

And I would prefer to achieve these without using a premium plugin. Budget issues.


texts: Depth interpolation for z-buffer, with scanline

texts:
I have to write my own software 3d rasterizer, and so far I am able to project my 3d model made of triangles into 2d space:

I rotate, translate and project my points to get a 2d space representation of each triangle.
Then, I take the 3 triangle points and I implement the scanline algorithm (using linear interpolation) to find all points[x][y] along the edges(left and right) of the triangles, so that I can scan the triangle horizontally, row by row, and fill it with pixels.

This works. Except I have to also implement z-buffering. This means that knowing the rotated&translated z coordinates of the 3 vertices of the triangle, I must interpolate the z coordinate for all other points I find with my scanline algorithm.

The concept seems clear enough, I first find Za and Zb with these calculations:

var Z_Slope = (bottom_point_z - top_point_z) / (bottom_point_y - top_point_y);
var Za = top_point_z + ((current_point_y - top_point_y) * Z_Slope);

Then for each Zp I do the same interpolation horizontally:

var Z_Slope = (right_z - left_z) / (right_x - left_x);
var Zp = left_z + ((current_point_x - left_x) * Z_Slope);

And if current z is closer to the viewer than the previous z at that index THEN write the color to the color buffer AND write the new z to the z buffer. (my coordinate system is x: left -> right; y: top -> bottom; z: your face -> computer screen;)

The problem is, it goes haywire.
The project is here and if you select the "Z-Buffered" radio button, you'll see the results... (note that I use the painter's algorithm (-only- to draw the wireframe) in "Z-Buffered" mode for debugging purposes)

PS: I've read here that you must turn the z's into their reciprocals (meaning z = 1/z) before you interpolate. I tried that, and it appears that there's no change.
What am I missing? (could anyone clarify, precisely where you must turn z into 1/z and where(if) to turn it back?)

[EDIT] Here's some data on what maximum and minimum z values I get:

    max z: 1;                  min z: -1;                 //<-- obvious, original z of the vertices of the triangles
    max z: 7.197753398761272;  min z: 3.791703256899924;   //<-- z of the points that were drawn to screen (you know, after rotation, translation), by the scanline with zbuffer, gotten with interpolation but not 1/z.
    max z: 0.2649908532179404; min z: 0.13849507306889008;//<-- same as above except I interpolated 1/z instead of z.
//yes, I am aware that changing z to 1/z means flipping the comparison in the zBuffer check. otherwise nothing gets drawn.

Before I go into painstaking debugging, can someone confirm that my concept so far is correct?

[EDIT2]

I have solved the z-buffering. As it turns out, the drawing order wasn't messed up at all. The z coordinates were being calculated correctly.

The problem was, in an attempt to increase my frame rate, I was drawing 4px/4px boxes, every 4th pixel, instead of actual pixels on screen. So I was drawing 16px per pixel, but checking the z buffer for only one of them. I'm such a boob.

TL/DR: The question still stands: How/why/when do you have to use the reciprocal of Z (as in 1/z) instead of Z? Because right now, everything works either way. (there's no noticeable difference).


texts:
I'm trying to understand if it's possible to create a game where the player can switch between 2d (strategic/bird view) and 3d (actual gameplay) using only the 3d supported JS/HTML5 game engine, like three.js or babylon.js?

I'm aware that there are few 2d/3d game engines like Godot, Turbulenz and Blend4Web, but still curious if i can do it same good only with a 3d game engine.

Thanks in advance.


texts: What is UVIndex and how do I use it on OpenGL?

texts:
I am a noob in OpenGL ES 2.0 (for WebGL) and I'm trying to draw a simple model I've made with a 3D tool and exported to .fbx format. I've been able to draw some models that only have: A vertex buffer, a index buffer for the vertices, a normal buffer and a texture coordinate buffer, but this model now has a "UVIndex" and I'm not sure where am I supposed to put this UVIndex. My code looks like this:

GL.bindBuffer(GL.ARRAY_BUFFER, this.Model.House.VertexBuffer);
GL.vertexAttribPointer(this.Shader.TextureAndLighting.Attribute["vPosition"],3,GL.FLOAT, false, 0, 0);
GL.bindBuffer(GL.ARRAY_BUFFER, this.Model.House.NormalBuffer);
GL.vertexAttribPointer(this.Shader.TextureAndLighting.Attribute["vNormal"], 3, GL.FLOAT, false, 0, 0);
GL.bindBuffer(GL.ARRAY_BUFFER, this.Model.House.TexCoordBuffer);
GL.vertexAttribPointer(this.Shader.TextureAndLighting.Attribute["TexCoord"], 2, GL.FLOAT, false, 0, 0);

GL.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, this.Model.House.IndexBuffer);

GL.bindTexture(GL.TEXTURE_2D, this.Texture.HTex1);
GL.activeTexture(GL.TEXTURE0);

GL.drawElements(GL.TRIANGLES, this.Model.House.IndexBuffer.Length, GL.UNSIGNED_SHORT, 0);

But my model renders totally incorrect and I think it has to do with the fact that I am ignoring this "UVIndex" in the .fbx file, since I've never drawn any model that uses this UVIndex I really have no clue on what to do with it.

This is the json file containing the model's data: http://pastebin.com/raw.php?i=G294TVmz


texts:
How can I change the root namespace for scripts in Unity?
I went to Edit - Project Settings... - Editor - Root namespace and put there the gameplay value.
I checked that the Assembly-CSharp.csproj has the <RootNamespace>gameplay</RootNamespace>
Now I go to VS Code editor, create a class and the class still uses a wrong namespace. What may I be missing here?


texts: considerations for local fog with raymarching

texts:
I want to implement local fog with ray marching.
I am not entirely sure how to make the fog behave like an actual volume.
The level designer is meant to place an arbitrary amount of fog volumes into the map - The shape can be arbitrary, too.
Let's say I have a sphere, raymarching with a pixel shader is trivial. But what should I do once the camera is inside the sphere?
I have the idea that I have two different shaders: One for the front face and one for the backface and setting the fog volume as double sided.

Is this a viable solution?


texts: How to texture voxel terrain without triplanar texturing?

texts:
How can a voxel terrain (marching cubes) be textured without triplanar mapping ?

The goal being to have more artistic freedom.

I think, I could unwrap the mesh while extracting the isosurface then use projective painting. But I do not know how to handle terrain modifications without breaking the texture. I also guess that virtual texturing could help here.

Links for these matters would be appreciated.


texts:
I'm benchmarking some simple code for drawing using OpenGL.

In the following code, the number of indices being drawn is 4,644 (or 1,548 triangles per frame = @60fps 92,880 Triangles per second).

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, screenSize.width, screenSize.height, 0, 0, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glDisable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnable(GL_TEXTURE_2D);

glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(venomGLAttribute), ,drawingTexturedList.attrib[0].color);
glVertexPointer(2, GL_SHORT, sizeof(venomGLAttribute), &drawingTexturedList.attrib[0].pos[0]);
glTexCoordPointer(2, GL_FLOAT, sizeof(venomGLAttribute), &drawingTexturedList.attrib[0].UV[0]);
glDrawElements(GL_TRIANGLES, drawingTexturedList[cnt].currentIndice /*4644*/, GL_UNSIGNED_INT, drawingTexturedList[cnt].Indices);

This takes 100% of one of my CPU's. If I take out the call to glDrawElements but still perform all the other steps (geometry preperation, gl*Pointer setup) I see my CPU stay at ~3%.

Is this expected behaviour? The machine I'm running on has a GeForce 8800GTX and a Dual Core @ 2.66Ghz.

Using fps as a measurement (which isn't perfect I realise) and using gDEBugger to confirm my findings, rendering 27,904 triangles a frame in a single call to glDrawElements brings my frame rate down to ~35fps (or 977,640 triangles a second).

Is there a better way to pack my data than I'm doing or perhaps a better way to send the data than glDrawElements? I don't think using a VBO will help as the data being sent changes every frame.

Any idea's would be appreciated!


texts:
I want a shape in pygame to fall down slowly. The user should be able to move the shape with the arrow keys. My code is given below:

while Running:
    Keys=pygame.key.get_pressed()
    if event.type == pygame.QUIT:
        Quit()
    elif event.type == pygame.KEYDOWN:
        if event.key ==pygame.K_LEFT:
            x=x-1
    y=y+1
    pygame.time.wait(3000)

However, it doesn't always take in the keyboard input if the shape is falling. e.g I will have to press the left arrow key 5 or 6 times for the shape to move. Any idea how I can sort this out?

update: I think the error is in the following code, but if I don't have it then the shape falls too quickly.

    pygame.time.wait(3000)


texts: How to generate doorways procedurally, on the fly, and guarantee acessibility

texts:
I'm currently creating a spaceship exploration game, and I have a massive problem I've been trying to solve for months, and through the rest of my group deciding to opt for a rewrite to fix some massive spaghetti.

Anyway, the problems goes as follows:

The player starts in a room, from which they can travel to some other adjacent rooms through doorways.

These doorways are stored in a map of the direction they're in, and the doorway object they reference. Each Doorway object keeps track of the two rooms it links, and will direct the player to each one when necessary.

However, all rooms need to be accessible by at least one route, and going through a doorway on the starboard side means that the other room needs to have the same doorway on the port side. I can do this by just having every wall be a door, but that gets boring to explore.

Pre-generating these proved enough of a glitchy mess for me to fail it, but now, the spec has changed. The world will be theoretically infinite, and as such, the pathing cannot be pre-generated, and instead must be done as new rooms are needed, or expected to be requested soon.

So I need to generate what is essentially a maze, with loops allowed, drawn on a grid, one square at a time, where not only is every room not directly aware the others exist, but acessible from every other. On top of this, going through a doorway on one side of a room means that the same doorway needs to be on the opposite side of the next room.

What's a good way to guarantee all these properties? I am willing to part with rooms having no knowledge of others, but would rather keep it this way for ease of re-generating a room's type later, should that become necessary.

Below is a text file ascii mockup of a 5x5 example I created
https://pastebin.com/EtdAWAwD
Lines are walls, Xs are doors, and the S is the player starting position.

Any advice at all is appreciated, even on alternate routes to consider for generating these.


texts:
My issue seems simple enough to me, but I can't break it down the the bare essentials to be able to program it into my game.

First of all different professions requires different skills, these skills are contained inside the class Person. I have a world map where I can ask for all empty buildings, thereby finding all available jobs.

With this information I want to calculate from some weights that the player can modify on each profession to how important it is to be fill a certain position.

so my current approach would be something like this pseudo code:

    Job findJob(wm : WorldMap) {
      Queue priority <- empty;
      for each building {
        queue.add(skill * need);
      }
      return prority.max();
    }

Does that sound inefficient stupid or do you see any special cases that you think I should be aware of?


texts: Implementing 2D CSG (for collision shapes)?

texts:
Are there any simple (or well documented) algorithms for basic CSG operations on 2D polygons?

I'm looking for a way to 'add' a number of overlapping 2D collision shapes. These may be convex or concave, but will be closed shapes, defined as a set of line segments, with no self-intersections.

The use of this would be to construct a clean set of collision edges, for use with a 2D physics engine, from a scene consisting of many arbitrarily placed (and frequently overlapping) objects, each with their own collision shape.

To begin with, I only need to 'add' shapes, but the ability to 'subtract', to create holes, may also be useful.


texts: Representing 3D World Space with 2D Tiles

texts:
How can I represent 3D world space with 2D tiles? I do not mean isometric, which is visually represent 3D objects in 2D space.

Let's say there's some height map, and each 2D tile (X, Y) represents a coordinate on the top of the map - so the Y is generated automatically, X stays the same and the tile's Y is the 3D Z component. Is it the right way to transform 2D coordinate to a 3D coordinate (again, on top of the terrain)?

Also - is it possible to implement water effect this way?

I'd like to read any articles/tutorials/opinions on this subject and how to implement it.

Thanks!


texts:
I'm having some problems porting my D3D code to OpenGL ES. I have a Graphics Device class that encapsulates all rendering commands. The code below is in an ObjC++ file.

The problem code is the called to get the render buffer width and height. It doesn't actually return any value in the w or h GLints.

It should be noted that the code below is from an older iPhone project, and it works there. Am I missing something really stupid?

Checking the framebuffer status returns a value of complete, since OpenGL ES seems quite happy to initialize a depth buffer with the garbage w and h values I pass to it!

bool GraphicsDevice::Initialize(id<EAGLDrawable> eaglLayer)
{
   EAGLContext *context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
   if(context == nil)
   {
      return false;
   }

   [EAGLContext setCurrentContext:context];

   this->eaglContext = context;

   glGenFramebuffers(1, &frameBuffer);
   glBindBuffer(GL_FRAMEBUFFER, frameBuffer);
   glGenRenderbuffers(1, &renderBuffer);
   glBindBuffer(GL_RENDERBUFFER, renderBuffer);
   [eaglContext renderbufferStorage:GL_RENDERBUFFER fromDrawable:eaglLayer];

   GLint w, h;
   glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &w);
   glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &h);

   SetWidth(static_cast<unsigned int>(w));
   SetHeight(static_cast<unsigned int>(h));

  glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER,    renderBuffer);

   glGenRenderbuffers(1, &depthBuffer);
   glBindBuffer(GL_RENDERBUFFER, depthBuffer);
   glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, w, h);

   glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthBuffer);

   GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
   if(status != GL_FRAMEBUFFER_COMPLETE)
   {
      System::Log("Framebuffer not complete");
      return false;
   }

   return true;
}


texts:
I'm working on a simple 2d puzzle with small textures (in count and quantity).
Now after I finished the game logic I'm considering tow options to switch between levels:

Remove all objects manually and de-attach their spirits from the current scene .
Drop the whole scene and start the new level on a new scene.

Both options are not much different in code complexity in my case. so the question is what are the drawbacks of the second approach ? specifically is a scene a heavy object?


texts: How do I best solve multiple component modifications via a single event?

texts:
I'm trying to solve multiple component modifications via a single event. Is there a better way of handling this?

I have an a label entity that cares about when a shield entity's hitpoints component is modified (damage, regeneration, etc).

The label will need to change

its text to display the current % of shield remaining.
its text color to display the severity of shield remaining.

When my ShieldSystem resolves the hitPoints component, the below code runs. For eah type of modification I plan to listen for, I need to add a new if-statement to the for-loop. This means I have a bunch of duplicated code between systems if more than one wants to modify any listening text component, sprite component, etc.

for(int i =0; i < listeners.size(); i++)
{
    if(listeners.count(MessageType::CHANGE_TEXT) == 1)
    {
        std::vector<Entity*> entities =  listeners[MessageType::CHANGE_TEXT];
        for(int j; j < entities.size(); j++)
        {
            Entity* e = entities[j];
            MessageInfo* messageInfo = new MessageInfo(MessageType::CHANGE_TEXT, e, "Some Text");
            MessageCenter::Dispatch(messageInfo);
        }
    }

    // Add an If(listeners.count(MessageType::CHANGE_TEXT_COLOR)...

    // Add an If(listeners.count(MessageType::CHANGE_SPRITE_RECT)...

    // etc

}


texts: How do I make a box don't slide up/walk normally on a slope?

texts:
I'm trying to implement slopes in my game. When I walk up the slope and suddenly stop, here is what happens:

And when I move down, it goes like this:

I have set density to 0.5, friction to 0 on both platform and a player. I have set friction to 0 because otherwise player gets stuck on a wall if he is jumping against it. What could I do to solve this? By the way, I'm using setLinearVelocity for movement:

body.setLinearVelocity(new Vector2(10, body.getLinearVelocity().y));


texts: how to accurately select a sprite on a scene with a click?

texts:
I have a scene with some sprite on it (added), the gamer has to select one of them and take the next action.

What is the simplest way to select one of the sprites accurately?

I am looking for a method that recieves a click coordinate and returns one of the sprites on the scene.

Since the sprites cant be well fitted in a bounding box I dont like to use a minimum bounding box approximation.

I was thinking of loading the sprites into a matrix and creating a scene matrix that each member belongs to a specified sprite, but it costs a lot( each pixel must be transformed using an affine transformation and it must be recalculated each time one of the sprites move)

Can someone show me a better way with a lower cost?

P.S I am using Swift and Apple's SpriteKit
There is a code for minimum bounding box but I am looking for an accurate method.

Inaccurate method if some interested is something like this :

     for touch in touches
     {
            var location : CGPoint = (touch as! UITouch).locationInNode(self)
            for asprite in self.viewIso.children
            {
                if (asprite.containsPoint(location))
                {
                    println("Selected : \(asprite.name as String)")
                    return
                }
            }
     }

Thanks
Iman


texts: Efficient way to go about acquiring game assets

texts: I was thinking about buying assets, but I don't want to waste time and want to acquire assets as fast as possible, and acquire a large amount of them, because I want to make several different games from the assets (rpg, action, shooter, etc.) Also, I want to commercialize the game, so what would you recommend me doing?


texts: Visual Studio not updating files made in Unity

texts: In the past Visual Studio simply updated solution based on files added in Unity but now all of them have to be added manually and they are as miscellaneous when they are added. How can I fix it?


texts:
I was wandering how easy is to interface existing Java programs/GUIs inside a game loop. Sorry if my question is a bit vague. I'll try to explain.

I am currently designing a simulation environment for a work-station. We have the actual programs running in the real compunters (which have a java GUI and run on linux virual machines). We also have 3D models of the room, chairs, monitors, etc. We can render those in Unreal engine. Currently, I have hard-coded very simple monitor textures that represent the programs running on the computers, but ideally, the player should have have the same experience as being in the actual control room, meaning that he should be able to use the programs in the same or almost the same manner.

My question is if it is possible to interface the I/O of the actual programs within the simulation. More specifically, if it possible to render the java awt as textures for the monitors, as well as taking the player actions and feeding them in the program as inputs. The actual program code may run inside or outside the game loop (preferably outside, in its native virtual machine).

Can you please direct me to the right path, since I am only remotely familiar with game development. Thank you in advance!

Edit: Just to clarify one thing: Running the program on an external machine (virtual or physical) and feeding this machine's display to a local texture is acceptable, but I was wandering if it could be possible to use Java's GUI library output directly into the game loop (instead of the host machine). I suppose this has to be supported by the game engine (eg. having support for an in-game desktop-environment/window-manager). Unreal engine was just chosen for testing. Any engine recommendation is welcome.


texts:
I wish to interpolate two quaternion values. As I still can not get working results, can I kindly ask you to verify my function calls? The code below supports GLM (OpenGL Mathemathics) library, so this questions might be for those, who know it.

Firstly, I perform Quaternion intialization from Euler Angles:

glm::quat myAxisQuat(pvAnimation->at(nFrameNo).vecRotation);
glm::quat myAxisNextQuat(pvAnimation->at(nFrameNo + 1).vecRotation);

Secondly, I interpolate between the two input quaternions. The variable fInterpolation contains value in the range 0.0f - 1.0f.

myInterpolatedRotQuat = glm::mix(myAxisQuat, myAxisNextQuat, fInterpolationTime);

Thirdly, I convert my interpolated quaternion back to Euler Angles:

vecInterpolatedRot = glm::gtx::quaternion::eulerAngles( myInterpolatedRotQuat) ;

At the end, the values in vecInterpolatedRot do not represent the interpolated EulerAngles. It is difficult to understand the Quaternion values after conversion from Euler Angles, so I would like to ask you for your help, please.

What can be wrong, please?

I double and tripple checked input variables, I tried various approaches, and the only issue, at this moment might be with the third Aplha parameter in glm::mix()

Update:

To provide you with more information, the returned values in vecInterpolatedRot are extremely low. At the end of the interpolation, I would expect valid Euler angles.

This is random sequence of interpolated values, as the object moves according to predefined animation path.

rotX:-1.7451 rotY:1.7993 rotZ-0.854642
rotX:-1.06451 rotY:1.18485 rotZ-0.694015
rotX:-0.254822 rotY:0.437004 rotZ-0.942035
rotX:0.578816 rotY:-0.335103 rotZ-0.716057
rotX:1.53934 rotY:-1.07602 rotZ-1.0182
rotX:2.5582 rotY:-1.87737 rotZ-0.759468
rotX:-2.58259 rotY:-2.47432 rotZ-1.06071
rotX:-1.35049 rotY:3.11548 rotZ-0.81839
rotX:0.0106472 rotY:2.78129 rotZ-1.04353
rotX:1.46636 rotY:2.33968 rotZ-0.879188
rotX:0.0289322 rotY:2.31166 rotZ-0.91746
rotX:-1.47901 rotY:2.37235 rotZ-0.938591
rotX:-2.59482 rotY:2.89469 rotZ-1.15554
rotX:2.47283 rotY:-2.76131 rotZ-0.992493
rotX:1.73065 rotY:-1.53285 rotZ-1.27898
rotX:0.85806 rotY:-0.176976 rotZ-1.03487
rotX:0.452009 rotY:-1.14604 rotZ-0.927788
rotX:0.0604701 rotY:-2.12479 rotZ-1.05684
rotX:0.107648 rotY:-2.07785 rotZ-1.05071
rotX:0.154894 rotY:-2.03083 rotZ-1.04569
rotX:0.809623 rotY:2.14456 rotZ-1.31262
rotX:1.15268 rotY:0.332553 rotZ-0.983604
rotX:2.16299 rotY:-0.545458 rotZ-1.11758
rotX:2.95376 rotY:-1.2008 rotZ-0.846527
rotX:-2.94892 rotY:-0.892473 rotZ-1.17334
rotX:-1.89716 rotY:-1.30162 rotZ-1.53247
rotX:0.804938 rotY:1.93659 rotZ-1.37281
rotX:0.653453 rotY:1.73722 rotZ-1.14364
rotX:2.24713 rotY:0.658935 rotZ-1.03684
rotX:2.97528 rotY:0.508203 rotZ-0.559124
rotX:-2.49988 rotY:0.640482 rotZ0.0117903
rotX:-1.57379 rotY:1.16303 rotZ0.288639
rotX:-1.4928 rotY:1.17794 rotZ0.902059
rotX:-0.667796 rotY:1.94995 rotZ1.49074
rotX:2.12971 rotY:-1.85782 rotZ0.904871
rotX:2.36951 rotY:-2.03682 rotZ0.189242
rotX:1.5574 rotY:-2.92156 rotZ-0.450418
rotX:1.6256 rotY:2.29519 rotZ-1.46659
rotX:2.85414 rotY:2.11303 rotZ-0.42888
rotX:-2.48503 rotY:2.96942 rotZ0.189887
rotX:-1.55656 rotY:3.00852 rotZ0.675669


texts: why the camera won't rotate around my object?

texts:
im new to unity scripting, and now am building upon "Roll a Ball" example in unity training. I wanted to make the camera rotate around the ball in the scene in Y axis, when mouse is moved, and watched some tutorials on it, and eventually wrote the code below. but it doesn't rotate around the ball. instead it does a simple rotate in place. camera still moves with the ball though.
what am i doing wrong?

public class CameraController : MonoBehaviour {

    public GameObject Player;
    private Vector3 offset;

    public float moveSpeed;
    private Vector3 point;

    void Start () {
        offset = transform.position - Player.transform.position;

        point = Player.transform.position;
        transform.LookAt(point);
    }

    void Update()
    {
        float mouseMovement = Input.GetAxis("Mouse X");

        transform.RotateAround(point, new Vector3(0f, mouseMovement, 0f) , moveSpeed * Time.deltaTime);
    }

    void LateUpdate()
    {
        transform.position = Player.transform.position + offset;

    }
}


texts: Why do games ask for screen resolution instead of automatically fitting the window size?

texts:
It seems to me that it would be more logical, reusable and user-friendly to implement flexible, responsive UI layout over a 3d or 2d screen, which can then be run on any screen resolution.

Some modern games auto-detect screen resolution and adjust the game to that, but the option to change the resolution still remains in the settings.

Why is this option there?

My guess is that this is one way to provide older machines with a way to improve performance by rendering less graphics and just stretching them across the screen, but surely there are better ways of improving performance (choosing different texture and model qualities, for example).


texts: Can a project made in Unreal Engine be converted to Unity project with a tool?

texts: Recently working on Unreal Engine for a project but want to convert the whole project to Unity. Is there any way?


texts: Changing sprite tint over time in Unity. Sprites affected by "light"

texts:
Recently I was playing "Altos Adventure" on mobile.

I was curious how I could implement an effect similar to their game background.

The sprites tint over time to match the time of a day. It's blue in the morning, orange in the evening. Sky color is changing and also mountains tint.

I believe it is possible to change solid color sprite and it seems like mountains have only one color individually. Maybe they use other half transparent sprites to change the tint of the entire scene? Like half transparent curtain. But it doesn't explain the smooth transition between colors during the time.

Any ideas how I can do the same with Unity and Photoshop? I am also interested in mountain fading effect which appears during rain or snowfall.

See the background behaviour lighting effect  in more detail in this video

Screenshots with different tints of background:


texts: How can I create a car mod for GTA: Vice City?

texts: I am a player of GTA games. I want to create my own car for GTA: Vice City. How do I create a mod that adds a new car to the game?


texts: Geometry shader-generated tile mesh isn't any faster than CPU-generated version

texts:
For practice, I'm writing a Rogue-like. In order to speed up tile rendering I have a dynamic Mesh/MeshBuilder that collects all the vertices of the visible tiles' quads (4 vertices per tile: position, color, UV; and 6 indicies) CPU-side and emits a single draw call of the large tiled triangle mesh. At 600 FPS/0.0017 ms this is fast enough for my purposes.
I recently decided to practice with the various rendering pipeline stages and thought that this would be a great candidate for the geometry stage and have the GPU generate the tiles for me, passing in only a single vertex/index pair per tile.
There are as many as 2000 tiles visible per frame, yet it was no faster than the CPU version despite passing one quarter the amount of vertices and one sixth the indicies across to the GPU.
It's my understanding that it is a best practice to minimize the amount of data passed between the CPU and GPU, and hand off work to the GPU that it is better suited to do.
Am I wrong in this understanding?
It seems like the geometry shader isn't that useful if offloading work to it doesn't have a benefit?
What can be achieved with the geometry shader that other techniques can't do?


texts:
One day I asked me: "How do game designers work?". I knew what the "main mission" of their work, but I didn't know: "How to do it?" and "What do they need to write?"

I want to know full "list" of terms with examples that they need to write.

For example:

Genre - Action

Setting - Retrofuturism etc...

Please answer me :)


texts: Is it alright to have hundreds of canvas object on screen?

texts: I am using html5 to build a game and it is based on Canvas not webGL. I am trying to build sprites from canvas object not from images. Because there will be many sprites on the screen and each of them has different size and moves to different direction I would be using many canvas objects. I wonder if it's OK to put so many canvas objects on the browser screen. Will this make the game very slow?


texts:
I am having the issue as seen below while using a textureAtlas with libgdx. I haven't found anyone else with the issue so I decided to ask here.

Here is an image of the textures in the game screen:

And to prove it's not a texture related issue, here is the spritesheet with the same background color as the game screen has applied:

Any suggestions? sorry for the sloppy write-up I am very preoccupied.


texts: LWJGL multiple keyboard/mouse input checks

texts:
As in many game libraries such as LWJGL, you can check mouse/keyboard events with Mouse.isButtonDown or Keyboard.IsKeyDown.

I want to check for button/key presses, not if it's currently pressed down (if that makes any sense) so I use Keyboard.next() and Mouse.next(). This works fine, except if you have multiple places where you want to do this check.

So if you do Mouse.next once for all the events in the 'queue', the queue is empty and future Mouse.next's don't return anything.

What would be the solution for this? Create a wrapper around the Keyboard class and save the keystate? If so, how can I save that state? Couldn't find anything in the javadocs.

Thanks in advance.


texts: COLLADA: Inverse bind pose in the wrong space?

texts:
(Crosspost from StackOverflow)

I'm working on writing my own COLLADA importer. I've gotten pretty far, loading meshes and materials and such. But I've hit a snag on animation, specifically: joint rotations.

The formula I'm using for skinning my meshes is straight-forward:

weighted;
for (i = 0; i < joint_influences; i++)
{
    weighted +=
        joint[joint_index[i]]->parent->local_matrix *
        joint[joint_index[i]]->local_matrix *
        skin->inverse_bind_pose[joint_index[i]] *
        position *
        skin->weight[j];
}
position = weighted;

And as far as the literature is concerned, this is the correct formula. Now, COLLADA specifies two types of rotations for the joints: local and global. You have to concatenate the rotations together to get the local transformation for the joint.

What the COLLADA documentation does not differentiate between is the joint's local rotation and the joint's global rotation. But in most of the models I've seen, rotations can have an id of either rotate (global) or jointOrient (local).

When I disregard the global rotations and only use the local ones, I get the bind pose for the model. But when I add the global rotations to the joint's local transformation, strange things start to happen.

This is without using global rotations:

And this is with global rotations:

In both screenshots I'm drawing the skeleton using lines, but in the first it's invisible because the joints are inside the mesh. In the second screenshot the vertices are all over the place!

For comparison, this is what the second screenshot should look like:

It's hard to see, but you can see that the joints are in the correct position in the second screenshot.

But now the weird thing. If I disregard the inverse bind pose as specified by COLLADA and instead take the inverse of the joint's parent local transform times the joint's local transform, I get the following:

In this screenshot I'm drawing a line from each vertex to the joints that have influence. The fact that I get the bind pose is not so strange, because the formula now becomes:

world_matrix * inverse_world_matrix * position * weight

But it leads me to suspect that COLLADA's inverse bind pose is in the wrong space.

So my question is: in what space does COLLADA specifies its inverse bind pose? And how can I transform the inverse bind pose to the space I need?


texts:
I've been thinking about the structure of an Item class.
There are many items which may or may not have effects in the game.

For example,
an item "Herb" has an effect to "Heal HP by 5". but
an item "Stone" has no effect.

As per a title, when you design a game, how do you structure the Item class?

The following is the structure I've come up with.

class Item{
    String id;
    // Status where s = HP, MP, ATK .. etc
    // Integer -> value which affects on the Status
    Map<Status, Integer> effect;
    SignType st; // +, -, *, /
}

class Player{
    Map<Status, Integer> status; // Status where s = HP, MP, ATK .. etc
}


texts:
I am currently trying to get randomly generated maps work in multiplayer but I have so many difficulties trying to figure out how. How do other games implement this(Minecraft, Terraria, Don't starve)? My current solutions are as follows.

Generate the map client side and verify(Hash?)

This is the least bandwidth intense but the algorithm needs to be EXACTLY the same as the server side and it is the easiest to exploit.

Generate Server side and transfer to client

This method will ensure that the players all have the EXACT same map, but it it very resource intensive for the server and requires a lot of bandwidth and increased loading times.


texts: How to load parts of a large tilemap like chunks in Unity 2d?

texts:
I use more pictures so you can understand my opinion better.
Here is the video link I recorded.
My code has a problem that I use for to render it and cause it to "lag" for 1-5 seconds, so I need to optimize it, and I found one way is to use chunks, and why I don't use the tilemap and it drops my fps
This links to my map data and my code.
// this is my function I use to create clone game object
if (Vector3.Distance(target.position, topLeft) < 25f
         || Vector3.Distance(target.position, topRight) < 25f
         || Vector3.Distance(target.position, bottomLeft) < 25f
         || Vector3.Distance(target.position, bottomRight) < 25f)
{
    // My code is currently running "fine", but when it renders the
    // map in 1-2s it will drop fps because of the for loop, then it will increase again
    xMin = xMin - 1;
    xMax = xMax + 1;

    yMin = yMin - 1;
    yMax = yMax + 1;

    GetCircumjacent();
    for (int x = xMin; x < xMax; x++)
    {
        for (int y = yMin; y < yMax; y++)
        {
            if (x == xMin || y == yMin || x == xMax - 1 || y == yMax - 1)
            {
                try
                {
                    int mapX = xCenter + x;
                    int mapY = yCenter + y;

                    // this is when I get the prefabs from the array prefabs I added
                    GameObject clone = Instantiate(prefabs[map[mapX, mapY]], this.transform);
                    clone.transform.position = zero + new Vector3(x, y);
                }
                catch (Exception e)
                {
                    Debug.Log("Error: Index out of range");
                }
            }
        }
    }
}

private void GetCircumjacent()
{
    topLeft = zero + new Vector3(xMin, yMax - 1);
    topRight = zero + new Vector3(xMax - 1, yMax - 1);

    bottomLeft = zero + new Vector3(xMin, yMin);
    bottomRight = zero + new Vector3(xMax - 1, yMin);
}


texts: Why do I have to run my 2D game at 300+ FPS for movement to be passably smooth?

texts:
I'm working on a simple game with SFML, and the only way to make the game reasonably smooth is to allow it the highest framerate my machine can handle (that is, giving it no limit). 60 FPS in my game looks like 5 FPS in most games.

I've made sure it wasn't any weird timing issue with sf::Clock by making my delta variable constant, and I've made a simple moving square with the default SFML template to make sure it wasn't anything else in my code.

Limiting framerate using window.setFramerateLimit(80), window.setVerticalSync(true), or by placing usleep(1000 * 15), a 15-millisecond pause (~67 FPS, in theory) in the game loop, cause the terribly glitchy, asymmetric animation.

I think the problem is my Mac. I hesitate to blame anything other than my code, but I just can't explain the problem otherwise. I'm running OS X Mavericks on a 15-inch MacBook Pro with a Retina display (2.4 GHz i7, Nvidia, 8GB RAM).

Is it the Retina display, or some issue with the sleep() system calls? Any thoughts are welcome. Thanks!


texts: How can I minimize visual clutter in an ASCII rougelike game?

texts:
I'm currently designing an old-school rouguelike, similar to games like Nethack or Dwarf Fortress. While I love the ASCII graphical style they employ (which my game will also employ), they also suffer from visual clutter, caused by the large amount of text usually present on the screen at any given time. The graphical style of my game without clutter-reducing improvements will effectively be identical to that of Dwarf Fortress's:

I've thought up a few things which could potentially alleviate this problem, but they're probably not enough:

Separate the UI rendering and game rendering into separate "layers".
Apply a unique color filter to each layer to visually separate them.
Tone down the use of ASCII characters, and instead opt for solid coloring in some places when possible.

How can I minimize this visual clutter?


texts: Can running unity of a system with nvidia graphics card speed up the simulation?

texts: I have a nvidia GTX 1080 graphics card in my computer, I don't know if unity by default makes use of GPU. Does having a GPU helps to speed up unity simulations.


texts: How can I my homing missile avoid walls (2D)?

texts: Okay, I have the homing missile implemented. It will follow the player, but I want it to avoid the walls. I tried out A* but I want to make my own. I need some help plzz.


texts:
My game can display tiles such as Grass tile, Dirt tile and Rock tile with no problems. Now I am trying to display water tile and animate it but for some reason it is not animating and only displaying single frame of water tile. What am I doing wrong?

Below are the appropriate classes that I am using to animate my water tiles. Please let me know if you require any more info to help me solve the problem. Thanks!

Tile class:

public abstract class Tile {

public static Tile[] tiles = new Tile[256];
public static Tile grassTile = new GrassTile(0);
public static Tile dirtTile = new DirtTile(1);
public static Tile rockTile = new RockTile(2);
public static Tile waterTile = new WaterTile(3);
public static Tile waterfallTile = new WaterfallTile(4);
public static Tile wateSplashTile = new WaterSplashTile(5);
public static final int TILE_WIDTH = 64, TILE_HEIGHT = 64;

protected BufferedImage texture;
protected final int id;

public Tile(BufferedImage texture, int id){
    this.texture = texture;
    this.id = id;
    tiles[id] = this;
}

public abstract void update();
public abstract void render(Graphics g, int x, int y);

public Boolean isSolid(){
    return false;
}

WaterTile class:

public class WaterTile extends Tile {
private Animation waterAnim;
private int speedAnim = 150;

public WaterTile(int id) {
    super(Assets.water[0], id);
    waterAnim = new Animation(speedAnim, Assets.water);
}

public void update(){
    waterAnim.update();
}

@Override
public void render(Graphics g, int x, int y) {
    g.drawImage(getAnimationFrame(), x, y, Tile.TILE_WIDTH, Tile.TILE_HEIGHT, null);
}

private BufferedImage getAnimationFrame() {

    return waterAnim.getFrames();

}

public Boolean isSolid(){
    return true;
}

Animation class:

public class Animation {

private int speed, index;
private long lastTime, timer;
private BufferedImage[] frames;

public Animation(int speed, BufferedImage[] frames){
    this.speed = speed;
    this.frames = frames;
    index = 0;
    timer = 0;
    lastTime = System.currentTimeMillis();
}

public void update(){
    timer+=System.currentTimeMillis() - lastTime;
    lastTime = System.currentTimeMillis();

    if (timer > speed){
        index++;
        timer = 0;
        if (index >= frames.length){
            index = 0;
        }
    }
}

public BufferedImage getFrames() {
    return frames[index];
}


texts:
For my game, I have a tool that lets me quickly create map geometry. You can see a (albeit early version) demo of the tool here. The main problem with the tool is that even a semi-large map can EASILY amount to around thousands to even 10s of thousands of tiles. The easiest way to fix this, I found, was to use a script I found online to merge all of the tiles into one mesh at the start of runtime (this is because I want to still be able to edit my tilemap in the editor)
This works and has a noticable improvement to the performance (especially if post-processing is enabled) however I'm left with a mesh that has a bunch of triangles that just aren't needed. You can see an image of the mesh here. The problem with this is that if I want to do any kind of point lights with shadows (baked lighting isn't possible, really, due to the interactivity of my game since you can turn lights on/off and I have a weird day/night system that is split into multiple periods of the day and only changes after a mission/event) would mean I'm rendering that mesh again from each point lights POV (and I need a LOT of point lights). I can't really just not use shadows since it causes very noticable light bleeding at walls.
I've tried to find some sort of algorithm to simplify the mesh and I came across a script that seems to do exactly what I want, but I couldn't get it to do anything except cause my mesh to become completely black with seemingly no change in mesh topology. Here's the script by the way
I've also found an algorithm called Greedy Meshing which seems to also do what I want, but seems to be meant for voxel based worlds like minecraft and I'm not sure how to implement it in my case since my tiles aren't voxels.
I've been trying to find other algorithms but the various game dev servers on discord can't seem to help me. Does anyone know how I can solve this problem? I'm not really smart enough to come up with my own algorithm/system to simplify the mesh.


texts: How can I continue to rotate a 2D UI Object using OnPointerEnter when object is on its side? (OnPointerExit is triggered)

texts:
I have been wracking my brain on this for days. I'm trying to create a nice looking hand of cards, when the card is hovered over, it bobs up and down and rotates. This is triggered by OnPointerEnter, however, whenever it turns on its side and out of the mouses path OnPointerExit triggers, I've tried MANY things, including a bool that triggers the hover effect OnPointerEnter but it is just toggled off when it's turned on its side.

Is it possible to use the collider on my card with OnPointerEnter? Because that would probably solve my problem but haven't found anything on this.

Since the card is on UI, I have some placeholder code in there in order the have the inspected card render on top and return to its place.

    void Update()
{
    if (inspect)
    {

        transform.localScale = cardUpscale;

        posOffset = transform.position;

        transform.Rotate(new Vector3(0f, Time.deltaTime * degreesPerSecond, 0f), Space.World);

        // Float up/down with a Sin()
        tempPos = posOffset;
        tempPos.y += Mathf.Sin(Time.fixedTime * Mathf.PI * frequency) * amplitude;

        transform.position = tempPos;
    }
}

public void OnPointerEnter(PointerEventData eventData)
{
    zoomPlaceholder = new GameObject();
    zoomPlaceholder.name = "zoomPlaceholder";
    zoomPlaceholder.transform.SetParent(this.transform.parent); //binds the placeholder to the hand
    zoomPlaceholder.transform.SetSiblingIndex(this.transform.GetSiblingIndex());

    LayoutElement cardProxy1 = zoomPlaceholder.AddComponent<LayoutElement>();
    cardProxy1.preferredHeight = this.GetComponent<LayoutElement>().preferredHeight;
    cardProxy1.preferredWidth = this.GetComponent<LayoutElement>().preferredWidth;
    cardProxy1.flexibleHeight = 0;
    cardProxy1.flexibleWidth = 0;

    zoomPosition = transform.parent;
    transform.SetParent(transform.parent.parent);
    inspect = true;
}

public void OnPointerExit(PointerEventData eventData)
{
    inspect = false;

    this.transform.SetParent(zoomPosition);
    this.transform.SetSiblingIndex(zoomPlaceholder.transform.GetSiblingIndex());

    transform.localScale = cardNormalScale;

    Destroy(zoomPlaceholder);

}


texts:
i'm developing a game with a top down view, the players body is a circle. To move the character you need to tap on the screen and it moves to the spot.

To achieve this i'm saving the coordinate of the touch and call a method every frame which applies linear velocity to the body with a vector of the direction the body should go

_body->SetLinearVelocity(b2Vec2((a.x - currPos.x)/SPEED_RATIO,(size.height - a.y - currPos.y)/SPEED_RATIO));
//click position - current position, screen height - click position (since the y axis is flipped, (0,0) is in the bottom left ) - current position = vector of the direction we want to go

now the problem with this is that the body slows down until it finally stops when getting closer to the point we want it to go, since the closer we are to that point the lenght of the vector gets smaller. Besides that i've read that it's bad practice to set linear velocity in box2d and i should use apply force instead, but that way the forces would add up and overshoot the target where it's supposed to stop.

So what i'm asking is how to move a box2d body to a coordinate in constant speed.


texts: How can I simulate multiple depth channels?

texts:
Here's what I'd like to achieve:

Rendering a first pass of objects in my scene, using standard depth comparison
Rendering another pass of objects in the same scene, but with the following rules:

A Pixel of the 2nd pass always override the first pass (no depth compare between them)
Use Depth comparison between pixels written from the second pass.

In English I want depth comparison made inside each pass but I always want the second pass pixels to override the first pass ones.

Some things I've thought:

I tried to think about using stencil to solve this, but I couldn't find a way.
I know I could render into a separate target the second pass then composite the result into the first, but I'd like to avoid that.
I could use two separate Depth Buffer, one dedicated to each pass. (I never tried, but I figure it's possible to switch the depth buffer in a Render Target "on the fly")

Any idea of the best solution?


texts: Logic for npc/customer for cafe simulator game

texts:
I need help for logic or pseudo code on how to implement a rules/formula for customer in how they choose drinks(& the toppings).
I have more than 10 types of customer and I want to set preferences for everyone of them.
E.g : a boy prefer juice (60%), soda(30%) and tea (10%), while an adult in suit prefer coffee(80%), juice (20%).
The boy would decide to add topping (70%), and would prefer chocolate(50%), jelly(30%),bubble(20%) as the topping.

What is the best way to implement that? And one thing that concern me that some of the toppings or even drinks are actually might be unavailable because its not ready or need to be unlocked first by leveling up or another reason.

Additional info: i am using unity, and have game manager, customer and player/shop scripts.


texts: How to make a moving platform in Godot not be affected by collisions?

texts:
I am trying to make a moving platform in Godot (for a 2D platform game, but I suspect the issue would be similar in 3D).
Basically, both my player and my platform are KinematicBody2D, and they move via the move_and_slide() method. The documentation says:

You can use this to make moving or rotating platforms, or to make nodes push other nodes.

This seems to fit my use case. However, when the player collides with the platform, the latter will be affected. For example, if the player stands on top of the platform, it will slowly start going down. I don't want that, I want the platform to move in a fixed fashion no matter what is throw at it (and if the player stands in the path of the platform for example, the player should be pushed).
How can I solve this? I was thinking about using a StaticBody2D for the platform, but the documentation says:

A StaticBody2D is a body that is not intended to move.

So I am not sure if this is the correct solution. It seems that the move_and_slide() method has some additional parameters, such as infinite_inertia, but the documentation is not very clear to me as to what they do exactly.


texts:
I'm working on an OpenGL application and some routines render textured objects, some are just colored primitives. I was wondering if there was a standard convention for how to deal with setting the OpenGL 'state'.

For example, consider this routine (using OpenGL ES / OpenTK):

/// <summary>
/// Renders the given tile at the corresponding screen-tile location.
/// </summary>
public static void RenderTile(float[] vertices, float xOffset, float yOffset, uint textureId)
{
    GL.EnableClientState(All.VertexArray);
    GL.EnableClientState(All.ColorArray);
    GL.EnableClientState(All.TextureCoordArray);

    GL.PushMatrix();

    GL.Translate(xOffset, yOffset, 0.0f);

    GL.BindTexture(All.Texture2D, textureId);
    GL.VertexPointer(2, All.Float, 0, vertices);
    GL.ColorPointer(4, All.Float, 0, SQUARE_COLORS);
    GL.TexCoordPointer(2, All.Float, 0, SQUARE_TEXTURE_COORDS);

    GL.DrawArrays(All.TriangleStrip, 0, 4);

    GL.PopMatrix();
}

I'm curious about that GL.EnableClientState(All.TextureCoordArray); bit. Should I just get into the habit of calling GL.Enable(...) / Gl.EnableClientState(...) for everything the current function needs? Even if it is largely redundant? Or is it better to just assume that the application has a certain set of things enabled (blending, back-face culling, 2D textures, etc.).

I know this question is pretty subjective, so I'm looking for advice from someone who has worked with a large OpenGL codebase. (As all my experience is for solo projects.)


texts:
I seem to have misunderstood something about how LERP works. Im not sure what is missing. The object is rotating as it should, but it cant seem to get it to end. The transform.rotation dont seem to reach its target even if it has done so visually.

Quaternion rotationTarget;
    Vector3 travelTarget;
    float rotationLerpProgress;
    float rotationLerpDuration = 1f;

    // Use this for initialization
    void Start ()
    {

    }

    // Update is called once per frame
    void Update ()
    {
            if (Input.GetMouseButtonDown (0)) {
                    var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
                    RaycastHit rayHit;
                    if (Physics.Raycast (ray, out rayHit)) {
                            var rayHitPoint = rayHit.point;
                            travelTarget = rayHitPoint;
                            var rotationDirection = rayHitPoint - transform.position;
                            rotationDirection.y = 0;

                            rotationTarget = Quaternion.LookRotation (rotationDirection);
                            rotationLerpProgress = Time.deltaTime;
                    }
            }
            if (transform.rotation != rotationTarget) {

                    if (rotationLerpProgress < rotationLerpDuration) {

                            transform.rotation = Quaternion.Lerp (transform.rotation, rotationTarget, rotationLerpProgress / rotationLerpDuration);
                            rotationLerpProgress += Time.deltaTime;
                            print (string.Format ("({2}) - progress: {0} - duration: {1}  ", rotationLerpProgress, rotationLerpDuration, rotationLerpProgress / rotationLerpDuration));
                    } else {

                            print (string.Format ("setting rotation ({0}) to target ({1})", transform.rotation, rotationTarget));
                            transform.rotation = rotationTarget;
                    }
            } else {
                    print ("rotaton is at target! :)");
                    if (transform.position != travelTarget) {
                            rigidbody.AddForce (Vector3.forward);
                    }
            }

    }


texts: Creating a game with in game programmable AI

texts:
I am looking to make a game where the player can access an in game terminal and then use this terminal to write AI logic in a programming language such as C++ or C#, then they can compile the code and apply the AI to NPC characters.

Of course if the code failed to compile error free then it would not be applied to the NPC. Mostly the code would be function calls with a few basic constructs available like int, float, bool etc.

My question is how could I achieve this in say Unity or another game engine. Would I need to use a scripting language such as LUA or Python to create the AI or could I be done in real time on a separate thread in Unity somehow?


texts:
Possible Duplicate:
  What is the future of XNA in Windows 8 or how will manged games be developed in Windows 8?

It's no secret XNA's future is uncertain. Windows 8 only supports XNA desktop applications and not metro style apps. A number of 'rumors' are going around concerning Microsoft no longer supporting XNA after 4.0.

Despite this, do you believe it's worth picking up XNA now?


texts: Why do I get this file loading exception when trying to draw sprites with libgdx?

texts:
I'm having trouble with the "Drawing Images" section on the libgdx tutorial.  I set up the documents completely and I typed the code as follows:

public class Game implements ApplicationListener {
        public static final String LOG = Game.class.getSimpleName();
        private FPSLogger fpsLogger;
        private SpriteBatch batch;
        private Texture texture;
        private Sprite sprite;
        private TextureRegion region;

        //removed irrelevant code for this question...

        @Override
        public void render() {
                texture = new Texture(Gdx.files.internal("android.png"));
                region = new TextureRegion(texture, 20, 20, 50, 50);
                sprite = new Sprite(texture, 20, 20, 50, 50);
                sprite.setPosition(10, 10);
                sprite.setRotation(45);

                Gdx.gl.glClearColor(0f, 1f, 0f, 1f);
                Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
                batch.begin();
                batch.draw(texture,10,10);
                batch.draw(region,10,10);
                sprite.draw(batch);
                batch.end();

                // output the current FPS
                fpsLogger.log();
        }
}

I went through the tutorial on the website but when I run the code I get errors:

Exception in thread "LWJGL Application"
com.badlogic.gdx.utils.GdxRuntimeException: Couldn't load file: android.png at
com.badlogic.gdx.graphics.Pixmap.<init>(Pixmap.java:137)  at
com.badlogic.gdx.graphics.glutils.FileTextureData.prepare(FileTextureData.java:55) at
com.badlogic.gdx.graphics.Texture.load(Texture.java:175)  at
com.badlogic.gdx.graphics.Texture.create(Texture.java:159)    at
com.badlogic.gdx.graphics.Texture.<init>(Texture.java:133)    at
com.badlogic.gdx.graphics.Texture.<init>(Texture.java:122)    at
com.game.Game.render(Game.java:46)    at
com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop (LwjglApplication.java:163) at
com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:113)
Caused by: com.badlogic.gdx.utils.GdxRuntimeException: File not found: android.png (Internal)     at
com.badlogic.gdx.files.FileHandle.read(FileHandle.java:108)   at
com.badlogic.gdx.files.FileHandle.length(FileHandle.java:364)     at
com.badlogic.gdx.files.FileHandle.readBytes(FileHandle.java:156)  at
com.badlogic.gdx.graphics.Pixmap.<init>(Pixmap.java:134)  ... 8 more

I set the android.png in my assests folder in my android project linking it to the desktop one, I don't understand what I'm doing wrong.  What is making these errors?


texts: How could I render a star like those in Elite Dangerous - coronas and some sort of 3D "plasma" effect on the surface?

texts:
Lets assume I wish to render a large, 3D, star object in a game engine using OpenGL. I can use a few different meshing methods: this includes mapping a cube to a sphere (with better subdivision to reduce distortion), a primitive lattitudional/longitudional based "globe" mesh, or a selectively subdivided icosphere. I would choose whatever would be easiest to apply the 3D effect to: I'm guessing an isocahedron, since it doesn't distort as much and the issues with mathematical discontinuities (when finding the Tangential, Normal, and Binormal) vectors should not be a worry (unless rendering the following effect would use a bump/normal mapping technique with a GPU-generated texture?)

Further, lets assume I wish to render a boiling, roiling, or vaguely evolving surface. The diamond-square algorithm could generate the proper effect, but how could this be used in 3D to generate something that looks vaguely like the surface of a star? Could I use the GPU to generate a texture that is then evolved with time, and use a procedural noise algorithm that includes the analytical derivatives to do so(for acquiring normal/bump map components to add "depth")? Should the noise algorithm be in 2D or 3D?

Lastly, what if I want to render the corona of the star in some volumetric fashion as well? Corona's created with billboards work well enough, but rapidly fall apart in appearance once the viewpoint gets closer to the star (as is common with sprite-based techniques).

Example images:


texts: How can I limit the y-rotation of a cinemachine POV camera based on the player's direction?

texts:
I'm using Unity (2019.4.11.f1, HDRP).
My goal is to create a first-person POV camera.
To this purpose, I tied a Cinemachine (2.7.3) Virtual Camera to the head of a third person player character (one from the Basic Locomotion demo of this asset).
The Body of the camera is set to 'Hard Lock to Target', Aim to 'POV', and Recenter Target to 'Follow Target Forward'. This works fine.
The camera has a Horizontal Axis Value Range (-# to #), that limits the rotation of the camera, but I cannot figure out how to tie this to the rotation of the Follow component (the head of the avatar).
When I walk my character around, the camera can only rotate within the set Value Range angle that has it's 0-point in one absolute direction (let's say north), independent of the player's orientation.
It seems to use World Orientation, but I don't know and wasn't able to find out where to change that.
Does anyone know how I can change this behaviour?


texts:
Languages / Libraries in use: C++, OpenGL, GLUT
Okay, here's the deal.
I've got a particle system which shoots out alpha blended textures to produce a flame. The system only keeps track of very basic things such as, time alive, life, xyz and spread.
The direction in which the flames are currently moving in is purely based on other things which are going on in my code ( I assume ).
My goal however, is to attach the flame to the camera (DONE) and have the flame pointing in the direction my camera is facing (NOT WORKING).
I've tried glRotate for both x,y,z and I can't get it to work properly.
I'm currently using gluLookAt to move the camera, and get the flame to follow the XYZ of the camera by calling glTranslatef(camX, camY - offset, camZ);
Any suggestions on how I can rotate the direction of the flame with the camera would be greatly appreciated.
Heres an image of what I've got: http://i.imgur.com/YhV4w.png

Notes: Crosshair depicts where camera is facing
if I turn the camera, flame doesn't follow the crosshair
Also asked here: https://stackoverflow.com/questions/9560396/rotate-a-particle-system
but was referred here


texts: How can I acheive a smooth 2D lighting effect?

texts:
I'm making a 2D tile based game in XNA.

Currently my lightning looks like this.

How can I get it to look like this?

Instead of each block having its own tint, it has a smooth overlay.

I'm assuming some sort of shader, and to pass the lighting values for the surrounding tiles to the shader, but I'm a beginner with shaders so I'm not sure.

My current lighting calculates the light, and then passes it to a SpriteBatch and draws with the tint parameter. Each tile has a Color that is calculated before draw in my lighting algorithm, which is used for the tint.

Here is an example on how I currently calculate lighting (I do this from left, right, and bottom too, but I got really tired of doing this frame by frame...)

So actually getting and drawing the light so far is no problem!

I have seen countless tutorials on fog of war and using gradient circular overlays to create smooth lightning, but I already have a nice method to assign each tile a lightning value, it just needs to be smoothed between them.

So to review

Calculate Lighting (Done)
Draw Tiles (Done, I know I will need to modify it for the shader)
Shade tiles (How to pass values and apply "gradient)


texts: How to store XMLs in Unity for web player deployment?

texts:
I've created with Unity a short demo that works as a standalone .exe on Windows, and I was interested in deploying it as a web player game too.

When I run the game on the web player, though, I get this error in the Unity console:

  StreamingAssets is not available on this platform.

I have some XMLs I parse at runtime in the StreamingAssets folder. Where can I put them in a web player build so to be able at runtime to load them?

Thanks for your answers.


texts: Is coroutine as good as a delay() function

texts:
I'm new to Unity and I was learning the usage of coroutines.
Is calling a coroutine as good as a delay() function?
Does Unity have a delay() function?


texts:
I'm trying to set sound panning in my game depending on camera position, rotation and audio source position.

I was able to set sound panning depending on camera position (listener), and audio source like this:

Vector3 toSourceVector = Vector3::subtract(sourceTransform->position, listenerTransform->position);
float value = MathUtil::clamp(toSourceVector.x, -1.5f, 1.5f);
value = value + 1.5f;
float perc = (value / 3.0f) * 254.0f;
AudioManager::setPanning(254.0f - perc, perc);

Max panning value on the right/left speaker is 254.
When I'm standing on the front of the audio source (without rotating my camera), panning values are: 127 and 127, for example, when the audio source
is on my right side, panning values are 0 and 254.

Obviously, if I rotate my camera, sound panning is same.

I've got Vector3 with camera (listener) rotation values (x, y, z).

My question is: how to calculate panning values depending on camera rotation too?


texts:
Is it possible to use OpenFileDialog in XNA 4.0 to get the file path? If not, what is the alternative?
I'm using XNA 4.0 to create a graphic display (not a game) and I have a file that contains informations on how and what to draw on screen. The only problem is that I hard-coded the path because I don't know how to dynamically get that path?
Do you know a solution for that?


texts: Reskinning assets on-the-fly with LibGDX TextureAtlas

texts:
I'm building a game for Android using LibGDX and I'm attempting to add in a skin feature so players can change the look of the game on-the-fly. I've packed the skinnable assets into their own .pack files, separate from those of the rest of the assets, and I want to swap out the packs being used when the player selects a new skin.

In my Game Class I've got a function like this one:

public void loadSkinnedAssets(String skin){
    if(skinnableAtlas != null){
        //Tried both with and without disposing.
        skinnableAtlas.dispose();
    }
    skinnableAtlas = new TextureAtlas(Gdx.files.internal("skins/" + skin + "/Assets.pack"), true);

    if(gameScreen != null){
        gameScreen.refreshSkinnedSprites();
    }
}

Then in the GameScreen it does something like this:

public void refreshSkinnedSprites(){
    mySprite = new Sprite(game.getSkinAtlas().findRegion("myRegion");
    //Rest of the sprite setup not important.
    //Also attempted to just use mySprite.setRegion().
}

When the player chooses a skin from a list, it calls game.loadSkinAssets("skinName"). This is only possible from an options screen separate from the GameScreen.

These two functions work properly when called on launch, but the result of running them to replace existing assets is all of the replaced assets being drawn as solid black rectangles. If the game is left and then returned to (dispose and resume being called organically) everything loads properly, which again calls the same functions.

Is there something I'm missing in the posted code, or is there some entirely different way of accomplishing this?


texts: How to control a 2d charter in an top-down android game with the standard joystick?

texts:
So I'm building a 2d top-down game and I need to control my character using unity cross-platform standard asset single joystick.
The problem is with the rotation, I don't want to use the dual-stick for some idea related reasons and the designs and the game mechanics that was considered for this game.
So I want the character to have the same rotation as the joystick and since the joystick only has the horizontal and the vertical axies it's hard to get a descent rotation.
So any ideas how to do this? if you need further clarification let me know.


texts:
I'm developing an RTS game and I want to add multiplayer support to my game.

I picked the easiest technique to implement for start frame locking technique.

I used server client networking architecture (I think it's my first mistake I think using peer to peer is a better one for this)
On game update every clients send their commands and maybe receive some command then render the frame and wait for all clients to send their update complete message then all of them can go for the next frame.

I send commands and all logic is calculated on the clients based on commands but the clients can go out of sync easily. Every AI controlled units make different decisions on each clients

What I have to do to sync my game?
Do you suggest me a better network architecture or technique?