texts: Unity - move with WASD in the way the camera is facing

texts:
I have this C# code for rotating the camera with the mouse:

public float mouseSensitivity = 100.0f;
public float clampAngle = 80.0f;

private float rotY = 0.0f; // rotation around the up/y axis
private float rotX = 0.0f; // rotation around the right/x axis

void Start()
{
    Screen.lockCursor = true;
    Vector3 rot = transform.localRotation.eulerAngles;
    rotY = rot.y;
    rotX = rot.x;
}

void Update()
{
    float mouseX = Input.GetAxis("Mouse X");
    float mouseY = -Input.GetAxis("Mouse Y");

    rotY += mouseX * mouseSensitivity * Time.deltaTime;
    rotX += mouseY * mouseSensitivity * Time.deltaTime;

    rotX = Mathf.Clamp(rotX, -clampAngle, clampAngle);

    Quaternion localRotation = Quaternion.Euler(rotX, rotY, 0.0f);
    transform.rotation = localRotation;
    transform.parent.transform.rotation = Quaternion.Euler(0.0f, rotY, 0.0f);
}

The script is on the camera, and camera object is a child to the player object.
Now I want to move the player object in the direction the camera is facing, how do I do this?


texts: How to save the 3D surface to bitmap in Flash 11 Stage3D

texts: I have been using Stage3D to create some 3D app in Flash. One of the items on my list is the ability to take a screen shot. Flash makes it easy to grab the stage content, but I can't find a way to grab the stage3D content. In DX I just used D3DXSaveSurfaceToFile. Anyone know of a way to do it in as3 and flash 11?


texts: How to set only one collider with OnCollisionEnter(Collision col) in Unity?

texts:
I tried with this:

void OnCollisionEnter(Collision col)
{
    Debug.Log("hit everything");
    if (col.gameObject.layer != LayerMask.NameToLayer("bico"))
    {
        if (col.gameObject.tag == "Floor")
        {
            Debug.Log("hit");
            Destroy(gameObject);
            ShipHealth ShipHealth = this.GetComponentInParent<ShipHealth>();
            if (ShipHealth != null)
            {
                Destroy(gameObject);
                ShipHealth.TakeDamageMissile(100);
            }
        }
    }
}

What I want is that it only chooses one collider and not all: I only want the capsule collider.


texts:
I want to create a plane that will be normal to the Z axis, but I am having difficulty  visualizing what rotation it needs to have.

I want to have a top-down view upon the plane such that I can use the X and Y coordinate system for position, and the Z axis for height.

It seems intuitive for me to point the camera in the same rotation as this plane, and give it an orthogonal view and a positive Z value (and set gravity to have a negative Z value), but I seem to be fighting against the grain and running into more issues than I should be, so I would like to ask what rotations I should be using for this.

What rotation should I use for the plane? can the camera share the same rotation? (assuming I want the top to be +y and the right to be +x as seen from the camera.


texts: How can I make my Camera's RenderTexture output have a transparent background?

texts:
I'm writing a 3D game using Unity 2017.1.0b1.  I have a disabled Camera that takes a "snapshot" of the current scene and stores it in a RenderTexture when a button is clicked.  I then display the RenderTexture in a RawImage within my scene.

This works, except that the output from the Camera into the RenderTexture doesn't take into account the alpha value of the Camera's clear color.

Here's a snapshot of how my disabled Camera is configured.  Notice the Background property has an alpha value of 0:

Here's a snapshot of what the RenderTexture (displayed using a RawImage) looks like in the game.  The blue square is the RenderTexture:

How can I make the Camera render into the RenderTexture with a transparent background?  I didn't expect the blue background to show up in the RenderTexture since its alpha value is 0.


texts: Problem with monogame reference in monodevelop MAC

texts:
I've downloaded monogame, monotouch (test version) and monodevelop for MAC and I created a monotouch IOS project, I included the Lidgren and Monogame csproject inside my monodevelop project and I added the monogame reference in my project. But when I try to build it, my Main class doesn't find the Game class and Game.run();

My Main is the same code that I got monogame site:

using MonoTouch.Foundation;
using MonoTouch.UIKit;
using Microsoft.Xna;
using Microsoft.Xna.Samples;
using Microsoft.Xna.Samples.Draw2D;

namespace Microsoft.Xna.Samples.Draw2D
{
    [Register ("AppDelegate")]
    class Program : UIApplicationDelegate
    {
        private Game1 game; //doesn't find

        public override void FinishedLaunching (UIApplication app)
        {
            // Fun begins..
            game = new Game1();
            game.Run();
        }

        static void Main (string [] args)
        {
            UIApplication.Main (args,null,"AppDelegate");
        }
    }
}

and My appDelegate:

using System;
using System.Collections.Generic;
using System.Linq;

using MonoTouch.Foundation;
using MonoTouch.UIKit;

namespace testeios
{
    // The UIApplicationDelegate for the application. This class is responsible for launching the
    // User Interface of the application, as well as listening (and optionally responding) to
    // application events from iOS.
    [Register ("AppDelegate")]
    public partial class AppDelegate : UIApplicationDelegate
    {
        // class-level declarations
        UIWindow window;

        //
        // This method is invoked when the application has loaded and is ready to run. In this
        // method you should instantiate the window, load the UI into it and then make the window
        // visible.
        //
        // You have 17 seconds to return from this method, or iOS will terminate your application.
        //
        public override bool FinishedLaunching (UIApplication app, NSDictionary options)
        {
            // create a new window instance based on the screen size
            window = new UIWindow (UIScreen.MainScreen.Bounds);

            // If you have defined a view, add it here:
            // window.AddSubview (navigationController.View);

            // make the window visible
            window.MakeKeyAndVisible ();

            return true;
        }
    }
}

I don't know what's happening, I follow every step to install it. has Someone the same problem?


texts: How do I make a moving object stop smoothly at the end of a path?

texts:
There are a dozen ways I could word this question, but to keep my thoughts in line, I'm phrasing it in line with my problem at hand.

So I'm creating a floating platform that I would like to be able to simply travel from one designated point to another, and then return back to the first, and just pass between the two in a straight line. However, just to make it a little more interesting, I want to add a few rules to the platform.

I'm coding it to travel multiples of whole tile values of world data. So if the platform is not stationary, then it will travel at least one whole tile width or tile height.
Within one tile length, I would like it to accelerate from a stop to a given max speed.
Upon reaching one tile length's distance, I would like it to slow to a stop at given tile coordinate and then repeat the process in reverse.

The first two parts aren't too difficult, essentially I'm having trouble with the third part. I would like the platform to stop exactly at a tile coordinate, but being as I'm working with acceleration, it would seem easy to simply begin applying acceleration in the opposite direction to a value storing the platform's current speed once it reaches one tile's length of distance (assuming that the tile is traveling more than one tile-length, but to keep things simple, let's just assume it is)- but then the question is what would the correct value be for acceleration to increment from to produce this effect? How would I find that value?


texts: Unity - Issue applying Render Texture to object imported from Blender

texts:
I'm new to Unity and am trying to create a sort of CRT computer monitor/terminal with text. To draw the text, I set up a Text Mesh Pro with its own camera, which renders to a Render Texture.

I then designed a simple computer monitor model in Blender split into two objects: one for the glass part of the screen, and another for the 'rest' of the monitor exterior case.
I saved a copy of the .blend file into the Assets folder and imported this into Unity.

My blender model: (two separate objects, with the separate "screen" piece moved out of the screen)

When I try to apply the Render Texture onto the screen object, the texture is rotated 90 degrees anti-clockwise and is too zoomed in:

I can't seem to rotate the texture so that it is the right way up to read the text, and only some of the text is visible.
I have tried rotating the object 90 deg. clockwise in Blender and "applying" the transform so unity then thinks the object is oriented correctly. this still caused the texture to be rotated.

I also tried exporting as an .obj file, with "Up" set to "Y-Up", but this didn't work.
I then tried applying the Render Texture to a material, which I then applied to the screen object which didn't work either.
If I apply the texture to a standard cube in Unity, it works fine and is rotated and scaled correctly to fit the cube.

How can I get the blender object oriented correctly so that the Render Texture applies in the correct orientation and scales so the whole of the Render Texture fits and is not zoomed in?

I'm using Unity 2019.3 and Blender 2.82.


texts:
Has anyone yet prototyped a game in both Unity3D and UDK?

If so, which features made prototyping the game easier or more difficult in each toolkit?

Was one prototype demonstrably better than the other (given the same starting assets)?

I'm looking for specific answers with regard to using the toolkit features, not a comparison of available features. E.g. Destructable terrain is easier in toolkit X for reasons Y and Z.

I can code, so the limitations of the inbuilt scripting languages are not a problem.


texts: Building meshes conforming to terrain deformation

texts:
I have an uneven terrain on which the player is supposed to build buildings. For most structures I can just fudge the foundations, have them extend through the terrain.
For roads, pipes, tracks and such I do have however the problem how to make them line up. What techniques can I best use to make the meshes of adjacent pieces line up, making it conform to the terrain?


texts: Achieving a fixed frame-rate with varying scenes

texts:
I am working on an OpenGL 3D model viewer app for iOS.

I have to load, view and navigate extra detailled 3D models on an iPad. I hardly achieve 2 fps, if i load and navigate a very complex model. I tried some optimizations like view-frustum-culling, area in pixel space, back-face-culling etc but still i am unable to improve the frame rate.

I would like to set fixed frame-rate to some X fps for my app and drop-out all the objects which don't have enough time to render at run-time. I would like to know if there is any algorithm to achieve this fixed frame-rate. I would appreciate any ideas.


texts: WinAPi OpenGL Borderless Fullscreen - Alt Tab problems

texts:
I'm implementing a borderless fullscreen functionality and managed to make something that almost works. Using: C++, Winapi, OpenGL 3.3.

When  in fullscreen borderless mode, if alt tab the game window loses focus but is still on top, not even the alt tab window shows.

I managed to track it down to SwapBuffers. If i disable it, no problems but also no rendering.

If i force the window to hide when it loses focus, the entire screen flickers. And if i alt tab back, only the game window flickers.

If i put the game in windowed mode, it works as normal.

Window Styles are first set to(windowed mode stops  here):

WS_OVERLAPPED | WS_MINIMIZEBOX | WS_SYSMENU | WS_VISIBLE

And then are set to(if fullscreen):

GetWindowLong(window, GWL_STYLE) & ~WS_OVERLAPPEDWINDOW

My gameloop:

while(isRunning)
{
    loopNewTime = timeGetTime();
    loopDuration = (r32)(loopNewTime - loopOldTime);
    loopTime = Clamp(0.0f, (loopDuration - sleepTime), 250.0f);

    loopOldTime = loopNewTime;
    loopAccumulator += loopTime + sleepTime;

    while(loopAccumulator >= loopFixedDeltaTime)
    {
        if(isFocused || canRunWithoutFocus)
        {
            DoStuff();
        }

        loopAccumulator -= loopFixedDeltaTime;
    }

    if(isFocused || canRunWithoutFocus)
    {
        DoStuff();

        glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

        DrawStuff();

        SwapBuffers(deviceContext);
    }

    framerateTimeThreshhold += loopTime + sleepTime;
    ++framerateCount;

    if(framerateTimeThreshhold >= 1)
    {
        framerate = framerateCount;
        framerateCount = 0;
        --framerateTimeThreshhold;
    }

    sleepTime = Max(timeStep - loopTime, 0.0f);

    Sleep((u32)sleepTime);
}

So, how can i solve this problem?

Thanks in advance.


texts: What category would this asynchronous production economy game fall under?

texts:
I'm thinking of getting into game development and my friend and I have this idea for a game. We want to do some research on similar games, and I have noticed that games seem to fall under certain categories like "platformer", "shooter", "racing games" or similar.

Our idea is a multiplayer, mobile game where you and around 4-5 other players are placed in a session.

Every player is given a different role in a market (like a farmer to grow crops, miller to make flour out of crops, baker to bake bread, etc.). The players are supposed to sell goods to each other in order to earn money (or similar). The resources are produced/generated over time, so it's like Travian and other city building games when it comes to stuff happening over time.

You own a production facility (like a farm, mill, etc.) and if you have enough resources/money it produces some good every 10 min (arbitrary time for the example).

This happens even when the user is not playing. Then once in a while, you can check in, put some of your goods up for sale that others can purchase.

So it's a passive loop that simply generates resources every x minutes, and in addition, the players can put up their goods for sale when they feel like it.

But the game is not "infinite". When one of the players reaches a certain goal, the game session ends and the players are ranked (or something, it's still a rough idea).

So in this regard, it's more like Wordfeud or Chess where your next move depends on what the other players do and there is a way to win the game (be it a winning condition or time running out).

So the question is, does this kind of game fall under a specific category that we can research?


texts:
Unity3D's reference describes the HDR Bloom as:

  Using HDR allows for much more control in post processing. LDR bloom
  has an unfortunate side effect of blurring many areas of a scene even
  if their pixel intensity is less than 1.0. By using HDR it is possible
  to only bloom areas where the intensity is greater than one.

My question is how to achieve it in a surface shader? I have tried to output both the Albedo and Emission greater than 1, but still when I set the Threshold of Bloom equal to or greater than 1, no visible effect can be seen.

The relevant part of shader snippet is:

float rim = saturate(dot(normalize(IN.viewDir), o.Normal));
if (rim >= 0.98) {
    o.Emission = 1.5; // or any large value
}

Which basically outputs a bright white circle when view angle and normal are at almost same angle, and I want to enhance it with HDR. But outputting a value greater than 1 is not being registered and setting the threshold almost equal to 1 (0.98 or above) creates the Bloom on areas other than the bright white spot, which is not what is needed. I have tried to output extremely large values of Emission and have also tried output Albedo > 1.

Please tell what I am doing wrong or missing. I think I have not been able to figure out what is the meaning of pixel intensity > 1 and what settings does this translate to.


texts: My script to play the intro scene the first time the player hits play from the main menu wont work

texts:
The script I am using determines if it is the players first time hitting the play button and if it is it will load the intro scene, but if they have played before it will take them strait to the game scene.
The problem is that it just takes them strait to the game scene.

public class SeenBefore : MonoBehaviour
{
    public string SceneName;

    AsyncOperation preload;

// Start is called before the first frame update
    void Start()
    {
        preload = SceneManager.LoadSceneAsync(SceneName);
        preload.allowSceneActivation = false;
    }

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

    }

    public void before()
    {
        if (PlayerPrefs.HasKey("HasSeenIntro"))
        {
        preload.allowSceneActivation = true;
        }
        else
        {
            PlayerPrefs.SetInt("HasSeenIntro", 1);
            SceneManager.LoadScene("Intro");

        }
    }
}


texts: Getting a sprite from multiple sprites for right material pattern

texts: Not sure how accurate the question was but I'll put it this way. I'm developing a game where player will construct his/her own stuff, like bridge, building etc. using cocos2d-iphone and Box2D. First they'll draw the draft on a blueprint and then what's drawn will be transported to physics engine and finally the bodies will be wrapped with costumes. Let's say we're building a bridge and the bridge is going to be made of wood. I don't want the wood to be plain brown, I rather want it to be more natural, have some woody patterns on it. Here's my problem: A bridge component might be of any length, how can I achieve maximum realistic wood pattern? The only idea that comes to my mind is to take an image, slice it into 1 pixel width images, number them by order and attach them side by side upon need. Do you have any other suggestions? What's the general practice?


texts: Projecting grid textures to select parts of the terrain (Unity)

texts:
So I'm trying to be smart and not use 500+ some tile prefabs to make a grid, and so far the back-end portion has gone swimmingly. I initially used a dedicated mesh to represent the grid, but as I'm now opting for 3D terrain (and not tilemapping), I figured that was a lot of unnecessary vertices - especially if I want to have the grid conform to the terrain.

My shader inexperience, on the other hand, is causing me to stop and overthink this.

Using FE as inspiration, I'm thinking about projecting the transparent grid texture onto a base terrain layer.

If I wanted parts of the terrain to not be covered by the grid (such as the water area in the picture), would I simply use the world coordinates to tell the shader don't do anything there?

The most confusing part for me, however, is how to go about highlighting tiles. I want movement and attack tiles to also be 'painted' onto the terrain in specific colors, but obviously they only affect an even smaller portion than the terrain than the grid.

Would I simply be using the same shader to grab world coordinates once again and more or less start/stop overlaying the movement/attack texture over the grid/terrain? And if I'm really being efficient, those textures belong to the same png and I just use UV's to switch between them like a sprite sheet?
Is this even a good practice for shaders in the first place? Redrawing and adding textures to only parts of a material? Should I be redrawing and updating the whole texture instead?

I guess I get thrown off because I'm only familiar with a 1:1 mesh to material design, so the so the thought of a single mesh but multiple textures on discrete parts that may or may not overlap makes somewhat sense on paper -- but implementation in Unity is just above me atm.

Thanks!


texts: How to fix cutting corner problem in A-star pathfinding

texts: So this is a problem when doing diagonal jumps (checking diagonal neighbor nodes). In 2d it can be prevented by doing some checks, like if up and right is blocked, don't take up-right neighbor for calculations. But in 3d thous check become a bit to much and to tedious.. so if I still want diagonal paths, what could be a good solution?


texts: Scanning a 2D tile map and detecting regions?

texts:
I have access to all points/tiles on the map with top-right most point being (0,0). Simplest way to traverse the map would be using for loops, one nested within the other to traverse the x axis, and then y (going through rows). But to solve this problem, I would probably need to scan the map in a more intelligent fashion. The important thing to note is that I'm only able to check one tile at a time and see what type it is. So t.getCoordinates() would return something like (32,54) and t.senseTile() would return: WALL, ROAD, OFF_MAP, etc.

I wanted to scan the entire map and divide it up into regions. The regions would be of two kinds: "open" and "paths". For open regions, I just want to fill the entire region until it starts hitting boundaries, walls/obstacles, etc and stop the fill when appropriate. A rule for an open space is that a player should be able to get from one edge to another edge taking any path, angle, etc without bumping into some wall/obstacle.

For paths, there's certain number of tiles a region is limited to, then a new region starts (see lightBlue and gray).

Also, the paths should have entrances/exists also stored and to which regions they connect to. For example, scanning through a map like this (see pic), these regions should be generated. Not sure which data structure to use to connect them, but maybe a tree/graph would look like this:

  Gray
    |
 LightBlue
    |
   Pink
    |
  Yellow
    |   \
   Red  Black

Edit: I think Dijkstra's search algorithm could be a good starting point although I've never implemented it before. That only solves a small part of the problem. It still doesn't solve how it's going to detect regions. Also, I'm afraid Dijkstra's would be too costly in terms of time/performance (both are extremely important).


texts: For timed levels, how do you determine time steps that are less than 1/(frames per second)?

texts:
I have made a simple HTML5 racing game.  The laps are timed.  I am running the game are 40 frames per second, each frame represents 40 milliseconds.  There for my timer will increase in 0.025 increments.

My question is how can I get my timer to record lap times more accurately, without running at 100 frames per second! How do other games do it?  Could it be to do with gauging the distance from the car to the finish line in the frame before and after it crosses the finish line?


texts: Canvas Infinite Map: How to have reappearing objects at static X,Y even when looping

texts:
I made a html canvas example of an infinite scrolling map with objects in static places. As you can see in the Fiddle below, when you move left with the Arrow Keys, you can see that the map does not show the other ends tiles and the objects do not appear either.

After the position is changed to the opposite edge of the map, the tiles appear and the object from that side of the map appears.

I made this Fiddle by modifying another Fiddle but it gets my point across.
https://jsfiddle.net/n8d5kbau/

Is there any way to duplicate the one edge of the map or am I approaching this the right way? I have been searching for this all over the place, finally deciding to ask here.

Thanks in advance.


texts: How do I know what button was clicked? (Unity)

texts:
I have a prefabbed button (UI.Button) which I'm instantiating ten times:

public void LayoutButtons() {

    GameObject newCanvas = Instantiate (canvas) as GameObject;

    for (int i = 0; i < 10; i++) {
        buttons[i] = Instantiate(button, new Vector2((i * 100.0F)-500, -100), Quaternion.identity) as GameObject;
        buttons[i].transform.SetParent(newCanvas.transform, false);
        buttons[i].GetComponentInChildren<Text>().text = "Button " + i;
    }
}

However, I'm now stuck when trying to figure out which button was clicked. The Unity onClick seems to only allow zero or one parameters. I've tried using public void onClick(Button button) with button.getComponentInChildren<Text>().text but I get ArgumentException: failed to convert parameters

All I want to do is print out the clicked button's text. How can I do this?


texts: UE4: "Ignore Move Input" Does not get Set back on

texts:
I have the following issue:

I have some logic which I call to Set Ignore Move Input on for a specific player character, based on a boolean. However, after half a second, I set it back on.

Everything works great, I can not move my character while it kicks.. However, if I press the "kick" input twice in succession.. the Set Ignore Move Input breaks and never gets turned off, even if I "Kick" again later.

Here is the blueprint .. Any help is greatly appreciated (and yes I realize that to somebody more experienced this blueprint makes little to no sense, but I'm just starting out... My core issue as a software developer here is I don't understand what locks me out of the logic that would reset Ignore Move Input back off).

Thank you for your time!


texts: Best ways to navigate a single step on a hexagonal grid depending on input

texts:
Problem

In my puzzle game, the player moves one step at a time on a hexagonal grid. (Not an action game.)
The sequence of steps is important for the gameplay, so it is not only about getting from A to B.
There are of course six possible move directions that I have to map my input to.
My hexagons have a pointy tip, so I do not have a North or South adjacent cell. So the ordinal directions are NW, NE, E, W, SW and SE. See the image.
I am particularly interested in ideas to accomplish this movement for mouse, keyboard and Xbox-like controllers, but feel free to post your thoughts on touch.
The main difficulty is that I am very experienced with my very clunky controls and new players are struggling to simply move the player around. Also, the movement controls cannot be accomplished via conventional square grid controls, e.g. a dpad or WASD.

What I have tried / Ideas
Keyboard

Mapping the characters around S directly to the six hexagonal directions, so W->NW, E->NE, A->W, D->E, Z->SW and X->SE. This is what I use basically.
Idea: Use WASD only. W is a North modifier, S is a South modifier and A and D correspond to East and West. Holding down the modifier will change what A/D does. Maybe show preview of current move possible with modifiers.

Controller

Flick controls: When you reach a certain threshold in displacement of the 2D left stick, this angle counts as as movement and will be mapped directly to a direction. You will see a small line/arrow pointing to the corresponding direction of the stick when you are not fully tilting the stick. Center stick to proceed.
Same as before, but you have to press A to go in that direction.

Mouse

Idea: Click on the adjacent tile to go there, maybe highlight possible moves.
Idea: Press a button and drag from that position to mimick stick controls, e.g. flicks.


texts: How can I get the window associated with a SDL_Renderer?

texts:
As the title says, is there a member or function to get this?

For example renderer->window? Or renderer.window? Or so?


texts: Is it possible to have FixedUpdate execute once every n frames?

texts:
I'm currently building a small game, and I've created this simple character controller using FixedUpdate, which executes every frame.

using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    /// <summary>
    /// Check for a key press, and if that key is pressed,
    /// move in a specified direction if there are no obstacles.
    /// </summary>
    private void MovePlayerOnKey(KeyCode keyCode, Vector3 direction)
    {
        Collider[] hitColliders = Physics.OverlapSphere(this.transform.position + direction, 0.1f);
        if(Input.GetKey(keyCode) && hitColliders.Length <= 0)
        {
            this.transform.position += direction;
        }
    }

    /// <summary>
    /// FixedUpdate is used to ensure that the player is
    /// moving in sync with the step of the Physics engine,
    /// and not executing a variable amount each frame.
    /// </summary>
    public void FixedUpdate()
    {
        this.MovePlayerOnKey(KeyCode.W, new Vector3(0, 1f, 0));
        this.MovePlayerOnKey(KeyCode.A, new Vector3(-1f, 0, 0));
        this.MovePlayerOnKey(KeyCode.S, new Vector3(0, -1f, 0));
        this.MovePlayerOnKey(KeyCode.D, new Vector3(1f, 0, 0));
    }
}

While the code itself works, the player moves much too fast for my liking, and I can't change the step of the player either, it has to stay at 1 in order for other game mechanics to function properly.

The only solution I can think of is changing how FixedUpdate runs by running it less often. Is it possible to make FixedUpdate run once every n frames?


texts:
I am looking to program my own little Role Playing Game using...

ANSI C or "standard C", (NOT C++) as my programming language
The SDL2 development library

I have got a very basic and simple type of game up and going,
(I am learning ANSI C as I develop this hobby game).

I want to implement an item system to the game, so I have been looking through the internet for advice, but it seems like the closest I can get are solutions to C++, Java and other object oriented languages. I can't seem to find a good implementation in C, other than THIS guide, so I thought I could post this question specifically for ANSI C both for me and for others that might be looking to achieve the same goal.

My attack plan is to create a struct to lay out a blue print of what an item is, much like a class in an OOP language. Then, perhaps create an array that defines objects of this type and fills in the details for each item.

This is what I have so far:

#ifndef ITEMS_H_INCLUDED
#define ITEMS_H_INCLUDED

/* Create a structure that represent an item.
   @see https://www.tutorialspoint.com/cprogramming/c_structures.htm */
typedef struct Item {
    //Unique ID to be used as a reference to the item.
    unsigned int id;

    //Name of the item.
    char name[20];

    //Brief description about the item.
    char description[50];

    //Defines the category of the item; equipment, consumable, etc...
    unsigned char type;

    //Used for equipment; defines the strength of the weapon/armor.
    unsigned char stats[4];

    //The X and Y coordinates of the starting point of the sprite.
    unsigned int sprite[2];
}item;

#endif // ITEMS_H_INCLUDED

The id-attribute will be used to spawn the item in different locations, such as...

In the player's inventory
In a store
On the floor to be picked up

I'm looking to hard code the item DATA in the source file, but I'm also open for solutions like reading item information from a file, and such.


texts: How to link the game class to the main menu class in XNA?

texts:
So I got my game in another class and my main menu in another class.

This is the update method in my Main menu class

MouseState mouse = Mouse.GetState();
            switch (CurrentGameState)
            {
                case GameState.MainMenu:
                    if (btnPlay.isClicked == true) CurrentGameState = GameState.Playing;
                    btnPlay.Update(mouse);
                    break;

                case GameState.Playing:

                    break;

            }
            base.Update(gameTime);

This is the draw method in my Main menu class

spriteBatch.Begin();
            switch (CurrentGameState)
            {
                case GameState.MainMenu:
                    spriteBatch.Draw(Content.Load<Texture2D> ("MainMenu"), new Rectangle (0,0, screenWidth, screenHeight),Color.White);
                    btnPlay.Draw(spriteBatch);

                    break;

                case GameState.Playing:
                    break;
                                    }

            spriteBatch.End();

But now I don't know how to link/call the actual game file..
Would someone be able to help me with this please?


texts: Why isn't my PlayerPrefs key detected across multiple games?

texts:
I am developing a level based game; I created a key in the PlayerPrefs class called "LevelNumber". It's default value is 0. If I pass level one, it increments by 1 and goes on.

Everything is working fine, but if I press "restart level" or if I close and reopen the game menu, the key is no longer detected. Every time I restart the game, it is printing "key not found" in the console. How do I fix this?

public class AppController : MonoBehaviour
{
    public int _currentLevel = 0;

    void Start ()
    {
        #if UNITY_ANDROID && UNITY_EDITOR
        if (PlayerPrefs.HasKey ("LevelNumber"))
        {
            Debug.Log("Key Found");
            _currentLevel = PlayerPrefs.GetInt ("LevelNumber");
            levels [_currentLevel].SetActive (true);
        }
        else
        {
            Debug.Log("Key not found");
            PlayerPrefs.SetInt ("LevelNumber",_currentLevel);
            levels [_currentLevel].SetActive (true);
            timeText.gameObject.SetActive (true);
        }
        #endif
    }

    public void nextLevelButtonClick()
    {
        int j = _currentLevel + 1;
        _currentLevel = j;
        PlayerPrefs.SetInt ("LevelNumber",_currentLevel);
        PlayerPrefs.Save ();
        SceneManager.LoadScene (0);
    }

    public void RestartLevelButtonClick()
    {
        SceneManager.LoadScene (0);
    }
}


texts:
This is the first game I have tried to make on PyGame, and I have followed the PyGame Primer tutorial (https://realpython.com/pygame-a-primer/) to do so. I'm practically done, but when I run the game, it runs incredibly slowly when I provide no input. when I spam-click an arrow key, the game will run smoothly, but if I don't do anything or hold down a key, it will run at < 10 FPS. How could I change it so that it will run consistently regardless of input? This is my code:

import pygame
import random
from pygame.locals import *

FPS = 25
fpsclock = pygame.time.Clock()

class Player(pygame.sprite.Sprite):
    def __init__(self):
        super(Player, self).__init__()
        self.image = pygame.image.load('Images/Star-Rider.png').convert()
        self.image.set_colorkey((0, 0, 0), RLEACCEL)
        self.rect = self.image.get_rect()

    def update(self, pressed_keys):
        if pressed_keys[K_UP]:
            self.rect.move_ip(0, -20)
        if pressed_keys[K_DOWN]:
            self.rect.move_ip(0, 20)
        if pressed_keys[K_LEFT]:
            self.rect.move_ip(-20, 0)
        if pressed_keys[K_RIGHT]:
            self.rect.move_ip(20, 0)

        if self.rect.left < 0:
            self.rect.left = 0
        elif self.rect.right > 800:
            self.rect.right = 800
        if self.rect.top < 0:
            self.rect.top = 0
        elif self.rect.bottom > 600:
            self.rect.bottom = 600

class Enemy(pygame.sprite.Sprite):
    def __init__(self):
        super(Enemy, self).__init__()
        self.image = pygame.image.load('Images/Hand-Projectile.png').convert()
        self.image.set_colorkey((0, 0, 0), RLEACCEL)
        self.rect = self.image.get_rect(center=(random.randint(820, 900), random.randint(0,600)))
        self.speed = random.randint(5,20)

    def update(self):
        self.rect.move_ip(-self.speed, 0)
        if self.rect.right < 0:
            self.kill

pygame.init()

screen = pygame.display.set_mode((800,600))

ADDENEMY = pygame.USEREVENT + 1
pygame.time.set_timer(ADDENEMY, 1000)

player = Player()

enemies = pygame.sprite.Group()
all_sprites = pygame.sprite.Group()
all_sprites.add(player)

running = True

while running:
    for event in pygame.event.get():
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                running = False
        elif event.type == QUIT:
            running = False
        elif event.type == ADDENEMY:
            new_enemy = Enemy()
            enemies.add(new_enemy)
            all_sprites.add(new_enemy)

        pressed_keys = pygame.key.get_pressed()

        if pressed_keys:
            player.update(pressed_keys)

        enemies.update()

        screen.fill((135,206,250))

            screen.blit(entity.image, entity.rect)

        if pygame.sprite.spritecollideany(player, enemies):
            player.kill()

        pygame.display.flip()

        fpsclock.tick(FPS)

Thank you for taking the time to read this! Any advice would be much appreciated!


texts: Creating a simple 2d engine (C++), best way to create an Sprite class?

texts:
Since MS announced that they are not give more support to XNA , for me was an opportunity to start to learn DirectX , so i wanted to learn DX11,
i was following this tutorials

http://www.rastertek.com/tutdx11.html

i want to build a simple 2D engine while im learning with basic thing,like render an sprite based on a spritesheet, ,animate it, scale, rotation, flip image

I started creating some simple basic structure,

Engine Class, this hold the initialization of the Window basically
RenderManager class, this hold all the DX stuff, initialize it, create the swapchain, store the device , etc

So now my next step is create the Sprite class , i wanted to create an method called "Quad2D" inside my RenderManager, so i can use it on my render method in my sprite class

//This is not actual code, is just oh i want to approach this
class Sprite{

public void Render(RenderManager *rm){

    rm->Quad2D(Texture,Position,Width,Height);

}
}

i have some experience with OpenGL and Directx9 and with those, it was easy to approach this, i just needed to create an Array with the vertices, send to the VertexBuffer, bind the Texture, and done

but because now DX10 and DX11 not used fixed pipeline, and you need create this with more advanced stuff (Shaders)

i stopped in here http://www.rastertek.com/dx11tut11.html , i can see how to render the image and everything, but i was thinking, do i need to create an separate Class just to render a Quad? if so, is this going to compile the shader everytime is used?, well one solution maybe is just declare an static atribute for the ps and vs and it will shared the same compiled shader within the instances

so i would like to hear how do you manage your Sprite class?

if is it necessary, i can attach my source code, but it doesnt has too much, just open a window

Note: i want to know how to do it in DX11, please dont reply, (used DX9,OpenGL,DX10, etc..)


texts:
On one of the slides of their presentation "Batch, Batch, Batch!" guys from NVidia suggest encoding animation matrices for pallet skinning into two float4s as:

• axis/angle
• translate/uniform scale

I wonder how can that be done (including decoding) and why do they say that this leads to:

Video memory overhead: model replication


texts: Clarifications about usage of delegates, events and coroutine in a Unity script

texts:
So, the question is a bit broad, but I need to clarify my ideas about how to use proficiently such tools.

Background: I am writing a simple demo that basically does what simcity does: it start a game, create a player entity, a city entity, set up the various electricity/gas/water services and generic bozo that will be part of the population of the city.
On top of that, the game spawn X competitors, each with a city on their own, so there is a sense of urgency in having the city up and running, and have it running properly.

This is by no mean a sim city clone; I am just using it to learn further the various aspects of a game, and since I know sim city in and out, and there is virtually no specific material for such games (because all love to do either 2d games, FPS, RPG or RTS, even in training material), it seems the best way to learn something related to the real world.

Now, done with the background and back to the question.

The demo start when you create a new game, spawn all the needed entity, and tehn goes on by cycles; where one cycle can be either 1 min, 5 min, 1 hour...whatever time you deem correct. When a cycle pass. I need to be sure that

The player expenses are deducted by the bank account
UI is updated
AI players has their expenses subtracted and cash updated
AI entities behave coherently, either driving around the city or going back home (imagine a night-day cycle).

In the beginning I just told myself that I could use a coroutine; where I loop into it, until each entity (AI, Player, AI citizens), are done with their workload, and when all 3 are done, I change a bool to set the coroutine bool to false, so a new cycle can start.

public class EntityCitizen()
{
    public bool runCitizenloop()
    {
        //do your things here
        return true;
    }
}

public class EntityPlayer()
{
    public bool runPlayerloop()
    {
        //do your things here
        return true;
    }
}

public class EntityAIPlayer()
{
    public bool runAIloop()
    {
        //do your things here
        return true;
    }
}

public class GameManager()
{

    private cycle = 0;

    public Awake()
    {
         StartCoroutine("cycleloop", 10f);
    }

    IEnumerator cycleloop(float cyclelenght)
    {
        while (!EntityAIPlayer.runAILoop() && !EntityPlayer.runPlayerLoop() && !EntityCitizen.runCitizenLoop())
        {
            // wait until all is done
            yield return void;

        }
        Debug.Log("A cycle has passed");
        cycle += 1;
    }
}

This feel somehow off to me, so before code a mess, I thought that it is better to think further about it. I realized that C# has delegates and events; which I could use to trigger the other way around, activities and updates on the various agents; every time that a cycle in the coroutine is done.

But even in this way, I see that something is off; the whole game cycle revolve around each entity completing their actions, and this means that somehow, they have to execute at the same time in parallel (so use coroutines), and also they have to happen in sequence (since an AI mayor can't have more turns than a player, just because he is faster).

What would be the correct way to lay down the overall architecture, to guarantee that each entity is finishing their workload, before that a new cycle may start?

I thought of coroutine for each entity, with events that fire once they are done, which trigger the new cycle in the main coroutine. Would that be correct or am I missing something?


texts:
I've got a pathfinding boss enemy that seeks the player using the A* algorithm.  It's a pretty complex environment, and I'm doing it in Flash, so the search can get a bit slow when it's searching over long distances.  If the player was stationary, I could just search once, but at the moment I'm searching every frame.  This takes long enough that my framerate is suffering.

What's the usual solution to this?  Is there a way to "replan" A* without redoing the entire search?  Should I just search a little less often (every half-second or second) and accept that there will be a little inaccuracy in the path?


texts: 2D Spatial partitioning alternatives to spatial hashes and quadtrees

texts:
I've been trying to implement a spatial partitioning algorithm in my game, but both spatial hashes and quadtrees aren't what I'm looking for.

My level size is not supposed to have a limit (only Int32 limits). I need a spatial partitioning algorithm that doesn't need a "Level Width" and a "Level Height".

I have many moving physical objects. I need the algorithm to be fast enough to support 500+ objects.

Any alternative?


texts: How could I implement something like Minecraft's crafting grid?

texts:
The crafting system in Minecraft uses a 2x2 or 3x3 grid. You place ingredients on the grid, and if you put the right ingredients in the right pattern, it will activate the recipe.

Some interesting points about the design:

Some recipes can exchange certain ingredients for others. For example, a pick uses sticks for the haft, and may use wooden planks, cobblestone, iron ingots, gold ingots, or diamond gems for the head.
Relative position within the pattern is what matters, not absolute position on the grid. That is, you can craft a torch by placing the stick and coal (or charcoal) in the correct pattern in any of six positions on the 3x3 grid.
Patterns may be flipped horizontally.

I may be overthinking it, but this seems like an interesting search/set-reduction problem. So, how does (or could) this work, algorithmically speaking?


texts:
I recently learned how to create shaders and was looking to make a simple top down game, starting with a tilemap. The problem I encountered, Whilke I can store a vbo of all the blocks in a "chunk" of blocks, I can't specify what texture it should have... or at least I don't see how! I could just bind the texture using GL.BindTexture() function, but that would only allow me to use one texture in the whole chunk! I don't know how many textures I might render, it could certainly be more than 8! Is there a way to bind a texture inside a vertex shader?

I basicly would like to do something like "Display Lists" in earlier opengl versions... but I want to use modern opengl techinques as much as possible!


texts: Linking error at tessellation shaders in GLSL

texts:
I'm testing the triangle tessellation from the link http://prideout.net/blog/?p=48#shaders . All the shader are compiled correctly, but when I try to link the program using the command:

glLinkProgram(programID);

I got the following error:

Tessellation control info
(0): error C6029: No input primitive type
----------------------------------------
Tessellation evaluation info
(0): error c7005: No tessellation primitive mode specified
-----------------------------------------------------------
Geometry info
(0): error C6022: No input primitive type
(0): error C6029: No ouput primitive type
----------------------------------------
Not valid

It's so strange I declare output for TC Shader using command:

layout(vertices = 3) out;

And input layout for TE shader using command:

layout(triangles, equal_spacing, cw) in;

Why I still got this error?
I hope to see you answer about it.

I put my shaders in below:

Vertex shader:

#version 410 core

in vec4 Position;
out vec3 vPosition;

void main()
{
    vPosition = Position.xyz;
}

TC shader:

#version 410 core

layout(vertices = 3) out;
in vec3 vPosition[];
out vec3 tcPosition[];

#define ID gl_InvocationID

void main()
{
    float TessLevelInner = 3;
    float TessLevelOuter = 2;
    tcPosition[ID] = vPosition[ID];
    if (ID == 0) {
        gl_TessLevelInner[0] = TessLevelInner;
        gl_TessLevelOuter[0] = TessLevelOuter;
        gl_TessLevelOuter[1] = TessLevelOuter;
        gl_TessLevelOuter[2] = TessLevelOuter;
    }
}

TE Shader:

#version 410 core
//TessEval

layout(triangles, equal_spacing, cw) in;
in vec3 tcPosition[];
out vec3 tePosition;
out vec3 tePatchDistance;
uniform mat4 Projection;
uniform mat4 Modelview;

void main()
{
    vec3 p0 = gl_TessCoord.x * tcPosition[0];
    vec3 p1 = gl_TessCoord.y * tcPosition[1];
    vec3 p2 = gl_TessCoord.z * tcPosition[2];
    tePatchDistance = gl_TessCoord;
    tePosition = normalize(p0 + p1 + p2);
    gl_Position = Projection * Modelview * vec4(tePosition, 1);
}

Geometry shader:

#version 410 core
//geometry shader
layout(triangles) in;
layout(triangle_strip, max_vertices = 3) out;
in vec3 tePosition[3];
in vec3 tePatchDistance[3];
out vec3 gFacetNormal;
out vec3 gPatchDistance;
out vec3 gTriDistance;
uniform mat4 Modelview;
uniform mat3 NormalMatrix;

void main()
{
    vec3 A = tePosition[2] - tePosition[0];
    vec3 B = tePosition[1] - tePosition[0];
    gFacetNormal = NormalMatrix * normalize(cross(A, B));

    gPatchDistance = tePatchDistance[0];
    gTriDistance = vec3(1, 0, 0);
    gl_Position = gl_in[0].gl_Position; EmitVertex();

    gPatchDistance = tePatchDistance[1];
    gTriDistance = vec3(0, 1, 0);
    gl_Position = gl_in[1].gl_Position; EmitVertex();

    gPatchDistance = tePatchDistance[2];
    gTriDistance = vec3(0, 0, 1);
    gl_Position = gl_in[2].gl_Position; EmitVertex();

    EndPrimitive();
}

Fragment Shader:

#version 410 core
//fragment shader
out vec4 FragColor;
in vec3 gFacetNormal;
in vec3 gTriDistance;
in vec3 gPatchDistance;
in float gPrimitive;
uniform vec3 LightPosition;

float amplify(float d, float scale, float offset)
{
    d = scale * d + offset;
    d = clamp(d, 0, 1);
    d = 1 - exp2(-2*d*d);
    return d;
}

void main()
{
    vec3 AmbientMaterial = vec3(0.04f, 0.04f, 0.04f);
    vec3 DiffuseMaterial = vec3(0, 0.75, 0.75);
vec3 LightPosition = vec3(0.25, 0.25, 1);
    vec3 N = normalize(gFacetNormal);
    vec3 L = LightPosition;
    float df = abs(dot(N, L));
    vec3 color = AmbientMaterial + df * DiffuseMaterial;

    float d1 = min(min(gTriDistance.x, gTriDistance.y), gTriDistance.z);
    float d2 = min(min(gPatchDistance.x, gPatchDistance.y), gPatchDistance.z);
    color = amplify(d1, 40, -0.5) * amplify(d2, 60, -0.5) * color;

    FragColor = vec4(color, 1.0);
}


texts: How can I access bitmaps created in another activity?

texts:
I am currently loading my game bitmaps when the user presses 'start' in my animated splash screen activity (the first / launch activity) and the app progresses from my this activity to the main game activity,

This is causing choppy animation in the splashscreen while it loads/creates the bitmaps for the new activity.

I've been told that I should load all my bitmaps in one go at the very beginning.

However, I can't work out how to do this - could anyone please point me in the right direction?

I have 2 activities, a splash screen and the main game.  Each consist of a class that extends activity and a class that extends SurfaceView (with an inner class for the rendering / logic updating).

So, for example at the moment I am creating my bitmaps in the constructor of my SurfaceView class like so:

public class OptionsScreen extends SurfaceView implements
  SurfaceHolder.Callback {

      //Create variables here

 public OptionsScreen(Context context) {

Create bitmaps here
}

public void intialise(){                         //This method is called from onCreate() of corresponding application context

// Create scaled bitmaps here (from bitmaps previously created)

}


texts:
I've already uploaded this question in the Unity forums but only got a response but not an answer or solution. Here's a link to the original post: https://forum.unity.com/threads/emission-material-on-top-of-ui.1032337/?fbclid=IwAR1X3sXn1X8XcEXHXjD3wffiQxuDK6KAjMF57XDv9RUb1FsofklORfDeRm0
In my latest project I tried to do a transition between scenes in the most simple way: Darkening the screen.
The problem is, when the image goes fully opaque (alpha = 1), there are emission materials that are clearly visible "through" the image.
This only happens to the emission type:
I'll leave three screenshots, screen before the image gets opaque, the screen after the image goes opaque and my canvas components.
Edit: Using UniversalRP - HighQuality(UniversalRenderPipelineAsset)


texts: How to project a Matcap correctly in Amplify Shader Editor

texts:
Unity's Amplify Shader Editor comes with an example of matcap nodes setup, however, the matcap projection in this example is incorrect.
As you can see the texture becomes distorted when it's on de edges of the screen, that shouldn't happen with a correct matcap:

On the secoud image, this is how a matcap should look, without major distortions.
Does any expert in shaders knows the right way to project a matcap using the nodes? I've done my search and there is absolutelly no information about this around the internet, any response would add for this Shader documentation.
I'm extremelly in need that matcap works with this shader.


texts: Getcomponent(), GameObject, and Component issues

texts:
I have been trying for over 2 hours now to get over these problems :

I have 2 GameObjects in my hierarchy, but I do not have them anywhere in any script. I would very much like to add those 2 objects into a script of mine. I used

GameObject thing1 = new GameObject("name of object");

but unfortunately this didn't work, gave me errors about how I can only create objects from main script? I pasted my code into game.cs, and added the game.cs script to the 2 objects I want, but I get the exact same errors.

So the reason for this problem is that I need to actually add those 2 objects in my lines of code, so I can use GetComponent(); to be able to modify the enabled status of my script. So the other problem here, is that when I use GetComponent on the 2 objects, I get a nullreference exception. I am very sure that I added the script to both the objects, and I'm pretty sure I didn't mistype them, so can anyone give me a hand please?


texts: 2d diagonally velocity greater than straight-line velocity. How to fix?

texts:
If I have a topdown rpg type game. And movement in 8 directions (N/E/S/W/NE/NW/SE/SW) in a 2d game that involves both x and y velocity. I'm finding when i'm moving in the diagonal directions i'm building both x and y velocity and its making my character move faster than they do in straightline directions. Is there a fix for this so no matter what of the 8 I travel its the same speed?
so say...
vel_x, vel_y=0
spd=1
then in my gameloop
vel_x*=0.2
vel_y*=0.2
Then my button presses add/subtract the spd value from their corresponding velocity direction x/y when pressed.
then I add the vel_x to my x sprite position and same with vel_y for my y sprite
How would I address this...? Would I look at btn press actions for when both keys are
held....or limits for when vel_x AnD vel_y are 'high' enough in tandem....
I've done the latter and it helps but I can't make it accurate.
Images: With velocity removed and just +-1 speed increases/decreases. Left is the proposed adjustment to the vertical movement. Right is no adjustment. Is Left moving at same speed all the time and right isn't?


texts: How do I randomly generate a top-down 2D level with separate sections and is infinite?

texts:
I've read many other questions/answers about random level generation but most of them deal with either randomly/proceduraly generating 2D levels viewed from the side or 3D levels. What I'm trying to achieve is sort of like you were looking straight down on a Minecraft map. There is no height, but the borders of each "biome" or "section" of the map are random and varied. I already have basic code that can generate a perfectly square level with the same tileset (randomly picking segments from the tileset image), but I've encountered a major issue for wanting the level to be infinite: Beyond a certain point, the tiles' positions become negative on one or both of the axis. The code I use to only draw tiles the player can see relies on taking the tiles position and converting it to the index number that represents it in the array. As you well know, arrays cannot have a negative index. Here is some of my code:

This generates the square (or rectangle) of tiles:

    //Scale is in tiles
    public void Generate(int sX, int sY)
    {
        scaleX = sX;
        scaleY = sY;

        for (int y = 0; y <= scaleY; y++)
        {
            tiles.Add(new List<Tile>());

            for (int x = 0; x <= scaleX; x++)
            {
                tiles[tiles.Count - 1].Add(tileset.randomTile(x * tileset.TileSize, y * tileset.TileSize));
            }
        }
    }

Before I changed the code after realizing an array index couldn't be negative my for loops looked something like this to center the map around (0, 0):

for (int y = -scaleY / 2; y <= scaleY / 2; y++)
for (int x = -scaleX / 2; x <= scaleX / 2; x++)

Here is the code that draws the tiles:

            int startX = (int)Math.Floor((player.Position.X - (graphics.Viewport.Width) - tileset.TileSize) / tileset.TileSize);
        int endX = (int)Math.Ceiling((player.Position.X + (graphics.Viewport.Width) + tileset.TileSize) / tileset.TileSize);
        int startY = (int)Math.Floor((player.Position.Y - (graphics.Viewport.Height) - tileset.TileSize) / tileset.TileSize);
        int endY = (int)Math.Ceiling((player.Position.Y + (graphics.Viewport.Height) + tileset.TileSize) / tileset.TileSize);

        for (int y = startY; y < endY; y++)
        {
            for (int x = startX; x < endX; x++)
            {
                if (x >= 0 && y >= 0 && x <= scaleX && y <= scaleY)
                    tiles[y][x].Draw(spriteBatch);
            }
        }

So to summarize what I'm asking: First, how do I randomly generate a top-down 2D map with different sections (not chunks per se, but areas with different tile sets) and second, how do I get past this negative array index issue?


texts: Any tips for creating cross-platform games?

texts: Do you have any tips/recommendations when creating a cross-platform game in C/C++?


texts: Using Unity as a front-end GUI for a non-unity application?

texts:
I'm working on a game right now that is 2D, and grid based, and for a variety of reasons have decided making it in Unity wouldn't be worth the hassle I'd have fighting the engine.

That said, I want to possibly add in VR support at some point, and Unity seems the easiest way to make that happen.
Right now, the game is structured so that part of the code takes in a grid from the game-core, and that grid tells it what sprite(s) to stick in each spot on said grid.

My thought was that it might be possible to replace the "take grid array, render sprite-grid" portion of my game with a Unity front-end. For example, perhaps this would be like a board game sitting on a table, and rather than a 2D grid, the "sprites" would be simple models on the grid-board, with the user looking down at it in VR.

Is this a thing that is possible? Essentially, all I would need is for my Unity program to take inputs, and send trigger signals to the game-core, then receive an updated grid-array and respond accordingly. I've not been able to find any information on this kind of thing, interfacing Unity with an external program in this way. The game is turn based, so 2-3 updates per second would be the absolute max I'd need, performance-wise, and the game core could run on a potato.

In specific: can Unity send triggers to and receive a data array from an external binary (written in c#), and how would I do this?

I really hope this is possible.


texts:
Im going through a tutorial to create a basic directx framework, and i've noticed that in there (and other tutorials, when i checked out) use DXGI_FORMAT_R32G32B32A32_FLOAT inside the input element description. is there any reason to use this in a program over DXGI_FORMAT_R8G8B8A8_<something> in terms of noticeable graphical difference? im thinking quadrupling the memory involved to store color would be a little heavy for larger programs.

Also, i don't know if i have this right, but pure coloring isn't used much in more complex programs, and textures are used instead. so does this really matter?


texts: Random Y Axis Movement Within Set Limits (C#)

texts:
I've searched everywhere for this answer but everything I find is in Javascript and a lot of it doesn't help/work in my situation since most of it is Vector3's and using each axis, and my game is 2D.

So I have these prefabs that get spawned off-screen and then I have a script attached to them that tells them to move left on the x axis. I need them to also pick a random direction (up or down) on the y axis, and travel that way until they get to a certain spot (range) and then to switch directions and go the opposite etc.

Here is what I have tried most recently:

public float itemUp = 0.1f;
public float itemMove = 0.7f;

public float x;
float y;
float z;
Vector3 pos;

void Update () {

    //transform.position = Vector2(Random.Range (1,4),Random.Range (1,4),10);

    transform.position -= Vector3.right * itemMove * Time.deltaTime;

    x = 0;
    y = Random.Range(-100, 100);
    z = 0;
    pos = new Vector3(-x, y, z);
    transform.position = pos * itemUp * Time.deltaTime;
}

Anyone know what I'm missing/not doing correctly? I'd really appreciate any help you can give, thank you.


texts: How can I use slerp to stop my orbit camera "shortcutting" across to its target position?

texts:
I'm working on a camera that moves around the player at a fixed distance. It's the standard right-stick-to-move-cam-around kind. The camera follows the player but stays at a fixed angle to (0,0,1) until moved by input, and the player is free to move in any direction without changing the camera rotation with respect to the world. Imagine the cam as being a point on an invisible sphere with the player at the centre.

However, there's a problem with it in that when I rotate the camera around the player too fast, the lerping I added to try and smooth the movement tries to "shortcut" across instead of moving around the sphere gracefully when the desired position gets too far away. The image below is a top-down view, the camera takes the red route, but I want it to take the green route while remaining smooth.

Currently I'm:

Checking whether the look controls are inverted, and setting a modifier value.
Updating the current angle to (0,0,1) using the normalized X component of a Vector2 set by keyboard input (cam left, cam right).
Updating the current angle to the Y axis using the Y component, set by input (cam up, cam down).
Finding the desired cam position from the two angles and position of the focus point (player).
Lerping between the current cam position and the desired one and updating the lookAt vector.

Here is the update code (it's in Go which isn't especially common for game dev, but hopefully the syntax should be easy enough to understand what's going on):

// Update the gameplay camera with the focus at focusPos.
func StepGameplayCam(focusPos math32.Vector3, delta float64) {
    invertLookMod := float32(1)
    if settings.Control().InvertLook {
        invertLookMod = -1
    }

    //Get up/down and left/right components and set angles.
    currentAngleToZ = util.WrapAngleRad(currentAngleToZ + float32(movementVec.X*float32(delta)*settings.Control().CamSpeed*invertLookMod))

    if !((movementVec.Y < 0 && currentAngleToY <= math32.DegToRad(15)) || (movementVec.Y > 0 && currentAngleToY >= math32.DegToRad(165))) {
        currentAngleToY = util.WrapAngleRad(currentAngleToY + float32(movementVec.Y*float32(delta)*settings.Control().CamSpeed*invertLookMod))
    }

    distanceToFocus = maxDistanceToFocus //TODO cam collisions/not clipping through things

    //Set desired cam position.
    targetPos.X = focusPos.X + distanceToFocus*math32.Cos(currentAngleToZ)*math32.Sin(currentAngleToY)
    targetPos.Z = focusPos.Z + distanceToFocus*math32.Sin(currentAngleToZ)*math32.Sin(currentAngleToY)
    targetPos.Y = focusPos.Y + distanceToFocus*math32.Cos(currentAngleToY)
    camPos.Lerp(targetPos, float32(delta)) //TODO problem is here, we're LERPing between vectors but we need to do it spherically
    gameCam.SetPositionVec(camPos)

    gameCam.LookAt(&focusPos)

    if settings.Dev().DebugEnabled {
        updateCamDebug(focusPos.X, focusPos.Y, focusPos.Z)
    }
}

I have a strong feeling slerp is what I'm looking for here, but my understanding of 3D mathematics is starting to brickwall at this point, and I have no idea how to use it in this context.

How can I stop my camera from "shortcutting" through the imaginary sphere around the player it is bound to?


texts: How do I create a manual object with colors for each vertex?

texts:
How do I create a shaded manual object with colours for each vertex?
Eg if ogreObj is the Ogre::ManualObject :

ogreObj->begin("BaseWhiteNoLighting", Ogre::RenderOperation::OT_TRIANGLE_LIST);

will allow me to select each vertex's colour with ogreObj->colour(r, g, b)
after each ogreObj->position(x, y, z) and ogreObj->normal(x, y, z) call.

However, if I change the material to BaseWhite, color() instructions are ignored.
I read that you must disable lighting int the .material script, but I need it active...
Any advice?

ANSWER: This Ogre forum's thread has a simple .material script that works for this purpose:

material Voxel/Default
{
   technique
   {
      pass
      {
         diffuse vertexcolour
         specular vertexcolour
         ambient vertexcolour
         lighting on

      }
   }
}


texts: How to avoid the collision of objects that move along a path?

texts:
There are 2 cars (same object) that go through a circuit:

Consider that the white part is an intention that they avoid (it would be as if it were a wall). The black part (circuit) would be just illustrative, it is not an object.
In the program the room looks like this:

Green -> background
Red square -> car
Other light colored squares -> points that are followed by the cars (to go through the circuit)
Black square -> wall

The walls are avoided as follows:
mp_grid_add_instances(grid,obj_Wall,false);

In addition to the walls, I would like cars to avoid each other. I did it as follows:
repeat(instance_number(obj_Car)){
    i++;

    if(instance_find(obj_Car,i-1).id!=id){
        carOtherID=instance_find(obj_Car,i-1).id;
        mp_grid_add_instances(grid,carOtherID,false);
    }
}

It happens more or less like this:

Cars avoid the starting position of other cars, but I would like you to avoid the current position of other cars. For that, I put this part of the code in the step event:
mp_grid_add_instances(grid,carOtherID,false);

I tried some changes, with some conditions, but none worked. Simply buggy, cars even go through walls (something that shouldn't happen, because I don't even change anything in them).
Documentation:
https://manual-en.yoyogames.com/#t=GameMaker_Language%2FGML_Reference%2FMovement_And_Collisions%2FMotion_Planning%2Fmp_grid_path.htm&rhsearch=mp_grid_path&rhhlterm=mp_grid_path


texts:
I've been working on a game engine and I model every object in my scene graph as an "entity" this includes my camera.

My camera therefore has a position and rotation in world space and at the moment I am able to create a view matrix by taking the inverse of the cameras world space matrix.

However when I do this the camera looks in the opposite direction to what I would expect.

Why is that so?


texts: Tiled2Unity depth sorting issue with multiple layers

texts:
I have been struggling with an issue for a couple of days now trying to get depth sorting properly when using multiple layers in tiled.

My tiled map is set up as follows:

The sorting Layers I have in unity are:

Tiled to Unity sorting layers map as follows:

Background : Level 0

Background Noise : Level 0

Shadows : Level 0

Paths : Level 0

Tree Bases : Level 1

Tree Tops : Level 2

House Bases: Level 1

Objects ( crates and barrels ) : Level 1

House Roofs : Level 2

House Roof Items : Level 3

I have set the player sprite to be on sorting layer 1 along with the tree stumps, walls and floor objects.

When exporting to unity I'm ticking the check box for Use Depth Buffer as below:

Now the problem I am having is that when setting the layer to interact with on the Sprite Depth in map script I can only seem to make one layer work at a time.

eg, if I set it to interact with the tree bases layer, then the depth sorting works on there, but the character appears below the walls and the crates etc, but  if I set the layer to interact with the objects layer then the character is always  on top of the tree trunks rather than behind.

Interacting with tree layer

Interact with object layer

If I have one layer with the tree trunks, walls and objects (crates, barrels etc) and interact with this layer then it works as expected, but with only one layer in tiled I cant put the barrels in front of the house, or trees behind the house etc.

Is what I'm trying to do even possible with Tiled2Unity? or should I be doing something else?

Any pointers would be appreciated.


texts: Screen transition effect like subway surfers

texts:
I would like to know how can I achieve this kind of screen transition effect ? The effect is screen independent.

https://www.youtube.com/watch?v=Muh7QFisCfE#t=01m57s


texts: How do I use threads together with DirectX11?

texts:
I have only found the documents on MSDN: http://msdn.microsoft.com/en-us/library/windows/desktop/ff476884(v=vs.85).aspx Although it doesn't say anything about creating them, it mentions that device is thread-safe while device context is not.

Does the framework use threads by itself (if driver supports it) when it thinks it's more optimal? Or do we have to use some external library like BOOST to play around with threads?


texts: Calculating distance in procedurally generated mesh LOD system

texts:
I'm creating a procedurally generated planet mesh based on quadtree splitting to support LOD system. I cannot find any relevant info how can I calculate distance between the camera and LOD chunks.
I have a surface view in my game where the camera is near at the planet surface and can move around the planet, it has also some zoom levels (elevation of the camera) but camera always looks in the direction to the surface like in strategy games.
A: Should I use simple distance calculation between the camera and the center of the chunk mesh or edge vertices of the mesh?
B: Is it better when I use Great-circle distance?
C: How should I modify the calculation when camera's elevation can be changed?
D: How can I determine the distance limits for each LOD level? Does it depend on the project or does it have some basics?
Update #1:
Here is a sample when I use simple distance calculation between the center vertex of the meshes and the camera object:

the camera is right above the point A
point A is the center of the level 0 mesh (it is not visible because it is already divided)
when the camera reaches the distance limit of B (which is a level 1 mesh and it is already divided in the sample) then it will be divided into four meshes where the centers are C, D, E, F
at this time the mesh where the center point is F will be also divided because the distance of the previously generated F point is under the current LOD level minimum distance

So the base problem this: after dividing a mesh the new submeshes can be also divided because the distance is under the current LOD level minimum distance. And I think it does not work like a normal LOD system because there is a level 1 neighbour next to level 3 mesh.

Update #2:
I tried some approaches to get the right distance calculation:

minimum distance between the corner edges (4) and the camera
minimum distance between the edge center vertices (4) and the camera
minimum distance between the corner and edge center vertices (8) and the camera

Important thing: I use great-circle distance calculation.
I got wrong results using these until I created a new algorithm to define transition distance limits. Maybe it is not a very well algorithm but currently this is the most acceptable result. Here is the algorithm:

Note: ignore the heightmap (noise) during the calculation, only a simple sphere with radius R is used

calculate the width of each meshes (arc length)
decrease the distance limit in each LOD level

float meshSphericalWidth = 2 * Mathf.PI * _shapeGenerator.Radius * (90 / (float)(CurrentLevelOfDetail + 1) / 360f);
float currentTransitionLimit = meshSphericalWidth * Mathf.Pow(0.90f, CurrentLevelOfDetail + 1);

After this distance calculation change I didn't notice any significant difference when I use the corner or the edge vertices to get the minimum distance.
And I got this. Green is LOD1, yellow is LOD2 and red is LOD3.

It seems a good progress but we can see sometimes between two chunks the LOD level difference is 2.
Can I fix it with another distance calculation adjustments or is it a different story? I want to solve the cracks between meshes.


texts: How to change a background from a list of images on button click?

texts: I'm trying to create a button within the settings menu that allows you to change the image of a GameObject per click. So, let's say there are only 2 different images available to choose from and it starts with Image1, if you press the button it changes to Image2 and if you press again it goes back to Image1, like a loop. My issue is on how to write the script for this.


texts: Effective & Efficient Way to Simulate a Desert

texts:
Introduction

I hope that this question isn't too broad, my apologies if it is. Anyway, getting to the point, our video game is set in ancient Egypt and, to nobody's surprise I'm sure, Egypt has a lot of sand in it. Sand is one of those substances that is notoriously difficult to simulate, however, in order to create a realistic desert I do have to deal with that aspect. Additionally, it also allows for the landscape to gradually change, which isn't just what real deserts do all the time, but it will also aid with making large stretches of desert seem a bit more interesting.

My primary concern is managing it in real time. On small scales, sand flows almost like a fluid, which needs to be done as characters interact with it, but even as a whole, a desert changes rapidly (compared to most other landscapes) as a result of environmental effects; sand moves, entire dunes displace themselves in a matter of days, and tracks created by humans and animals can quickly dissipate.

Current Approach

Hence I am requesting methods that are good at achieving all these effects in an efficient manner. Personally, I was thinking about using the incompressible Euler equations utilising Lagrangian mechanics, thus working with particles, and then using something like Marching Cubes to render. However, it sounds like that'd be extremely time–consuming, so I wonder if there's a different, better approach.

Technology

Currently we're working on our own game engine that is written in C and uses Vulkan as the primary, and probably only, graphics API. Hence, plenty is possible, although we'd prefer to keep the number of dependencies down to a minimum.

Thanks a lot in advance.


texts: Draw user interface in OpenGL using web technologies

texts:
I am developing a desktop game in C++ and OpenGL. Frameworks I use are GLM and SFML. Since today I used the console window for debug messages. But I want to get rid of that and display debug information right into the render window.

Since I also want to implement a generic way to realize user interface, I decided to use web technologies for that. Note that the user interface will be only a two dimensional overlay on the rendered three dimensional scene. I consider using the webkit browser engine but that might be overkill since I do not need page loading and networking but only HTML and CSS rendering (and maybe JS execution). Because the user interface and debug messages will change every few frames, this is performance related.

How to render fullscreen webpages (with a transparent background) over my OpenGL scene? I would like a cross-platform solution.


texts: Should the main game object be static in c++

texts:
I am creating a 2d platformer using SDL and I was thinking that my game object could be static, but I wasn't sure if this was a good idea.

The pros (that I can see):

Accessing settings options (such as screen size and keyboard bindings) would be easier accessed
There should only ever be one main game loop, so this makes sure for me.

The cons:

From what I've heard, static classes in C++ are a bear to work with
I've read that this may cause problems later in development (things don't work right or can't be used properly


texts:
I'm using libGDX for my android game in which I'm trying to use bitmap fonts. I have created .fnt and .png bitmap files using Bitmap font generator of angel code.Both .fnt and .png have been placed under same folder /asset/data in my project.

Now when I try to run my project I get exception errors. Here is my sample code -

FileHandle handle = Gdx.files.internal("data/calib.fnt");
FileHandle handle2 = Gdx.files.internal("calib_0.png");
font = new BitmapFont(handle,handle2,true);
font.draw(batchmaker, "abcdef", x,y);

The error on console looks like this (showing only relevant lines):

  Exception in thread "LWJGL Application"
  com.badlogic.gdx.utils.GdxRuntimeException: Error loading font file:
  data/calib.fnt . . . at
  com.badlogic.gdx.graphics.g2d.BitmapFont$BitmapFontData.(BitmapFont.java:809)
  Caused by: com.badlogic.gdx.utils.GdxRuntimeException: Invalid font
  file: data/calib.fnt

I do not believe this error has something to do with issue with paths, because it gives me different errors when I play around by changing the paths.

I have been trying to fix this since almost last 2 days but couldn't come up with a solution. Can someone please let me know what could be the problem or am I missing something?

Edit: Or could there be some checks in which the parameters of calib.fnt is not passing (due to upper/lower case name mismatch with libGDX lib files) ? Please help!


texts: Remove or skip splash screen from Unity Free/Personal game binary for modding

texts:
How can I modify a Unity game (Windows) binary to skip the 5-second Unity logo splash screen?
I know how to mod game code using dnspy to modify Assembly-CSharp.dll. I'm able to find isShowingSplashScreen but that appears to be irrelevant. I'm at a loss whether I can find the splash screen code in any .dll or if one would have to edit the game .exe or some other file.
Looking at the game .exe in HxD (hex editor), I see multiple occurrences of unity_SplashScreen but have no idea whether I can use this for anything.
Background
I'm modding a Unity game and I am not very good at it. I have to try a lot and start the game a lot. This means each time I test something, I lose five seconds because the game was made with the free Unity version.
As a player I made no commitment to the Unity ToS. I also have no intent to distribute a modded file that removes the splash screen. However, I want to remove it during development.
I am not asking how to remove the splash screen while building the game. I am not developing in Unity, I am modding a game made in Unity and I'm trying to streamline the process.
I did see Unity remove logo in splash screen, Alternatives to remove Unity splash screen after developing a game with the free version?, Can I legally remove the default Unity splash screen by removing it from the APK?. They revolve around the question of removing the splash screen with intent to distribute, which is not the topic here.
I had hesitations about asking this question, due to the answer being useful to developers willing to violate the ToS. However it seems on-topic and legal. I would also argue that the solution to my problem is probably going to be too much effort for active game dev projects to bother using it (having to repeat the steps for each new update) and that "bad apple" devs would rather use pirated versions of Unity Pro.


texts: Canvas - darken sprites rendered by drawImage

texts:
I am implementing lighting in a tile engine, and I need a way to darken tiles, based on their light level.

For the ground tiles, I can clear the context to black, then set the globalAlpha and use drawImage normally. But what about foreground tiles, such as trees? I don't want them to be translucent, just darker. Is there any way to filter the output of drawImage?


texts: Equivalent of glDrawTexfOES in OpenGL ES 2.0?

texts:
I have been using the glDrawTexf extension to draw labels in my Android app using OpenGL ES 1.1.

But I have now moved to OpenGL ES 2.0 and can't figure out what is the equivalent of this call? I could create triangles to hold the texture and draw it like a regular texture. But the glDrawTexf was very convenient:

It didn't require any triangles/quads to be setup.
You could give it screen co-ordinates.
You could specify cropping parameters to pick smaller areas from a large texture.


texts: After changing the mouse cursor texture how can i resize the texture/cursor and how to center it?

texts:
I want to center it to the middle of screen.

And the size i tried to make both width and height  * 0.02f but it's still too big when running the game.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.Characters.FirstPerson;

public class RotateObject : MonoBehaviour
{
    public Texture2D cursorTexture;
    public CursorMode cursorMode = CursorMode.Auto;
    public bool autoCenterHotSpot = false;
    public Vector2 hotSpotCustom = Vector2.zero;
    private Vector2 hotSpotAuto;

    void Awake()
    {
        Cursor.lockState = CursorLockMode.Locked;

        Vector2 hotSpot;
        if (autoCenterHotSpot)
        {
            hotSpotAuto = new Vector2(cursorTexture.width * 0.02f, cursorTexture.height * 0.02f);
            hotSpot = hotSpotAuto;

        }
        else { hotSpot = hotSpotCustom; }

        Cursor.SetCursor(cursorTexture, hotSpot, CursorMode.ForceSoftware);
    }
}

In the screenshot the mouse cursor is the image on the left in the game view and it's not in the center it's a bit on the right bottom(The ball is the mouse cursor). On the right the inspector of the script. The script is attached to the FPSController.


texts: How should we be storing procedurally generated behavioural code?

texts:
Me and a group of friends are developing a game and we've run into a road block. Before we describe that road block, here's a simplified explanation of our game:

The game will be able to take in a song in .wav format, and from that song procedurally generate a "level" whose elements and features vary depending on the properties of the song.

Seems simple enough on the surface (aside from the massively understated complexity of the procedural generation algorithms), but there's a problem. We want to be able to store the procedurally generated content in some portable format, but we also want to be able to execute it very quickly.

Here's the deal. The procedurally generated objects all have procedurally generated behaviours. They each have an update "method" that encapsulates this behaviour. The behaviour may be something like "if position is some position, do something" or "do this 10 times in a for loop", or something else (most likely only very simple code).

So I was thinking of using the bytecode pattern, and writing a very basic language in which we could encode the behaviour of each object. There's a problem with this though; there's a good chance it won't be fast enough.

On screen at once there will be thousands of these objects with procedurally generated behaviours. If the behaviours were coded in the native language (C# by the way), it would most likely be fast enough, but since we would be parsing and executing our own language bytecode in C# there would be a lot of added overhead that we think is enough to make our game unplayable.

Of course, we haven't tried implementing our own language to see if it actually would be fast enough, but we're kind of on a tight time constraint and don't want to take the risk of wasting time implementing something that won't work.

What should we do?


texts: Why is fog in games exponential and has a start distance?

texts: In most tutorials I see on how to achieve fog with shaders the fog is exponential and has a minimum / start distance from the camera. Why? Both seem counterintuitive, especially the minimum distance. Is this an artistic / design choice or is this how our eyes see fog in real life?


texts: Will a better CPU (or one with more cores) reduce Unity script compile time?

texts: It usually takes 10-15 seconds to compile for small changes in any of the scripts in my project. The project contains over hundred scripts, which are in C#.


texts: A game that can balance itself over time?

texts:
So after reading some history and learning about how some countries were allowed to survive by stronger countries, just so that a power gap wouldn't exist. That being said, we can assume that if this power gap did exist, eventually the world will rebalance itself one way or another.

Would that be applicable in games? Can a game (for example, Overwatch or any MMORPG) balance itself over time whether the imbalances are a result of how the classes are built or even the population of people in every faction?

I thought about it a lot and I tried finding dissimilarities between my real world example and games.

In games, you are allowed to have many identities. You can essentially have a character in every faction. In a game like OW you can pick any hero. You don't have a fixed identity that defines you like IRL so cloning the idea of a "Country/Nation" in real life to a game is nearly impossible as developers don't have power over how many characters/factions the player can have.
Nations have finite resources. All MMOs I played have infinite resources which simply doesn't make sense compared to the real world. Finite resources is what makes nations great whether by smart utilization of said resources or conquering/invading other nations.

That being said, I still have a feeling that it's possible, one day, to have a game that can balance itself over time. But to achieve that, I believe we need to put many constraints on the gameplay to mimic real life constraints that "define" a nation.

What do you guys think? What would those constraints be?


texts:
Im working on a small project to learn the basics of post-processing, shaders and other effects in Unity.
My project is in 2D, so I followed this Brackey's tutorial and this tutorial. The bloom effect did not work for me with the expiremental 2D renderer, so I used a forward renderer instead.
Problem is, now all of my gizmos (including the camera's gizmos) are gone!
Anyone knows what could be the problem? Do I need to set something in the renderer so it will show?


texts: How to make something happen every N seconds in game?

texts: I want to have something happen every N seconds, how would I do that? Maybe use a timer but how?


texts: IsoSurface Normals\Texture Coords Problems(DX11\SharpDX)

texts:
Hi and thanks for your time!

So over the past few days I have been playing with isosurface construction from volume textures, I have it running on the cpu and all is well from a "just got it working" stand point eg. surface reconstruction works and I have my really cool voxel mesh drawing.

I have based my code(converted to VB.net) on Paul Bourke's work here: Polygonising a scalar field
and like I said it works well apart from the fact that my normals are wrong and I have these strange fully black on both sides triangles, I think I'm doing my normals wrong but the way they are now is the beast I can get, I tried a few ways to build the normals and this one is the only way I could get smooth normals.

Here you can see how my normals are wrong, green should be up, gray\dark should be unlit and the hay'ish colour is the lit side.

I have tried to flip and invert them but as you can see they are not wrong all the same way.

HLSL Normals 1st try:

float3x3 cotangent_frame(float3 N, float3 p, float2 uv)

// get edge vectors of the pixel triangle
float3 dp1 = ddx(p);
float3 dp2 = ddy(p);
float2 duv1 = ddx(uv);
float2 duv2 = ddy(uv);

// solve the linear system
float3 dp2perp = cross(dp2, N);
float3 dp1perp = cross(N, dp1);
float3 T = dp2perp * duv1.x + dp1perp * duv2.x;
float3 B = dp2perp * duv1.y + dp1perp * duv2.y;

// construct a scale-invariant frame
float invmax =   -sqrt(max(dot(T, T), dot(B, B)));
return float3x3(T * invmax, B * invmax, N);

HLSL Normals 2nd try:

NormalData CalcWS_Normal(float2 WS_TexCoord, float3 WS_Pos)

NormalData dout;

float3 dp1 = ddx(WS_Pos);
float3 dp2 = ddy(WS_Pos);
float2 duv1 = ddx(WS_TexCoord);
float2 duv2 = ddy(WS_TexCoord);

float3x3 M = float3x3(dp1, dp2, cross(dp1, dp2));
float2x3 inverseM = float2x3(cross(M[1], M[2]), cross(M[2], M[0]));

float3 t = mul(float2(duv1.x, duv2.x), inverseM);
float3 b = mul(float2(duv1.y, duv2.y), inverseM);
float3 normal = normalize(cross(normalize(b), normalize(t)));

dout.Normal = normal;
dout.Tang = t;
dout.BiTang = b;

return dout;

Heres is how I'm doing it now, takes a vertex and then samples the volume texture

VB.net

   Private Function vGetNormal(fX As Single, fY As Single, fZ As Single, fScale As Single) As Vector3
    Dim rfNormal As Vector3
    rfNormal.X = fSample1(fX - fScale, fY, fZ) - fSample1(fX + fScale, fY, fZ)
    rfNormal.Y = fSample1(fX, fY - fScale, fZ) - fSample1(fX, fY + fScale, fZ)
    rfNormal.Z = fSample1(fX, fY, fZ - fScale) - fSample1(fX, fY, fZ + fScale)
    Return Vector3.Normalize(rfNormal)
End Function

Private Function vGetNormal(fX As Single, fY As Single, fZ As Single, fScale As Vector3) As Vector3
    Dim rfNormal As Vector3
    rfNormal.X = fSample1(fX - fScale.X, fY, fZ) - fSample1(fX + fScale.X, fY, fZ)
    rfNormal.Y = fSample1(fX, fY - fScale.Y, fZ) - fSample1(fX, fY + fScale.Y, fZ)
    rfNormal.Z = fSample1(fX, fY, fZ - fScale.Z) - fSample1(fX, fY, fZ + fScale.Z)
    Return Vector3.Normalize(rfNormal)
End Function

Volume sampling code:

VB.net

Public Function GetVolumeData(_pos As Vector3) As Half
    Dim x2 As Single = Math.Abs((_pos.X / CellsPerPatch * 32) Mod mWidth)
    Dim y2 As Single = Math.Abs((_pos.Y / CellsPerPatch * 8) Mod mDepth)
    Dim z2 As Single = Math.Abs((_pos.Z / CellsPerPatch * 32) Mod mHeight)

    Return mScalars(CInt(Math.Truncate(x2)) + (CInt(Math.Truncate(z2)) * mWidth) + (CInt(Math.Truncate(y2) * mWidth * mWidth)))
End Function

The rest of the isosurface construction code is just a copy-> convert-> paste of Paul Bourke's c code.

Just to makes sure everyone knows what I'm asking: Can anyone tell me what I'm doing wrong? Is it a problem with my normals or the isosurface stuffs or both?

All of the above is just so u have some context, I'm happy to post more code if ppl need to see it

[EDIT]: Black squares come from having no depth info at that point so my deferred render hates those spots, this is leading back to maybe a problem with the surface reconstruction? But why its only happening in those spots, one would think that it would happen everywhere?


texts: C/C++ Flexible yet fast way of linking UI elements to functions

texts:
I am currently working on the UI functionality of my game, which will have very minimal GUI design, yet it needs to be functional and flexible e.g. easy to redesign.

I am planning to construct all my GUI elements (buttons, sliders, knobs, checkboxes) from Quads with an optional texture and a color. These quads will also serve as boundaries for text and mouse-click detection.

But I am having trouble to figure out an efficient way of linking actual functionality to triggers like buttons. I have thought of defining a Button like this:

struct Button{
    unsigned int quadIndex; //an index into the array of quads, which themselves store indices into arrays of positions and sizes
    void (*func)(int); //a pointer to the function to be called when this button is being interacted with. the parameter of the function will be the state of the relevant mouse button
}

But this way I could only make a button call a function void func(int), which will often force me to write a wrapper function for every individual button functionality. Is this the way everybody does it or is there a better, more flexible way?

Edit:
Since performance/high responsiveness is very important to me, i would like to avoid pointers, virtual functions and derived classes. I am looking for a transparent, concrete solution which focusses on the minimal data which has to come in play for a functional and flexible solution


texts: Getting a surface compatible with the texture / renderer

texts:
I'm trying to convert my emulator to SDL2 (from SDL 1.2).
As I'm drawing pixel per pixel, I follow "If your game just wants to get fully rendered frames to the screen" in the migration guide:
https://wiki.libsdl.org/MigrationGuide#If_your_game_just_wants_to_get_fully-rendered_frames_to_the_screen
I basically do:
SDL_CreateWindowAndRenderer(...);
vid = SDL_CreateRGBSurface(..., bpp, ...);
texture = SDL_CreateTextureFromSurface(renderer, vid);

// ... and then later, when "blitting" ...

SDL_UpdateTexture(texture, NULL, vid->pixels, vid->pitch);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, NULL, NULL);
SDL_RenderPresent(renderer);

It works fine if I use 32bpp but this doesn't work for other bpp: the colors are not as expected. This is because the surface has a pixel format with the BPP I want but the texture has a different pixel format.
This is problematic because:

I have some (optional) specific scaling algorithms that require 16bpp surfaces
I'm not sure whether it will behave the same for all users
When not scaling with my own algorithms, the performance is better if I directly use the bpp of the display

The reason why the bpp doesn't match is that the SDL_UpdateTexture accesses the surface data (pixels) without even looking at the pixel format and  SDL_CreateTextureFromSurface creates a texture compatible with the renderer, not caring about the surface format.
So my questions are:

Is there a simple way to get a surface that is compatible with the renderer? [1]
Is there a way to blit the surface on the texture that does the color conversion? [2]

[1] I found:
SDL_RendererInfo infos;
SDL_GetRendererInfo(renderer, &infos);
vid = SDL_CreateRGBSurfaceWithFormat(0, w, h, SDL_BITSPERPIXEL(infos.texture_formats[0]), infos.texture_formats[0]);

but it's a bit heavy, there are multiple supported so I'm not sure which one to choose and I also had some display issues that suggest the result is not really what I want.
[2] One idea I had is to have another surface with the format taken from [1] and to blit to it first for the conversion, before copying it to the texture, but I'm surprised there's no simpler way to do it.


texts: How can I snap player-constructed objects in a 3d world together?

texts:
I m trying to build minecraft type of game with more complex builds like that of fortnite, so I wanted to start with the best practices i have to follow to create those builds.

the blocks in minecraft are aligned with proper precision to create those humongous buildings and arts needs to have some kind of alignment algorithm that the developers must have followed. similarly, fortnite follows placement of walls and roof with proper precision.In fornite when the player places a stair it takes some area of the space and when you try to place another stair on the same level a little forward it leaves some space and places another stair after some distance of the first floor....like a stair takes a cube space around itself and then places another after another cube space distance.

now the tricky part is when the player places a stair and goes up to place another stair right above the first one to reach height, what transform position does the second floor needs to have to connect itself to the previous builds.

any suggestions or ideas on how have they achieved this would be a great help!Thanks!


texts: Certain Unicode Characters not displaying when setting text to TextButton in libgdx

texts:
Ok I am trying to do a word game much like Hangman Pro but for a different language(specifically amharic) using libgdx . And I have got a list of words saved to text file and I have taken care of BOM problem when reading the file. Problem arises when setting the individual characters from a random word to a TextButton.

Here is a snapshot of the problem:

The part I marked red are the ones missing and it is the same word in both cases. And I know the word is correctly being read because it outputs correctly on console

Here is init code and console output

public void init(){
        char [] indiv = WordList.randomWord.toCharArray();
        int index = 0;
        Skin skinCanyonBunny = new Skin(Gdx.files.internal(Constants.SKIN_WORDGAME_UI),
                new TextureAtlas(Constants.TEXTURE_ATLAS_UI));
        String name = "textb-dn";
        TextButtonStyle tbs = new TextButtonStyle(skinCanyonBunny.getDrawable("textb-up"),
                skinCanyonBunny.getDrawable("textb-dn"),
                skinCanyonBunny.getDrawable("textb-checked"),
                Assets.instance.assetFonts.defaultNormal);
        for(int i =0;i<Constants.WORD_TABLE_SIZE;i++){
            String tempText = String.valueOf(indiv[(index++)%indiv.length]);
            TextButton temp = new TextButton(tempText, skinLibgdx);
            btnPlayArray.add(temp);
        }

        for(int i = 0;i<Constants.WORD_TABLE_SIZE;i++){
            btnPlayArray.get(i).addListener(new TestInputtListenerOverflow(btnPlayArray.get(i).hashCode()));
        }

    }

And a sample of console output. the last one is the random selected word.

entry: ቴክኖሎጂ 5
entry: ኢንዱስትሪ 6
entry: ሀይል 3
entry: ወደፊት 4
entry: አቅጣጫዎች 6
entry: ሰው 2
com.tamirat.wordgame.WordGame: ኢንዱስትሪ

Can anyone tell me what is happening? If it helps I am using Nyala ttf font and converting them to bitmap using Font Forge. Alternatively I use BMFont. Thanks


texts: What are some ways to texture map a terrain?

texts:
I'm working with XNA on a 3D Game, and I'm trying to have a proper and nice environnement.
I actually followed a tutorial to create a terrain from a heightmap. To texture it, I just apply a grass texture on it and tile it a number of times.

But what I want to do is to have a really realistic texturing, but also generate it automatically (for example if I want to use Perlin noise to generate a terrain and then texture it).

I already learned about multi-texturing, loading a map file with different colors for different textures, but I don't think this is really efficient, for instance for cliffs or very steep areas it will tile a texture badly as it's a view from the top.
(Also, I don't know how I'll draw roads or dirt paths with that.)

I'm looking for an efficient solution to realistically texture mapping procedurally-generated terrain.


texts:
I wrote my own state machine tool in C and at this point I'm faced with two choices for specifying state machines.

Crafting a little language and writing a interpreter.
Writing a compiler for that language.

I know the advantages/disadvantages of each. I'd like to know what choices game programmers have made for their games. If you've used a state machine in your game in any form, I'd be interested in knowing how you did it.


texts:
T<----------------------Q

While making a view matrix, I usually cross product a (0,1,0) with W TO GET U
W = (T-Q)/||T-Q||
  U = (W X (0,1,0)/||W X (0,1,0)
v = w x u
this works most of the time. But what about when I want to go y axis and look straight down at 0,0,0

What would be the value of the vector? (0,1,0) does not work. Tried every combination even negatives and didn't work.


texts: How can I call a native mobile API in Construct 2?

texts:
How can I use mobile API features in a Construct 2 game (HTML 5/JavaScrit engine)?

I didn't find anything about that on the net, unlike other game frameworks like Corona Enterprise or Cocos2d.