texts: Codes for walking on platforms along with jumping using actionscript 2.0

texts:
I want to know the shortest and most understandable code for walking on platforms using actionscript 2.0.

I know there are multiple ways in doing it but my method becomes too tedious when a lot of platforms are needed.

So I just want to know:

1.) A code for walking on platforms and an easy way for me to add another working platform

2.) Code for jumping.

Codes I've been using so far:

//Gravity Variables

var grav:Number = 0;

var gravity:Number = 5;

var touchingGround:Boolean = false;

//Jump Variable

var maxJump:Number = -40;

//Code for player1

p1.onEnterFrame = function() {

//Gravity code

p1._y += grav;

grav += gravity;

while (ground.hitTest(p1._x, p1._y, true)) {

    p1._y -= gravity;

    grav = 0;

}

if (ground.hitTest(p1._x, p1._y+5, true)) {

    touchingGround = true;

} else {

    touchingGround = false;

}

//Jumping

//Jump Code

if (Key.isDown(Key.UP) && touchingGround) {

    grav = maxJump;

Optional, but can someone explain this part for me:

while (ground.hitTest(p1._x, p1._y, true)) {

    p1._y -= gravity;

    grav = 0;

}


texts: How should I send packets to multiple clients on UDP?

texts:
I'm developing a 2D action side-scroller shoot-em-up game and I recently implemented the multiplayer aspect.

When the server sends packets containing the game state (which are about 500-700 bytes) to a single client, the ping is around 32ms and it works smoothly, but the moment another client connects, both clients start to lag and the ping increases to 200ms and I am assuming that the problem lies with network congestion

So my question is, should the server automatically send data to all clients simultaneously OR should the client ask the server for an update on the game world OR is there another method I do not know about?

BTW I am using UDP protocol as I found TCP to be pretty slow after a certain amount of time in-game.


texts: How do I include XML files in an Android build?

texts: I have a few XML files I want to include in a build of my game, and I want to have access to those XML files in Android. How to I store and load those XML files?


texts:
i'm using SDL2.0/OpenGL + Box2D with C++ to learn some stuff about games, so i created two rectangles bodies: a small box(dynamic) wich will fall into the second body: the ground(static), i draw them on the screen with OpenGL primitives, as recomended i'm not using "pixel thinking", i'm using meters to represent everything, well, the problem is that i can't get a good physic simulation, just almost, when rendering i can see the small box falling into the ground but it don't touch the ground, it gets real close but don't touch, i really can't understand why, so i came here to see if can get some help:

Here we create the bodies(and do other things):

void MyLoop::onCreate(){
world = new b2World(b2Vec2(0, -10));

player = new Player(world);
//creates the player body
player->create();

//Creates the ground
b2BodyDef bdef;
b2PolygonShape* pshape = new b2PolygonShape();
b2FixtureDef fdef;

bdef.type = b2_staticBody;
ground = world->CreateBody(&bdef);

pshape->SetAsBox(40.0f, 1.0f);
fdef.shape = pshape;

ground->CreateFixture(&fdef);
ground->SetTransform(b2Vec2(20.0f, 0.5f), 0);

glMatrixMode(GL_MATRIX_MODE);
glLoadIdentity();
//configurating the apropriate scale
glOrtho(0, 40, 0, 20, 1, -1);

delete pshape;
}

The most important here is the bodies creation and the glOrtho call wich will set the camera to our coordinate system.

The creation of the player body:

b2BodyDef bdef;
bdef.type = b2_dynamicBody;

pbody = world->CreateBody(&bdef);

b2PolygonShape* pshape = new b2PolygonShape();
pshape->SetAsBox(0.5f, 1.0f);

b2FixtureDef fdef;
fdef.shape = pshape;
pbody->CreateFixture(&fdef);
pbody->SetTransform(b2Vec2(19.0f, 10.0f), 0);

So now we go to the render loop: i get the bodies position with getPosition() method and use them to draw the bodies:

glClearColor(1.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);

player->render();

float x = ground->GetPosition().x;
float y = ground->GetPosition().y;

renderer.begin(GL_QUADS);
renderer.setColor(0.0f, 0.0f, 1.0f);
renderer.drawRectangle(x - 20.0f, y + 0.5f, 40.0f, 1.0f);
renderer.end();

SDL_GL_SwapWindow(window);

world->Step(1 / 20.0f, 8, 3);

The player render:

float x = pbody->GetPosition().x;
float y = pbody->GetPosition().y;

renderer.begin(GL_QUADS);
renderer.setColor(0.0f, 1.0f, 0.0f);
renderer.drawRectangle(x - 0.25f, y + 0.5f, 0.5f, 1.0f);
renderer.end();


texts: How to set a body to a specific position using Andengine

texts:
I'm developing a game with a single player and multiplayer mode. Lets say I have walls (static bodies), vehicles (dynamic bodies) and bullets (dynamic bodies).

It works fine to control my own vehicle using vehicleBody.setLinearVelocity(velocityX, velocityY);. The vehicle can collide with walls and bullets as expected.
Now I like to move the enemy vehicles in multiplayer mode. When I use the same method to move the body by its velocity values (in multiplayer mode), the vehicles get out of sync really quickly, means they don't have the same position on all devices because some data packages get lost.

What I'm currently doing is the following:

On device #1:

1) I move the body using setLinearVelocity

2) Then I get the X and Y position of the body and send a data package to the other device

On device #2:

3) I receive the data package and set the position of the body. I tried different ways, hopefully you can tell me the best way or alternatives I did not try yet:

using vehicleBody.setTransform(...):

activity.runOnUpdateThread(new Runnable() {
    @Override
    public void run() {
        vehicleBody.setTransform(new Vector2(newPosX, newPosY), angle);
    }
});

I also tried using MouseJoint (based on that tutorial),
    but somehow the body was bouncing randomly to the next position. Sometimes it was working great, but when I restarted the game the vehicle of the enemy started bouncing again. Maybe I failed to setup the parameters. Here is what I used:

public MouseJoint createMouseJoint(float newPosX, float newPosY) {
    final float PIXEL_TO_METER_RATIO = PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT;
    Vector2 v = vehicleBody.getWorldPoint(
            new Vector2(newPosX / PIXEL_TO_METER_RATIO, newPosY / PIXEL_TO_METER_RATIO));

    MouseJointDef mjd = new MouseJointDef();
    mjd.bodyA = groundBody;
    mjd.bodyB = vehicleBody;
    mjd.dampingRatio = 0.2f;
    mjd.frequencyHz = 30;
    mjd.maxForce = (float) (1000.0f * vehicleBody.getMass());
    mjd.collideConnected = true;
    mjd.target.set(v);

    return (MouseJoint) mScene.mPhysicsWorld.createJoint(mjd);
}

Before I've used bodies I was using simple sprites and it worked perfectly. I sent data packages to the other device(s) and set the position and rotation of the enemy vehicle by using vehicleSprite.setX(newPosX), vehicleSprite.setY(newPosY) and vehicleSprite.setRotation(angle). Compared to that, bodies seem to be very complicated. So how I can I keep positions synced without bouncing?

By the way, on some pages I read about using KinematicBody instead of DynamicBody for a vehicle. What is the advantage? My vehicle needs to collide with the environment, so I think DynamicBody is the correct choice, isn't it?


texts:
I'm releasing a game soon and thinking about adding some simple anti-piracy techniques.

It's an offline adventure game but I'm thinking of doing a quick background check on startup for updates if the user is connected online.

Since it'd connect to the game site to check this, maybe there's some anti-piracy check I can do at the same time?

I don't want anything that'd annoy the user, and I'm not too bothered about completely removing the ability to pirate it because that'd be fighting a losing battle. I just want something that'd deter casual pirates.

Any ideas?


texts: Difference between "texture" vs "texture2d" in OpenGL ES?

texts:
I see many example in shadertoy use texture, but in the cocos2d-x, only texture2d.

Does texture use normalized coordinate and texture2d doesn't?
Because when I use texture2d, it returns wrong result.


texts: How to Store Design Data in Unity including Formulas?

texts:
My team is switching to Unity 3D for an upcoming project. I'm tasked with converting our game data system into Unity.

Our existing games use spreadsheet documents (Google Docs) for designers to set values and formulas. This is then exported into an XML doc (and obfuscated) and read in by our game client. I'm trying to figure out a way to accomplish this same thing but solely through Unity. Storing, exposing, and reading data through Unity is pretty straightforward but I'm not sure on supporting formulas.

I realize I can write a custom parser and interpreter which can handle formulas but I'm wondering if there is already a way to do this in Unity.

For example, let's say I have a unit with various stats: Level, Max HP, HP, Damage, Victory Reward, etc. That unit may receive a reward after combat which is based on its Level and remaining HP. A designer would be able to enter into the Victory Reward field either a flat value, like 3, or a formula such as "Floor({Level} * ({HP} / {Max HP}))", something like that.

My question is basically, is there an existing solution for handling data with formulas in Unity, via a downloadable asset or something in Unity itself, or is there a simple framework or technology which already can do something like this which can be easily integrated (example: some kind of JSON extension which supports self-referencing other values and basic mathematical/logical operations)?


texts:
I understand that using real time frame elapses (which should vary between 16-17ms on average) are provided by a lot of frameworks.  GetTimeElapsedSinceLastFrame, and it gives you the wall clock time.

But should we use this information in basic physics simulation?  It looks to me to be a bad idea.

Say there is a slight lag on the machine, for whatever reason (say a virus scanner starts up).  The calculations all jump, and there is no need for this.  Why not use a virtual second and ignore wall clock time?  For gameplay on the level of Commander Keen, shouldn't you always use the virtual second and not real-time?  (Besides stopwatch timing for race games) I don't see a need to use real time and not a fixed 16ms time step.


texts: Manage game objects depending on visibility

texts:
I'm trying to create an adventure game in 2D and I'm thinking about map management/objects.

Here is what I've got in mind in terms of modelling:

Now, I would like to create entities based on player's position, to avoid high memory and CPU load.

The goal is to have objects removed from memory when they are out of screen and far from the character (for the moment, I'm thinking about something like twice the viewport):

Here is a picture showing that:

Note: red spots in the image are entities.

What do you thing about that? Is there is a better technique?


texts:
I am looking to push the 2D physics in Unity to the extent where when so much is going on that there becomes noticeable lag in a game. This is for testing purposes, so that when so much is going on that a button can be pressed to reduce the amount of physics objects on screen then see what affect that has. So in my small 2D demo I have placed alot of barrels on the map, all of which have physics on them, player bumps into them and they move. I have went to the extent of placing alot of them on the map (864 to be exact), bumping into them I still don't see any effect on the gameplay. Other things I have tried, besides adding alot in, is increasing the mass of the barrels, changing their linear and angluar drag and making them bouncy.

Is there anything I can do besides adding alot more in?
Thanks!


texts: Coroutine to move to position passing the movement speed?

texts:
I'm using this coroutine to move my player to a new position. The problem is that it takes the duration as an argument instead of the speed of the object. Which makes it hard for me to make sure the object always moves at the same speed.

How can I create a coroutine that takes the source position, target position and movement speed to move my character?

This is my current code:

IEnumerator MoveObject(Vector3 source, Vector3 target, float duration)
{
    float startTime = Time.time;
    while(Time.time < startTime + duration)
    {
        player.transform.position = Vector3.Lerp(source, target, (Time.time - startTime) / overTime);
        yield return null;
    }
    player.transform.position = target;
}


texts: How to add post process volume script in unity 2019?

texts: i have old unity 2018 project and imported standard character asset. The 3d player has this script : post process volume and post process layer. In 2018 i can add this component but not in 2019 . This component is not available in 2019. What is the replacement for this ? or how to achieve the same result for 2019 ?


texts: LWRP Custom Shader Graph material casts no shadow

texts:
I created an empty Shader Graph by clicking Create -> Shaders -> PBR Graph.

I created the material for this shader and assigned it to my game object, but the object does not cast a shadow.

If I assign the default LWRP Lit material, then everything works and the shadows are dropped, but with a custom shader there is no shadow.

How can I make my custom shader material cast shadows?


texts: If I want to become a professional game developer, is learning Win32 API a must?

texts:
If I want to become a game developer, is learning Win32 API a must?

Does X-BOX or PS based game developers need to know Win32 API?

Is it possible for a professional game developer to develop games by only scripting game engines and not using Win32 API?


texts: Random 100x100 map using all levels from 1 to 100

texts:
I'm developing a game where players walk though a 100x100 grid of different rooms.
Each room has a level associated with it starting from lvl 1 to lvl 100.
The map is divided into 10x10 areas and in the middle of each area there's a 2x2 "castle" which players must conquer in order to access next levels castles (so if players start off at lvl 1 they need to conquer the lvl 1 castle before being able to enter lvl 2 castles).
Each room in a castle (2x2 area in the middle of each 10x10 area) has the same level and there must be a castle for each level from 1 to 100.
As for now I was generating the whole map "statically" and use the matrix blur to interpolate room levels between castles.
What I would like to achieve is having a seeded function f(x,y) that returns the level of the room at position (x,y) without pre-defining the matrix.
I checked out Perlin Noise functions, but it doesn't guarantee each level between 1 and 100 is taken nor the right position of the "castles".

The image above is the starting point of the game map, lower levels of green represent lower room levels, the blue squares in the center are the castles. This image is then blurred preserving just the castles level.
Players can move around the map and will meet harder challenges in higher level rooms. The goal is reaching level 100 by spotting and conquering each castle in sequence.


texts: How to convert from frag position to UV coordinates when my viewport doesn't cover the screen?

texts:
So, I'm implementing SSAO as part of my rendering pipeline using OpenGL/GLSL. It works pretty well when I have a camera that takes up the entire screen. However, when my camera is smaller than the full screen size, the SSAO texture doesn't get sampled correctly. Here is the relevant GLSL shader code:
// Convert from clip-space
vec2 fragCoords = (fragPos.xy/ fragPos.w); // fragPos is MVP * worldPosition
vec2 screenCoords = fragCoords * 0.5 + 0.5; // Convert from [-1, 1] to [0, 1] to sample UV coordinates

// Sample texture
float ssaoFactor = texture2D(ssaoTexture, screenCoords).r;

I know that there is some funkiness going on with the viewport, but the fixes that I've tried haven't worked. My first thought was to scale fragCoords by normalized size of my viewport (e.g. vec2(0.5, 0.5) for a viewport with half of the width and height of the screen), but that just produced a very strange result. Any thoughts?


texts:
I wish to use this method

byte[] vertexShaderByteCode = ShaderBytecode.CompileFromFile(".......Transf_VS.hlsl", "VS", "vs_5_0");
                this.vertexShader = new D3D11.VertexShader(
                    device,
                    vertexShaderByteCode
                    );

But it throws exception of either file not found or file cannot be open.

Is there any solution to this? I saw HelixToolkit using shader files that has already been compiled, how is it done then?
https://github.com/helix-toolkit/helix-toolkit/blob/master/Source/HelixToolkit.UWP/Model/ExampleCube3D.cs

// Loads vertex shader bytecode
            var vertexShaderByteCode = NativeFile.ReadAllBytes(path + "\\MiniCube_VS.fxo");
            this.vertexShader = new VertexShader(d3dDevice, vertexShaderByteCode);

Thank you


texts: Are there "meta games" with customizable tasks?

texts: I considered making an educational game but since I don't know much about game design I had hoped that something as follows exists: A game that is already almost completely designed but can be customized by defining tasks/exercises. Basically I want to take a complete game with its own story and replace some of the tasks by educational tasks, e.g. to level up or buy a certain item the main character has to solve an exercise defined by me (e.g. 5+3=?). In other words, I want to make solving exercises more interesting by gamification but I don't want to develop the actual game but rather insert the tasks into a generic game. Does such a framework exist?


texts: How does Trine's lighting look so spectacular?

texts: Is there some kind of "special" lighting in this scene? I notice that the sun seems to "pop".


texts: Why does OpenGL require all coordinates in [-1,1] (NDC)?

texts: Why shouldn't the z coordinate be normalized to the [0,1] range instead of [-1,1]? As I understand it, that happens some time after anyways, so what's the catch with this?


texts: How to import .obj file from server without using asset bundle in unity3d

texts:
I want to import .obj file from a server on run time in unity3D, read lot of questions/answers but not able to find a suitable solution.
Using WWW in unity I am able to get .png file and store it in local repository but this thing not works for .obj file.
Following is the code I used to get image from server

public string url = "http://images.earthcam.com/ec_metros/ourcams/fridays.jpg";
    IEnumerator Start() {
        WWW www = new WWW(url);

        while (!www.isDone)
            yield return www;

        if (www.isDone)
            Debug.LogError ("Done");

        File.WriteAllBytes("C:\\Users\\Admin\\Downloads\\conan\\test1.jpg", www.bytes);
    }

ans similarly I tried to get .obj file but it not works test .obj file created but without any data

public string url = "https://drive.google.com/open?id=0B5_UUyYa_2XdZUpuNlE4Z3pqWUk";
    IEnumerator Start() {
        WWW www = new WWW(url);

        while (!www.isDone)
            yield return www;

        if (www.isDone)
            Debug.LogError ("Done");

        File.WriteAllBytes("C:\\Users\\Admin\\Downloads\\conan\\test.obj", www.bytes);
    }

Kindly give me help in this regard.


texts:
In the version 2.7 everything was pretty simple:

glfwOpenWindow(Width, Height, 8, 8, 8, 8, 24, 0, isFullscr ? GLFW_FULLSCREEN : GLFW_WINDOW);

But in version 3.x there is no place where i can specify how my my window should be and by default its windowed:

glfwCreateWindow(width, height, m_windowName.c_str(), nullptr, nullptr);

How can i change my window to fullscreen mode?


texts: Slick2D re-starting particle system/emitter

texts:
I am trying to use a particle system/emitter in Slick2D to produce a thrust jet from a space ship.  I can get the emitter running continuously without any problem, however I can't get it to run for a fixed duration when I press the thrust key (which I need to do so that it only emits particles when the thrust is active).  Note I can get the emitter to run for a fixed duration once when the program starts, but can't get the emitter to restart afterwards.  I have variously tried (all attached to the thrust key press):

disabling/re-enabling the configurable emitter
resetting the particle system
resetting the configurable emitter
resetting the State of the configurable emitter
replaying the configurable emitter
running 2 separate emitters and re-adding these to the particle system when turning the jet on

... which either do nothing (no particles) or give a short burst of particles at the start of the program (for the initial emitter length if emitter length is enabled), but then do nothing whenever I press the thrust key.  The last option (running 2 emitters) causes the particle system to run out of particles after about 10 seconds.

Is there a way to stop and restart a particle emitter that will give the effect that I want?

Just to cover any initial questions, I have read and re-read the javadocs (which are, as ever, reductive and unhelpful) and have read what I can find on the internet (mainly FrumsNL videos on youtube, which mention but don't cover this case) as well as doing my own trials as per the list above.

Any help gratefully received.


texts: Literature for Inverse Kinematics: Joint Limits and beyond

texts:
Recently I've been playing around with Inverse Kinematics and have been pretty impressed with the results. Naturally I want to take it further, but have no clue where to start. In particular, I would like to introduce joint limits (ie for a prismatic joint how far it can move, hinge joint what angles it has to be between, etc etc).

Currently I understand how to produce the Jacobian matrix for the various joint types. I am particularly looking for literature (preferably free, and preferably easy to understand) on various ways to implement joint limits. Also I would like to find out different ideas on how inverse kinematics can be used.


texts:
I'm playing around with PyGame.

Now I'm trying to implement a QIX clone.

I have my game loop, and I can move the player (cursor) on the screen.

In QIX, the movment of the player leaves a trace (tail) on the screen, creating a polyline.

If the polyline with the screen boundaries creates a polygon, the area is filled.

How I can accomplish this behaviour ?

How store the tail in memory ?

How to detect when it build a closed shape that should be filled ?

I don't need an exact working solution, some pointers, algo names would be cool.

At start, there is only the gray border, where the player can move his cursor around.

First scenario:

The user moves his cursor from point A trough point B, drawing the red multiline until point C. At this point, because of crossing the border, the point A should be connected with point C automaticaly, creating a polygon, which should be filled (that orange stuff on my drawing). Filling the polygon is damn simple in PyGame, because I provide the sequence of points,and PyGame cares of the rest.

Second scenario:

The user moves on the border to point D, from where he draws a line to point E. Because he is crossing the line of the previous polygon, and with his lines and the border another polygon can be created, it should be filled too. (the green one).

Third scenario:

The player moves further on the polygon (he can move on existing polygon lines), and draws a line from point G to point F. Here again, because of the border and the existing lines, another polygon should be filled (the blue one).


texts: GLSL shader error on different computers

texts:
I recently discovered a strange error with my fragment shader:

#version 330 core

in vec4 v_color;
in vec2 v_texCoords[10];

out vec4 frag_color;

uniform int actual_textures;
uniform sampler2D u_texture[10];

void main() {
    vec4 final_color = texture2D(u_texture[0], v_texCoords[0]);
    for(int i = 1; i < actual_textures; i++){
        vec4 tex = texture2D(u_texture[i], v_texCoords[i]);
        final_color = tex * tex.a + final_color * (1 - tex.a);
    }

    frag_color = v_color * final_color;
}

On my PC with a GTX 960 and OpenGL 4.5.1 there is no error at all. But on my laptop with an Intel HD 3000 and OpenGL 3.3, I get a compile error that the texture2D function is deprecated and that the sampler2D array size is too big because I only pass 3 textures at the moment and I want the array to be able to handle up to 10 textures. On any other computer I testedm the error didn't occur, but they all had nvidia or amd gpus. Why do I keep getting this error on my laptop?


texts:
i found this page Protocols. I'm currently working on a game similar to agario and i find that page is helpful for my game.

They using WebSocket for sending game messages which is mine too. But i'm use text message (JSON) instead of binary message and i'm planning to switch to binary message for minimizing bandwidth reason because JSON are verbose even it's easy to serialize/deserialize.

On the section server->client protocol and client->server protocol, they used term of opcode. I don't about what opcode is and what the purpose of those number, but i know in WebSocket protocol RFC 6455, they used term of opcode too like 1 for text message and 2 for binary message.

My Question is:

How to serialize/deserialize game messages in binary message?
What is those number in opcode used for? for now, my assumption is those number are used for serialization in binary message, maybe not i don't know
If my assumption in Q2 is right, how to implement those number to my protocol? maybe some code demonstration? it will be great if the code in javascript and golang because i'm use go for server and javascript for client.

Thanks


texts: How to extract a point in LibGdx from Tiled map?

texts: Tiled has a feature to insert a point in to an Object layer. But there doesn't seem to be a "PointMapObject" implementation in Libgdx on the doc. currently i am being forced to use a PolylineMap Object with two vertices but all i want is only the x or y of the first vertex.


texts: How do you rotate the camera using right mouse clicks with Cinemachine?

texts: How can I rotate the camera around the player using right-click?


texts: Getting looping music to work in Roblox Studio

texts:
I've been trying for a few days now to get my background music to work on one of my Roblox places, but every time I get the error:

13:50:23.806 - Players.PungentZeus0.PlayerGui.bgmusic:21: attempt to index global 'Sound' (a nil value)

Here's the code:

local ContentProvider = game:GetService("ContentProvider")

local pageTurnId = "rbxassetid://144585389"

local sound = Instance.new("Sound")
sound.SoundId = pageTurnId

local assets = { sound }

ContentProvider:PreloadAsync(assets)

print("All assets loaded.")

local sound = Instance.new("Sound", game.Workspace)
sound.SoundId = "rbxassetid://144585389"

if not sound.IsLoaded then
    sound.Loaded:wait()
end

Sound:Play()


texts:
I have a standart Unity car with Unity Car physics.
What would be the best approach to protect my car from a rollover?

I dont want to mess up and try and error 10 different approaches, so maybe here is an expert who really knows how to do it right?

I couldnt find anything decent on the internet.


texts:
I am attempting to create a simple Jeopardy game using the UI features of Unity:

However as im trying to change the size of the screen it does not seem that my UI is responsive:

Here is it in 16:9:

Here it is in 600x900

My Question is. is there a way to make it responsive?

Is it even nessary to do so in unity or am i thinking way to much web based? :)

Hope someone is able to help me and guide me abit


texts:
I have a empty scene, which loads another scene which is loading player data onStart. When the empty scene transition to the loading player scene. A loading bar is created on the empty scene and it shows me 100% and stuck for couple seconds. I've used Debug.Log and i only see is 0-9. Nothing between like 0.20, 0.40 and etc...

I can see on the hierarchy that loading player data scene, is loading while it's stuck on the 100%

Update:
I've made some futher tests, it seems my problem is that loading player data through awake or start. Does not get executed while loading a scene async. How can i load the player data aswell with the progress bar. Since the player data is stored as a file. This is purely because when i open my game, after the unity splash logo. It's a black screen, due to it's loading the player data.

    private IEnumerator LoadSceneProgress(Scene scene)
    {
        AsyncOperation operation = SceneManager.LoadSceneAsync(Tools.TitleCase(scene.ToString()));
        while (!operation.isDone)
        {
            float progress = Mathf.Clamp01(operation.progress / .9f);
            loadingSlider.value = progress;
            loadingSliderText.text = progress * 100 + "%";
            Debug.Log(operation.progress);
            yield return null;
        }
    }

public static bool LoadPlayer(PlayerObject player)
{
    SaveData loadData = LoadFile();
    player.Level = loadData.Level;

    // Load items inventory
    List<Item> itemList = loadData.ItemsInventory;
    if (itemList != null)
    {
        for (int a = 0; a < itemList.Count; a++)
        {
            Item item = itemList[a];
            Item newItem = player.GetInventory.AddItem(new Item(item.Id, item.Amount));
        }
    }
}

private static SaveData LoadFile()
{
    string path = Application.persistentDataPath + "/save.dat";
    SaveData data = null;
    using (FileStream fileStream = File.OpenRead(path))
    {
        data = ZeroFormatterSerializer.Deserialize<SaveData>(fileStream);
    }

    return data;
}


texts:
I'm doing this game where with cards you assign different beats to different channels. You drag and drop the beat to a channel and it gets added to the mixer. What I'm having trouble with is when i try to play each channel individually with an UI Button. This is the script attached to the channels:
public class ManageChannel : MonoBehaviour
{
    public AudioSource thisAudioSource;
    bool chequeo;
    string Nombre;

    public AudioMixer audioMixer;

    public void AsignaCanal (){
        Nombre = this.name; // tomo el nombre del canal actual
        thisAudioSource = this.GetComponent<AudioSource>();

        var carta = this.transform.GetChild(0); // llamo a la carta hija de este objeto
        thisAudioSource.clip = carta.GetComponent<AudioSource>().clip;
        thisAudioSource.outputAudioMixerGroup = audioMixer.FindMatchingGroups(Nombre)[0]; // asigno al AudioSource el grupo correspondiente

    }

    public void comienzaAudio (){
        if (!thisAudioSource.isPlaying){
            thisAudioSource.Play();
        }
        else {
            thisAudioSource.Stop();
        }
    }

    // Start is called before the first frame update
    void Start()
    {
        chequeo = true;

    }

    // Update is called once per frame
    void Update()
    {
        if (this.transform.childCount != 0 && chequeo) {
                AsignaCanal();
                chequeo = false;
                thisAudioSource.Play();

        }

    }
}

What the script does is when a card is dropped, it takes the clip of the card and get its into the AudioSource of the channel, and that AudioSource gets outputted to its respective channel (for example, the GameObject "Channel 1" goes to the mixer group "Channel 1" and so on). Then i've tried to build the buttons to reproduce the track of each channel individually, but using AudioSource.Play() since I believe I cannot do it with the AudioMixer directly. What i did is create a UIButton and then assign the respective GameObject Channel to the OnClick() section on the inspector, and then i choose the following function on the script that i showed before
public void comienzaAudio (){
        if (!thisAudioSource.isPlaying){
            thisAudioSource.Play();
        }
        else {
            thisAudioSource.Stop();
        }
    }

Then, every time i press the button, that function should be called. The problem is nothing happens. I'm positive the button is working because i tested with a bool value and a Debug.Log() to see if it changes values with every click, and it does. So, i honestly have no clue what the issue is. Any help would be appreciated. Thanks!


texts: How to position two objects relative to each other

texts:
I am trying to make a modular vehicle editor similar to Kerbal Space Program. The user selects an initial vehicle part which is spawned in the center of the "work area". To add another part to the initial one, the user clicks and drags a part from a list onto the "work area" and then drags that part towards the initial one. When a node on the new part is close enough to a node on the initial part, the new part snaps onto the initial one. The user can then click to confirm the connection or drag it somewhere else. For a visual example.

The spawning of the parts I have no problem with.

For moving the parts in the environment I have an invisible plane that is parallel to the camera and rotates to always face the camera. I then draw a ray from the mouse to the plane and update the parts position to the location where the ray hits the plane.

When the new part is in the correct position I will add I make it the child object of the part I want to connect it to.

The problem occurs with positioning the new part relative to the part I want to attach it to. I'd like to make it like Kerbal Space Program where when the connecting node of the new part is within range of the connecting node of the part I'm attaching to, the new part's position snaps to the part I'm attaching to.


texts:
I'm making a game in coffeescript (although for the sake of this problem that's probably not all that relevant) and html5's canvas. It's a game that involves a paint cannon, that fires circular particles of paint that can paint elements of the level and the player. The problem is I'm not sure how to accomplish the painting. The diagram below illustrates what I'm trying to accomplish:

Using canvas, the particles are drawn using context.arc(), the players using drawRect.arc() and the floor can be an arbitrary polygon with drawing code as follows:

    @drawingContext.beginPath();

    tV = b2Math.AddVV(pos, b2Math.MulMV(body.GetTransform().R, @vertices[0]))
    @drawingContext.moveTo(tV.x, tV.y)
    for i in [1..@vertices.length - 1]
        v = b2Math.AddVV(pos, b2Math.MulMV(body.GetTransform().R, @vertices[i]))

        @drawingContext.lineTo(v.x, v.y)
    @drawingContext.lineTo(tV.x, tV.y)

    @drawingContext.closePath()
    @drawingContext.stroke()
    @drawingContext.fill()

It would be too intensive to keep track of all the circles that should be painted on to objects and would soon bog down, with potentially 60 clipped circles per second being added to be drawn on top of objects.

The original thought was to stack two canvases on top of each other, so then we could draw the levels once and then when ever necessary just draw the paint splat over them once and forget about it (changing the composition mode to source-atop to get appropriate clipping), and since we're not redrawing it would stay there. However, this won't work on moving objects (like players) (that can also rotate and change size relative to the camera). I'm not sure how to do it, since all objects are made up of solid colour to start with there's no texture data or anything we can modify.


texts:
I understand that when sampling the brightness of a given point on the surface, a certain cutoff needs to be taken into consideration.

Other words, when the light is further away, the intensity decreases.

I came across the following formula that is used to compute the aforementioned:

attenuation = 1.0 / (1.0 + a * dist + b * dist * dist)

However, I have not been able to find out why and how this formula is derived.

From the formula what I can understand is that as the distance get larger, the result will become smaller; but how it is derived is beyond me.

If distance takes an important role in the above formula, which helps determine the intensity, could we simply ignore a and b from the formula and simply use:

attenuation = 1.0 / (1.0 + dist)

?

Does anyone know how the formula is derived and the importance the values a and b play within the formula?

Thanks.


texts: Why is Metal is rendering textures SLIGHTLY darker than they should be?

texts:
I already checked this question. Using [MTKTextureLoader.Option.SRGB : false] in texture loader options doesn't work. All that happens is when I do [MTKTextureLoader.Option.SRGB : true], it's a lot darker instead of slightly darker. There must be something else. Here is an example of this unwanted behavior.

As you can see I am using the mouse to hold the original packed ice texture over the rendered one. It's considerably lighter, even with [MTKTextureLoader.Option.SRGB : false].

Here is my fragment function:

fragment half4 TextureFragment(VertexOut VertexIn [[stage_in]], texture2d<float> Texture [[texture(0)]]) {
    constexpr sampler ColorSampler(mip_filter::nearest, mag_filter::nearest, min_filter::nearest);
    float4 Color = Texture.sample(ColorSampler, VertexIn.TexCoord.xy / VertexIn.TexCoord.z);
    return half4(Color.r, Color.g, Color.b, 1);
}

How can I fix the problem? How can I render the actual texture instead of a darker version?

Note: I must fix the problem, not work around it. A workaround would be like return half4(Color.r, Color.g, Color.b, 1); from the fragment shader. I must fix the problem from the root.


texts: Sphere turns to ellipsoid further away from origin (OpenGL ES 2, Android)

texts:
I'm not even sure what code to share, but maybe someone's been in a similar situation or has a good suggestion.

I'm basically rendering a sphere in the middle of the screen (placed at (0, 0, 0)) and it looks fine. However, if I choose to render the same sphere further away from the origin, it gets an egg shape. I think the egg shape is in the direction of the translation. Here's the code that sets up the model matrix:

Matrix.setIdentityM(mModelMatrix, 0);
Matrix.scaleM(mModelMatrix, 0, 0.15f, 0.15f, 0.15f);
Matrix.translateM(mModelMatrix, 0, 0, 0, distance);

When distance = 0, the sphere shows up normally, however if distance = -1.5f, then the sphere is sort of stretched on the z axis. Any suggestions for fixing this behavior?


texts: Depth buffer values reset on change shader?

texts:
I have 2 different shaders, and when I change the shader (glUseProgram), it seems that the depth information is lost, because everything drawn with the 2nd shader appears completely on top of anything drawn by the first shader.

If I switch the order of shader use/drawing, then it's the same (the last drawn object always appears on top of the first drawn object if there is a shader change between the 2 objects, even if the last drawn object is further away)


texts: Legal status of games with similar titles

texts:
I've been working on a game for around a year and a half named Planetfall, in which you build a colony on a new planet.

I've bee working on it with that title since before the announcement of Age of Wonders: Planetfall. The games have some overlapping mechanics and aesthetic, but other than that it would be clear that my game is not a clone or a rip-off.

I know that I probably should change the name anyway (so there's no confusion between the titles) but I was wondering what the legal status is of a title that was in development since before the announcement of another similar title. If I decided to go ahead and not change the name, what could happen?


texts: How to calculate ray unit grid intersections?

texts: P is ray origin, D direction. How do I calculate tx, ty(s)? This is for octree raycast. The primary goal is to get 1st intersection voxel (v) then second (v") and so on.


texts: Modern way of getting points within a distance?

texts:
I'm making a game engine, and some components may want to interact with others based on distance. Currently, the component registers an update listener which runs on a loop, then it checks the distance for each object. This is obviously wrong.

I thought about creating a system just for spacial relations, where the component would ask every frame if there are objects within a radius to that system, and it would have something like an octree inside to accelerate the calculations. I can also just register a listener for when objects are closer than a radius, and it would update only when an object changed from one node to the other on the tree.

Is the octree appropriate or is it just better for static objects like terrain? What do physics engines use?


texts: IronPython with Python in Unity: How should I manage dependencies Python-side?

texts:
I am currently trying to get Python working in Unity, and I was wondering how would I manage dependencies on the Python end. For example, say I have a Python script with the following dependencies:

 import tensorflow as tf
 import numpy as np
 import cv2

I would like to get these working in IronPython in Unity. Does IronPython have it's own package manager like pip for this, and if so, how would I go about integrating this in Unity? Is there other .dlls for specific packages? Thanks in advance.


texts: What type of networking archtitecture does Unreal Engine 4 have?

texts:
I am working on online multiplayer FPS on UE 4 with up to 16 players.
I am now at the making architecture model, stage.

I am doing research on possible server architecture model with respect for future scalability, bandwidth support etc.
However I could not find any good information on how UE 4 networking work and what it's architecture. In order to know whether it will suit my needs and whether I will be able to modify it


texts:
Hi I want to know the width of the text inside the CCTextFieldTTF but I can't find a way to do it, I want this width so I can move a CCLabelTTF in that position so it can be like a cursor for the CCTextFieldTTF

Thanks


texts: How player(sprite) in the phaser will opposite or reverse while going left and right?

texts: I am developing a game where my player has to look to see forward when I am pressing right arrow key. But how can I make it look reverse after pressing left arrow? I can create a sprite of reverse look but how can load that while pressing left and at the same time forward player should be destroyed?


texts: Checking Scriptable Object equality without references

texts:
A rather simple question, how do you check equality of a scriptable object without references?
For example, I have a weapon class that holds a list of damage types the weapon deals, which consists of a float and a ScriptableObject class (Element).
[System.Serializable]
public class DamageInfo
{
    public float damage;
    public Element damageType;

    public DamageInfo(float damage, Element damageType)
    {
        this.damage = damage;
        this.damageType = damageType;
    }
}

Elsewhere in my code on the weapon I have my DoDamage function.
private IEnumerator DoDamage(WeaponAttack attack, Health otherHealth, Vector3 position)
{
    OnHitObject?.Invoke(this, otherHealth.gameObject, position);
    foreach (var damageInfo in Damage)
    {
        //if(damageInfo == Fire) etc

        yield return new WaitForSeconds(0.1f);
    }
    yield break;
}

What I would like to do is check what type of Element damage I am currently iterating in order to apply different modifiers, I know this can be done through setting up editor references  and comparing against them, but that would require far too much editor setup each time and seems to me using a simple enum while less flexible would be less work overall(even to change in future).
Even setting all the references one time on a globally accessible class, removes the modularity/easy extensibility of using ScriptableObjects in the first place.
Is there any better way I can check for equality without having to use editor set references? Seems to me to be a huge downside of ScriptableObjects.
Thanks


texts: How do I modify the health of an entity after it has been created?

texts:
Is there any way to add or remove health after an entity has been created?

For example, I'd like to have a mob regenerate "hearts" when some event happens.


texts: Popular genres in Asian (non-Japanese) markets?

texts:
From time-to-time I've wondered what kind of games are popular in Asia (India, China, Korea, Singapore, etc...). I hear about developers in the US and UK who outsource work there, but what goes into the games they make for themselves?

Related, you hear these days about how Japanese developers have been marketing their games more for American audiences these days (with mixed success). In what ways could American developers aim their development toward Asian audiences?


texts:
How to manage different speed of actions in RogueLike games?

What I mean is that turn based games may have actors acting at different "speed", depending on the action and some other characteristics. The actors then effectively do more actions/turns than others if they have greater speed, or not.

How to determine when an actor should be able to act (turn scheduling?)?

It looks like there is different ways to do it?
Can you explain some with algorithms?


texts: How to get the position of individual characters in TextMeshPro (Unity)?

texts:
I am making a typing game.
There are words falling down what the user have to type, before they can call the OnBecameInvisible() event.

When the user types a character I want to apply a force and a torque to it and make it fall down. But to do this I have to instantiate a TextMeshPro GameObject at the position where that letter was located inside that word.
But how can I get that position?

  Just to make things clear:


texts: Reading a text file and changing each digit into a value inside an array c#

texts:
I'm having a bit of an ordeal with the StreamReader.

I'm working on a game where you build the map with a 2D array by imputing different numbers so the array like this:

    int[,] map = new int[,]
    {
        {0,0,0,0,0,0,0,0,0,0,0,0,0,0},
        {0,1,1,1,1,1,2,1,1,1,1,1,1,0},
        {0,1,1,1,1,1,1,1,1,1,1,1,1,0},
        {0,1,1,1,1,1,1,1,1,1,1,1,1,0},
        {0,1,1,1,1,1,1,1,1,1,1,1,1,0},
        {0,1,1,1,1,1,1,1,1,1,1,1,1,0},
        {0,1,1,1,1,1,1,1,1,1,1,1,1,0},
        {0,1,1,1,1,1,1,1,1,1,1,1,1,0},
        {0,1,1,1,1,1,1,1,1,1,1,1,1,0},
        {0,1,1,1,1,1,1,1,1,1,1,1,1,0},
        {0,1,1,1,1,1,1,1,1,1,1,1,1,0},
        {0,1,1,1,1,1,1,1,1,1,1,1,1,0},
        {0,1,1,1,1,1,1,1,1,1,1,1,1,0},
        {0,1,1,1,1,1,1,1,1,1,1,1,1,0},
        {0,1,1,1,1,1,1,1,1,1,1,1,1,0},
        {0,0,0,0,0,0,0,0,0,0,0,0,0,0},
    };

will give you the outcome where the 0's are one type of block and the 1's another and so on.

I currently have that working, however the array is hardcoded in.

What I am now trying to solve is how to read it from a text file. I attempted doing it in a Console Application with this code but I keep on receiving errors.

    static void Main(string[] args)
    {
        int[,] map = new int[300, 300];

        StreamReader SR = new StreamReader(@"F:\test.txt");

        for (int y = 0; y < 300; y++)
        {
            for (int x = 0; x < 300; x++)
            {
                map[y, x] = int.Parse(SR.ReadLine());
            }
        }
        SR.Close();

        for (int y = 0; y < 300; y++)
        {
            for (int x = 0; x < 300; x++)
            {
                Console.Write(map[y, x]);
            }
        }
        Console.ReadLine();
    }

Any idea how I can make it work for a 2D array so that whenever the compiler reads a digit, it allocates a number into a specific area in the array, so for example when a file like this is read:

11111
10001
10001
10001
10001
11111

It will turn into an array like this:

1,1,1,1,1
1,0,0,0,1
1,0,0,0,1
1,0,0,0,1
1,0,0,0,1
1,1,1,1,1

Thanks for any help provided. :)


texts: Separating UI and logic in Objective-C at iOS based Games

texts:
How to separate UI and logic in Objective-C based mobile games?

To develop games, I use Cocos2d library.

I need a good reference to separate my UI code from game logic code.


texts: unity & c# - File.ReadAllLines() vs TextAsset Split('\n')

texts:
I switched from one approach to the other in my code and I noticed that File.ReadAllLines() has a string length of equal to the alpha-numeric chars in the string, with exception of the last line of the file. I assume that is eol. String.Split('\n') however will result in that extra char for every string in the array, and so only matches ReadAllLines() on the final string. Am I write in assuming its an end of line character that's introduced on every string in the split version? How can I trim these? I don't know of any eol in the special chars. I tried to trim \n and \r but it didn't change the line lengths

--- further clarification as to why I put it here instead of stackoverflow

I am not familiar enough with the workings to be sure. I thought perhaps the results might be due to unity. The File.ReadAllLines() version works on the path to the txt file, the string.Split() version works on the TextAsset.text and the TextAsset is passed through the inspector as reference.

Sorry if I made the wrong decision in posting here!


texts: Best way to constrain character to a path?

texts:
I'm in the process of developing a level-based runner for mobile phones, and I've hit a wall when deciding which method to use to get the character to move through the level.

Basically - I need my character to travel a constrained path across the level as I manipulate the character by speeding up/down and jumping to avoid obstacles. I couldn't just place a straight path and use Curved World look as I needed a realistic feel to character motion. I also have up/down slopes that have to affect the character's speed.

I'm not use whether using iTween is the best for this as it makes it difficult to manipulate character speed and especially the jumping 'arc'. I've tried using MoveTo() but problems arose when trying to change character parameters... PutOnPath() made sense in theory but I found it harder to implement.

Is there any easier way to go about this? I'm almost completely new to Unity, so an easier implementation is what I'm going for, for now.

Thanks in advance!


texts:
I am currently making a MMORPG game, which is turn-based. The client is supposed to run on Android. Now, my friend is doing the graphics, and I have been doing the game classes (player, weaponry, etc.). Now, if the fight is started, the classes can be manipulated by interfaces (actually for my partner, it is like working with pure interfaces, he does not need any access to the implementaton classes).

Now we need to introduce a game server to allow for multiple players. And a few very important questions arise:

1) Shall I copy the game model to the server completely, leaving no classes on the client or is it better to have 2 copies of the model - 1 on the server and 1 on the device and to complete periodic synchronization between those?

2) Which method of connection to choose between the client and the server (client in sight is android phone)? As for the server - I am turning towards java cause I have some experience with it. But now the questions is - is it better to use sockets for this task or I can use REST services, or it is even possible to connect it somehow to Java EE server which is cool from my point of view cause it removes a lot of programming complication? Even though the game is multiplayer, it is turn based, so it does not need to be renewed very often.

3) What about threading? Should every client have his own thread(in case of sockets)?

4) Are there any books on REAL MMORPG server game programming out there???


texts: Why Canvas is used more than JPanel for making games in Java?

texts: I saw many ludum dare games, which are written in Java ( using it's standart library ), I checked the code of one or two of them and the thing that I saw is in their Game class, they extends Canvas.So my question is why they extends Canvas not JPanel?


texts:
Friends, I am making games using photon. But I could not do the delay animation as described in this link.
The action appears to be late on the player according to the ping. Can you give an ideas about this?


texts:
I want to create a 2D map composed of small tiles, that should look like voxels (eg. this just from side).

I think I can make a structure like Voxel2D, that have int X, Y and some Color, and every Voxel2D is going to be 5x5 pixels (so multiply X and Y by 5 when drawing).

But now how should I store the whole map? In a 2D array like classic Tile-map, or is there any faster way?


texts:
Scene graph contains game nodes representing game objects. At a first glance, it might seem practical to use Scene Graph as physical container for in game objects, instead of std::vector<> for example.

My question is, is it practical to use Scene Graph to contain the game objects, or should it be used only to define scene objects/nodes linkages, while keepig the objects stored in separate container, such as std::vector<>?


texts: I have recently added Vivox general voice chat to the game I am working on. Ever since adding it, I have run into issues with the application reload time after editing a script. If I edit a script and switch back to Unity, it hangs on the application reload window for a very long time, most times never recovering until I force close Unity or until Unity just crashes. Has anyone run into a similar issue with this or any other package?


texts: How to make a tile vanish after player steps on it, in a tilebased game?

texts:
So I'm adding the basic mechanic of making frail/breaking tiles, those that break apart and disappear after the player has walked ontop of them. Now I thought this would be as easy as...:

//Breaking tiles represents the 2d array number, that describes the breaking tiletype.

if( TileWeAreStandingOn == breakingTile){

        //frameCount is a variable that counts the frames, after 30 frames (1 second) the tile disappears.

            frameCount++;
            if(frameCount > 30){

        //So, when 30 frames has passed, the tile is removed

            TileWeAreStandingOn = noTile;
            frameCount = 0;

        }
}

Now this works, but it only works WHILE you are standing on the breaking tile, once you jump, the countdown stops since the initial if-statement is not valid anymore. So I am trying to find ways around this where the player could jump onto a frail/breakable tile, and then jump onwards, and the tile would still break after 1 second.
Also, if he walks past several breakable tiles in a row, they should all break timely, that is, they should all break after a second of the player has moved off of that tile. (which would result in a domino like timing, where one breaks shortly after another)

I need to make the tiles work independently, so that each tile reacts and starts to disappear/break whenever the player touches it. But my system is build around how the player interacts with the 2d array map and the tiles aren't independent entities, only the player is.

So I'm asking for suggestions how I can make the tiles react independently based on Players interactions with them? Especially in this case, where a tile should disappear a second after the players has touched it.

Thanks in advance guys!


texts: Is it important for reflection-based serialization maintain consistent field ordering?

texts:
I just finished writing a packet builder that dynamically loads data into a data stream for eventual network transmission. Each builder operates by finding fields in a given class (and its superclasses) that are marked with a @data annotation.

When I finishing my implementation, I remembered that getFields() does not return results in any specific order.

Should reflection-based methods for serializing arbitrary data (like my packets) attempt to preserve a specific field ordering (such as alphabetical), and if so, how?


texts: How can I incorporate the path of a jump into my A* implementation?

texts:
I need to calculate the path of a jump via A* for a simple platformer game. Calculating the direction is simple, but translating the jump physics into pre-calcuted voxel paths is a bit difficult. Especially when you factor things in like obstacles. Based on the image below, what is the best way to calculate jump in A*?

To give better context, here is a video of the game I'm working on. Will be implemented here to get companions following the player

http://www.youtube.com/watch?v=yMrbCtb2Buk


texts: I would like to understand on a fundamental level the way in which D* pathfinding works. Any code or psuedo-code implementations as well as visualizations would be helpful.


texts:
I'm trying to create a level editor for a 2D game and I wanted to instantiate radio buttons, the backgrounds and numbers of which are determined by the tilesheet I load.

I'm sure I'm doing something simple wrong but I can't figure it out. When I instantiate these radio buttons and set their locations and backgrounds to the values I want, they appear in the object hierarchy and each have the correct location but are not displayed. The "Toggle" resource I'm using is the basic Unity toggle object saved in my resources folder. In the screenshot you can see in the scene view that they appear to be in the correct location (the large box at the bottom) since the bounds for the rect transforms show up in the right spot.

In the script I'm using, my tileset is sliced into 32x32 squares using unity's slicing tool and has been placed into the script's public tilesheets[] array. It is then used to load all the component sprites, each of which should be used to make a unique radio button. These radio buttons are all parented to the transform of the script, which is the toggleGroup "group_sprites".
The script is as follows:

using UnityEngine;
using UnityEngine.UI;
using UnityEditor;
using System.Collections;
using System.Linq;

public class SpriteSelector : MonoBehaviour {

    ToggleGroup group_sprites;
    Toggle[][] toggles;
    public Texture2D[] tilesheets;
    public Texture2D checkmark;
    int sliceSize = 32;
    int level;

    public void Setup()
    {
        group_sprites = GameObject.Find ("group_sprites").GetComponent<ToggleGroup> ();
        //Slice the current thingy
        LoadTileset (0);

        //Make a toggle group
    }

    public void LoadTileset(int _level)
    {
        level = _level;
        //Slice em up
        string spriteSheet = AssetDatabase.GetAssetPath(tilesheets[level]);
        Sprite[] sprites = AssetDatabase.LoadAllAssetsAtPath (spriteSheet)
            .OfType<Sprite> ().ToArray ();

        RectTransform parentRect = gameObject.GetComponent<RectTransform> ();
        int buffer = 1;
        float toggleWidth = parentRect.rect.width/8 - buffer;
        float xPos = -76.45f;
        float yPos = 42.3f;
        foreach(Sprite sprite in sprites)
        {
            GameObject terrainToggle = (GameObject)GameObject.Instantiate(Resources.Load ("Toggle"));
            terrainToggle.transform.SetParent(transform);
            GameObject Background = terrainToggle.transform.FindChild("Background").gameObject;
            GameObject CheckMark = Background.transform.FindChild("Checkmark").gameObject;

            //location
            RectTransform trans = terrainToggle.GetComponent<RectTransform>();
            trans.sizeDelta = new Vector2(toggleWidth, toggleWidth);
            trans.anchoredPosition = new Vector2(xPos ,yPos);//+ trans.sizeDelta.x/2, yPos - trans.sizeDelta.y/2);

            //background
            //Background.GetComponent<Image>().overrideSprite = sprite;
            Image backImage  = Background.GetComponent<Image>();
            backImage.sprite = sprite;
            //checkmark
            CheckMark.GetComponent<Image>().sprite = Sprite.Create (checkmark, new Rect(0,0,checkmark.width, checkmark.height), new Vector2(0.5f,0.5f));

            xPos += parentRect.rect.width/8;
            if(xPos > parentRect.rect.width/2)
            {
                xPos = -76.45f;
                yPos -= parentRect.rect.width/8;
            }
        }

        //foreach slice, make a toggle
    }

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

        //if click on a tile,
    }
}

Thanks!!


texts: How can i properly display 2D Pixel sprite's pixels without distortion while it's moving ? (in unity)

texts:
Introduction to what i'm trying to do

Hi, I'm trying to make a 2D Pixel Platformer Game in Unity. Before that i used godot and for some reasons (not about the engine) i switched to unity. And in Unity there are things need to handle by myself, and they were handled by the engine in godot (i guess), because godot is more suitable and compatible with 2D Pixel games (i guess).
So; i am not sure why the problem happens

The Problem

In the scene, my pixel sprite is playing his Idle animation (he's only breathing so you can think of that as head and the body moving 1px up and down repeatedly) While playing that simple animation, if my sprite is big enough on the screen, there is no problem and it looks pixel perfect animation is playing without distortion (or disruption idk what was the right word). But if the character looks smaller on the screen, i mean if i scale the character down or keep the scale same and make camera's angle of view bigger, so character looks smaller (not too small a regular platformer character size), What happens is character's eyes visibly goes thinner and thicker as the character plays his animation (head and the body moving 1px up and down repeatedly). Character's eye is 2 black pixels side by side thats it. While the animation playing it kinda distorts. Height changes.

Yes I fixed it somehow but..

I fixed it, but idk how and seems like a temporary fix AND i don't think that is how it's supposed to be fixed because we wrote code, I'm okay with writing code for fixing it but first i want to know what was the problem and how to fix it in editor. aaand it just seems weird to write code for simply having a properly functioning pixel sprite animation.

How did i fixed it ? just watched this video and added the same script to the camera i have no idea how it worked and why my animation problem was occuring at the first place.

What I'm asking for

Pleaaaase somebody explain all that to me, why is that happening what are the possible and proper fixes. i'm researching for days and i thought unity had a "big community a lot of tutorials too easy to learn"

TL;DR : when playing animation pixel sprite character's some pixels distorts

version: Unity 2019.3.3f1

I imported sprite the right way (Filter mode: Point(no filter) Compression: none, Pixels per unit: 16 (that option seems suspicious maybe the problem is about that pixels and units thingies))
I can provide more information about project or directly send you the whole project if you can't reproduce the error. I'm just too curious and want to learn how to have a proper 2D display setup and finally start the fun part coding mechanics etc.
since a code about camera solved the issue the problem might be unity's camera settings because unity has no 2D special camera component while godot has Camera2D and Camera3D seperatly. These are just my guesses please teach me what you know.


texts: How can I rotate cubemap in shadergraph?

texts:
I know how to rotate cube map with legacy surface shader

Shader Rotation Matrix:

uniform float4x4 _Rotation;
          o.Emission = texCUBE (_Cube,  mul(_Rotation, float4(IN.worldRefl,0))).rgb;

RotateCubeMap:

using UnityEngine;

public class RotateCubeMap : MonoBehaviour
{
    public float speed = 20;
    private MeshRenderer _meshRenderer;

    private void Awake()
    {
        _meshRenderer = GetComponent<MeshRenderer>();
    }

    public void Update()
    {
        var rot = Quaternion.Euler (0, Time.time*speed, 0);
        var m = new Matrix4x4 ();
        m.SetTRS(Vector3.zero, rot,new Vector3(1,1,1) );
        _meshRenderer.material.SetMatrix ("_Rotation", m);
    }
}

I tried to recreate it by shadergraph

but it didn't work!

I need a result like this:


texts: Polygon doesn't bounce enough in edge-ground collisions (but it does in vertex-ground collisions)

texts:
I'm currently making a (basic) physics engine in Python in which I want a polygon to bounce off the ground (\$y=0\$).

When a vertex hits the ground, I apply the (linear) impulse $$\overrightarrow{P}\left(0,\;\frac{-(1+\epsilon)\overrightarrow{n}\cdot\overrightarrow{v}}{\frac{1}{m} + \overrightarrow{n}\cdot\left(I^{-1}(\overrightarrow{r}\times\overrightarrow{n})\right)\times\overrightarrow{r}}\right)$$
(where \$\overrightarrow{n}(0,1)\$ is the normal on the floor, \$\overrightarrow{r}\$ is a vector going from the center of mass to the contact point and \$\epsilon\in[0,1]\$ is an elasticity constant)

In my code:

class POLYGON:
    def bounce(self):
        #Checks whether the polygon is under the ground and rebounces it if necessary

        #Finds the nodes with y <= 0
        low_nodes = []
        for node in self.nodes:
            if node[1] < 0:
                low_nodes.append(node)

        if len(low_nodes) > 0:
            #Translates the polygon above the ground
            lowest_node = low_nodes[np.argmax(low_nodes,axis=0)[1]]
            self.translate([0, (1+restituence_constant)*(-lowest_node[1])])

            #Makes a list of the (linear) velocities of all low nodes
            speed = []
            for node in low_nodes:
                speed.append(self.getLinearVelocity(node))

            for (i,node) in enumerate(low_nodes):
                r = node - self.pos

                ut = -(1+restituence_constant) * speed[i][1]
                lt = 1/self.mass + 1/self.rot_inertia * cross(r[0], r)[1]
                j = ut/lt
                impulse = [0, j/len(low_nodes)]
                self.applyLinearImpulse(impulse, node)

As a side note: I make the list of linear velocities of the nodes in advance because those are influenced by applying impulses.
Also, it is necessary to divide the length of the magnitude of the impulse by the number of 'low nodes'.

When there is only one vertex hitting the ground, this all works fine.
But in the case of an edge-ground collision, I find the impulses to be too small.

When I drop the square with nodes \$(\pm100,\pm100)\$, it doesn't even bounce!
However, when I drop the polygon with nodes \$(\pm10,-100)\$ and \$(\pm100,100)\$ on its 'small side', the impulse ís big enough to make it bounce back.
Therefore, I conclude that the issue is caused by the vertices being too far from the center of mass in the \$x\$-direction.

My question is: how can I resolve this issue?
My first idea was to replace the impulses at the vertices by one linear impulse at the middle of the edge. However, this seems a bit 'hacky' and mathematically incorrect.
Can you please help me out?

EDIT:
To help you understand what I'm saying, I measured the bounce height of some 'truncated triangles'. I worked on a 900pxl high screen and dropped the polygons from the middle (so the bottom nodes were at a height of 350pxl).

relative heights (pxl): 150, 144, 72, 14 and 0

I also figured out that this problem occurs because the impulses are too low to flip the velocity.
(Even if I don't divide the impulses by the number of low nodes, they are too weak to lift the square off the ground.)


texts: Unity 2d diffuse sprites not rendering on mobile

texts:
EDIT:  Just an update, did change from sprite/diffuse to Diffuse and zordering of my level using t2dtk map stuff was backwards. Like the camera flipped around so i had to shuffle things around on the Z axis.  Also things that were rendering in 2d with their y rotated 180 degrees no longer were so I had to change how the other engine I was using (Corgi engine) was moving projectiles.

This all worked then in the editor.  When I pushed to the system, still nothing renders unless the rendering path is legacy vertex lit.  And then it will render but dark like my directional light and point lights are meaningless.  Apparently I am not cool enough to mess with Shaders/Unity 5 and mobile.

It seems like Mobile is having an issue rendering my diffuse sprites.  I just made some of the sprites in my game diffuse so point lights would give them a nice lit up effect.  This works great on PC but when I push the game to my mobile phone (a Galaxy Note 3) nothing that has that diffuse material renders at all.  I am assuming it is just setting but I cannot figure out for the life me how to get this to work.  I tried to muck with settings (rendering paths etc) nothing seemed to help.  Of note:  The stuff renders fine in Unity editor when the mobile target is selected even.


texts: Do I have to explain the mechanical superiority of the player-character within the fiction of the game?

texts:
For quite a while I wonder how to formulate this concept, which seems to be common, yet barely addressed within games. It is about the concept of player controlled characters (PC) being consistently superior to generic non-player controlled characters (NPC). This also must not depend on the actual player skill (defined as what the player can actively do), and instead be inherent to the PC itself.

Now for RPGs it's usually something like destiny, magic, superior skill, backstory, better (enchanted) equipment, having a rare power.

But what if it's about space ships with equal size, type and equipment? How could I explain that a player can repeatedly and easily grind through 5-10 space ships which he himself is using without having much room for player skill due to weapons and thrusters working automatically? Effectively pushing a button to start attacking just as his opponents are doing. Let's say it's the early phase of the game, just to keep this abstract. Also let's assume a standard, futuristic setting with no special lore-based elements like psi powers or crystals.

What guidelines or concepts exist which can be used to justify PC superiority in general? In a mathematical sense, do I have to explain -75% damage taken and +300% damage dealt as baseline for all PCs in a credible way? Or is that a silently accepted premise of games in general?


texts: Path-finding algorithms for Polar coordinate based maze?

texts:
Following on from my question about moving a sprite in a circle, assuming that you have a maze which is shaped like a a set of circles with holes in them and barriers between them.

Location of a sprite is stored in polar coordinates and then translated into cartesian coordinates to be rendered.

I'm going to assume that most path finding algorithms rely on cartesian geometry, is there a path finding algorithm I can use to allow "beasties" to chase my players sprite?


texts: Bluring behind something then drawing text?

texts:
I want to basically make a blur shader in glsl and use it like Windows 7 does for Windows. I want to for example draw something and then blur a rectangle, then draw text over it.

If someone could point me in the right direction on how to do this I'd be very grateful.

Thanks


texts: In A star, how does the heuristic help determine your path?

texts:
Say you're using a 4 by 5 grid. The G cost for horizontal and vertical movement is 10, and the G cost for diagonal movement is 14. On this page: http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html
it says  "At one extreme, if h(n) is 0, then only g(n) plays a role, and A* turns into Dijkstra’s algorithm, which is guaranteed to find a shortest path."

Why would it find the shortest path? Wouldn't it find the longest path instead? If the heuristic no longer plays a role then it will never consider going diagonal because the cost of diagonal movement is 14. Previously, even if the G cost was higher than another adjacent node, it could still be chosen if the H cost was a bit lower.

Now, even if the shortest path was by going diagonal, it would never go diagonal because the G cost of diagonal movement will always be higher than the G cost for horizontal/vertical movement. So why exactly would it be guaranteed to find the shortest path if the heuristic was 0?

Another thing, what would be the difference if, let's say we're using the Manhatten method, and after calculating the total number of squares moved horizontally and vertically to reach the target square from the current square the heuristic was multiplied by 1 or if it was multiplied by 100? Wouldn't the path be the same either way?


texts: Checking Collisions Within a Sprite List in MonoGame

texts: I'm trying to learn game dev, and I'm using some of Oyyou's tutorials. My problem is: I have a list of sprites, using a sprite object, and I would like to know how to check for collisions between different sprites. I have a basic understanding of bounding boxes, and can use them to some extent, but I don't know how to check collisions in a list. Any help would be appreciated. :D


texts: How would I write a shader that supports 2 different texture coordinates?

texts: Hi I am not very good with writing shaders. How would I make a shader that simply supports 2 texture coordinates so I can load up 2 different textures to be used at the same time but on different parts of my world? Right now I have 1 texturecoord variable setup and I load a texture through it using GraphicsDevice->SetTexture(0, &Texture); and making sure my VertexDeclaration and FVF both support that, but how can I add a second texture to this? Would I make it so that I make separate coordinates and link the coordinates to a texture? How would I write that?


texts: Handling lost graphics device XNA 4.0 in winforms

texts:
I'm trying to put in a new feature into my level editor. Part of the feature is to bring up a form when a user places a new tile onto the map, but once the form is brought up the XNA embedded screen throws up a big red X.  I think this is due to the embedded screen losing focus to the form and then crashing.

This is where the form is initialized

 public Form1()
   {
    InitializeComponent();

    //Node Editor

    tileDisplay1.OnInitialize += new EventHandler(tileDisplay1_OnInitialize);
    tileDisplay1.OnDraw += new EventHandler(tileDisplay1_OnDraw);

    Microsoft.Xna.Framework.Input.Keys[] allKeys = (Microsoft.Xna.Framework.Input.Keys[])
     Enum.GetValues(typeof(Microsoft.Xna.Framework.Input.Keys));

    foreach (var key in allKeys)
    KeyboardInput.AddKey(key);

     KeyboardInput.KeyRelease += new KeyHandler(KeyboardInput_KeyRelease);
     MouseInput.MouseMove += new MouseMoveHandler(MouseInput_MouseMove);
     MouseInput.MouseDown += new MouseClickHandler(MouseInput_MouseDown);
     MouseInput.MouseUp += new MouseClickHandler(MouseInput_MouseUp);

     Application.Idle += delegate { tileDisplay1.Invalidate(); };

     saveFileDialog1.Filter = "Map File|*.map";

     Mouse.WindowHandle = tileDisplay1.Handle;

   }

This is where the draw event is fired off

void tileDisplay1_OnDraw(object sender, EventArgs e)
        {
            Logic();
            Render();

            KeyboardInput.Update();
            MouseInput.Update();

            foreach (var actor in Actor.Actors)
                actor.Update();
        }

This is where the form is being called

     private void Logic()
    {
               if (colIndex == 8 && AssociateBox.SelectedIndex == 0)
                {
                    currentCollisionLayer.SetCellIndex(collideCellX, collideCellY,form.spawnNumber.ToString());

                    if(form.spawnNumber == "12")
                    {
                       camdetails.ShowDialog();
                    }
                }
    }


texts:
I'm trying to change the attack animation of my player in relation to the attack animation for the item he has in his hand.

For example, the default attack animation of my player is puching and once he picked up a sword I want his attack animation to be sword attack, for a hammer a hammer attack, etc ..

I searched a lot on the internet but didn't find much, I saw a few post talking about AnimatorOverrideController but I'm not sure if it's what I need because it overrides every animation clip of the AnimatorController. In my case I just want to change the attack Animation Clip.

So if you cloud give me some tips about the right way to do it, I would really appreciate because I'm a bit confused.

Thanks

Edit : BTW, I'm in Unity 3d


texts: Extending the camera vs CameraHelper class vs camera field

texts:
I am following an eBook called "Learning Libgdx Game Development"

In it, the author implements a CameraHelper class that implements Zoom, target-following behaviour, and probably some other things along the way.

Can I do this just by extending the camera class, or using composition?

Approaching it like this seems like a clearer code to me:

public class Camera extends OrthographicCamera {
    GameObject target;
    boolean followTarget;

    Camera(float viewWidth, float viewHeight){
        super(viewWidth, viewHeight);
    }

    public void setTarget(GameObject target) {
        this.target = target;
    }

    public GameObject getTarget() {
        return target;
    }

    @Override
    public void update(){
        if(followTarget && target != null){
            this.position.x = target.position.x;
            this.position.y = target.position.y;
        }
        update(true);
    }
}

Any problems with this that I can expect?


texts:
I'm making a game, and right now I'm working on the user interface. I'm just wondering when I should be loading my resources.

Should I do it in small pieces at a time?

Load resources for part 1 of menu
Run part 1 of menu
Free resources for part 1 of menu
Load resources for part 2 of menu
Run part 2 of menu
Free resources for part 2 of menu
(So on)

Or all at once?

Load resources for all parts of menu
Run part 1 of menu
Run part 2 of menu
(So on)
Free resources for all of menu

It would seem to me that the pros of the first method are that my code can be much cleaner, as I can isolate the resources to specific parts of my class:

class UI {
    method run() {
         part1();
         part2();
    }
    method part1() {
         // part1's resources can be declared here
    }
    method part2() {
         // part2's resources can be declared here
    }
}

Whereas with the second method, it will probably run faster, but then all my resources have to be global:

class UI {
    // resources are declared here
    method run() {
        part1();
        part2();
    }
}

I'm using OpenGL, so right now what I'm doing is loading all my textures and audio at once, but I'm allocating and freeing my Vertex Buffer Objects as they're needed. For those of you who have more experience writing games, what method do you think I should use?


texts: How to set player rotation to direction the player is moving?

texts:
I'm having an issue with my click to move mechanic. I want the player to move to a specific position in the game when the mouse is clicked (and it does just that) but the issue I'm having is that the player doesn't face the direction in which it is travelling.

Lets say I click a position diagonally right to where the player is. Immediately after clicking that point, the character will face that direction and run to it, instead of facing the direction it has to take to get there... if that makes sense.

Here's my code snippet:

public void moveToTargetPosition() {
    Seeker seeker = GetComponent<Seeker>();
    seeker.StartPath (transform.position, targetPlayerPosition, OnPathComplete);

    transform.rotation = Quaternion.Lerp (transform.rotation,  Quaternion.LookRotation(targetPlayerPosition - transform.position), Time.fixedDeltaTime * lookSpeed);
}

Obviously I'm missing some modifier in here.

Any ideas?

Thanks!


texts: How can I make object to follow first person character and the camera without making the object child?

texts:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjectFollowCamera : MonoBehaviour
{
    public Transform cameraToFollow;
    public Transform objectToFollow;
    public float distanceFromCamera;

    private void Update()
    {
        objectToFollow.position = new Vector3(cameraToFollow.position.x,cameraToFollow.position.y,cameraToFollow.position.z - distanceFromCamera);
    }
}

This script is attached to a empty GameObject.
The objectToFollow will move once i'm moving the Player with the keys. But when i'm rotating the camera of the player around the objectToFollow is not moving.

The Player have attached to it: Character Controller , First Person Controller , Rigidbody

And the Camera is child of the Player.


texts: OpenGL ES 2.0 Best Practices / Architecture Guide

texts:
I've recently started working with OpenGL (ES 2.0) on the Android. While there is lots of documentation about the basics, I can't seem to find much about the overall architecture of OpenGL. In particular, while I see how a Program works, shaders are linked, and vertices are loaded, I can't find any indication of how this should be used to create entire scenes.

That is, does one create multiple programs, reuse the programs, create multiple indexes, try to share textures/shaders, etc. What I'm looking for are some solid references that explain the trade-offs, and intended use, of these functions in the production of scenes. The various Android docs, and OpenGL docs also hint at several limitations in using the API, but don't give concrete information in many cases.

I understand this may be a bit subjective, but I really can't find anything useful on this topic by searching. I'm  unsure where else to ask and I believe that concrete useful answers can be given.


texts:
I'm making a RPG with libGDX. I've loaded a TiledMap and now I'm implementing the player movement. The view is top-down.

In my game I want two ways of input: one is using the ARROW keys to move the player. This implementation works pretty well, including collisions. The second one is a movement based in the mouse. When I click, then the player starts to follow the mouse pointer

 private void autoMove(float speed)
{
    //Start or stop moving
    if (Gdx.input.justTouched())
    {
        autoMoving = !autoMoving;
    }

    //Start follow the mouse
    if (autoMoving)
    {
        //Get direction
        Vector3 point = this.getStage().getViewport().getCamera().unproject(new Vector3(Gdx.input.getX(),Gdx.input.getY(),0));
        dir = new Vector2(point.x - pos.x, point.y- pos.y);

        //Normalize
        dir.nor();

        //Set correct animation
        if (Math.abs(dir.x) <= 0.5)
        {
            if (dir.y >= 0)
            {
                lookingDirection = UP;
            }
            else
            {
                lookingDirection = DOWN;
            }

        }
        else
        {
            if (dir.x >= 0)
            {
                lookingDirection = RIGHT;
            }
            else
            {
                lookingDirection = LEFT;
            }
        }

        //Scale to speed and move
        dir.scl(speed);
        pos.add(dir);
    }

As you can see, I use global variable dirto store the direction of the player. Now I want to handle the collisions with this input. However, I'm not able to do this. I've tried, for example, using pos.add(dir.scl(-1.0f)) but doing this the player gets blocked in every direction. After that, I tried to make the same but blocking only x or y movement based on the lookingDirecion variable. However, player can be looking at right and move a bit upwards, to it's possible to "hack" the system and introduce the player inside the block. I tried with more complex if structures but they didn't worked at all.

The collision code looks like this, if it's useful.

public void checkBounds(float speed)
{
    for (int i=0; i < map.getWidthInTiles(); i++)
    {
        for (int j=0; j < map.getHeightInTiles(); j++)
        {
            //bound is player's rectangle. colBounds are map's impenetrable objects.
            if (bound.overlaps(map.colBounds[i][j]))
            {
                if (!autoMoving) //Control with ARROW keys
                {
                    if (lookingDirection == UP)
                    {
                        pos.y -= speed;
                    }
                    else if (lookingDirection == DOWN)
                    {
                        pos.y += speed;
                    }
                    else if (lookingDirection == RIGHT)
                    {
                        pos.x -= speed;
                    }
                    else if (lookingDirection == LEFT)
                    {
                        pos.x += speed;
                    }
                }
                else
                {
                    //MOUSE COLLISION DETECTION
                }
            }
        }
    }

The question is: how can I implement the collision detection for this kind of movement?

Thank you!


texts: How to use mocaps in your game if they don't loop smoothly?

texts: Following suggestions on IRC, I've downloaded, parsed and incorporated the Free Release of 2500 mocaps to my game. I've noticed, though, that none of those loop perfectly. It does not connect and thus won't form proper walking/jumping/etc cycles. So how I'm supposed to use them in my game? Is there a tool or some trick to solve that problem I'm not aware of?


texts: Debugging multiplayer games without killing network thread?

texts: How do I approach multiplayer games for debugging? When debugging locally - how can you prevent yourself from disconnecting? The debugger halts network activity.


texts: Can you use a standard multi-thread if only reading unity objects?

texts:
First of all I know about coroutines and how to use them (they're awesome).

A friend of mine was telling me about the way the he implemented his saving system in a game he was working on, after asking him what he was using I found out that he is using system.threading and not coroutines to save data.

I know that Unity isn't thread safe but apparently he has had no issues with saving which leads me to wonder if it is ok to use normal threads as long as you're only reading data and no pre-existing data is modified in the gameworld? would this affect the game at all (other than some moving objects being slightly ahead of where they should be because of the time it took to get to that object and save it)?


texts: How to realize a camera that is following the player

texts:
I want to create a simple space game, like Asteroids. Unlike Asteroids, the map is supposed to be larger than what the player can see:

The grey part is what the player can see in the game window, to see the rest of the level he needs to move his spaceship. When his spaceship reaches the borders eventually, the camera is supposed to stop and not move any further. Thus, the spaceship wouldn't be central anymore.

I am using libgdx and have no idea how to do this.


texts: JBox2D becomes very slow on mobile phones after 80-90 dynamic and static bodies

texts:
I have a simple game with 20-30 physics bodies (static, and dynamic)

If I add some additional Dynamic bodies and joints (over 80-90 item), then JBox2D will become very laggy, and a little slow.

Am I doing something wrong, or is this the limit of JBox2D? If I change to Box2D JNI via java native calls, will it be faster?


texts: Are there performance benefits to full-screen haze filters?

texts:
Some games apply a full-screen filter effect that desaturates picture, causing the colors to be "washed out".

For example, in Zelda: Breath of the Wild:

Someone used Photoshop to remove the filter, giving this result:

Is there a performance or other technical benefit to applying this kind of filter, or is it a purely aesthetic choice?


texts:
I am building lightmaps for 3D models. My lightmap algorithm needs to determine which pixels( lumels ) within the lightmap texture fall within the boundary of a mesh face( triangle )...this process takes place for each mesh face...

I was using barycentric coordinate techniques to accomplish this task. It works for the most part...here is code:

bool PixelIsWithinBounds( const D3DXVECTOR2 &t0,
                            const D3DXVECTOR2 &t1,
                            const D3DXVECTOR2 &t2,
                            const D3DXVECTOR2 &pUV )
{
    // compute vectors
    D3DXVECTOR2 v0 = t1 - t0,
        v1 = t2 - t0,
        v2 = pUV - t0;

    // do bounds test for each position
    float f00 = D3DXVec2Dot( &v0, &v0 );
    float f01 = D3DXVec2Dot( &v0, &v1 );
    float f11 = D3DXVec2Dot( &v1, &v1 );

    float f02 = D3DXVec2Dot( &v0, &v2 );
    float f12 = D3DXVec2Dot( &v1, &v2 );

    // Compute barycentric coordinates
    float invDenom = 1 / ( f00 * f11 - f01 * f01 );
    float fU = ( f11 * f02 - f01 * f12 ) * invDenom;
    float fV = ( f00 * f12 - f01 * f02 ) * invDenom;

    // Check if point is in triangle
    if( ( fU >= 0 ) && ( fV >= 0 ) && ( fU + fV <= 1 ) )
        return true;

    return false;
}

This function takes as input 3 UV coordinates( mesh face ) and a pixel UV coordinate. The problem with this method is that if the pixel is only partially covered by the face, the function returns false( because the pixel center does not ly within the triangle ). I could do overlap tests for each point on the triangle...I would like to know if there is a more efficient method...as this process takes place many times per generation of a lightmap...

...any ideas?

here is a screenshot showing the endpoint of a mesh face after lightmap generation...the corner of this face overlaps a pixel surface but doesn't overlap the pixel center...the algorithm left this pixel black( no light )...

EDIT: Shader code to dilate pixels

//--------------------------------------------------------------//
// Dilation Pass
//--------------------------------------------------------------//
PS_INPUT_Quad DilationPass_Vertex_Shader( VS_INPUT_Quad Input )
{
    PS_INPUT_Quad Output = ( PS_INPUT_Quad )0;

    Output.Position = mul( Input.Position, mOrtho );
    Output.UV = Input.UV;
    return Output;
}
float4 DilationPass_Pixel_Shader( PS_INPUT_Quad Input ) : COLOR0
{
    float4 vC = tex2D( g_SamplerLightMap, Input.UV );
    if( vC.w != 0 )
        return vC;

    int nValidPixels = 0;
    float4 vFinalColor = 0;
    for( int i = 0; i < 8; ++i )
    {
        float4 vNeighborColor = tex2D( g_SamplerLightMap, Input.UV + TexelKernel[ i ] );
        if( vNeighborColor.w == 0 )
            continue;

        //vFinalColor = ( length( vFinalColor ) > length( vNeighborColor ) ) ? vFinalColor : vNeighborColor;
        vFinalColor += vNeighborColor;
        nValidPixels++;
    }
    return vFinalColor / max( nValidPixels, 1 );
}


texts:
I am currently having issues with HLSL shaders. I am trying to implement point lights but I am getting unusual data when debugging the shader in Visual Studio.

I have read on several sites that say that the data stored in CBuffers should be aligned to 4 bytes, thus I added padding where it was needed (is this correct?).

When I set the data in c++, some of it comes through alright but other data is not. For example the color comes through alright but the range is being displayed as NaN in the VS graphics debugger.

Is there something wrong with the code below? (All structs are the same as those in c++ structs)

Please ask if there is anything else you would like to see code wise. Thanks!

PointLight Code:

float4 calcPointLight(PointLight pointLight, float3 normal, float3 worldPos0, float4 specularMap, float4 diffuseTex)
{
    float3 lightDirection = worldPos0 - pointLight.pos;
    float distanceToPoint = length(lightDirection);

    //  if (distanceToPoint > pointLight.range)
   //   return float4(0, 0, 0, 0);

    lightDirection = normalize(lightDirection);

    float4 color = calcLight(pointLight.base, lightDirection, normal, worldPos0, specularMap);

    float attenuation = pointLight.atten[0] +
    pointLight.atten[1] * distanceToPoint +
    pointLight.atten[2] * distanceToPoint * distanceToPoint +
    0.0001;

    return color / attenuation;
}

float4 calcLight(BaseLight base, float3 direction, float3 normal, float3 worldPos0, float4 specularMap)
{
    float diffuseFactor = (dot(normal, -direction));

    float4 diffuseColor = float4(0, 0, 0, 0);
    float4 specularColor = float4(0, 0, 0, 0);

    if (diffuseFactor > 0.0f)
    {
        diffuseColor = base.color * base.intensity * diffuseFactor;
        diffuseColor = saturate(diffuseColor);

        float3 directionToEye = normalize(cameraPos - worldPos0);
        float3 reflectDirection = normalize(reflect(direction, normal));

        float specularFactor = dot(directionToEye, reflectDirection);
        specularFactor = pow(abs(specularFactor), specularPower);

        if (specularFactor > 0)
        {
            specularColor = base.color * 1.0f * specularFactor;
        }
        if (specularMap.a > 0.0f)
            specularColor = specularColor * specularMap;
    }

    return saturate(ambient + diffuseColor + specularColor);
}

Structs

struct BaseLight
{
    float4 color;
    float intensity;

    float3 padding3; //TEST
};

struct DirectionalLight
{
    BaseLight base;
    float3 direction;
};

struct PointLight
{
    BaseLight base;
    float3 atten;
    float padding;
    float3 pos;
    float range;
};

CBuffers

    cbuffer MatrixBuffer : register(b0)
{
    matrix worldMatrix;
    matrix viewMatrix;
    matrix projectionMatrix;
};

cbuffer LightingBuffer : register(b1)
{
    float4 ambient;

    float specularPower;
    float3 padding3;

    PointLight pointLight;
    //DirectionalLight light;

 };

 cbuffer CameraBuffer : register(b2)
{
    float4 cameraPos;
};


texts:
I'm trying to create a geometry generator for a "Chamfered Cube". I've got the vertices working, but I'm stuck with creating the faces. I don't really know how I could re-arrange my algorithm to create the vertices in the right order for a triangle list / strip / fan / whatever.

This is what I've done so far: starting from the 8 vertices of a normal cube, I "push" out vertices in the shape of an eight of a sphere:

//start 0,0,0
var width = 8;
var radius = 3;
var segments = 16;

var half = width / 2;
var segmentStepSize = Math.PI / 2 / segments;

//displacement
var w = Math.sqrt(Math.pow((half-radius),2)*2);

// the 8 original vertex vectors
var startPoints = [
    [ 1,  1,  1],
    [ 1,  1, -1],
    [ 1, -1,  1],
    [ 1, -1, -1],
    [-1,  1,  1],
    [-1,  1, -1],
    [-1, -1,  1],
    [-1, -1, -1]
]

var x, y, z, v, x1, y1, z1, j, k;

var points = [];

for(var i = 0; i < 8; i++) {
    v = startPoints[i];
    x = w * v[0];
    y = w * v[1];
    z = w * v[2];

    for(j = 0; j < segments +1; j++) {

        for(k = 0; k < segments+1; k++) {

            x1 = x + radius * Math.cos(k*segmentStepSize) * Math.sin(j*segmentStepSize) * v[0];
            y1 = y + radius * Math.sin(k*segmentStepSize) * Math.sin(j*segmentStepSize) * v[1];
            z1 = z + radius * Math.cos(j*segmentStepSize) * v[2];
            points.push(x1);
            points.push(y1);
            points.push(z1);

        }
    }
}

module.exports = points;

This code results in this: http://requirebin.com/?gist=fdea95e3bfe069d7f363

Edit

for anyone who's interested: I've shared the code here: https://github.com/ToastCommunicationLab/mesh-primitive-chamfercube


texts: Map tile terrain transitions with 3-4 different types

texts:
Making transitions between two different tiles is a fairly well understood problem. The easiest way is to look at the 0.5, 0.5 and use the resulting 4 corner points to select a transition tile, as mentioned here for example: http://playtechs.blogspot.se/2007/04/tileset-design-tip.html

The problem comes when three or four tiles meet, for example:

(s for swamp, p for plains and . for water)

pppp
..sp
..pp

If we look at the offset in the corner, the edges in our transition tile looks like:

pp
.s

In this case there are no suitable transition tiles to be found, as they typically are created to work between 2 types only. Unless we work out a three way transition tile with these types, we appear to be stuck.

I'm well aware of this often referenced article on the tile transitions in Artifact: http://archive.gamedev.net/archive/reference/articles/article934.html

But looking at the actual screenshots from that game, it doesn't seem like it will yield professional looking maps: http://www.samugames.com/artifact/screenshots.htm

Aside from using intermediary tiles (which frankly would be problematic since two out of grassland/swamp/desert would then not be able to border directly to water), are there any solutions?

EDIT

I think I've found a solution that can will create terrain transitions for 3-4 different types, using only one extra transition tile to each set of transition tiles. I've yet to make an implementation of the algorithm, but the mockups look fine. This solution will work well for pixel art.


texts:
I am trying to create a 2D Stage3D game where you can move the camera around the level in an RTS style. I thought about using Orthographic Matrix3D functions for this but when I try to scroll the whole "stage" also scrolls.

This is the Camera code:

    public function Camera2D(width:int, height:int, zoom:Number = 1) {
        resize(width, height);
                    _zoom = zoom;
    }

    public function resize(width:Number, height:Number):void {
        _width = width;
        _height = height;

        _projectionMatrix = makeMatrix(0, width, 0, height);

        _recalculate = true;
    }

    protected function makeMatrix(left:Number, right:Number, top:Number, bottom:Number, zNear:Number = 0, zFar:Number = 1):Matrix3D {
        return new Matrix3D(Vector.<Number>([
            2 / (right - left), 0, 0, 0,
            0, 2 / (top - bottom), 0, 0,
            0, 0, 1 / (zFar - zNear), 0,
            0, 0, zNear / (zNear - zFar), 1
        ]));
    }

    public function get viewMatrix():Matrix3D {
        if (_recalculate) {
            _recalculate = false;

            _viewMatrix.identity();
            _viewMatrix.appendTranslation( -_width / 2 - _x, -_height / 2 - y, 0);
            _viewMatrix.appendScale(_zoom, _zoom, 1);

            _renderMatrix.identity();
            _renderMatrix.append(_viewMatrix);

            _renderMatrix.append(_projectionMatrix);
        }

        return _renderMatrix;
    }

And the camera is send directly to the GPU with: c3d.setProgramConstantsFromMatrix(Context3DProgramType.VERTEX, 0, cameraMatrix, true);

And these are the shaders:

------Vertex Shader------
m44 op, va0, vc0
mov v0, va1.xy
mov v0.z, va0.z

------Fragment Shader------
tex ft0, v0, fs0 <2d,linear,nomip>
mov oc, ft1

Here is a example and here are two screenshots to show what I mean:

How do I only let the inside of the stage3D scroll and not the whole stage?