texts: Weird behavior with XNA SpriteBatch.Draw origin

texts:
I have a texture with 256x256 pixels.

Consider this piece of code:

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        spriteBatch.Begin();
        spriteBatch.Draw(texture, new Rectangle(0, 0, 100, 100), null, Color.White);
        spriteBatch.End();

        base.Draw(gameTime);
    }

If I run this, the texture appears (predictably) at the top-left corner of the window with the correct size (100x100).

If I do this instead (XNA 4.0-only):

spriteBatch.Draw(texture, new Rectangle(0, 0, 100, 100), null, Color.White, 0, new Vector2(0, 0), SpriteEffects.None, 0);

Everything is still as expected. However, as soon as I change the origin parameter, the position gets weird.

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        spriteBatch.Begin();
        spriteBatch.Draw(texture, new Rectangle(0, 0, 100, 100), null, Color.White, 0, new Vector2(128, 128), SpriteEffects.None, 0);
        spriteBatch.End();

        base.Draw(gameTime);
    }

In this last example, only 1/4 of the texture is visible.

In other words, the origin parameter not only changes the origin of the rotation, but also the destination rectangle. In other words, the Top/Left coordinates of the rectangle are not the Top/Left coordinates of the drawn sprite, but rather the coordinates of the Origin.X/Origin.Y texture pixel.

If the target position was just a Vector2, I'd understand (and fully support) this behavior, but with a destination rectangle it just seems odd, especially since the documentation does not seem to mention this fact (although to be honest, the documentation barely says anything at all).

A StackOverflow answer even suggests that a destination rectangle with rotation doesn't make much sense, but XNA offers it anyway.

What is the reason for this behavior?


texts: Can I do server side programming with unity?

texts: Another thought to my last question. If i were to do a client/server game with unity3d would i be able to do serverside programming with unity? if not can i use C# .net? if not then is there some sort of package or lib i can use with C++? is the communication just raw sockets?


texts:
I have a 3D scene, and a player that can move about in it.

In a time-step the player can move from point A to point B.  The player should follow the terrain height but slow going up cliffs and then fall back, or stop when jumping and hitting a wall and so on.

In my first prototype I determine the Y at the player's centre's X,Z by intersecting a ray with every triangle in the scene.  I am not checking their path, but rather just sampling their end-point for each tick.  Despite this being Javascript, it works acceptably performance-wise.

However, because I am modeling the player as a single point, the player can position themselves so that they are half-in a cliff face and so on.  I need to model them as as a solid e.g. some cluster of spheres or a even their fuller mesh.  I am also concerned that if they were moving faster they might miss the test altogether.

How should I solve this?


texts: GeForce FPS Counter is not displaying and G-SYNC is not working on games developed using Unity

texts:
I have developed a small game for learning purpose and here is src of that, when I play the game GeForce FPS Counter is not displaying.

I thought there might be some kind of bug in my src. So, I installed two popular games developed using Unity.

"Life is Strange: Before the Storm" - FPS not displaying.
"INSIDE" - FPS displaying.

Can anyone tell me what is happening. And also I noticed that when playing "Life is Strange: Before the Storm" my CPU and GPU temperature goes hotter than playing "Rise of the Tomb Raider".

Note: I have played all the game in full screen mode and all settings to highest.

UPDATE:

Firewatch and INSIDE both shows FPS Counter. but,
when Enable G-SYNC for full screen mode is selected, G-SYNC is not working in all the games developed using Unity even when launched in full screen mode. But when I enable Enable G-SYNC for windowed and full screen mode then the G-SYNC is working. But when it comes to Life is Strange: Before the Storm is not showing FPS Counter but shows G-SYNC indicator on the screen.

Is Unity games not actually runs in Full Screen mode?


texts:
How is game difficulty typically tested or balanced so that there's a steady progression of difficulty; how do I ensure that no level is too difficult or too easy for its point in the game?

Are play testers of various skills brought in, or a random sampling of people? What considerations are/should be taken into account during the actual level design process?


texts:
What does multiplying an object in local space with a WVP(world,view,projection) matrix do?
My book says "local space to homogeneous clip space"

Luna, Frank D. (2012-05-21). Introduction to 3D Game Programming with DirectX 11 (Kindle Location 5444). Mercury Learning and Information. Kindle Edition.


texts: libgdx default saving mechanism for box2d world

texts:
I want to save my game in libgdx, and I have no problem using Kryo to save everything, except the box2d Worlds and the RayHandlers from box2dlights - these are not Serializable and do not have default constructor, ruling out most of the methods. I have no idea how to save them, but I'm aware the most used approach is JSON - which I'm ok with. I even found this, but it seems to be specific for jBox2D alone, because I'd have to change all the names and packages in the code to match libgdx's box2d version's. Also, it uses the famous original JSON lib for java, whereas libgdx has it's own internal JSON handler and parser. So, I could just convert everything, as I said, it's all opensource. But it is such an absolutely essential task (serializing), present in every single game, that I think libgdx might also have something to do this. I can't, however, find anything about it, anywhere. Can someone put a light on this?

Just some background: my game happens in a galaxy, and every single planet has it's own World for handling. But I only load one planet at a time in the memory: when the player leaves, I save it on a file. So my save consist of one main file with player data, galaxy structure, anyway, everything else, and a folder with one file for each Area (planet's map). This map contains some objects and data plus the World and RayHandler from box2d and box2dlights. I'm using JSON (libgdx's default) already for the Area class, but if the world and rayHandler fields are no transient, I get a StackOverflow, probably due to circular refences not supported by JSON writers. As I said, I can't use kryo due to the lack of private default constructors in most classes, and JSON does seem to be the standard approach for this. The lack of a solution built-in in libgdx, however, is really making me wonder what I'm not seeing in all this.


texts: How do I spawn trees so that they stick out perpendicular to a 3D planet?

texts:
I have a 3D tree that I want to clone so that it is perpendicular to a planet gameobject, so it looks upright when spawned. I tried by copying down all desired rotations of the tree and adding them into a dictionary full of vector3’s so that I can access any one of them when I need to. However, using Quaternion.Euler() doesn’t copy the coordinates exactly when I pass them in; they are always wrong. Below is the code:

public void PlaceFauna(GameObject prefab, Vector3 position, Vector3 rotation, GameObject icosphere)
{
    prefab.transform.position = position;       // Moves prefab into scene and sets position
    prefab.transform.rotation = Quaternion.EulerAngles[rotation];   // Sets rotation to that of the one in the dictionary
    GameObject clone = Instantiate(prefab) as GameObject;   // Creates clone
    clone.name = clone.GetInstanceID().ToString();  // Gives clone a unique name
    clone.transform.parent = icosphere.transform;   // Puts clone under region
    prefab.transform.position = new Vector3(0, 0, 40);  // Moves prefab out of scene
}

It takes in the position and the rotation from the dictionary and applies .Euler() to the prefab so that the tree (should) match the position. However it does not do this. Where am I going wrong?


texts: How to make part of the Texture not to be scaled.?

texts:
I am new to LibGdx, i was doing one example for my learning and struck with this question, i had searched in google but i am not able to find the answer for this.

1) How to make part of the Texture not to be scaled.

as you can see in the image i am reducing the height of bottom pipes so that the top pipe scale is reduced to fit the height given but i want the top part of the pipe not to be scaled.

in this example whole pipe is one texture, for fixing this problem i thought to split the top and body to separate texture and set height for only body but i thought there should be some other solution so that only i had put this question here.


texts: How do you save and load settings for an iOS game?

texts:
I've read a few beginning iPhone game programming books, and they've helped tremendously in my education and advancement in creating a few simple games, but of all the books I've read, there doesn't seem to be anything about creating a Settings Menu or how to change and save settings within a game.

What are some ways that settings can be saved/loaded? Where are these settings saved?

This may seem like a simple, uninteresting question, but I can't find anywhere that has a good explanation on how to go about creating a settings menu and how the data is saved/loaded each time the program ends/starts...

Mind you I'm not really expecting to have code thrown at me, but an explanation on how the structure works and how to wrap my head around the whole concept (though code is pretty ;)). Or even some articles that explain the concept that I could read would be very helpful.


texts: Rotating an object continously in UNITY with onclick

texts:
I have a script that works but it does not do what I want it to do. My script makes an object rotate on when another is clicked. However, I want the object to continuously rotate until I click on the other object again. Right now when I click it rotates just a bit and stops.

Here is my script

 using UnityEngine;
 using System.Collections;

 public class Rotate : MonoBehaviour {

public float speed =50f;
public GameObject target;

public void OnMouseDown(){

    target.transform.Rotate (new Vector3(0, Time.deltaTime, 0) * speed);

}

 }

Any assistance? I created what I have now using what I found on the internet but cant find another solution.


texts: What game engines can publish to Android and iOS?

texts: I am about to start on a project which, at a minimum, will release to Android and iOS. Are there any game engines, other than Unity, which can publish to both? I fear that Unity might contain more overhead then we need, for what is essentially a 2D game.


texts: Wrapping 3D noise functions like simplex and perlin in c#

texts:
I'm experimenting with loop-able worlds that have a height-map for terrain data.
While I can easily create loop-able .BMP textures for this in Photoshop and just load the terrain from them, but that limits the size and variance of the worlds to whatever I pre-generate for the player.

I would like to proceduralize the process. I have got a simplex terrain and a perlin terrain generator and I'd like to wrap them so that the world loops back around to the same place if you travel in a straight line in any direction North East South West

What would be the best techniques to use to wrap the noise to a tillable terrain.

This question Different as it is for both perlin AND simplex.
It is also different as I forgot to mention I am using 3D noise for some of my work.


texts: Difference between a normal function and coroutine without yeilding anything

texts:
I just came across a coroutine in my project, which does few calculation, which could have been done using normal function.There is no loop in that coroutine and contains yield return null; in the last line. Is there any specific reason to use coroutine rather than normal function?

void Init(){
RenderObject();

}

IEnumerator Init(){
RenderObject();
yield return null;
}

EDIT:

Inside the RenderObject function, they are calling another coroutine which has two yield instructions yield return true; and yield return new WaitUntil(() => based on certain condition, calling to server takes place primarily.


texts:
I'm quite sure that I'm missing something very simple here, but I'm a complete Unity noob and I absolutely can't figure out what I'm seeing.

I'm trying to light a sphere from both sides, perpendicular to the camera angle, to create an effect where each side of the sphere is illuminated but there's a strip of darkness down the center. Instead, I'm getting really weird angles from the two lights.

My setup (I've quintuple checked all numbers)...

A single sphere (textured like Mars) at position (0, 0, 0).
An orthographic camera pointed at it from position (0, 0, -20) and rotation (0, 0, 0).
Two Point lights at (-5, 0, 0) and (5, 0, 0), with the same intensity and all other light settings.

By my understanding, that should position each light equidistant from the sphere, exactly on either side from the camera's POV. Sort of like a capital " T " configuration. In theory their shine on the sphere should be mirrored on each side, complimentary angles toward the sphere from exactly horizontal. Instead, I'm getting this:

Left Light...

Right Light...

So, instead of being horizontal and mirrored, it appears as though the Right Light is significantly closer to the camera than the Left Light along the Z axis, and they both seem to be somewhat below the vertical center of the sphere (despite all elements having a Y value of zero).

Even weirder, viewing it in the Scene panel from above, there's a spiral pattern of darkness when both lights are on, rather than a single dark band between them...

Can someone help me out here? Does Unity handle perspective in a way I'm not getting, or have I messed up my arrangement of elements? And aside from eyeballing it, what positions should I use to create the effect I'm going for?


texts: Unity calculate the size of a text box before text gets drawn so it can lerp to the next size

texts:
Im trying to make a dialog box image that lerps to the next size.

In order to do that I need to calculate the size of the image before the text gets drawn.

My idea is to use the legacy GUI stuff like guiStyle.CalcSize to get the width and guiStyle.CalcHeight to get the height. then im setting the image's layout elements min values = to the GUI sizes.

the width is set to the longest string in the array of "lines"

the problem is that while the image does scale it doesn't do so correctly. perhaps my approach is wrong and there's an easier way?

private void Update()
{
    lineText = dialogueRunner.dialogText;
    drawnText = dialogueUI.lineText.text;

    //Debug.Log(prefferedValues);

    numberOfCharactersInLine = dialogueRunner.dialogText.Length;

    lineTextWithNewLine = NewLineAfterNChar(lineText, 18);

    string[] lines = lineTextWithNewLine.Split(new[] { "\n" }, StringSplitOptions.None);
    for (int i = 0; i < lines.Length; i++)
    {
        longest = lines.OrderByDescending(s => s.Length).First();

        prefferedValues = textMesh.GetPreferredValues(longest);

        Debug.Log(longest.Length);
    }

    //scale isnt correct
    layoutElement.minWidth = size.x;
    layoutElement.minHeight = size.y;

}

void OnGUI()
{
    guiContent = new GUIContent(longest);

    guiStyle = GUI.skin.box;
    guiStyle.alignment = TextAnchor.UpperLeft;
    guiStyle.wordWrap = true;

    //------
    boxSize = new Rect(Screen.width / 2, Screen.height / 1, txtBGRect.sizeDelta.x, txtBGRect.sizeDelta.y);
    boxSize.center = new Vector2(Screen.width / 2, Screen.height / 2);

    // // Compute how large the button needs to be.
    size.x = guiStyle.CalcSize(guiContent).x;
    width = size.x / 1;
    size.y = guiStyle.CalcHeight(guiContent, width);
    height = size.y;

    GUI.Box(boxSize, longest); //this draws the box

}

//Pass it a string and it will insert a line break after every n characters at end of words.

public static string NewLineAfterNChar(string inputText, int lineLength)
{
    string[] stringSplit = inputText.Split(' ');//Split string into array seperatly "word1" "word2" "word3" etc...
    int charCounter = 0;
    string finalString = "";

    for (int i = 0; i < stringSplit.Length; i++)// iterates per word count
    {
        finalString += stringSplit[i] + " ";// "word1 "  "word2 " "word3 "
        charCounter += stringSplit[i].Length;

        if (charCounter > lineLength)//after n characters
        {
            finalString += "\n";
            charCounter = 0;
        }

    }
    return finalString;
}


texts: Are all referenced sprites loaded into memory for each object?

texts:
I'm trying to understand how Unity works behind the scenes.  Let's say I have a GameObject that has a large number of sprites attached to it in an array (think a deck of cards).  Each GameObject represents 1 card.

For simplicity, each card has all the sprites for all the card faces.  So it has 52 sprites + 1 for the card back (all in a sprite sheet of course).

If I have all 52 cards placed in the world.  Does this mean I have 53*52=2756 sprites, or is there only one instance of each sprite that's being displayed (ie does it only use the resources of 52 active sprites)?

I guess what i'm asking is if I have a bunch of sprites attached to a GameObject, are they all instantiated when the object is created, or are they only created when they are actually attached to the sprite renderer?

Would it be more efficient to only attach the current cards value sprite (ie just the back and the face for the cards value)?


texts: How can I create a stretchy, breakable pizza cheese material?

texts:
I want to create realistic pizza and allow user interact with it.

What I want:

What I created:

I created model of the pizza (8 pieces) in Blender, then imported it into Unity. The piece of pizza looks very artificial, mostly because it is "rigid triangle".

How can I make the cheese stretch and break when the user moves a piece?


texts: 2D game engine for UI - suggestion needed

texts:
I am planning on making a simple real-time strategy game from the series Stargate Universe. For those who don't know, in the series' center is a spaceship called Destiny. It has a nice control room, with a control interface, what has a holographic control screen. The game basically would run on this. That's what I want to do, easily.

Can you suggest me ANY free 2D engine, what has:
- A top-view area for combat and ship management

Many UI elements what can be used easily
a top-on GUI part, where the actual GUI can be put
a nice GUI for putting all together (a game development framework or workbench)

And written in:

C#
ActionScript (Flash)

It is a bit reverse-like, as at the bottom of the layers would be the UI, over it the buttons, and over them would be the actual playground (battlefields, ship elements, etc).

Can you please help me?


texts: I think I know what is rig - it's a set of bones for animation. But recently I watched a presentation where the guy mentioned animation rig, mesh rig, dynamic rig. What each mean?


texts:
I need to change texture size from for example 800x600 to 80x60. I have two ideas of how to do that, but i have problems with both approaches.
1) changre render target then draw and save resized. the problem is blinking screen while this method is working.

public static Texture2D Resize(Texture2D image, Rectangle source)
        {
            var graphics = image.GraphicsDevice;

            var ret = new RenderTarget2D(graphics, source.Width, source.Height);
            var sb = new SpriteBatch(graphics);

            graphics.SetRenderTarget(ret); // draw to image
            graphics.Clear(new Color(0, 0, 0, 0));

            sb.Begin();
            sb.Draw(image, source, Color.White);
            sb.End();

            graphics.SetRenderTarget(null); // set back to main window

            return (Texture2D)ret;
        }

2) use Texture.SaveAsPng(); this aproach is extremly stupid but it works

public static Texture2D Resize(Texture2D banner,Rectangle rectangle)
        {

                using (var file = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    using (var IsolatedStream = new IsolatedStorageFileStream("banner.te2", FileMode.Create, file))
                    {
                        IsolatedStream.Position = 0;
                        banner.SaveAsPng(IsolatedStream, rectangle.Width, rectangle.Height);
                        IsolatedStream.Close();
                    }
                }

                if (IsolatedStorageFile.GetUserStoreForApplication().FileExists("banner.te2"))
                {
                    using (var file = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        var IsolatedStream = new IsolatedStorageFileStream("banner.te2", FileMode.Open, file);
                        IsolatedStream.Position = 0;
                        banner = Texture2D.FromStream(Consts.GraphicsDevice, IsolatedStream);
                        IsolatedStream.Close();
                    }
                }
                return banner;

        }

I'm looking for a clean fast solution, any suggestions? Resizing in Draw() method is not solution for me.


texts: Have several classes with a common interface, but still able to access MonoBehaviour methods through that interface?

texts:
In our project we used to have a PlayerObject class and then Unit and Building derived from that class. We recently started taking a look at Bolt, which requires classes that define objects that may have different states to inherit directly from a Bolt class. So Unit and Building can no longer inherit from PlayerObject.

This turns out to create a few problems, a significant portion of our game uses PlayerObject rather than Unit or Building to perform actions that are the same for both. Separating them would really throw a wrench into the program, since you now have to have methods that use both Unit and Building instead of just PlayerObject.

I thought making a common interface IPlayerObject, and defining common properties and methods in the interface and making Building and Unit both derive from IPlayerObject would do the trick. I did not think it through enough and came to find out that if I use IPlayerObject I can no longer access MonoBehaviour methods and fields (such as transform, or render).

Can I make this in such a way that I can use the IPlayerObject type, with a Unit or Building type and still have access to MonoBehaviour through that interface?

If not, is there a proper way to do this, past just adding in extra methods to handle Unit and Building types separately.


texts: I've been reading up some hacks on Kinect development to work around the fact that there is no official SDK from Microsoft. Even if we do manage to create a game, can we distribute it through the XBox marketplace? Or will it cause any issues?


texts:
I'm making a very simple cube in OpenTK and it seemed to be going fine until I tried to move it around. Moving it along the X Axis seems to elongate the cube, not the result I hoped for.

My Vertex Shader

#version 330

in vec3 vPosition;
in  vec3 vColor;
out vec4 color;
uniform mat4 modelview;
void
main()
{
    gl_Position = modelview * vec4(vPosition, 1.0);
    color = vec4( vColor, 1.0);
}

My Fragment Shader

#version 330

in vec4 color;
out vec4 outputColor;

void
main()
{
    outputColor = color;
}

How I make modelview

    Matrix4 c = Matrix4.LookAt(Game.camera.Position, new Vector3(Game.camera.X + 1f, 0, Game.camera.Z + 0f), new Vector3(0, 1, 0)) * Matrix4.CreatePerspectiveFieldOfView(
    (float)(0.5 * Math.PI),
    (float)1366 / 768,
    0.1f,
    1000.0f); * Matrix4.CreateTranslation(Origin);
GL.UniformMatrix4(Game.uniform_mview, false, ref c);

What I'm doing here is adding 0.01 to Origin.X while moving the camera the opposite direction.

Does anyone know why it produces this result? Thanks in advance for your help.

EDIT: Multiplied matrices by perspective * view * model

This weird line seems to blink in and out as I move the camera around.

EDIT 2: Matrix Printout

(0, 0.9999995, 0.001019571, 0.001019367)
(0, 0.001019367, -1.0002, -0.9999995)
(0.5622255, 0, 0, 0)
(1207.66, -0.9999995, 980.9957, 980.9995)


texts:
What is the best way to smooth a long path with splines?
I first implemented a Bezier curve but then realised that I would have to join a lot of them.

I used A* on a weighted grid so I can't use Theta or other any angle algorithms stuff.

I basically would like to achieve the light blue path on the following picture (credit to Amit), but on much longer paths:

How do game programmers do?


texts: What's the process for making a PS4 game?

texts:
Now that Sony has said that devs can self publish for PS4, I'm betting that a lot more people will be interested in producing games for that platform.

What is the process for getting the SDK, documentation, and testing environment for a PS4?


texts: DX9 Deferred Rendering, GBuffer displays as clear color only

texts:
I'm trying to implement Catalin Zima's Deferred Renderer in a very lightweight c++ DirectX 9 app (only renders a skydome and a model), at this moment I'm trying to render the gbuffer, but I'm having a problem, the screen shows only the clear color, no matter how much I move the camera around.

However, removing all the render target operations lets the app render the scene normally, even if the models are being applied the renderGBuffer effect.

Any ideas of what I'm doing wrong?


texts:
I'm working on a 2D game, so most of the graphics are sprites. However, some elements are drawn using trianglestrips in Orthographic projection. The thing is that I can't do a 3D projection because the coordinates of the vertices have to line up with some of the sprites in the game.

I'm running into a problem trying to texture these triangles.
I understand how the texturing works, so I understand that the interpolation causes the effect:

For now I have no idea where to start. I Googled and looked for similar questions, but all seem to deal with fixing this in OpenGL. like this one I have no clue how to apply it to Monogame/DirectX. I also don't know how to start with a shader, as I don't really grasp how to interpolate across two triangles.

If it makes the issue easier, I don't care for accurate perspective, just that the texture is correctly stretched over the two triangles.

So far I have only used a BasicEffect like this:

        checkered = Content.Load<Texture2D>("checkered");

        basicEffect = new BasicEffect(GraphicsDevice);
        basicEffect.VertexColorEnabled = true;
        basicEffect.TextureEnabled = true;
        basicEffect.Texture = checkered;
        basicEffect.Projection = Matrix.CreateOrthographicOffCenter
        (0, GraphicsDevice.Viewport.Width,     // left, right
        GraphicsDevice.Viewport.Height, 0,    // bottom, top
        0, 1);

The draw function is like this (nothing special):

        GraphicsDevice.Clear(Color.Green);

        basicEffect.CurrentTechnique.Passes[0].Apply();

        VertexPositionColorTexture[] vertices = new VertexPositionColorTexture[4];

        vertices[0].Position = new Vector3(100,50, 0);
        vertices[1].Position = new Vector3(200, 50, 0);
        vertices[2].Position = new Vector3(50,200, 0);
        vertices[3].Position = new Vector3(250, 200, 0);

        Color color = Color.White;
        vertices[0].Color = color;
        vertices[1].Color = color;
        vertices[2].Color = color;
        vertices[3].Color = color;

        vertices[0].TextureCoordinate = new Vector2(1, 0);
        vertices[1].TextureCoordinate = new Vector2(0, 0);
        vertices[2].TextureCoordinate = new Vector2(1, 1);
        vertices[3].TextureCoordinate = new Vector2(0, 1);

        GraphicsDevice.DrawUserPrimitives<VertexPositionColorTexture>(PrimitiveType.TriangleStrip, vertices, 0, 2);


texts: How can I make an AI agent avoid screen edges?

texts:
I'm programming an AI agent and I want them to avoid the screen edges. I've been considering using either the obstacle avoidance or the fleeing behaviour. Do either of these make sense?

How should I approach this?


texts:
I want to move an object on screen and when the object intersect with the obstacle he change the position, for example he's going to the right and he found an obstacle, so he change to the left.

    directionObj = 2;
    if(Intersector.overlaps(obj, screen)){
        posBall -= directionObj ;
    }else{
        posball += directionObj;
    }

but when the object found the obstacle he dont change the direction

[edited]

this is my render.
When the ball intersect with the screen, he dont change the direction

public void render () {
    fallSpeed++;
    if (posYBall > 0) {
        posYBall -= fallSpeed;
    }
    spriteBatch.begin();
    spriteBatch.draw(ball[1], posXBall, posYBall);
    spriteBatch.end();
    ballDirection = 2;
    if (Intersector.overlaps(circleBall, screen)) {
        posXBall = ballDirection;
    } else {
        posXBall += ballDirection;
    }


texts: Trouble rigging rotating head to pivoting arm

texts:
I've got a 3ds max model and I'm trying to rig it. I followed some tutorials, but I got stuck. I've got my rotating head, and the arm that holds it and pivots up and down, but the two don't "connect" well.

Here's my rigging set up:

The leftmost dummy should move up and down and control the height of the miner head (the jagged-edge wheel) and the arm that holds it.

But, when I move my dummy up vertically to test, the arm works perfectly, but the miner head ... uh, doesn't. This is from the same angle as the first shot and you can see that the miner head tilts, instead of moving straight up and down.

I tried playing with the miner head's pivot points, but they seemed perfectly centered. Is there a way to make my miner head only go straight up and down (that will still work with my rotation constraint? ) instead of doing this strange sideways tilting motion? Maybe that's not the right thing to do, I could really use some hints in where to go from here to fix this strange tilting motion..


texts: SerializationException: Type UnityEngine.MonoBehaviour in assembly UnityEngine,l is not marked as serializable

texts:
I am trying to save/persist some data between my scenes but I keep getting the error:

SerializationException: Type UnityEngine.MonoBehaviour in assembly UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null is not marked as serializable.

Here is my script:

public static void SaveState()
    {

        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Open(Application.persistentDataPath + "/EmpireGame", FileMode.OpenOrCreate);

        SaveClass sc = new SaveClass()
        {
            food = Player.food.amount,
            wood = Player.wood.amount,
            iron = Player.iron.amount,
            stone = Player.stone.amount,
            buildingList = new List<Building>(),

    };
        sc.buildingList = playerBuilt;

        Debug.Log("State Saved!");

        bf.Serialize(file, sc);
        file.Close();
    }
}

[Serializable]
class SaveClass
    {
        public int food, wood, iron, stone;
    public List<Building> buildingList;

}

I've narrowed it down to: public List buildingList; being the offending code, but I don't know how else to save this list. I think the MonoBehaviour part of it is the "" as it inherits from MonoBehaviour.

I've read:

Unity Docs: Serialization

Watched:

persistence-saving-and-loading-data

Saving Data In Unity

I've looked up so many Q&A's over this but still can't figure it out.


texts: Communicate Unity application via a series of Json

texts:
I am working on communicating unity application via a series of Json. Since I am new to JSON, I don't have any idea how that work with Wnity.

Here is my JSON structure

{
    "id": “id",
    "payload": {
            “image”: "Image Url”
            "text":"text message"
            "option" : {
               "option1":"1" ,
               "option2": "2"
                }
    }

}

Now I have created a button in Unity scene. I have hardcoded the image and text data. When I click on the button the data should get converted into Json and should send JSON data to the server and print a data log message.

I have used this code.Iam getting the output

using UnityEngine;
using System.Collections;
using LitJson;
using System.IO;
public class JsonScript : MonoBehaviour {
JsonData json;
void Start()
{
    Data data = new Data();
    data.id = 1;
    data.payload = new Payload() { text = "wwwwwww", image = "hello" };
    //json = JsonMapper.ToJson(data) ;
    string json = JsonUtility.ToJson(data);
    P (json);
    //      P(json + "\t\n");

 }

// Use this for initialization
void P(string aText)
{
    print (aText +"\n");
}

}

  [System.Serializable]
 public class Payload
  {
    public string text;
       public string image;
 }

     [System.Serializable]
    public class Data
  {
        public int id;
        public Payload payload;
  }

The output is getting displayed in a single line

{"id":1,"payload":{"text":"wwwwwww","image":"hello"}}

But I need the output to be printed as the Json format.I tried giving space.

Can anybody please help me out?


texts: Godot: how to use _draw to draw textures at an angle

texts: So simple question that I just can't find an answer to, how do I use Godot's _draw function to draw textures rotated at an angle (more specifically how do I get them turned completely 90° onto their side).


texts:
So I'm accustomed to Lightwave where selecting a point in orthographic view selects all the points along that ray from the viewport. I've been watching videos of people using older versions of Blender and it seems like that was the default behavior before. Am I just missing a setting?

Steps to reproduce the problem using the latest version available on the site:

Open new project
Set view to ortho and front
Hit tab to enter edit mode on default Cube object
Right mouse click the top right vertici

Only the front most vertex is selected, rather than both.


texts: Loading .PNG file and using it for UnityEngine.UI.Image

texts:
Have an Unity UI Image.

I want to load a .PNG file that is in my persistent data path and use it as the sprite source for the UI Image. Code:

    byte[] bytes = File.ReadAllBytes(Application.persistentDataPath + "/sprite.png");
    Texture2D texture = new Texture2D(width, height);
    texture.filterMode = FilterMode.Trilinear;
    texture.LoadImage(bytes);
    Sprite sprite = Sprite.Create(texture, new Rect(0,0,width, height), new Vector2(0.5f,0.0f), 1.0f);

    myObject.GetComponent<UnityEngine.UI.Image> ().sprite = sprite;

This almost works. Only a portion of the image is displayed.

The initial guess would be that I didn't load the image properly. However, if you use a SpriteRenderer instead of UnityEngine.UI.Image like

    myObject.GetComponent<SpriteRenderer>().sprite = sprite;

The image is displayed in full. So this seems to be a problem with UnityEngine.UI.Image specifically...

... However, if you drag an image from the editor into the Sprite Source property of UnityEngine.UI.Image, then such image is displayed in full - then suggesting that there is something wrong with the way I load my image bytes.

What should I do?

Edit: If you set the image type to Tiled, you can see that it tiles with the full image... So apparently the UI Image component DOES have all the image data but for some reason it won't render all of it.


texts: My app crash using OpenAL but only in Release Mode

texts:
I'm building up a complete game engine so, basically, it integrate a sound system. The problem is that a line make me crash in my code. The strange thig is that my app crash ONLY when I compile using Release mode, in Debug Mode it run just fine.

I'm using MSVC 16.XX (I don't know exact version, but it is the latest at the time I am asking this question)

(language used is c++)

void PSound::GetDevice()
{
    const ALchar* DeviceList = alcGetString(NULL, ALC_DEVICE_SPECIFIER); //This Line make app crash

    if(DeviceList) {
        while(strlen(DeviceList) > 0) {
            Devices.push_back(DeviceList);
            DeviceList += strlen(DeviceList) + 1;
        }
    }
}


texts: How to move a portion of bezier/spline curve along its complete bezier/spline curve?

texts:
Based on the image below, I have a curve (orange) which is a bezier sub-curve of an original curve (longer black curve). The original curve consists of a number of cubic bezier curves joined together.  How can I move the sub-curve (which could be contain more than one cubic bezier curve) along it’s original curve whiles preserving its length?

Please note that the original curve/spline could be open or closed curve with the ends joining. I know that arc length is key to achieving this, but I’m not sure to do this.

UPDATE

The smaller curve was reduced using the solution from How to move points of a multi-segmented bezier curve to one side. DMGregory recommended Moving ships between two planets along a bezier, missing some equations for acceleration, which I have to admit I didn’t understand enough to fully utilise to solve my problem. One thing though that I took away from the solution was I needed to express the smaller curve as percentage of the original curve, so I implemented a slider as below.

 public void ReplaceCurveWithSubCurve(float curveVal) {

    subCurve = IntervalFromTo(curve, 0, curveVal);

}

In CurveEditor:

curveLengthValue = EditorGUILayout.Slider("Curve Length", creator.curveSizeValue, 0f, 1.0f);

if (!Mathf.Approximately(creator.curveSizeValue, curveLengthValue))
            {
    creator.IntervalFromTo(curveLengthValue);
    creator.curveSizeValue = curveLengthValue;
}

My general understanding is the original (full) curve say runs from some t = 0.0 to t = 1.0 and my sub curve at any given point is made of a subset of those values, so I need to change the values along the full curve whiles preserving the arc length. Below are the methods I use to calculate the arc length. My problem is how to tie all this together to arrive at a working solution.

 public float SegLength(int segmentIndex)
{
    var steps = 10;
    var t = 1 / (float)steps;
    var sumArc = 0.0f;
    var j = 0.0f;
    var a = new Vector2(0.0f, 0.0f);

    var b = points[segmentIndex * 3];

    var dX = 0.0f;
    var dY = 0.0f;
    var dS = 0.0f;

    for (int i = 0; i < steps; j = j + t)
    {
        a = SegmentAtPoint(segmentIndex, j);

        dX = a.x - b.x;
        dY = a.y - b.y;
        dS = Mathf.Sqrt((dX * dX) + (dY * dY));

        sumArc = sumArc + dS;
        b.x = a.x;
        b.y = a.y;
        i++;
    }

    return sumArc;

}

public float FullLength()
{
    var totalLength = 0.0f;

    for (int i = 0; i < NumSegments; i++)
    {

        totalLength += SegLength(i);
    }

    return totalLength;
}


texts:
I'm planning to use Voronoi cells to break up an infinite 2D (procedurally-generated) tile map into biomes. I've been reading a bunch of tutorials and introductions to voronoi, and I understand how cells are calculated based on points, but I'm failing to understand how to apply this to an infinite 2D tile map.

Voronoi cells are calculated from a series of points, but given a 2D tile map, how do I consistently generate a list of points? I can randomly choose points but this has to be completely reproducible with the given RNG seed.
How can I calculate cells for an infinite map when every Voronoi implementation I can find requires a bounding rectangle?


texts: How would I determine whether or not to render the player over or behind a tree in a 2d top down game?

texts:
In games like Factorio, you might notice that when the player is at a certain coordinate relative to the tree, it renders in front of the player, thereby giving the effect that the player is behind the tree. My question is, how is this accomplished?

Here are some examples:
Behind a telephone pole:

In front of one:


texts:
I'm taking the plunge and am getting into game dev, it's been going well but I've got stuck on a problem.

I have a maze that is 100x100 with 0,1 to indicate if its a path or a wall.

Within the maze I have 300 or so enemies and a player.

The outcome I'm looking for is all the enemies work their way towards the player position.

Originally I did this using an A* path finding algorithm but with 300 enemies it was taking forever to path find each one individually.

After some research I found that an influence map / collaborative diffusion would be the best way to go.

But I'm having a real hard time working out how this is actually done.

Firstly.. How do you create a influence map?

From what I understand each of my walls with have a scent of 0 so that makes them impassable.. then basically a radial effect from my player position to each other cell (So my player starts at 100 and then going outwards from that each other cell will be reduced value)

Is that correct? If so,.. How would you do that (Math magic?)

My next problem is if that is correct how would my "enemies" stop from getting stuck if they have gone down the wrong way? As say if my player was standing on the otherside of a wall if the enemy is just looking for larger numbers wont it keep getting stuck?

I'm doing this in JavaScript so performance is key.

Thanks for any help!

EDIT:

Or if anyones got a better solution? I've been reading about navmeshs, steering pathing, pre calculating all paths on load etc etc


texts:
I am going to start a chess like board game. And for that I have reviewed a number of things available.

One is http://www.mapeditor.org/, using which you can create a grid base games.

Another option is geekgameboard for iphone available at http://mooseyard.lighthouseapp.com/projects/23201-geekgameboard

Now I want your expert opinion on what would be better to make a game in cocos2d, using the first option or the second option? Both looks promising to me and give good control over board design.

PS: Sorry for duplicates, I found about the https://gamedev.stackexchange.com/ lately after posting it on stackexchange. So I am just posting it here again as I feel this is a more relevant board.


texts:
I've implemented OpenTK as a secondary renderer which would let me support Mac/Linux only to realize that for some reason, even without any modifications (new MonoGame project), the application would make mono crash, but it runs perfectly fine on .NET.

I've been looking for some templates and demos to start with OpenTK for Mono/Mac/Linux but all I can find is Xamarin Studio guides for iOS and Android.


texts: Why does physics interpolation give me periodic jumps/flickers?

texts:
I have seen this question but it didn't solve the problem.

I have followed the same steps as in this article.

What I notice in my Android game is that my interpolation alpha (or fraction or accumulatorRatio) varies with this pattern as frames progress:

0.13
0.22
0.31
0.45
0.49
0.62
0.81
0.94
0.03
0.1

The above is an illustration but the point is that it goes from 0 to 1 and cycles back to 0 periodically. I believe this is due to the game frame rate being slight faster than the physics update interval.

Every time the interpolation alpha cycles around, it gives me a jitter (or jump).

Here is a log file: http://pastebin.com/3Yb7nVxX

The two columns are (i) interpolation alpha (ii) physics step count

The "jumps" happen roughly in lines 262 to 266 in the log.

Here is the code: http://pastebin.com/vWC7yNGM

What is causing these periodic "jumps"?

EDIT: Here is more detailed code: http://pastebin.com/PSZrntZP


texts: Unity: Will a 2D animator controller load all sprites for all animations into memory?

texts: I've got a massive animator controller for my main character in my 2D game. I want to know if my animator controller will load every animation for my main character all at once since all of his animation clips are in the controller. That would represent a huge number of sprites. The game uses sprite animation.


texts: Texturize a shape of multiple triangles in 2D

texts:
This is an example of a shape consisting of multiple points, triangles and eventually a shape:

Red Dots = Vector3 (X, Y, Z) or Vector2 (X, Y)

If I have a Texture of a certain size, how do I texturize this area in the best way so that the texture inside the shape matches the shape and does not overlap anywhere? Perhaps also with a chance to scale the texture in case it's too small or to big for the shape, but still so that it gets rendered correctly.

Do I treat the shape as a rectangle? Figure out it's 4 corners?
Or do I calculate the distance between Center - (Texture Width / 2) and Point (to see how "many" times the texture can fit between on that axis to estimate at what Coordinates the Texture should be at that certain point?

I've looked at Texture Mapping but haven't found any concrete examples that it explains it well, it's also confusing with 0.0-1.0 values for Texture Coordinates.


texts: Are there any conventions and/or best known methods around coordinate systems in game maps? Is the origin usually positioned in the center of the map? Or does it live in a corner and the map is built in a single octant of the 3D space?


texts: client/server Silverlight turn based game - domain model question

texts:
I am making multiplayer (2 players) Minesweeper like the one that's available on MS Live Messenger.

Client side is going to be silverlight, server side will be MVC Application. Client (the one who is waiting for his turn) will poll server every X seconds to get current state, the other client (who's turn it is will post his click to server and than roles will reverse)

Now my question is: should domain model classes be the same for client and server side?
I mean you need Minefield class on both sides, but while server-side class will have rules and logic, client-side will be more or less a data holder.


texts: Where to place "Set XYZ over life" blocks in Unity VFX graph?

texts:
As the title says, I am learning VFX graph in Unity and I am curious where I should place "Set ... over Life", for example "Set Color over Life" which adjust the color based on the particle's age.
When we create a new visual effect graph, they are placed in the Output context by default, which kind of seems odd to me, since it seems more like a Update function?
It also works if I place it in the Update context, but I am afraid that I probably mess with the performance if the block should not be placed there for some reason.
Also, why can't I set it in the Initialize context - if I do, no changes over time are applied.
Probably someone could point me to the right documentation or some explanation for this, thanks.
In general, it would be nice to have a documentation that states which blocks should be used within which context (Initialize, Update, Output).


texts: DX11 application running on Windows XP using only DX9?

texts:
I'm developing an application that utilizes DX11. I know that DX11 is only available on Windows 7 (and Vista with SP). I wonder if there is some way to run the application on Windows XP and use only the old DX9? I need to prevent the loading of DX11 dlls when on Windows XP. How can this be done?

I've got an old renderer, that runs entirely on DX9 and a new renderer that uses DX11. My idea is to run the old renderer underr Windows XP and load only DX9 dlls, and to run the new renderer on Windows Vista / 7 and load DX11 stuff as well.

I've heard about a LoadLibrary() function that loads libraries at runtime. So far I have my Visual Studio project with all that DX11 .lib files in Additional Dependecies. How should I change this to load it completely at runtime? Do I need to define all symbols in DX11 .dlls manually?


texts: Balancing stats in a monster fighting game (similar to Pokemon battle/stats)

texts:
I'm trying to create a game that uses a battle and monster system like Pokemon.  I'm using some similar equations that I've modified to fit my desired level/tier system.  One thing I'm trying to figure out is how to balance my monsters when I am creating them.  I will have stats for health, attack, defense, special attack, special defense, and possibly speed.  Unlike Pokemon, I'd like to have all my monster's be relatively balanced so that at high levels you could conceivably use any one.

One thought I had was to write a simple program that allowed me to create a monster.  Its stats would start at a base 50 and every time I increased its stat by 4, the other stats would drop by 1.  I could then tailor my monsters to be defense heavy while lacking offense, etc.  One issues, is that my health equation yields a higher amount of health per increase in stat point versus the other stats.

Do you have any suggestions for improvements or a new system.


texts: How does one achieve a 'shimmering' effect similiar to the ones from the Pokemon games?

texts:
I have an assignment to make a game in C++ using Winapi. As such I've decided to recreate pieces of the Pokemon games. I'm pretty well underway with the project, but there's one effect I would like to achieve that I don't really know how to achieve.

It can first be seen just before the game's title screen. (Pictured below)

As you can see, the logo sort of 'shimmers' from left to right a few times.

A similiar effect can be seen inside of combat when a pokemon's stats are altered. (Pictured below)

The effects I am talking about are the reddish shimmer appearing on the wolf (Poochyena), and the blue 'waves' appearing on the beaver (Bibarel).

I would like to know if there is a generalized method of applying such effects, as I aspire to have more than one Pokemon in the project, and I would therefore want a method that works on all cases. If the effect cannot be effectively achieved using winapi, then I am open to suggestions of other libraries, etc, to use.


texts: How to draw multiple shapes in one draw call?

texts:
I have a misunderstanding about vertex buffers in DirectX. I'm trying to draw infinite vertices that they may represent a line or a circle or a rectangle in a single draw call. I can bind them all together and set a flag for each vertex to determine which shape I have to draw now with DrawPrimitive(), but the questions are:

When I first create the vertex buffer, I set a constant length of 1000 for it because I don't know how many vertices I'm going to draw. How can I avoid this?
I don't know the proper way of drawing these vertices at all. I mean I can draw them right now with a dynamic VB, but I have no idea on performance and etc.

BTW, I've read this article which is pretty good, but it doesn't apply to my issue.

Edit

For example, I have 6 vertices which 2 of them are shaping a line and the other 4 are shaping a rectangle. I can bind them all together and copy them into the vertex buffer and then draw. Now, what if next time I wanted to draw a line and two rectangles? In this case I have to add 4 other vertices to my current list and we suppose my VB is not big enough to do that. This is my misunderstanding that I don't know if I should reserve enough space at first place for my VB or there is an alternative to pitch the length during runtime.

I'm trying to draw basic 2d shapes here nothing 3d:

// A class member
std::vector<Vertex2D> mVertices;

// Draw method
{
void* buffer = new char[this->mVertices.size() * sizeof(Vertex2D)];

Device()->VertexBuffer()->Lock(0, sizeof(buffer), &buffer, D3DLOCK_DISCARD);
memcpy(buffer, this->mVertices.data(), sizeof(buffer));
Device()->VertexBuffer()->Unlock();

Device()->SetStreamSource(0, Device()->VertexBuffer(), sizeof(Vertex2D), sizeof(Vertex2D));
Device()->SetFVF(D3DFVF_VERTEX2D);
Device()->DrawPrimitive(D3DPT_LINELIST, 0, this->mVertices.size());

delete[] buffer;
}

It's a simple draw call in a bigger loop. mVertices is a collection of different vertices for different shapes. My second question was, how to draw different shapes from one vertex buffer in a single draw call. My first question was, how can I adjust vertex buffer's length with a relevant length to my vertices and not a default value at compile time.


texts: Moving a character according to the animation, rather than code

texts:
I'm using 3ds Max to export character animations in which my character is moving. I expected this to mean that the character will move in Unity, but it doesn't...

For example, if my animation (in 3ds Max) moves my character forward for a second, from 0,0,0 to 1,0,0, in Unity, the character snaps back to 0,0,0 once the animation ends.

Is there a way to change the position of the character according to the animation, without something like CharacterController.Move?


texts: How can I stop looking for keyboard input for a length of time?

texts:
I'm pretty new to programming, and even newer to C# and XNA. I currently call a method that looks for keyboard input in my Update method. This method has if statements for doing what needs to be done when a key has been pressed. The problem is, since it's being called constantly, it's impossible to press a key quickly enough for it to register only once.

One issue this creates is going through a menu. A short tap of a key sends the "cursor" that indicates which menu item is selected wheeling through the menu several times. I'd like to be able to "turn off" keyboard input for perhaps a fourth of a second after any valid key has been pressed.


texts: How do I prevent modders from creating malicious code?

texts: Let's say I have both a game and a modding system for it. The modding system loads DLL files containing custom features and allows mod creators to override certain functions to change game mechanics. This is all well and good until some mod creator decides to put a keylogger or a virus in one of those DLL files. What can be done to prevent this problem? Is there any way to allow a high level of customisability in a modding system while still maintaining a strong level of security for the end user?


texts: Is it possible to create a homemade depth buffer?

texts:
Studying the case of isometric rendering, I'm facing a big and well-known problem : depth sorting.

After many researches it seems that without tile mapping or 'height-leveling' it's impossible to solve this problem in a 2D game.
So I imagined a depth buffer that I could use with sdl_textures . The process : each sprite would contain pixels , with rgba AND a depth variable . When it comes to blit, I would check in a backbuffer the pixels that are nearer than the current pixels and replace them. Then I would convert the buffer to a texture with only four channels  (rgba without depth) in order to SDL_Rendercopy it .

My questions are:

Is it possible to do so ?
Isn't it too slow to check each pixel of a 1024×768 screen in this kind of scheme ?
How do I create a sdl_texture from an simple array of int ?


texts: Why are gaming graphics not as beautiful as animated movies?

texts:
I remember watching the Tomb Raider pre-rendered trailer, and wished those graphics could be in the game itself.

Why there is such a big difference between the trailer and the actual game? I understand the game is a completely different concept, it has different pipeline, it has to go through different kinds of player interactions etc. I want to know what it is about games that makes rendering them so difficult compared to animated films.

So far I know that making a game and an animated movie share some basic workload, e.g. making 3d models, rendering them (only in-game it happens live). Animated movies render for a long time and we only see pre-rendered scenes. That's all I know so I hope you'll answer from that perspective!

What about animated movies rendering for hours and hours makes them so beautiful while in-game live rendering is less beautiful (from a general point of view)?


texts: Revert a GameObject to a previous version

texts:
Is there a way to use an old version of a scene.unity file to revert changes for specific GameObjects only?

Occasionally Unity GameObjects can lose all their references in the Inspector (If a prefab instance, it keeps the prefabs defaults).  I have the missing references committed in my previous git commit, and have not changed any scripts on that GameObjects.

If I discard all my working changes to my scene.unity file I get my inspector references back OK.

But is there a script or process which allows you to revert specific gameobjects only to HEAD.
This would be useful when GameObjects lose their settings, and also when you want to revert only parts of your scene.


texts: Infinite space 2d map - how to implement in js

texts:
Im not exactly sure how to implement this in JS.

So I want to have a 2d infinite map, but not tiled. The coordinates are there only so that if you are travelling around space you know in what coordinates you are. Or if I want to add a couple of things here and there I can specify the coordinates for the placement.

So the coordinates only serve as grid points, but how would I got about implementing this in JS?

Also, how would I go about storing the different things I want to add to the map. Meaning this is not procedural or anything, it's static, a static map.

Could I just use the canvas grid system?


texts: Second Animation is not working after Collision?

texts:
I want to show an accident of Character with car. so I wrote this code
and in update function I wrote this...

        if (Once) {

                    Criminal.GetComponent<Animation> ().Play ("Running"); // after collision This animation will work
                    Criminal.GetComponent<BezierMover> ().enabled = true;
                    TrafficCar.GetComponent<BezierMover> ().enabled = true;
        }
void OnCollisionEnter (Collision col)
{
    if (col.gameObject.tag == "Vehicle") {
        if (!Criminal.GetComponent<Animation> ().IsPlaying ("Stumbling"))
            Criminal.GetComponent<Animation> ().Play ("Stumbling"); // Animation for Accident
        Criminal.GetComponent<BezierMover> ().enabled = false; // to Deactivate the AI Script.
        TrafficCar.GetComponent<BezierMover> ().enabled = false; //to Deactivate the Trrafic cars Path Script.
        Once = true;
    }
}

but after first animation second animation should work but this is not happening..


texts: Setting a texture's "Max Size" while ensuring that its dimensions are still multiples of 4

texts:
A version of my game has several large textures with dimensions that are multiples of 4 so that Crunch compression can kick in.
A ported version of my game, for platforms that have very limited RAM restrictions, will need us to limit the "Max Size" of our textures to 512 or 256, etc.
There are some cases in which a Crunch-friendly texture, when resized by Unity's "Max Size" parameter, will actually end up with dimensions that aren't multiples of 4.
944x800 would end up as 512x434, if we select "512", which isn't good for Crunch.
The naive solution in my mind is to write a simple script/tool that resizes/pads all my textures by a couple of pixels in such a way that Unity's resize will end up in a Crunch friendly way. However, I'd rather do that as a last recourse if possible.
Is there a more standard way to approach this situation of mine?


texts:
I want to find out the best way of creating time based events in games. Lets talk for example about Texas Holdem Poker. Server can handle thousands of tables and in every table we have timers: turn timer, hold seat timer and so on.

What is the best way of timers realization for this purpose?

Is System.Timers.Timer class can handle this or it will be more reasonable to create a separate thread with sorted time queue (for example an ascending sorted list with int values which represent time in ms remained)?

Thanks in advance, Valentin


texts: Default Game Window Size To Take While Making Games

texts:
I am planning to make a game for mobiles and tablets, I wanted to know what would be the default resolution that I should set for my game so that it covers all or most of the devices out there.
I read an article someplace that says we should design the game for lowest resolution like 480 x 360 and then scale it according to devicePixelRatio for the target device, Is this the right approach because according to me it will be good only for devices that have 3:2 resolution but what about other 16:9, 16:10 etc
So What should be the base resolution I design my game so that it gets scaled to all mobiles and tablets?


texts:
What is a fast way of limiting the heading vector to a certain angle so that it turns in greater distance relative to the limit.

A smaller cone/angle should make the object take a far bigger curve to traverse to reach its goal where a larger cone/angel allows the object to rotate faster in the direction of its goal.

If there are some vector tricks i'll be glad to know them!


texts: How can I fix the artifacts near the shadow edges in my variance shadow map?

texts:
I'm trying to implement variance shadow mapping in my engine. I'm using WebGL 2 and now I have only one directional light source.  It's working, but it has a serious issue near the shadow edges and I don't know how to solve it.

The back of the cube isn't entirely in shadow, the edges are in light.

The shadow on the sphere is too small, I think about half of the sphere should be in shadow.

This is how I implemented variance shadow mapping:

Create the shadow map

Vertex shader:

#version 300 es

layout(location = 0) in vec3 i_positiom;

uniform mat4 projectionViewModelMatrix;

void main(){
    gl_Position = projectionViewModelMatrix * vec4(i_positiom, 1.0f);
}

Fragment shader:

#version 300 es

precision highp float;

out vec4 o_color;

void main(){
    float depth = gl_FragCoord.z;
    float depthSquared = depth * depth;
    float dx = dFdx(depth);
    float dy = dFdy(depth);
    depthSquared += 0.25f * (dx * dx + dy * dy);
    o_color = vec4(depth, depthSquared, 0.0, 1.0);
}

The texture's size is 1024x1024, it uses linear filtering, but doesn't use mipmapping or multisampling. The result looks like this:

Blur the shadow map, horizontally, then vertically

Vertex shader:

#version 300 es

layout (location = 0) in vec3 i_position;
layout (location = 1) in vec2 i_textureCoordinates;

out vec2 io_textureCoordinates;

void main(){
    io_textureCoordinates = i_textureCoordinates;
    gl_Position = vec4(i_position, 1.0f);
}

Fragment shader:

#version 300 es

precision highp float;

in vec2 io_textureCoordinates;

uniform sampler2D image;
uniform bool horizontal;

out vec4 o_color;

void main(){
    ivec2 texSize = textureSize(image, 0);
    float blurAmount = 1.0;
    vec2 blurScale = horizontal ? vec2(blurAmount / float(texSize.x), 0.0) : vec2(0.0, blurAmount / float(texSize.y));
    vec4 color = vec4(0);

    color += texture(image, io_textureCoordinates + (vec2(-2.0) * blurScale)) * (1.0 / 16.0);
    color += texture(image, io_textureCoordinates + (vec2(-1.0) * blurScale)) * (4.0 / 16.0);
    color += texture(image, io_textureCoordinates + (vec2(0.0) * blurScale)) * (6.0 / 16.0);
    color += texture(image, io_textureCoordinates + (vec2(1.0) * blurScale)) * (4.0 / 16.0);
    color += texture(image, io_textureCoordinates + (vec2(2.0) * blurScale)) * (1.0 / 16.0);

    o_color = color;
}

Render the scene and calculate the shadows

float calculateShadow(vec3 N, vec3 L){
    /*if(dot(N, -L) < 0.0){
        return 0.0;
    }*/
    vec3 projectionCoordinates = io_fragmentPositionLightSpace.xyz / io_fragmentPositionLightSpace.w;
    projectionCoordinates = projectionCoordinates * 0.5 + 0.5;
    float currentDepth = projectionCoordinates.z;
    vec2 moments = texture(shadowMap, projectionCoordinates.xy).xy;
    if (currentDepth <= moments.x) {
    return 1.0;
    }
  float variance = moments.y - (moments.x * moments.x);
  variance = max(variance, 0.00002);
  float d = currentDepth - moments.x;
  float pMax = variance / (variance + d * d);
    return smoothstep(0.1f, 1.0f, pMax);
}

I tried many things, like changing shadow map resolution, filtering, blur kernel size, blur amount, changing the magic numbers in calculateShadow (which are there to prevent light bleeding), but the best I could do is what you can see (it's commented out) at the beginning of the calculateShadow function. If the angle between the surface's normal vector and the light direction is greater than 90°, then it's in shadow.

It solves the problem, however on the sphere the shadow becomes too sharp:


texts: Algorithm for making sets in a Rummikub game

texts:
I'm developing an Okey game (a Turkish version of Rummikub/Rummy). In it, each players has a bunch of tiles. Tiles have a colour and a number, like playing cards. Now, the player needs to make sets of these tiles, with three options:

Groups: Same number, different colours (Red 1, Blue 1, Black 1)
Straights: Same colour, sequence of numbers (Red 1, Red 2, Red 3)
Doubles: Two identical tiles

I'm now trying to create a simple AI for the game. I want it to be able to find and create sets in/from its own tiles.

I already have a TileSet class. Feed it a list of tiles and it will say whether it's a valid set and of what type.

Using this, what kind of algorithm can I use to find the sets in an unordered heap of tiles?


texts:
I was watching the teaser trailer for Seasons After Fall, and I was struck by the effect they use to transition between seasons (around 21-24 seconds):

The level art, including the background and the foreground platforms, change from a sepia-coloured autumn to a lavender winter, with the effect spreading outward from the player character a bit like water soaking through paper.

It looks like more than just a palette change, as details in the leaf and bark patterns change in the transition.

How could I achieve an effect similar to this in a 2D Unity game?


texts: HLSL grayscale pixel shader: How to get the original colors of the model?

texts:
The following code gives me a completely black colored model, while it should be a model shaded in greyscale:

float4 SimplePixelShader(VertexShaderOutput input) : COLOR0
{
    //some lambertian shading done in the code I left out here

    return color;
}

sampler TextureSampler = sampler_state
{
    Texture = <ScreenTexture>;
};

float4 GrayscalePixelShader(float2 TextureCoordinate : TEXCOORD0) : COLOR0
{
    // Get the color.
    float4 color = tex2D(TextureSampler, TextureCoordinate);

    // Turn pixel to grayscale.
    float grayscale = dot(color.rgb, float3(0.3, 0.59, 0.11));
    color.r = grayscale;
    color.g = grayscale;
    color.b = grayscale;
    color.a = 1.0f;

    // Return the result.
    return color;
}

technique Simple
{

    pass Pass0
    {
        VertexShader = compile vs_2_0 SimpleVertexShader();
        PixelShader  = compile ps_2_0 SimplePixelShader();
    }

    pass Pass1
    {
        PixelShader  = compile ps_2_0 GrayscalePixelShader();
    }
}

As far as I could find out the problem lies here:

// Get the color.
float4 color = tex2D(TextureSampler, TextureCoordinate);

The whole lambertian coloring works, the grayscale seems to work properly by itself after some testing, but what doesnt seem to work is getting the red lambertian shaded model colors. Anybody any clue what I'm doing wrong?

Edit: Thanks to a lot of help in the chat from LuisW I now have a working greyscale shader, I didnt have to change anything about my GreyscalePixelShader but I did have to remove the second pass of the simple techique and put it into a seperate technique, as such:

technique Greyscale
{
    pass Pass0
    {
        PixelShader = compile ps_2_0 GrayscalePixelShader();
    }
}

I also had to update my XNA/C# Draw method to create a fullscreen quad that I rendered my scene with the first technique to so I could use my greyscale technique on that quad as an input. Mind you, the method Im using, with spritebatch, is known to be slow (for me that didnt matter, but if you need fast, then drawing the quad directly is supposably faster) My updated draw method:

protected override void Draw(GameTime gameTime)
{
    this.device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.DeepSkyBlue, 1.0f, 0);

    PresentationParameters pp = this.device.PresentationParameters;
    RenderTarget2D renderTarget;
    renderTarget = new RenderTarget2D(this.device, pp.BackBufferWidth, pp.BackBufferHeight, true, pp.BackBufferFormat, pp.DepthStencilFormat);
    this.device.SetRenderTarget(renderTarget);
    this.device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.DeepSkyBlue, 1.0f, 0);
    Rectangle screenRectangle = new Rectangle(0, 0, screenWidth, screenHeight);

    // Get the model's only mesh
    ModelMesh mesh = this.model.Meshes[0];
    Effect effect = mesh.Effects[0];

    effect.CurrentTechnique = effect.Techniques["Simple"];

    //<left out some noninteresting worldmatrix calculations here not relevent for this question/answer>

    device.DepthStencilState = DepthStencilState.Default;
    device.BlendState = BlendState.Opaque;

    mesh.Draw();

    this.device.SetRenderTarget(null);

    effect.CurrentTechnique = effect.Techniques["Greyscale"];

    spriteBatch.Begin(0, BlendState.Opaque, null, null, null, effect);
    spriteBatch.Draw((Texture2D)renderTarget, screenRectangle, Color.White);
    spriteBatch.End();

    base.Draw(gameTime);
}


texts: How to create enemy "flash-light" for 2D game?

texts:
I'm developing a 2D stealth game but I cannot figure out how to create something like a torch (flashlight) that the enemies hold and look around with.Any help?
Also, if relevant, I'm using MonoGame.


texts:
So I'm not 100% sure what you would call this type of keypress, but it is essentially a keyTyped event but in reverse order. Instead of being triggered when the button is released, it is triggered when the button is first pressed, but can't be triggered again until the button is released and pressed again.

Right now I have events for buttonDown and buttonUp and I also have two HashMaps to keep track of the currentInput and previousInput of each action in the game (jumping, moving, crouching, etc...) How can I provide a function that when called returns true for this type of button push?


texts:
I'm making a little 2D tank game that fires bullets depending on where you click (This has been done and works a treat).

I'm currently working on a timer class with a simple function that displays a little countdown depending on the inputted time. (This will be used for bullet fire delays).

bool timer makeTimer(int waitTime)

This is the start of the timer, it is a simple boolean function which returns "true" when the timer has reached 0.

I can make it decrement down until it reaches 0 easily, but the part I'm having issues with is making it countdown based on an actual time event, so once per second. I've tried lots of different things but I just can't get this darn part to work.

The variables I have to work with are;

waitTime // inputted timeDelay
sf::Clock // To show the elapsed time per frame
sf::seconds(1) // Not too sure if I need this

So, to wrap up.
 - I'm trying to get it to countdown from the inputted time once per second.


texts: Visual Studio 2013 is missing the installed templates related to graphics, SPECIFICALLY the fbx scene template.. Why is this so? And where do I get them ?


texts: What is the shortcut to rename stuff in Unity on Linux?

texts:
I am using Unity on Ubuntu 16.04 and I can't rename objects or assets using the F2 key as I could when I was using Windows.

What is the shortcut on Linux then?


texts: Trying to add a feature to my (basic) level parsing algorithm - not sure how to (JAVA)

texts:
Right now this method goes through a list of GameObjects (e.g. JetPack, Platform) with their respective x and y positions in a text file called level1.txt:

platform 840 280
platform 1130 280
coin 900 300
coin 950 300
coin 1000 300
coin 1000 400
jetpack 1090 400
platform 650 500
platform 500 400
platform 200 400
NEXT
platform 200 200
coin 250 300
coin 350 700

What currently happens is whenever my Player reaches the end of the screen, he goes back to the start (x = 0). When he does reach the end of the screen, I want all the objects BEFORE NEXTto disappear and all the objects AFTER NEXT to be drawn. I know why my algorithm doesn't work as it should but I'm unsure how to fix it. Can anyone have a look at it and tell me how I can modify it to do what I want it to? listis a list of GameObjects in the text file btw.

public void loadLevel(String level) {
        list.clear();
        FileHandle file = Gdx.files.internal(level);
        StringTokenizer tokens = new StringTokenizer(file.readString());
        while (tokens.hasMoreTokens()) {
            String type = tokens.nextToken();

            if (type.equals("platform")) {
                list.add(new Platform(Integer.parseInt(tokens.nextToken()),
                        Integer.parseInt(tokens.nextToken())));
            }
            else if (type.equals("coin")) {
                list.add(new Coin(Integer.parseInt(tokens.nextToken()), Integer
                        .parseInt(tokens.nextToken())));
            } else if (type.equals("flag")) {
                list.add(new Flag(Integer.parseInt(tokens.nextToken()), Integer
                        .parseInt(tokens.nextToken())));
            } else if (type.equals("jetpack")) {
                list.add(new JetPack(Integer.parseInt(tokens.nextToken()),
                        Integer.parseInt(tokens.nextToken())));
            } else if (type.equals("pipe")) {
                list.add(new Pipe(Integer.parseInt(tokens.nextToken()), Integer
                        .parseInt(tokens.nextToken())));
            } else if (type.equals("NEXT") && player.getxPos() > SCREEN_WIDTH) {
                list.clear();
            }
        }
    }

Any help is highly appreciated, many thanks in advance.


texts: Proper way to handle Movement/Animation/AI functions of an AI character in Unity3D

texts:
My team is currently building a 2D game in Unity and we've run into some workflow/script organization blockades for many of our game's characters.

For example, we're not sure what the standard method of encapsulating/organizing a character's movement, animation, and more complex AI code is so that things don't become a behemoth mess.

Originally, we had all a character's code in one file -- movement, animation, and AI decision-making code. Needless to say, this became messy really quickly and horrendous to debug.

Then, we redesigned it so that there were three scripts on the character: a movementHandler, animationHandler, and AIHandler. These scripts would communicate to each other, but encapsulate their own functions. This worked better than before, but also grew to a point where it was a bit messy organizationally and debugging is becoming a nightmare again.

We're interested in knowing how people typically organize their scripts. Is there a way people know to organize these code sections so that they're more scalable and don't become headaches to manage once the project grows and grows?


texts: Packaging Jar with External Libraries in Eclipse

texts:
I have a class called Game in the package net.aGameName and am trying to export a runnable Jar using eclipse.  In the project I have two external Jar files added, lwjgl.jar and lwjgl_util.jar.

When I go to File->Export->Runnable Jar File and choose the Launch configuration I use for testing (which works successfully) I am able to export the Jar file without any errors.  Finally I open cmd and use java aGameName.jar and receive the following error:

Exception in thread "main" java.lang.NoClassDefFoundError: aGameName/jar
Caused by: java.lang.ClassNotFoundException: aGameName.jar
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: aGameName.jar.  Program will exit.

When I open the manifest file it says:

Manifest-Version: 1.0
Class-Path: .
Main-Class: net.aGameName.Game

Can anyone easily spot the error that would be causing this?  Thanks


texts: How does condition 5 of the Open Font License apply to using a font in my game/engine?

texts:
For my game-engine I have created an debug-console I use for more complex operations and tests, logging, etc.

When looking for a good & clean font I considered using Google Fonts. Many if not all fonts on there are licensed under the Open Font License1, which seems to be the real deal.

Yet when reading the license I got confused if condition 5 also applies to videogames/engines:

  5) The Font Software, modified or unmodified, in part or in whole,
  must be distributed entirely under this license, and must not be
  distributed under any other license. The requirement for fonts to
  remain under this license does not apply to any document created
  using the Font Software.

emphasis mine

So, how does this condition translate to me using it for my engine/game? And how would I go about properly attributing?

1Link to the license definition: http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&id=OFL


texts:
Am considering porting over from XNA to the Stage3D API's (Molehill).
So as a performance examination I've implemented sprite-batching, but the performance is not all that great, while with XNA i can easily draw up to 500 000 quads but with my Molehill implementation i can draw around a measly 1000 quads and while a rather dramatic performance difference was expected on the CPU side this is due to being GPU bound.
So currently the implementation is as follows.
set render states

let texture be null
let batchSize be arbitrary

for each sprite in queue
    if texture is not sprite texture
    or buffers are full

        upload vertex data to index buffer
        upload index data to vertex buffer

        bind texture
        draw triangles

        flush vertex data
        flush index data

    add sprite vertices to vertex data
    add sprite indices to index data
end

upload remaining vertex data to vertex buffer
upload remaining index data to index buffer
draw remaining triangles

flush data

The bottleneck is uploading the buffers, but as for a better implementation I'm hoping for a discussion here.
Cheers.
Revision:

One optimization that comes to mind is to persist the index buffer, since the indices are predictable and will always follow the same format. Am going to benchmark that now.

Caching the index buffer had no noticeable performance gains, so in an effort to try to understand where the bottleneck is, I ported it over to C#/XNA, ever so slightly slower than Microsoft's implementation but still has a GPU capacity over 500 times more than the Molehill implementation.
Is Molehill simply an extremely bad abstraction layer?


texts: How can I store additional attributes on DCEL edges?

texts:
I am currently working on a city generator, and I've ran into some issues with data storage while working on the roads. I currently use a doubly-connected edge list (DCEL for short), to store the road data. Each road would consist of two half edges, each connecting to a vertex.

The advantage of a DCEL is that I can easily access the space partitions of the roads, or the faces contained by the half edges. However, I am running into trouble storing additional data for roads.

I currently store (alongside the DCEL) a vector that simple contains all the roads as simple pairs of the indices of their beginnings and ends. However, I only use this vector to access data in bulk (for a bounding box test or rendering), nothing specific.

I want to store additional information about roads as some struct, but I don't know where to store it. I would need to access it easily through the DCEL, but I don't want to duplicate the data between the two half edges. What should I do?


texts: Refactoring out asynchronous webrequests to an interface

texts:
I have a Unity project with UnityWebRequest calls in it. They are all working correctly, but I'd like to refactor them out (they are implemented pretty badly at the moment).

The way I would like to do this is with a WebRequestSender class that implements an IWebRequest interface. Each call would return a WebResult object that I can use.

public class WebResult
{
    public long ResponseCode { get; set; }
    public bool IsError { get; set; }
    public string Value { get; set; }

    public static WebResult Success(long responseCode, string value)
    {
        return new WebResult
        {
            IsError = false,
            ResponseCode = responseCode,
            Value = value
        };
    }

    public static WebResult Failure(long responseCode)
    {
        return new WebResult
        {
            IsError = true,
            ResponseCode = responseCode,
        };
    }
}

I'm having trouble understanding how to implement the interface, as these calls are asynchronous.

Ideally, in the script when I need to make a call, I would have one line, like so:

WebRequest.Login(form) and that would return the result. I'm not sure what I have to add for it to wait for the call, or however it is executed.

public interface IWebRequest
{
    WebResult Register(WWWForm form);
}

Do I need to alter the return object so it allows for asynchronous calls? Or do I have to change the implementation/the call of the implementation?

As for my implementation, it doesn't work. The return statement on the Register function isn't called (even if it was, I'm not sure the return object would be populated?)  Sample below:

public class WebRequestSender : MonoBehaviour, IWebRequest
{
    private const string REGISTER_URL = "http://localhost:51044/api/Users/Register";

    private WebResult webResult;

    public WebResult Register(WWWForm form)
    {
        StartCoroutine(MakeWebCall(REGISTER_URL, form, (UnityWebRequest webRequest) => RegisterDelegate(webRequest)));

        return webResult;
    }

    private void RegisterDelegate(UnityWebRequest webRequest)
    {
        if (webRequest.isHttpError || webRequest.isNetworkError)
        {
            webResult = WebResult.Failure(webRequest.responseCode);
        }
        else
        {
            webResult = WebResult.Success(webRequest.responseCode, webRequest.downloadHandler.text);
        }
    }

    private IEnumerator MakeWebCall(string url, WWWForm form, Action<UnityWebRequest> finishDelegate)
    {
        using (UnityWebRequest www = UnityWebRequest.Post(url, form))
        {
            yield return www.SendWebRequest();
            finishDelegate(www);
        }
    }
}


texts:
I'm trying simply to display an openGL surface when I click the screen using GLSurfaceView.RENDERMODE_WHEN_DIRTY mode

but the surface does not display when I click it , why ?

my Activity :

public class ViewManager extends Activity {
    private GLSurfaceView surfaceView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        surfaceView = new GLSurfaceView(this);
        surfaceView.setEGLContextClientVersion(2);
        surfaceView.setRenderer(new MyRenderer());
        surfaceView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);

        surfaceView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event!=null){
                    if (event.getAction()==MotionEvent.ACTION_DOWN)
                        surfaceView.requestRender();
                    return true;
                }else{
                    return false;
                }
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        surfaceView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        surfaceView.onPause();
    }
}


texts: Is there a name for this algorithm for 2d shape collision?

texts:
A while ago I was considering my possibilities for implementing collisions between 2D shapes, and after much googling (which mostly turned up SAT), I came up with this:

let A, B = two shapes
let V = Speed of A relative to B

for a:point in vertices of A
  for b:segment in segments of B
    if segment(a, a+V) intersects b
      return intersection point
return false

Now, I'm far from the smartest person out there, so I am 99.8% sure someone must have come up with that before me and, what's more important, since I didn't find anything describing this method, I assume it's a bad one.

Can anybody identify this algorithm and/or point me towards any literature on it explaining if, when and why it should be used?

I've failed to see any significant problems at first sight; all the complex calculations can be hoisted outside of the loops and then it's just matrix multiplications within both loops, and I couldn't find any algorithm that makes do without any nested loops over two sets of elements (be they vertices, segments or normals)

Feel free to trash-talk my algo all you like, I never expected it to be the second greatest discovery right after general relativity or anything ;)

PS: Sorry for the poor title, but I can hardly explain the entire algo in one line :)


texts: Dealing with occlusion in an isometric sandbox game

texts:
Imagine a 3D sandbox game like Minecraft with third-person isometric graphics. If the camera only moves in two dimensions, and doesn't rotate, then a large portion of the world will always be occluded e.g. caves, areas behind mountains and buildings, etc. Obviously this isn't acceptable.

I'm trying to figure out how such a game could deal with this issue while preserving certain properties: the world must be entirely buildable/destructible and must extend in some manner along all three axes. Other than that, nothing is off the table.

I can't think of any simple culling algorithm that wouldn't either leave too much occluded or needlessly cull things. Which features are visible where seems to be a very high level design issue. If you are underground, you don't want to see the ground above you at all. But some small objects you probably never want culled, even when standing behind them.

And it's not at all clear what you would want to do with medium-sized objects, like buildings... perhaps make them translucent when the player walks behind them. But how would such objects be classified? And how would you distinguish the outside of the building from the inside? You probably don't want the inside of buildings to become visible when you walk behind them.

If the player can place objects anywhere, what happens if they place an object behind an occluder? Is it now impossible to interact with this object without destroying the thing in front of it, even when the player is standing right next to it? What about important features on back-facing surfaces? Are they never rendered at all?

It seems to me that isometry is just not capable of practically representing arbitrary three dimensional architecture, which suggests that the game needs to be designed in such a way that arbitrary architecture can't be built. Rather, it needs to be constrained to some kind of 2.5D model, where occluded things simply cannot exist. But how could a world like that feel consistent and logical to the player while they dig and build in it?


texts: Java: Updating entities in composite design

texts:
I'm trying to move beyond inheritance based design, but I've been doing it like that for 6 years. My current hurdle is this: What's the simplest( or proper) way to update all my objects? Before, everything was a subclass of an Entity class. It was as simple as throwing them into ArrayList and iterating through them all, calling update() on each object. How does this translate in composition? Where the Entity class is within classes that can't be simply passed as each other.

for(Entity e : Entites) // I know this is bad practice, but good for an example
    e.update();
// e could be any subclass of entity

Since moving to a component - composition based system I can't do that, as each game object is it's own class. I can't make an ArrayList of my objects and call update on each of them. And as far as I know,

My game objects are setup like this

class Apple implements iEntity {
    Entity  innerEntity;
    public Apple{
        innerEntity = new Entity(1); // 1 represents Apple as an identifier
    }
    @override // From iEntity
    public void update(){
    }
}

Because Apple no longer extends Entity, I can't load it into an ArrayList with Pears(example). All my other objects are similar. Id' rather not make a AppleManager class for Apples, a PearManager for Pears, and build functionality between them. That just seems messy.

Maybe I'm missing a few points, but that's why I'm here. Before this gets closed for some obscure reason, I googled the heck out of this. Each article explained the advantages of a system like this, but failed explaining beyond that. Thanks and advance dudes.


texts: A texture pack for a sponza model contains mask textures (black and white). I guess that I should read only a red channel from that texture, right ? I use deferred rendering and for  shading calculations I use additive blending. A result is first save in a texture (for some post-process operations), so doesn't go directly to the default framebuffer. How to use a mask texture ?


texts: Is there any API that returns information about "all games"?

texts:
I'm building a project about games and I need to make a "portfolio" of games.

Something like a catalog of Netflix, but about games, and I need some basic information about the game, like Publisher, Genre, Developer, Release Date and some more information.

Someone know a free API that returns the date that I need? I tried Steam API, but doesn't work for me.

Obs: Returns a JSON.


texts: Problem with sprite direction and rotation

texts:
I have a sprite called Tool that moves with a speed represented as a float and in a direction represented as a Vector2. When I click the mouse on the screen the sprite change its direction and starts to move towards the mouseclick. In addition to that I rotate the sprite so that it is facing in the direction it is heading. However, when I add a camera that is suppose to follow the sprite so that the sprite is always centered on the screen, the sprite won't move in the given direction and the rotation isn't accurate anymore. This only happens when I add the Camera.View in the spriteBatch.Begin(). I was hoping anyone could maybe shed a light on what I am missing in my code, that would be highly appreciated.

Here is the camera class i use:

    public class Camera
{
    private const float zoomUpperLimit = 1.5f;
    private const float zoomLowerLimit = 0.1f;

    private float _zoom;
    private Vector2 _pos;

    private int ViewportWidth, ViewportHeight;

    #region Properties

    public float Zoom
    {
        get { return _zoom; }
        set
        {
            _zoom = value;
            if (_zoom < zoomLowerLimit)
                _zoom = zoomLowerLimit;
            if (_zoom > zoomUpperLimit)
                _zoom = zoomUpperLimit;
        }
    }

    public Rectangle Viewport
    {
        get
        {
            int width = (int)((ViewportWidth / _zoom));
            int height = (int)((ViewportHeight / _zoom));
            return new Rectangle((int)(_pos.X - width / 2), (int)(_pos.Y - height / 2), width, height);
        }
    }

    public void Move(Vector2 amount)
    {
        _pos += amount;
    }

    public Vector2 Position
    {
        get { return _pos; }
        set { _pos = value; }
    }

    public Matrix View
    {
        get
        {
            return Matrix.CreateTranslation(new Vector3(-_pos.X, -_pos.Y, 0)) *
                Matrix.CreateScale(new Vector3(Zoom, Zoom, 1)) *
                    Matrix.CreateTranslation(new Vector3(ViewportWidth * 0.5f, ViewportHeight * 0.5f, 0));
        }
    }

    #endregion

    public Camera(Viewport viewport, float initialZoom)
    {
        _zoom = initialZoom;
        _pos = Vector2.Zero;
        ViewportWidth = viewport.Width;
        ViewportHeight = viewport.Height;
    }

}

And here is my Update and Draw-method:

protected override void Update (GameTime gameTime)
    {
        float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
        TouchCollection touchCollection = TouchPanel.GetState ();

        foreach (TouchLocation tl in touchCollection) {
            if (tl.State == TouchLocationState.Pressed || tl.State == TouchLocationState.Moved) {

                //direction the tool shall move towards
                direction = touchCollection [0].Position - toolPos;

                if (direction != Vector2.Zero) {
                    direction.Normalize ();
                }

                //change the direction the tool is moving and find the rotationangle the texture must rotate to point in given direction
                toolPos += (direction * speed * elapsed);
                RotationAngle = (float)Math.Atan2 (direction.Y, direction.X);
            }
        }

        if (direction != Vector2.Zero) {
            direction.Normalize ();
        }

        //move tool in given direction
        toolPos += (direction * speed * elapsed);
        //change cameracentre to the tools position
        Camera.Position = toolPos;
        base.Update (gameTime);
    }

        protected override void Draw (GameTime gameTime)
    {
        graphics.GraphicsDevice.Clear (Color.Blue);
        spriteBatch.Begin (SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, null, Camera.View);
        spriteBatch.Draw (tool, new Vector2 (toolPos.X, toolPos.Y), null, Color.White, RotationAngle, originOfToolTexture, 1, SpriteEffects.None, 1);
        spriteBatch.End ();

        base.Draw (gameTime);
    }


texts: Unity custom camera projection only working in scene editor

texts:
I've found this article on Gamasutra on a custom camera projection to make 3D look more 2D and decided to implement it to make some gameplay tests.
I had to make some changes to make it work on URP(on unity 2019.3.6f1) but it "worked" with the following code:
using UnityEngine;
using System.Collections;
using UnityEngine.Rendering;

// This script is meant to be attached to your main camera.
// If you want to use it on more than one camera at a time, it will require
// modifcations due to the Camera.on* delegates in OnEnable()/OnDisable().

[ExecuteInEditMode]
public class CustomProjectionTest : MonoBehaviour {
    private void OnEnable(){
        RenderPipelineManager.beginFrameRendering += ScenePreCull;
        RenderPipelineManager.endFrameRendering += ScenePostRender;
        //Camera.onPreCull += ScenePreCull;
    }

    private void OnDisable(){
        RenderPipelineManager.beginFrameRendering -= ScenePreCull;
        RenderPipelineManager.endFrameRendering -= ScenePostRender;

        GetComponent<Camera>().ResetWorldToCameraMatrix();
    }

    private void ScenePreCull(ScriptableRenderContext context, Camera[] cam){
        // If the camera is the scene view camera, call our OnPreCull() event method for it.
        OnPreCull();
    }

    private void ScenePostRender(ScriptableRenderContext context, Camera[] cam){
        // Unity's gizmos don't like it when you change the worldToCameraMatrix.
        // The workaround is to reset it after rendering.

        foreach(var camm in cam)
            camm.ResetWorldToCameraMatrix();
    }

    private Camera _cam;
    private void Start(){
        _cam = GetComponent<Camera>();

        // Set the camera this script is attached to to use orthographic sorting order.
        // Instead of using the euclidean distance from the camera, objects will be sorted based on their depth into the scene.
        _cam.transparencySortMode = TransparencySortMode.Orthographic;
    }

    public Vector4 up = new Vector4(0, 1, 0, 0);

    // This is a Unity callback and is the ideal place to set the worldToCameraMatrix.
    private void OnPreCull(){
        var cam = !Application.isPlaying? Camera.current : _cam;

        // First calculate the regular worldToCameraMatrix.
        // Start with transform.worldToLocalMatrix.
        var m = cam.transform.worldToLocalMatrix;

        // Then, since Unity uses OpenGL's view matrix conventions we have to flip the output z-value.
        m.SetRow(2, -m.GetRow(2));

        // Now for the custom projection.
        // Set the world's up vector to always align with the camera's up vector.
        // Add a small amount of the original up vector to ensure the matrix will be invertible.
        m.SetColumn(2, 1e-3f*m.GetColumn(2) - up);

        cam.worldToCameraMatrix = m;
    }

    public static Matrix4x4 ScreenToWorldMatrix(Camera cam){
        // Make a matrix that converts from screen coordinates to clip coordinates.
        var rect = cam.pixelRect;
        var viewportMatrix = Matrix4x4.Ortho(rect.xMin, rect.xMax, rect.yMin, rect.yMax, -1, 1);

        // The camera's view-projection matrix converts from world coordinates to clip coordinates.
        var vpMatrix = cam.projectionMatrix*cam.worldToCameraMatrix;

        // Setting column 2 (z-axis) to identity makes the matrix ignore the z-axis.
        // Instead you get the value on the xy plane.
        vpMatrix.SetColumn(2, new Vector4(0, 0, 1, 0));

        // Going from right to left:
        // convert screen coords to clip coords, then clip coords to world coords.
        return vpMatrix.inverse*viewportMatrix;
    }

    public Vector2 ScreenToWorldPoint(Vector2 point){
        return ScreenToWorldMatrix(_cam).MultiplyPoint(point);
    }

    private void Update(){
        if(Input.GetMouseButtonUp(0)){
            Debug.Log(ScreenToWorldPoint(Input.mousePosition));
        }
    }
}

Well, kinda. For some reason, it only works in the scene editor, but not in the game. I just have no clue why
With Scene Editor:

In Game


texts: How to have the game world get rendered on just a part of the screen?

texts:
I am implementing a game on both Desktop and Android.

The Desktop version will just rely on the keyboard to handle the user input on the game screen, whilst the Android one will have to have a set of buttons placed in a bar at the bottom of the game screen, using a Stage.

Consequently, I am expecting the game world to take up the entire space available on the Desktop screen, whilst on Android it should expand to the entire width of the screen, and to the screen height minus the height of the buttons bar I've mentioned.

What would be an appropriate approach of handling space sharing between the game world and the buttons bar?

Thank you.