texts: Is Unity + Scala.js possible or even makes sense?

texts:
I never actually used Unity (yet) and I have no possibility to check anything now, but I'm thinking about Unity for my project. I actually know C# (and hate it for some unimportant reason) and I think I'm able to learn JS or UnityScript, but I just want to use a language I know and love - Scala.

There is Scala.js - a tool that compiles Scala code to JS code. And i'm thinking: is it possible to write Scala code in some IDE (Intellij), compile it to JS code and load into Unity? And if it IS possible, what difficulties may I encounter? Does this idea even makes sense, or should I forget it, use C#/Learn JS/UnityScript or just search some Scala game frameworks?


texts: What tools are needed for making 3D games?

texts:
Hi I'm new to 3D games developing, I can a little c++, C#, VB.Net, 3D Max, ArchiCad ..etc. my problem is where to get started, which tools I need to start a own 3D game like GTA, I have tried some tools like : 'Unity3D' (crashes on start), '3D Rad' (uses only built-in items), 'Game Maker A7' (only 2D games can be made there).. could you help me to find the tools of making a 3D game..plz
I'm using Windows XP SP 2, I don't have pixel shader 1.1 into my video card


texts: How can I rotate a Texture2D into / out of the screen?

texts: I am drawing a Texture2D onto the screen and have the need to rotate the texture forward, in a 3D way.  I'm using the SpriteBatch Draw() method and it only allows limited 2D rotation around the Z axis.  From tons of research online I have boiled down the solution to passing either an effect or matrix to SpriteBatch's Begin() method; however, after many hours of trial and error I haven't come up with anything working.


texts: How to get quaternion from two orthogonal 3D vectors?

texts: I have a unit vector representing the direction I want to "look" and a unit vector for up. They are orthogonal. How can I get the quaternion that represents that orientation from those two vectors?


texts: iPhone Game framework on top of cocos2d?

texts:
I am using cocos2d to develop iPhone game, however, it is just an 2D engine and developer is too flexible to use them - i.e. codes tends to be unmanageable.

Are there any more high level framework for game development, perfer using cocos2d?


texts: How do I get a Metal texture ID to render to it with Ogre?

texts:
I looked in the documentation, but I don't know how to get the texture ID.

void* texPtr = SixDegreesSDK_GetBackgroundTexture();
            if (texPtr != nil) {
                id<MTLTexture> mtlTexture = (__bridge id<MTLTexture>)texPtr;

                id<MTLDevice> device = [mtlTexture device];
                // !!! Not fond of creating a new command queue for every texture
                id<MTLCommandQueue> commandQueue = [device newCommandQueue];
                id<MTLCommandBuffer> commandBuffer = [commandQueue commandBuffer];
                id<MTLBlitCommandEncoder> blitEncoder = [commandBuffer blitCommandEncoder];

                NSUInteger textureWidth = mtlTexture.width;
                NSUInteger textureHeight = mtlTexture.height;
                NSUInteger rowbytes = mtlTexture.bufferBytesPerRow;
                MTLPixelFormat  pixFormat = mtlTexture.pixelFormat;
                CVPixelBufferRef _CVPixelBuffer = NULL;
                NSDictionary* cvBufferProperties = @{
                                                     (__bridge NSString*)kCVPixelBufferOpenGLCompatibilityKey : @YES,
                                                     (__bridge NSString*)kCVPixelBufferMetalCompatibilityKey : @YES,
                                                     };
                CVReturn cvret = CVPixelBufferCreate(kCFAllocatorDefault,
                                                     textureWidth, textureHeight,
                                                     kCVPixelFormatType_32RGBA,
                                                     (__bridge CFDictionaryRef)cvBufferProperties,
                                                     &_CVPixelBuffer);
                const IOSurfaceRef surface  = CVPixelBufferGetIOSurface(_CVPixelBuffer);             // available in ios11 sdk, ios4 runtime

                MTLTextureDescriptor* textureDescriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:pixFormat
                                                                                width:textureWidth
                                                                                height:textureHeight
                                                                                mipmapped:NO];
                id<MTLTexture> metalTexture = [device newTextureWithDescriptor:textureDescriptor
                                                                          ioSurface:surface
                                                                              plane:0];

                MTLRegion region = MTLRegionMake2D(0, 0, textureWidth, textureHeight);

                [blitEncoder copyFromTexture:mtlTexture
                                 sourceSlice:0
                                 sourceLevel:0
                                sourceOrigin:region.origin
                                  sourceSize:region.size
                                   toTexture:metalTexture
                            destinationSlice:0
                            destinationLevel:0
                           destinationOrigin:region.origin];

                [blitEncoder endEncoding];
                [commandBuffer commit];
                [self.mEAGLContext texImageIOSurface:surface target:GL_TEXTURE_2D internalFormat:GL_RGBA width:textureWidth height:textureHeight format:GL_RGBA type:GL_UNSIGNED_BYTE plane:0];


texts:
I'm making my first game and I just finished adding animations for walking and jumping. Everything looked good at first but with time they started distorting, even rotating (Rotation is Frozen).
This is how the character looks in the beginning:

But after some time of walking and jumping:

Did anyone have a similar error?
Can anyone Help?


texts: Does anyone have a better way to make an object with a rigidbody check for ground and then jump, right now I wrote a script where a raycast is cast downwards and it checks for distance but then I discovered that a player can still jump when close to the ground and when I decrease the distance amount on raycast then the jumping works a few times (5 or 6) and then stops working, so I had to increase the distance a bit and add a delay so the player can't jump for some time after a jump. But I think there might be a better way of doing it. So does anyone have suggestions on how can I improve my script or what other method I can use to make a character with a rigidbody to check if grounded and jump?


texts:
Just for background, I'm designing a soft engine in C# using the SharpDX DirectX wrapper library. I've gotten around to implementing the render engine, and I can render a texture to a face, except it only renders exactly one frame. It renders a triangle once, but on the next draw call, the screen is cleared. Even though I've made sure the render call is still firing every frame, the rendered item goes away, and does not get re-drawn in the next or any subsequent frame.

I think it has something to do with the way I initialize my resources; to minimize shader switching and boost performance, I have my render engine hold a set of pre-defined shader classes. Then, only when it is necessary will the shader access the device context and set the vertex, constant, index, etc. buffers one time when the method Shader.SetActive() is called. When the shader needs to render something, it can write directly to the buffers that have been created and set in the Shader.SetActive() method, using a method called UpdateShader().

Here's the source for SetActive():

public override void SetActive(D3D11.Device device, D3D11.DeviceContext context)
{
    /*========================== Set Pointers to GPU Buffers ==========================*/
    // write Matrix data first to constant buffer
    matrixBuffer = new D3D11.Buffer(device, matrixBufferDesc);
    vertexBuffer = new D3D11.Buffer(device, vertexBufferDesc);
    indexBuffer = new D3D11.Buffer(device, indexBufferDesc);

    context.InputAssembler.SetVertexBuffers(0, new D3D11.VertexBufferBinding(vertexBuffer,
    Utilities.SizeOf<VertexPositionTexture>(), 0));
    context.InputAssembler.SetIndexBuffer(indexBuffer, Format.R32_UInt, 0);
    context.VertexShader.SetConstantBuffer(matrixBufferPos, matrixBuffer);
    context.PixelShader.SetShaderResource(0, shaderTexture);

    context.InputAssembler.InputLayout = inputLayout;

    /*========================== set context shaders ==========================*/
    context.VertexShader.Set(vertexShader);
    context.PixelShader.Set(pixelShader);
    context.PixelShader.SetSampler(0, samplerState);

    context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
}

Here's the code for UpdateShader():

public void UpdateShader(D3D11.Device device, D3D11.DeviceContext context,
    Matrix worldViewProj, VertexPositionTexture[] vpts, int[] indices)
{
    DataStream mappedResource;

    //write to buffers
    context.MapSubresource(matrixBuffer, D3D11.MapMode.WriteDiscard, D3D11.MapFlags.None,
        out mappedResource);
    mappedResource.Write(worldViewProj);
    context.UnmapSubresource(matrixBuffer, 0);

    context.MapSubresource(vertexBuffer, D3D11.MapMode.WriteDiscard, D3D11.MapFlags.None,
        out mappedResource);
    mappedResource.WriteRange(vpts);
    context.UnmapSubresource(vertexBuffer, 0);

    context.MapSubresource(indexBuffer, D3D11.MapMode.WriteDiscard, D3D11.MapFlags.None,
        out mappedResource);
    mappedResource.WriteRange(indices);
    context.UnmapSubresource(indexBuffer, 0);

    context.DrawIndexed(indices.Length, 0, 0);
}

I think something that happens once in the SetActive() method should need to actually happen multiple times, and should be moved to the UpdateShader() method, but for the life of me I can't figure out what it is, or even if my reasoning is the correct.

Why is my render engine only rendering one frame?


texts: GJK algorithm in case of circle and polygon?

texts:
I wonder if it's possible to modify GJK so I can use it to detect collision between circle and n points polygon.
I implemented for polygon and polygon before, and I tried modifying the support function (to get furthest point of a circle), but apparently, this results in infinite loop.
Is this possible to do? do I need to change other thing than the support function? (because I don't see any)


texts: Simulate dirt spread (Normal distribution?)

texts:
-This question is technically more math related, but it has to do with a simulation so I am here first. I can post this in the math SE instead if needed.

I am in the process of trying out some mesh deformation simulating the effect of sand/dirt being poured in a pile (Think hourglass sand) and I am trying to determine the best way to calculate the spread instead of becoming increasingly taller. I don't intend on actually matching sand/dirt physics, I just want to get my mesh to be somewhat close to the shape that pile would make as it grows.

I'm pretty sure that Normal Distribution is what I want, so in my desmos graph below, think of f(x) -green line- as the current dirt/sand piling up (where I am at in my code) and f1(x) -purple line- as the spread version (what I want to happen instead).

f1(x) is not correct but I think it is pretty close. Essentially i need the area of f1(x) to always equal the area of f(x) but as f(x) gets taller, f1(x) gets wider and taller, but not as tall as f(x).

https://www.desmos.com/calculator/ir8if2u8qq

I hope this makes sense to you gurus. If not, I can try to clarify more.

Edit: Also, if you open that graph, the slider for variable 'h' is the one im essentially trying to work with.


texts: How can I avoid referring directly to the state type when transition to new states in a state machine?

texts:
I finally found a good way to implement a "stack-of-states" to manage what screen I am on.
Minimal example:

    class gameEngine {
public:
    //Removes state at the "back" of the stack and puts the new state at the "back" of the stack
    void ChangeState(std::shared_ptr<gameState> state);

    //Adds new state to top of stack
    void PushState(std::shared_ptr<gameState> state);

    //Removes back state from stack
    void PopState();

private:
    // The stack of states
    std::vector<gameState*> stateStack;
};

Now how I call the (for example) PushState command from inside a state itself (using tGUI library), where "stateGame" and "stateMainMenu" are game states:

void stateMainMenu::Init(gameEngine* game) {

    //Creates a new button
    tgui::Button::Ptr buttonStart = std::make_shared<tgui::Button>();

    //Connects the PushState function to this button. When clicked the engine will run the
    //PushState function with the arguments 'game' and a pointer to a new StateGame.
    buttonStart->connect("clicked", &gameEngine::PushState, game, std::make_shared<stateGame>());
}

This works, and I can transition between screens easily. However, I had a strange feeling that I shouldn't allow gameStates to know about the internals of other game states (I am including the header file for each gameState into each cpp file where I will need to transition to that state). Is it better to re-write the ChangeState and PushState functions to take an enum which refers to each game state, and then generate the shared pointers inside those functions? I'm really scratching my head, it probably makes no difference at all but I want to know what the better practice would be.

If anyone can make any sense of my rambling and put it to rest I would be extremely grateful.

Here is the full source for anyone interested, or who wants more context.


texts: Keyboard input not working for me in derived class

texts:
My code is unable to accept keyboard inputs in a specific class.

I know that I have used inheritance for that class, but I'm pretty sure that it is not the main reason why it doesn't work.

Can you guys look over my code to see if you can help me with my specific issue? The problem is in the Update() in HowToPlayMenu.cs.

HowToPlayMenu.cs (derived class)

using System;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace Our_First_Game
{
    class HowToPlayMenu : SplashScreen
    {
        private static KeyboardState keyOldState, keyNewState;

        public HowToPlayMenu(Texture2D Instructions) : base(Instructions)
        {
            image = Instructions;
            endScreen = true;
        }

        public override void Update()
        {
            if (endScreen && keyNewState.IsKeyDown(Keys.M))
            {
                endScreen = false;
                Console.WriteLine("end Screen false!");
            }
            else if (!endScreen && keyNewState.IsKeyDown(Keys.M) && keyOldState.IsKeyUp(Keys.M))
            {
                endScreen = true;
                Console.WriteLine("end Screen true!");
            }
        }

        public override void Draw(SpriteBatch spriteBatch)
        {
            base.Draw(spriteBatch);
        }
    }
}

SplashScreen.cs (base class)

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace Our_First_Game
{
    class SplashScreen
    {
        protected Texture2D image;
        protected bool endScreen = false;

        public SplashScreen(Texture2D SplashImage)
        {
            image = SplashImage;
        }

        public virtual void Update()
        {
            if (!endScreen)
            {
                if (Keyboard.GetState().IsKeyDown(Keys.Space))
                {
                    endScreen = true;
                    Game1.isGameActive = true;
                    Game1.reload1 = 0;
                    Game1.reload2 = 0;
                }
            }
        }

        public virtual void Draw(SpriteBatch spriteBatch)
        {
            if (!endScreen)
            {
                Game1.isGameActive = false;
                spriteBatch.Draw(image, new Rectangle(0 ,0 , 800, 480), Color.White);
            }
        }
    }
}


texts: Any fixed-point portable open-source 3D physics engines?

texts:
I'm looking for a fixed-point 3D physics engine (basic kynematics and collision detection-resolution... nothing too fancy.)

I need fixed-point math because I'd like to have deterministic results, for reproducibility purposes, and high portability, because I expect my game to be highly portable for devices such as mobile phones or portable gaming consoles without floating point units.


texts: Unity Debug - UnityGfxDeviceWorker (34): EXC_RESOURCE RESOURCE_TYPE_MEMORY

texts:
Unity - How does one debug this Xcode error on an iOS device?
Debug - UnityGfxDeviceWorker (34): EXC_RESOURCE RESOURCE_TYPE_MEMORY


texts: I want to make a countdown timer for my racing game such as "3... 2... 1... GO!" I'm using GLUT, OpenGL, and C++. I was wondering what the most appropriate method to handle this in C++. clock()? glutTimerFunc()? I plan on having 4 textured polygons that shrink and fade one after the other.


texts: License for a casino game with virtual money (chips)

texts:
Do I need a specific license for operating a casino game (lets say poker Hold'em or video slots) that players are supposed to play with virtual money (chips) only? I am speaking about games like Zynga poker, Poker Deluxe, Slotomania and the hundreds other similar games on iTunes or Google Play. Players start with a certain amount of chips and if they run out they can rebuy a bundle of coins to keep playing. The users may not exchange those collected virtual funds (chips) for products or services, or cash out for real money, but just keep on playing for a fun.

Do I need any license for operating such a game?


texts: Controlling Unity 3D cube with remote gyroscope

texts:
This probably will go into conceptual things as well, but what I would like to do is take a Raspberry Pi (with a Sense Hat), transmit the gyro values to Unity, and effectively have a 1-1 realistic representation of orientation changes.

I have no problem transmitting values from the Pi to Unity (though learning about hidden firewall rules was fun), however I am lacking some understanding of how to transform raw gyro values to something representative in Unity.

I have not calibrated the Sense hat recently, but know that is something that should be done.

For example, I am transmitting the pitch/roll/yaw values from the Pi (resting normally, these are about: 100.30272132022793, 351.3885231076573 354.9306950697191).

I have a cube gameobject that I've flattened out and set to the origin.

My question is basically, what is the best way to translate raw values from some anonymous object to the Unity coordinate system, and have it rotate appropriately?  I don't necessarily want its position to change, just rotation.

Screenshot for reference.  Raspberry Pi sending gyro data is on the left, Unity is on the right.  Tabletop (flattened cube) is what I'd like to rotate to simulate a ball balancer.


texts:
I am currently programming a very simple 2d game in C# with XNA.

I was wondering how to implement a console-type interface in a game or graphical software like there is in Skyrim or Counter-strike or some many more games?

These "consoles" can allow you through various command to change many parameters directly in-game.

I find this very interesting for debugging purposes and I was hoping to implement something similar in my program. Is there a particular way to achieve this?


texts: Unity WWW: Post a request to an URL with custom headers

texts:
I am using  C# to try retrieve a token and my code is based on this example:https://docs.unity3d.com/ScriptReference/WWWForm-headers.html

IEnumerator Start() {
  string urlToken = "myUrl";

  WWWForm form = new WWWForm ();
  form.AddField ("username", username);
  form.AddField ("password", password);

  Hashtable header = form.headers;//where I am getting my error*

  header.Add("content-type", "application/json"); //header I need send over

  WWW tokenRequest = new WWW (urlToken, form, header);

  yield return tokenRequest;
  print ("Anything back?" + tokenRequest.bytesDownloaded);
}

*Assets/WWWDemo.cs(46,19): error CS0029: Cannot implicitly convert type System.Collections.Generic.Dictionary to System.Collections.Hashtable

How would the header be assigned correctly? Does anyone have any ideas?


texts: Script attached to one button triggers other buttons too in unity

texts:
As you can see in the image above, I have 4 buttons.

I have attached a C# script to only one button to change the scene on click.

Now the scene should change only when I click on the button to which I have attached the script.

But the scene changes even if I click anywhere else on the screen.

This is the script that I have attached -

public class ButnDoSmthng : MonoBehaviour {

        void Update () {

        if (Input.GetMouseButtonDown(0))
            Application.LoadLevel ("Scene1");
    }
}

Whats wrong here and what might be a solution ?


texts: OnMouseEnter() function stops working when I set the canvas render mode to: Camera Overlay

texts:
Basically the title says it all. I have a OnMouseEnter() function that works fine when I have the canvas render mode on Worldspace but stops working when I change it to Camera Overlay.

Before, it would work with just the script with the mouse functions on it attached to the image object. Now to work I need to use an event trigger and add the script to another object to put it into the trigger.

Any idea why?


texts:
I'm interested in developing a game who's background music changes with the mood and scenario of the game's action. Of course many existing games do this (halo for example), but I was interested in any resources/papers/articles talking about the techniques to develop a system like this.

I have some ideas, and I understand that this will be equally challenging to implement at the code level as it will be to come up or acquire music that fits this model. Any links or, answers with ideas in them would he appreciated.

Edit: this is the kind of info I'm looking for :)
http://halo.bungie.org/misc/gdc.2002.music/


texts: Simple pass-through geometry shader with normal and color

texts:
I've written a very simple pass-through geometry shader. My input and output primitives are points. I also want to forward the color and normal from vertex shader to fragment shader through geometry shader. The shaders are compiled and linked flawlessly but the final color is very weird. I think there is something wrong with this forwarding. Can anyone point out the problem? Here are my shaders:

Vertex shader:

#version 330 compatibility

struct vData
{
    vec3 normal;
    vec4 color;
};

out vData vertex;

void main()
{
    vertex.normal = gl_NormalMatrix * gl_Normal;
    vertex.color = gl_Color;
    gl_Position = ftransform();
}

Geometry shader:

#version 330

layout (points) in;
layout (points) out;
layout (max_vertices = 1) out;

struct vData
{
    vec3 normal;
    vec4 color;
};

in vData vertices[];
out vData frag;

void main()
{
    int i;
    for(i = 0;i < gl_in.length();i++)
    {
        frag.normal = vertices[i].normal;
        frag.color = vertices[i].color;
        gl_Position = gl_in[i].gl_Position;
        EmitVertex();
    }
    EndPrimitive();
}

Fragment shader:

#version 330

struct vData
{
    vec3 normal;
    vec4 color;
};

in vData frag;

void main()
{
    gl_FragColor = frag.color;
}


texts: Execute a trigger after research is complete

texts:
I'm making a map where I want to destroy a building when it finishes researching a certain ability.

How do I create a trigger that accomplishes this?


texts: LibGDX - Centering different sized Tile Map Levels

texts:
Suppose I have a Level 1 tilemap which is 32 x 16 tiles in size, and when the player exits into another room, which is on 10 x 6 tiles in size, what's the best way to center the viewport. At the moment I am positioning my game cam as follows:

    gameCam = new OrthographicCamera();
    gameCam.setToOrtho(false,320,240);
    gamePort = new FitViewport(Darkcaster.V_WIDTH / Darkcaster.PPM, Darkcaster.V_HEIGHT / Darkcaster.PPM, gameCam);
    gameCam.position.set(gamePort.getWorldWidth() / 2, gamePort.getWorldHeight() / 2, 0);

The 320x240 is the screen resolution I wanted, and V_WIDTH/V_HEIGHT was also set to 320/240, as this was the size of my first level.

What I want is the smaller level to be centered in the screen (like a mini bonus room) and then I can fill the rest with black, but the scale of the tiles etc needs to stay the same.

I can get the map properties to work out how wide and tall each map is, but can't work out the math I need to get it working.

Obviously on levels which are bigger than the viewport (scrolling levels) the camera would just be centered on the player, but the smaller level would be in the center of the screen and not scroll.

Any ideas on the best way to achieve this?

Thanks

J


texts: How to improve performance with a lot of bullets and Mirror networking

texts:
The game
I have 300 enemies with rigidbodies. I also have 1 to 4 players with rigidbodies.
And they shot a lot of bullets. I have 1000 bullets with circle coliders only (no rigidbodies for bullets)
I'm here because I think the performance is really slow and I would like to improve it.
Here is what I've tried and already improved the performance a bit:
Defining a Layer Collision Matrix so that only enemies bullets collide with players, and players bullets collide with enemies.
Thanks to the comments, here is what I tried
Added rigidbodies to bullets to use velocity to translate them instead of translating them with "transform.position".
This resulted in a nice performance improvement of almost +29 fps.
Now enemies, bullets and players use rididbodies2D.
The profiler
I also used the profiler and noticed that Mirror (a network asset) is using a lot of the total performance. I don't know how to improve this.
All the enemies movement scripts also take a lot of "time" to run.
I can't find where the bullets are instanciated on the profiler.

How bullets are fired
I seem to get reduced performance once the enemies start shooting a lot of bullets. Here is what I do:
[ClientRpc]
public void Fire(Transform target)
{
    if (lastShootTime >= timeBetweenShoot)
    {
        for (int i = 0; i < enemyData.shotAngles.Length; i++)
        {
            Vector3 dir = target.position - transform.position;
            dir = Quaternion.Euler(0, 0, enemyData.shotAngles[i]) * dir;
            float angle = Mathf.Atan2(dir.y, dir.x);

            GameObject bullet = BulletPool.bulletPoolInstance.GetBullet();
            bullet.transform.position = transform.position;
            bullet.transform.rotation = Quaternion.identity;
            bullet.SetActive(true);
            bullet.GetComponent<Bullet>().SetMoveDirection(ShootBehaviour.RadianToVector2(angle));
            bullet.GetComponent<Bullet>().SetSpeed(bulletSpeed);
            bullet.GetComponent<Bullet>().SetType(Entity.Type.ENEMY);
            bullet.GetComponent<Bullet>().SetColor(Color.red);
            bullet.gameObject.layer = 8;
        }

        lastShootTime = 0;
    }
}

So I use a ClientRpc from Mirror to shoot bullets in server and clients.
If I comment the ClientRpc, this is what I get:


texts: How can I implement a directional melee attack?

texts:
I am attempting to make a top down game similar to the SNES Zelda games, in Unity 4.3, in 2D. When my character swings their sword, every enemy within a radius takes damage. I want to make sure that melee attacks only damage enemies the player is facing.

How can I do this?

The relevant code in PlayerAttack.cs looks like this:

// Update is called once per frame
void Update () {
    // have the player initiate an attack on the object
    if(Input.GetKeyUp(KeyCode.F)){
        MeleeAttack();
    }
}

private void MeleeAttack(){
    // create a variable called distance to make sure the distance is close enough
    // to inflict damage from a melee attack target.transform.positon = the position
    // of the object to attack and transform.position is the position of the players
    // transform
    float distance = Vector3.Distance(target.transform.position, transform.position);

    // make sure the distance is not greater than 1.5 so the player cannot
    // melee an enemy from to far away
    if(distance < 1.5f){
            // get a reference to the enemy's health script and type cast it.
            EnemyHealth eh = (EnemyHealth)target.GetComponent("EnemyHealth");
            // now call the function that will decrease the enemy's health
            eh.AdjustCurrentHealth(-10);
    }
}


texts:
I've been seeing lots of simple interactive programs popping up all over the internet that generate basic music, usually quite nice sounding, from simple interactions from the user. Otomata is one recent popular example; on the iDevices there are a variety of programs, like Bloom.

I'm just wondering how these programs work. How do they generate the music live? Are there established APIs for doing this? I'm interested in the technical aspects of how this is implemented. My knowledge is so lacking here I'm honestly not sure how to better phrase the question. Ask if anything isn't clear!


texts: Unity: Can't press space to unpause. Is this a Unity UI bug? Or maybe poorly written code?

texts:
So I think I have a bug with my pause menu. For the sake of simplicity I've boiled down what I'm trying to acheive: When the player first starts up the game there's a UI menu with one button: 'Start Game' that they have to press to start the game. They can then pause and bring up this menu again at any time by pressing space. The player can resume the game either by pressing 'Start Game' or by pressing space again.

The problem right now is that when the player presses space again to unpause, nothing happens - unless they click anywhere on the screen. It's sort of complicated to explain but I'll try my best.

Say the player previously started or unpaused the game by clicking the 'Start Game' button. If they pause the game again, they can only unpause the game by pressing space if they click somewhere on the screen. This works if the player clicks somewhere on the screen before or after they press pause.

However, If the player previously unpaused the game by pressing space, they can pause and unpause by pressing space indefinitely (until they unpause by pressing 'Start Game'). Is this a bug with the Unity UI system (I'm using Unity 5.0)? Or maybe with my code?

Here's my code:

public class GameController : MonoBehaviour
    {bool paused;
    public GameObject canvas; //in the editor I set this to reference the canvas that
                              //the 'Start Game' button is on

    void Awake()
        {PauseGame ();}

    void Update()
        {if (Input.GetKeyDown (KeyCode.Space))
            {PauseGame ();
            Debug.Log ("Pressed 'Space'");}
        }

    public void PauseGame()
        {paused = !paused;
        if (paused == true)
            {Time.timeScale = 0;
            canvas.SetActive (true);
            Debug.Log ("'Pause' Called");}

        else
            {Time.timeScale = 1;
            canvas.SetActive (false);
            Debug.Log ("'Unpause' Called");}
        }
    }

*The 'Start Game' button calls the PauseGame() method from the GameController script

Update

I wrote some debugging lines to figure out what was happening. Apparently, if the player previously unpauses by pressing 'Start Game' then pauses again, when they try to unpause by pressing space the game does indeed unpause but then immediately pauses again. However it only does this if the player previously unpaused by pressing 'Start Game' (and can be remedied by clicking somewhere on the screen before or after pausing). This doesn't happen if the player previously unpaused by pressing space.

Update

Apparently the 'Unpause' is being called by the event system, and the 'Pause' is being called by pressing space. I guess Unity has it built in that if a player previously clicked a UI button, pressing space will click that button again when the option is available. Does anyone know how to alter this?


texts: What is the value of gameTime.ElapsedGameTime.TotalSeconds?

texts: I was wondering what is exactly the value of gameTime.ElapsedGameTime.TotalSeconds in a second? Please explain it to me completely and as great as you can.


texts: Uploading APK build to Google Play Console error "You uploaded a debuggable APK or Android App Bundle"

texts:
I was trying to upload my andoid app apk build to my play console account and I keep getting this error:

You uploaded a debuggable APK or Android App Bundle. For security reasons you need to disable debugging before it can be published in Google Play.

In accordance with the informations given at

https://developer.android.com/studio/publish/preparing.html#publishing-configure

and

https://answers.unity.com/questions/1653647/you-uploaded-a-debuggable-apk-or-android-app-bundl.html

Here are what I have done so far:

1) I have gone to the root folder of my unity project, searched for AndroidManifest.xml, and I found multiple Manifest files, and changed the value of "android:debuggable" to false for each of these manifest files that were generated by unity(and I did not edit the google generated manifest files).

2) I have scanned every c# file on my project that contains the keyword "Debug" and I have either deleted or commented out the Debug.log lines except on the files generated by google(as a result of the integration of google play services into my game).

And yet, I still have the same problem when I try to upload my apk to play console. What else am I missing? Should I also remove the Debug.log lines from google generated c# script files?


texts: What to consider when deciding on 2D vs 3D for a game?

texts:
How much "harder" is 3D than 2D in terms of:

Amount/complexity of the code
Level of math skills required
Time involved in making art assets

Original title: How hard is 3D game development versus 2D?


texts:
In 3d space, objects can be occluded by another objects.
By depth testing, the occluded faces are skipped rendering. Only the nearest(smallest) depth value pixels are drawn.
But, sometime we need to render the occluded object or pixels for game play.

To differentiate the occluded object's pixels from foreground pixels, some game use gray color to render the pixels.

This is the sample images for the case.

I guess this can be achieved by some sort of shader.
How can I make this effects in Unity 3D Engine? Any hints or idea plz.


texts:
I cannot figure out how to apply collision to a turtle. I am in need of help for collision with pen lines and turtles. I want the two to hit and restart the game but I can't get collision on either.

import turtle
import pygame

wn = turtle.Screen()
wn.bgcolor("black")

#Draw border
mypen = turtle.Turtle()
mypen.penup()
mypen.pencolor('white')
mypen.setposition(-300,-300)
mypen.pendown()
mypen.pensize(3)
for side in range (4):
    mypen.forward(600)
    mypen.left(90)
mypen.hideturtle()

#Create player 1
player = turtle.Turtle()
player.setposition(240,240)
player.setheading(180)
player.color("red")
player.shape("classic")

player.speed(0)

#Create player 2
player2 = turtle.Turtle()
player2.setposition(-240,-240)
player2.color("aqua")
player2.shape("triangle")

player2.speed(0)

#Set speed variable
speed = 3

#Define functions
def turnleft():
    player.left(30)

def turnright():
    player.right(30)

def increasespeed():
    global speed
    speed += 3

#Set keyboard bindings for p1ayer 1

turtle.listen()
turtle.onkey(turnleft,"Left")
turtle.onkey(turnright,"Right")

#Define player 2 functions

def turnleft():
    player2.left(30)

def turnright():
    player2.right(30)

def increasespeed():
    global speed
    speed += 3

#Set keyboard bindings for player 2
turtle.listen()
turtle.onkey(turnleft,"a")
turtle.onkey(turnright,"d")

#turtle.onkey(increasespeed,"Up")

while True:
    player.forward(speed)
    player2.forward(speed)

    #Bouandary
    if player.xcor() > 300 or player.xcor() < -300:
        player.right(100)
    #Boundary
    if player.ycor() > 300 or player.ycor() < -300:
        player.right(100)
    #Bouandary2
    if player2.xcor() > 300 or player2.xcor() < -300:
        player2.right(100)
    #Boundary2
    if player2.ycor() > 300 or player2.ycor() < -300:
        player2.right(100)


texts: How to assign an instance of an object to an array?

texts:
Game Engine: Gamemaker Studio

I am making a game similar to bejeweled. I decided to use an array to control everything. Placing instances of objects themselves in to the array seems to be the best way to accomplish this because then I won't have to check where the square is in the room, and then compare it to where in the array that lines up, and so on and so forth.

However, I can't figure out how to do that. How do I do it?


texts: Unity3D Making timescale freeze and resume

texts:
So, I'm  trying to make it where when a popup(Ui panel and text) appears, the game's time(timescale) would freeze. Then when the user enters input and clicks enter button, the popup would disappear and time would resume.

How could I make time follow this?


texts:
I have a plane GameObject on which I want to place cubes. The user can move the cube around on the plane and when LMB is clicked, the cube is placed at that position. Everything works great, besides the position of the cube is not that accurate. In the center of my plane, mouse pointer and cube position match perfectly, moving the mouse along the x-Axis also works fine, but up or down (z-axis in game world) doesn't work well, the mouse moves "more" than the cube object. Here's photos of the issue:

and here's my source code:

void Update()
    {
        Vector3 m = Input.mousePosition;
        Vector3 n = Camera.main.ScreenToWorldPoint(new Vector3(m.x, m.y, 1));
        float camDistance = (float)Math.Sqrt((Math.Pow(n.y, 2.0f) + Math.Pow(6, 2.0f)));
        Vector3 p = Camera.main.ScreenToWorldPoint(new Vector3(m.x, m.y, camDistance));

        cube.position = new Vector3(p.x, 0.3f, p.z);
    }

At first I used camDistance as a constant that doesn't change (distance from the camera to the center of the plane), then I tried to adjust it depending on where the object is (distance from the camera to the mouse position in world coordinates). It still doesn't look great, so I need some help.

Thank you!


texts: Checkers movement and capture logic in java

texts:
I am making a checkers game.

I implemented a 2D array to store the board position, and made a grid layout with all my squares as panels. I also have my pieces drawn.

I wanted some info on how I would make the movement methods or the capture method. My main issue is finding a mathematical way to code the jump and what I need to do in order to move the pieces properly.

I was thinking of having a method to check if the move is legal and a method to actually move.


texts: Entity Component Systems, Input, and Angry Birds!

texts:
I am using Artemis ECS. I have the very basics of a game already. I am now trying to determine how to gracefully handle input and to a lesser extent collisions. Some people say with ECSs, everything should be a component and data driven and you shouldn't really use events/messages, or at least avoid them where possible.

Input handling in component based design covers what I am asking as well, but I would understand when and how to raise events, add components or whatever much more fully by using a game we all know (Angry Birds) as an example.

So, for Angry Birds I would have some entities with components (where components are pure data, and an entity is just an id):

catapult (position, sprite, state{free, available}?, clickable?, dragable? releasable?)
bird (position, velocity, physics{density}, sprite)
baddy (position, velocity, physics {density}, sprite, health)
box (position, velocity, physics{density}, sprite, health)

And the following systems to start with:

SpriteSystem (has all entities with sprite component)
PhysicsSystem (has all entities with position, velocity and physics components)
HealthSystem (has all entities with health component)
InputSystem (knows about keyboard/mouse events such as clicked, dragged, released, key down etc, not sure what entities should have...)

How would the InputSystem interact with other Systems to say the catapult was clicked, and if there are birds left, and none are in flight, allow it to be dragged and release/fire the bird.

Would the InputSystem modify ClickableComponent, DragableComponent and ReleasableComponents on the catapult entity? Or, should it raise some sort of Click, Drag and Release Events? What System would listen for the component changes/events? A CatapultSystem perhaps?

When the PhysicsSystem notices a collision between the bird and a baddy, should it create a Collision event, that I guess the HealthSystem would listen for? Or again, should it modify a collision Component already on the Entity?

Collision and click components would need to be cleared every game loop if I took the component approach (seems a bit naff...)


texts: How do I determine if a tile is a slope based on the tile image?

texts: In my game, every tile is a 32x32 texture. All the slopes are a 0 - 45 degree angle. I would like to determine, at the time I load the tile, if the is sloped by examining its texture/bitmap data. How can I do this?


texts:
I'm in the middle of an encounter system for an XNA RPG. The idea is, you walk around a dungeon, and certain tiles are makred as RandomBattleTiles, and you have an area in the map defining what monsters can be encountered. What I need is a way to layout the way a monster levels and how it's stat's increase. I was thinking something along these lines:

<Species>
    <Name>MonsterA</Name>
    <ID>001</ID>
    <SpriteName>monstera_sprite</SpriteName>
    <Levels>
       <Level>
          <LevelID>1</LevelID>
          <Stats>
              <Attack>12</Attack>
              <Defense>10</Defense>
              <Speed>20</Speed>
          </Stats>
          <Moves>
               <Move ID="1" Level="2"/>
          </Moves>
        </Level>
     </Levels>
</Species>

Would this be proper? Moves would follow a similar definition pattern.


texts: What are the steps in creating app icon for ios?

texts:
I have completed developing my game (iOS) and now preparing it to submit to the appstore. However, i have some confusion regarding app icon.

1>In Unity build->player settings, there are various sizes mentioned. Largest size is 180x180 px. But i read somewhere apple requires 512x512 px icon.

2>Is the build-->player settings the only place where i provide app icons or are there more steps involved in xcode? If there are, please provide link to some documentation.

Thanks.


texts:
I am a beginner Unity-user, and interested in high-tech thems.
So I'm looking to make a high-tech futuristic gaming-room in HDRP. I'm therefore looking to do some effect on my window in the room. The plan was to make it so that I can turn it on/off, show a movie, and show text changing all the time. No need for interaction with the windows, but more like an animation on a transparent surface. Is this something an n00b can possibly make, or is it really complex?


texts: How to nerf something without the player community hating you?

texts:
No matter how well you conceptualize an online game, there will always be certain gameplay elements which will turn out to be vastly overpowered and dominate the gameplay.

The obvious solution in that case is to do an update and make that gameplay element weaker (to "nerf" it).

But when developers do this, it often causes an outrage among the player community. Player liked to dominate the game by overusing that overpowered gameplay-element and are now angry that their game now plays differently and is thus ruined forever. The game might be objectively better after the nerf, but the natural human resistance to change outweighs this positive effect for many players.

How can you correct balance mistakes without causing a player outrage?


texts: Unity Matrix4x4 to rotate a point around a pivot / axis

texts:
I need the Matrix4x4 to rotate around a given axis that does not go through (0,0,0). Is there some built in straightforward way to do this in the Unity libraries, or do I need to build and maintain my own?
Below is the formula I'd use to build my own in case somebody needs it:

We will define an arbitrary line by a point the line goes through and
a direction vector. If the axis of rotation is given by two points P1
= (a,b,c) and P2 = (d,e,f), then a direction vector can be obtained by ⟨u,v,w⟩ = ⟨d-a,e-b,f -c⟩. [...] Assuming that ⟨u,v,w⟩ is a unit vector
so that L = 1, we obtain [...]

Source

I do need the rotation Matrix, not just the rotation. If I didn't need the Matrix I could use (not tested, may contain flaws, but you get the idea):
public Vector3 RotatePointAroundAxis(Vector3 point, Ray axis, float rotation) {
    return Quaternion.AngleAxis(rotation,axis.direction) * (point - axis.origin) + axis.origin;
}

So far the best I've got is the equivalent of the above (not tested, may contain flaws, but you get the idea), but it looks quite wasteful:
public Matrix4x4 RotationMatrixAroundAxis(Ray axis, float rotation) {
    return Matrix4x4.TRS(-Axis.origin, Quaternion.AngleAxis(rotation, Axis.direction), Vector3.one)
         * Matrix4x4.TRS(Axis.origin, Quaternion.identity, Vector3.one);
}


texts: What resources are available to read and share pyglet code?

texts:
I am a Python programmer (I know the ins and outs decently well), and I have dabbled with Pygame. I want to make 3D applications and games, and so naturally I've been looking at OpenGL.

pyglet uses OpenGL, and the programming website and documentation is up there with the best I've seen as far as libraries and APIs go.

Is there a place on the net where other pyglet programmers go to share projects and source code, like there is for Pygame?

I would love to see how other people are combining game logic and OpenGL graphical code to create a simple game (it really helps the learning process).


texts: How to do I make my sprite move when it's instantiated in Unity5?

texts:
Here's the code I currently try to use to move my instantiated sprite:

time++;

    if (cow == 1 && time >= wait)
    {
        Cow0Walk();
    }

    if (cow == 2 && time >= wait)
    {
        Cow1Walk();
    }

    if (cow == 3 && time >= wait)
    {
        Cow2Walk();
    }

    if (cow == 4 && time >= wait)
    {
        Cow3Walk();
    }

    if (cow == 5 && time >= wait)
    {
        Cow4Walk();
    }

    if (time >= walkTime)
    {
        wait = rnd.Next(45, 140);
        cow = rnd.Next(1, cowAmount);
        walkTime = rnd.Next(1, 4);
        direction = rnd.Next(1, 4);
    }

Heres the one of the walk methods:

    void Cow0Walk()
{
    if (time <= walkTime && direction == 1)
    {
        cows[0].transform.Translate(Vector2.up * speed);
        cows[0].transform.Translate(Vector2.right * speed);
    }

    if (time <= walkTime && direction == 2)
    {
        cows[0].transform.Translate(Vector2.up * speed);
        cows[0].transform.Translate(Vector2.left * speed);
    }

    if (time <= walkTime && direction == 3)
    {
        cows[0].transform.Translate(Vector2.down * speed);
        cows[0].transform.Translate(Vector2.right * speed);
    }

    if (time <= walkTime && direction == 4)
    {
        cows[0].transform.Translate(Vector2.down * speed);
        cows[0].transform.Translate(Vector2.left * speed);
    }
}


texts: Moving a Sprite using Mouse in SFML (setOrigin logic needed)

texts:
I trying to make a card game using SFML. I want to move the card relative to the position the player selects on the card. I managed to check if the card is pressed. However, when I click and drag, the top-left (the origin) of the card is immediately moved to where the mouse is. I tried to set the origin, in the process_events function, to 'event.mouseButton' (both x and y) each time the card is pressed but it moves to the top-left corner of the screen. I spent a lot of time on this. I hope you guys will help me out.

const int card_width = 79;
const int card_height = 123;

Game::Game()
: window(sf::VideoMode(1024, 800), "SFML")
, frame_rate(sf::seconds(1.f / 60.f))
, card(card_sheet, sf::IntRect(0, 0, card_width, card_height))
// 'card' is an sf::Sprite object pointing to an sf::Texture object that holds the sprite sheet.
, selected(false)
{
    card.setPosition(500.f, 400.f);
    card.setOrigin(card_width / 2, card_height / 2);
    // I tried to set the origin to the center of the card.
    // Still doesn't look nice.
}

void Game::process_events()
{
    sf::Event event;
    while (window.pollEvent(event))
    {
        switch (event.type)
        {
            case sf::Event::Closed:
                window.close();
            break;
            case sf::Event::MouseButtonPressed:
                if (event.mouseButton.button == sf::Mouse::Left)
                    if (card.getGlobalBounds().
                                   contains(sf::Mouse::getPosition(window).x,
                                            sf::Mouse::getPosition(window).y))
                    {
                        // the problem is here
                        card.setOrigin(event.mouseButton.x, event.mouseButton.y);
                        selected = true;
                    }

            break;
            case sf::Event::MouseMoved:

                if (selected)
                {
                    // stuff might need to be added here too
                    card.setPosition(sf::Mouse::getPosition(window).x, sf::Mouse::getPosition(window).y);
                }
            break;
            case sf::Event::MouseButtonReleased:
                selected = false;
            break;
            default: break;
        }
    }
}

void Game::update(sf::Time dt)
{
}

void Game::render()
{
    window.clear();
    window.draw(card);
    window.display();
}

void Game::run()
{
    sf::Clock clock;
    while(window.isOpen())
    {
        sf::Time dt = clock.restart();
        process_events();
        update(dt);
        render();
    }
}


texts: DXGI - Frame rate drops from ~8000 FPS to ~1500 FPS when switching to full screen mode

texts:
I've created a simple app with a DirectX11 device and swap chain (IDXGISwapChain). All it does is clear the screen with a color and call Present(0, 0) on the swap chain. The app handles full screen/windowed mode transition by itself (I passed DXGI_MWA_NO_WINDOW_CHANGES) to the IDXGIFactory object. After switching from windowed mode to full screen, the VS graphics profiler shows a drop in the frame rate, from ~8000 FPS (window mode) to ~1500 FPS (full screen mode). I think I'm resizing my buffers properly (in response to WM_SIZE), I'm not getting any warnings about presentation inefficiencies in the debug window. The mode used to create the swap chain is obtained by enumerating the supported modes of the output device and selecting the proper resolution info. Isn't full screen mode supposed to be more efficient (as I understand, it can simply do a flip instead of a bit blit).
The code is here in case you want to take a look.


texts:
I'm making an RPG in Unity3D and I am trying to make a script for a chest to open. So I built this script! But it doesn't work. I just want some help fixing this script.

#pragma strict
var Text : GameObject;
var OpenedChest : GameObject;
var CurrentChest : GameObject;

function OnTriggerEnter()
{
    Text.SetActive(true);
    if (Input.GetKeyDown("e"))
    {
        CurrentChest.SetActive(false);
        OpenedChest.SetActive(true);
    }
}

function OnTriggerExit()
{
    Text.SetActive(false);
}

I get no compiler errors. When I go into the collider that triggers the text, that works, but what doesn't is when I press E to open the chest. It doesn't activate the other chest. What is wrong with my script?


texts: Moving along a flat plane with accordance to camera view

texts:
I'm making a 3D game, and I'm stuck on a little experiment.

I currently have a flat plane with a free camera running around, and a sphere (really, a light approximated as a sphere) that rests above the surface of the plane at, say, 50 units up. I'm trying to move the sphere, and I can do this easily by simply adding to the position in the X and Z direction. However, I got a bit messed up because when I move the camera, pressing the left arrow might move the sphere to the right, because of the coordinates. So I'm trying to move the sphere along the X and Z dependant on where my camera is looking.

For example, if I was looking at it from behind, down on an angle, I expect the sphere to move to the camera's left along the plane, or move down towards the camera, still along the plane.

I have seemed to get left and right working with
a.Position -= Vector3.Cross(((FreeCamera)camera).Forward, ((FreeCamera)camera).Up); but trying to move the sphere using just the camera's forward causes the sphere to move into or out of the plane, depending on the angle of the camera (this makes sense, because the camera's forward may be pointing into the plane).

My question is, how do I move an object left or right along a plane (remaining 50 units above the Y axis) in accordance to the camera's direction? For example, viewing the plane from its left facing towards the center, moving left should make it move towards the top of the plane if viewed from the back or to the camera's local left.

Here's two screenshots showing what I mean:

When viewing the red light from here:

Pressing right should give me this. Notice how the red sphere has moved (disregard the fact the camera angle changed slightly):


texts: Understanding this terrain intersection algorithm

texts:
I was looking for a fast way to get a ray intersection point of a terrain defined by a heightmap and I stumbled upon this: https://publications.lib.chalmers.se/records/fulltext/250170/250170.pdf
At part 3.2, I don't quite understand why we would get an intersection point in the beginning of the while loop, since it starts with the first quadtree node which is basically the whole map. Thus, there shouldn't be an intersection point with the ray (except if the ray starts out of AABB, higher than the max height of the terrain but that is never the case for me).


texts: Can I add non-trees to terrain.terrainData.treeInstances on Unity 3D?

texts:
I need to create a brush in which there will be stones, poles, bushes and other elements of the environment. I bought a Prefab Brush. Whether it is possible to add the objects that I draw on the Prefab Brush scene to terrainData.treeInstances, as regular trees add?

Is it possible to use a not prefab tree as an object for the TreeInstance class?


texts: I have a texture sfml but this texture have a format RGBA how i can change it to BGRA? Or how to create texture with need able format for me?


texts: DirectX11 CreateWICTextureFromMemory Using PNG

texts:
I've currently got textures loading using CreateWICTextureFromFile however I'd like a little more control over it, and I'd like to store images in their byte form in a resource loader. Below is just two sets of test code that return two separate results and I'm looking for any insight into a possible solution.

ID3D11ShaderResourceView* srv;

std::basic_ifstream<unsigned char> file("image.png", std::ios::binary);

file.seekg(0,std::ios::end);
int length = file.tellg();
file.seekg(0,std::ios::beg);

unsigned char* buffer = new unsigned char[length];
file.read(&buffer[0],length);

file.close();

HRESULT hr;
hr = DirectX::CreateWICTextureFromMemory(_D3D->GetDevice(), _D3D->GetDeviceContext(), &buffer[0], sizeof(buffer), nullptr, &srv, NULL);

As a return for the above code I get Component not found.

std::ifstream file;
ID3D11ShaderResourceView* srv;

file.open("image.png", std::ios::binary);

file.seekg(0,std::ios::end);
int length = file.tellg();
file.seekg(0,std::ios::beg);

std::vector<char> buffer(length);
file.read(&buffer[0],length);

file.close();

HRESULT hr;
hr = DirectX::CreateWICTextureFromMemory(_D3D->GetDevice(), _D3D->GetDeviceContext(), (const uint8_t*)&buffer[0], sizeof(buffer), nullptr, &srv, NULL);

The above code returns that the image format is unknown.

I'm clearly doing something wrong here, any help is greatly appreciated. Tried finding anything even similar on stackoverflow, and google to no avail.


texts: Using LibGDX, is it necessary to clip what I'm rendering for efficiency?

texts:
So I am working on a game, and I've noticed that everything in the world is sent to be rendered. Of course with the camera, only some of the world is rendered.

Does this mean there is there any expense for when I send all those extra vertices to OpenGL that don't show up on screen? Will OpenGL/LibGDX do it automatically?

If I should clip it, is ScissorStack the way to go?


texts:
So I've been working on my game for roughly two years now and although it's significantly more balanced than it was a year ago, I still feel like it's too easy, or rather, doesn't really have any sort of difficulty curve over time. It's a top-down shooter, and more enemies appear as you get to later waves, but the bosses are all a joke in terms of difficulty and some of the weapons can easily obliterate large groups of enemies if you know how to use them properly.

So how do I know what "magic numbers" to pick to have a consistent difficulty to my game, and is there a good way to determine a formula to increase that difficulty in later waves? Should I be increasing health of enemies over time? Or would that not make sense since they're the same enemies? I increase number of enemies over time by having a "spawning pool" which is just an integer that increases on a logarithmic scale according to a formula I just came up with and plotted a while ago. Each enemy has a "cost" to spawn and at the beginning of each wave, random enemies are chosen and their cost deducted until the spawning pool is depleted for that wave.

The enemies' damage and health are calculated randomly using a sort of D20 system like Dungeons & Dragons where, for example, the very first enemy you encounter in the game's health is calculated by rolling 2d8+12 (roll two 8-sided die and add 12), so the range of health values they can have is 14-28. All enemies' health is calculated this way. The enemies' attacks and damage over time effects, as well as the player's weapons all use this method to generate numbers.

Is there a good way to decide on good numbers short of just playing over and over again until it feels right? Would it be bad to increase their health and damage over time since they're still the same enemies? Or maybe I should get rid of them in later waves and replace them with an upgraded basic enemy that's identical (maybe a color swap) but with better stats?

Examples would be awesome.


texts: How do multiplayer servers handle receiving, handling, and sending packets?

texts:
I want to make a fighter jet simulator game.
The server (authoritative) and client communicate over udp.
The server sends out updates about the gamestate at a fixed rate. Think of plane positions, speeds, rotation, basically anything to do with physics.
On demand, the server sends out packets for spawning bullets and applying damage. So this is not at a fixed tickrate. This is done to sidestep the problem of superbullets and syncing fire rates with tick rates entirely. This class of packets also include chat messages.
How do I go about implementing this? I am using c/c++, programming raw sockets. I am running into the issue where the recvfrom function is blocking. I can set it to non-blocking using fnctl, yes, but that spams error messages because sometimes there are no packets waiting to be handled (I could handle it but egh, inelegant). Ideally I would like to prevent multithreading, but given that there seems to be no native event-driven or interrupt-driven way of receiving packets it seems I need to do that.
How do other game servers, like quake arena, set up their threads?
My idea:

Main thread calculates game state, sends out packets at a fixed rate
1 child thread for listening for new packets (recvfrom loop)

If the incoming packet is a "i am shooting" packet, it performs checks, and broadcasts to every client that a bullet has spawned. It adds the bullet to the world, and the main thread will calculate the continued trajectory in the next or current tickcycle, using the time difference and initial spawn data.
if the incoming packet is a chat message, perform checks and just broadcast it across clients.
if the incoming packet is any other kind of packet, put it in a queue for the main thread to handle (the queue is mutexxed)

Is this how I should make the child and main communicate?


texts:
I am working on a project in 3ds Max, but when I render the project it looks very weird. See this picture for an example:

How can I fix this?


texts:
I have a hierarchy like this

Body
  - Head
  - Arms

Currently this works fine in that the Body's transformation is reacting as it should. Being children, the Head and Arms match the Body's transform. Is it possible however to separate just the rotation transform? I would like the head to translate with the body but not necessarily rotate the same way.

I tried using Transform.DetachChildren but that removes the translate transform which is a bit of an issue as I move the object using physics so there's a chance the head and arms would react differently and physically separate from the body.

Thanks


texts: How can I make a chest that can be opened and shut in SteamVR?

texts:
I'm working in Unity with SteamVR for a school project. I'm trying to have a chest that can be opened and shut. I tried using a hinge joint but it would break if the attached body was static which is what I want.
I'm now trying to use a circular drive which works better but the lid to the box will move away from the intended position when colliding with the body of the box which is set to static and kinematic.
I can fix this by setting the lid to kinematic but it won't collide with the body anymore. Both the lid and body are properly colliding with the hand and with a sphere I added to help test collisions.
I'm assuming the issue is that two kinematic objects can't collide with each other but I don't know how else to approach this.


texts: My texture blends into one single color (DirectX11)

texts:
First thread on gamedev stackexchange. I am currently creating a cube with a single texture on each side. I got my cube up and running. But when I apply my texture, I get this:

It blends the texture into a single color and apply it. I have various of examples that look near identical but do not have the same problem. Anyone know what can be the cause of this issue?

3D programming in general contains quite a bit of code. I wont copy paste all of it. If you want to see anything specific, you can request it. But here are some of the functions. Thanks in advance.

HRESULT Cubes::Render(ID3D11DeviceContext* _deviceContext, Camera _camera)
{
    HRESULT hr = S_OK;

    unsigned int stride = sizeof(Vertex);
    unsigned int offset = 0;

    _deviceContext->IASetVertexBuffers(0, 1, &this->mVertexBuffer, &stride, &offset);
    _deviceContext->IASetIndexBuffer(this->mIndexBuffer, DXGI_FORMAT_R32_UINT, 0);
    _deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

    D3D11_MAPPED_SUBRESOURCE ms;
    hr = _deviceContext->Map(this->mMatrixBuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &ms );
    if(FAILED(hr))
    {
        OutputDebugString("Failed to map matrixbuffer in Cubes.\n");
        return hr;
    }

    WVPBuffer* dataPtr;
    dataPtr = (WVPBuffer*)ms.pData;
    dataPtr->worldMatrix        = DirectX::XMMatrixTranspose( this->mWorld);
    dataPtr->viewMatrix         = DirectX::XMMatrixTranspose( _camera.GetView());
    dataPtr->projectionMatrix   = DirectX::XMMatrixTranspose( _camera.GetProj());

    _deviceContext->Unmap(this->mMatrixBuffer, NULL );

    // Set the position of the constant buffer in the vertex shader.
    int bufferNumber = 0;
    _deviceContext->VSSetConstantBuffers( 0, 1, &this->mMatrixBuffer );

    // Set the vertex input layout.
    _deviceContext->IASetInputLayout(this->mInputLayout);

    // Set the vertex and pixel shaders that will be used to render this triangle.
    _deviceContext->VSSetShader(this->mVertexShader, NULL, 0);
    _deviceContext->PSSetShader(this->mPixelShader, NULL, 0);
    _deviceContext->RSSetState(this->mRasterState);

    // Set shader texture resource in the pixel shader.
    _deviceContext->PSSetShaderResources(0, 1, &this->mTexture);
    _deviceContext->PSSetSamplers(0, 1, &this->mSamplerState);

    // Render the triangle.
    _deviceContext->DrawIndexed(this->mNoIndex, 0, 0);

    return hr;
}

HRESULT Cubes::LoadTexture(ID3D11Device* _device)
{
    HRESULT hr = S_OK;

    hr = D3DX11CreateShaderResourceViewFromFile(_device, "../Pictures/cube.png", nullptr, nullptr, &this->mTexture, nullptr);
    if(FAILED(hr))
    {
        OutputDebugString("Failed to create Cubes texture.\n");
        return hr;
    }

    return hr;
}

Pixelshader:

Texture2D shaderTexture;
SamplerState Sampler;

struct PSIn
{
    float4 Position : SV_POSITION;
    float2 Tex : TEX;
};

float4 PS_Cubes(PSIn _input) : SV_TARGET
{
    float4 textureColor;

    // Sample the pixel color from the texture using the sampler at this texture coordinate location.
    textureColor = shaderTexture.Sample(Sampler, _input.Tex);

    return textureColor;
}


texts: How can I handle bouncy collision lag in an online game?

texts:
In my online game, each client sends its player's x/y location to the other clients, and the other clients update the location as they receive it, with some interpolation.

Issue:
The game has bouncy collisions. So if one player collides with another player at speed, it should push that player away. But if I push another player, it won't move away because it's still receiving info from the other end, where it's stationary.

The other player will move away, however, but only after receiving that info from its client.

Question: What are some good ways of handling this problem, while keeping player positions as accurate as possible?

P.S.: I know having an authoritative server can make this better, but we don't have the time to switch over.


texts: How to determine the amount of idel time left in main thread for Unity before next frame?

texts: Hi I'm trying to improve a thread tool and would like to make a function which use the idle time before the next frame. So how can I determine  the time left?


texts: Unity Event Register / Deregister and Scene Unload

texts:
From what I understand in C#, normally when you register an event, it maintains a reference to the object of the containing method, so in order for garbage collection to pick up an object, you need to first deregister it.
My question:  In unity when one scene is loaded and another is unloaded, do I need to first clean up and deregister any registered events, or does the scene unload process destroy objects and remaining references?


texts:
I am working on a skill system for use in a game project I'm chipping away at. The project is entirely in C# so I'm using .NET to its advantage.

In my preliminary implementation of a Skill Category -> Skill types system I'm using subclasses of ISkill and SkillCategory (base class with some virtuals) and using System.Type based reflection to generate a map of these at runtime (on demand).

The great thing about this implementation is that it entirely decouples specific skill types (such as Engineering / LaserWeapons from the SkillLibrary (the container for the generated skill mapping).

The goal is to remove the need to explicitly add each skill at some point as they are automatically detected by the library throughout the entire AppDomain.

Only game logic which relies on these skills use concrete types.

ISkill

public interface ISkill
{
  string GetName();
  string GetDescription();
  int GetSkillLevels();
  float GetMinutesOfTrainingForLevel(int level);
}

[SkillCategory(typeof(EngineeringSkills))]
[PrerequisiteSkill(typeof(ElectronicsSkill))]
public class LaserWeaponSkill : ISkill
{
  public string GetName()
  {
    return "Laser Weapons";
  }

  public string GetDescription()
  {
    return "Allows you to maintain and improve laser based weapons on your ship.";
  }
}

Usage example:

[RequiredUpgradeSkill(typeof(Skills.Engineering.LaserWeapons))]
public class LaserTurretWeapon : IShipWeapon
{
}

There's two slight ugliness's with being very System.Type based, though. One is that my Player._skillLevels dictionary can't serialize as Dictionary<Type, int> because Type isn't supported by DataContractSerializer (what I'm using at the moment).

So what I'm doing in SetSkillLevel<TSkill>(int level) and GetSkillLevel<TSkill>() is translating typeof(TSkill) to and from a string using typeof(TSkill).FullName (i.e. "Game.Skills.Engineering.LaserWeapons").

And the other is potential performance problems, which is something I should profile.

This all works, of course, but it feels like the weak point in an otherwise enum-less, strongly typed skill definition system.

I don't really want to use enums and a "list" of Skill structures, or move it to an external data definition file because then that requires more maintenance of created and deleted enum values and such.

Do you think this is worth it, or do topics such as performance of Type based operations and other considerations make it worth rethinking?


texts: What's the most efficient way to implement low poly flat shading style?

texts:
I want to know what's the most efficient way to implement low poly style flat shading. I have checked this post, however the options listed in the page don't feel perfect to me. I list them below for reference.

Duplicate each vertex so that same vertex can associate with a different normal.
Use flat to disable interpolation.
Evaluate normal at fragment shader using dFdx and dFdy.

To me, option 1 wastes some vertex attributes, since duplicate vertices have the same position. Option 3 perform unnecessary calculation on every fragment even though the normal should all be the same. Option 2 feels conceptually right to me, but I don't know what normal value should be saved at each vertex. This is also the approach hinted in book 'Real Time Rendering' (4e, p120).

My question is: what's the best way to implement it? Given so many commercial games used this style, I want to know how it is typically implemented by real world games?


texts: How can I determine if an object hit the top of a tile rectangle in MonoGame?

texts:
I've been implementing an AI system in my 2D game using MonoGame.

In some situations when a collision between two objects occurs, I need the NPC to move in different directions depending on the direction of the collision. With the simple Rectangle.Intersects method I can't handle this, because it only detects if two rectangles intersect and doesn't tell me how they intersect.

Basically I need to know if the top of the NPC rectangle collides with the bottom of a tile rectangle, and so on.

This question talks about something similar but I don't think there is CollisionDetection2D.BoundingRectangle in MonoGame.


texts: Retrieve variable from another class and send to another scene in Unity

texts:
Sorry for asking a noob question, but I have never used c# in Unity, only unityscript.

Basically I have a public int score variable stored in Players Class.

I need to retrieve it in the following method:

void OnTriggerEnter(Collider c)
{
    if(c.tag == "PlayerCollision")
    {
        if(!c.gameObject.transform.parent.gameObject.GetComponent<Player>().isDead)
        {
            Debug.Log("Hit");
            //Load next scene
        }
    }
}

How can I retrieve the score variable in this method below and send the variable to the next scene? (In unity script I had to do something like Application.LoadLevel(1); after of course building the scene as levels. Thanks


texts: LibGDX - On the "slowness" of loading assets

texts:
Many tutorials I've seen put the loading of assets via AssetManager in a dedicated screen which displays some progress bar or image while the loading happens in background. Each "real" screen then gets the resources it needs from the asset manager, typically in the constructor, eg

public class GameScreen extends ScreenAdapter {

  private MyGame game;

  private Texture t1;
  private Sound s1;

  public GameScreen(MyGame game) {
    this.game = game;

    AssetManager am = game.getAssetManager();

    t1 = am.get("....", Texture.class);
    s1 = am.get("....", Sound.class);
  }
  // use t1 and s1

Now another source I've seen takes this concept a bit further and also does the actual get()s in the asset loading class, so screens don't have to do them themselves, eg

// in the Loader class

public AssetManager am = new AssetManager();
public Texture t1;
public Sound s1;

...
am.load(...);
am.load(...);
am.load(...);

// finishLoading() or update()....
...
t1 = am.get(...);
s1 = am.get(...);
...

// in the screen class

t1 = game.am.t1;
s1 = game.am.s1;
...
// use t1 and s1

Now my question is: is this good practice? What's the expensive part of loading assets, the AssetManager's .load()s or also the .get()s? (I thought it was only the .load()s.) Is removing the get()s from the screens really a performance gain?


texts: Saving data across same game in multiple devices

texts: Is there any library or something that works like iCloud but for different operating systems (Android, IOS, Windows Phone) that allow me to save game data to cloud and open the game data from another device to sync the game progress?


texts: Viewport.Unproject - Checking if a model intersects a large sprite

texts:
Let's say I have a sprite, drawn like this:

spriteBatch.Draw(levelCannons[i].texture, levelCannons[i].position, null, alpha, levelCannons[i].rotation, Vector2.Zero, scale, SpriteEffects.None, 0);

Picture levelCannon as being a laser beam that goes across the entire screen. I need to see if my 3d model intersects with the screen space inhabited by the sprite. I managed to dig up Viewport.Unproject, but that seems to only be useful when dealing with a single point in 2d space, rather than an area. What can I do in my case?


texts: Photon Unity Network with Socket IO Ambiguities

texts:
When trying to use Socket.IO along with PUN I get multiple errors similar to the one below:

The call is ambiguous between the following methods or properties: ``WebSocketSharp.Ext.SubArray<byte>(this byte[], int, int)' and ``WebSocketSharp.Ext.SubArray<byte>(this byte[], int, int)'

I searched a lot and couldn't find any other class with the same name/namespace that could lead to this ambiguity. Please help.


texts: Using sprites in pygame without classes and objects

texts:
Relevant information

I'm in a grade 11 computer science class that uses Python & Pygame. We're aloud to use sprites and images though we're never taught it, just drawing graphics like squares and circles. We were taught arrays, lists, functions but not classes and objects. We also relatively do things without using functions like the init main one I see a lot on line, we also don't use self or super.

If it's anything relevant, I'm making a top down (bird's eye view) 2D shooter game similar to a 2D version of dead ops arcade in Call Of Duty: Black Ops.

What I'm trying to do

I've been programming with Java & LibGDX before hand. So I want to use sprites in images in Pygame the same way I've been using it in LibGDX. Getting images, obtaining image rectangles for collision, rotating/transforming images, changing the images of the sprite.

Though every tutorial I've seen for sprites and images in Pygame that I can search up uses objects, classes and function calls that I'm not familiar with.

What I've done

I've loaded a PNG into my program and drew it to the screen. Simple and straight forward. Though the Pygame documentation doesn't give me a lot of options in terms of manipulating these images other than moving their location.

What I'm asking for

A simple run down syntax of how I would use a sprite in Pygame, without objects/classes or any weird function terminology. In terms of functions I can make a function, pass information through parameters and return values. I'm not aware of global variables, self or super.

The simplest of simple where I can resize an image, change the image of a sprite, transform/rotate it, and get a rectangle that I can use to overlap with another one.


texts:
After some fine-tuning on my game's GUI I am finally ready to begin with the gameplay. But that's a tall order. My game will be something like a 2D platformer with RPG elements like collecting armor, helmets, weapons etc. So with that in mind I begun thinking about a way to create my player. First, I thought a single Player class would do the job for me but since I want to equip the armor/helmet I've acquired, I quickly abandoned this concept.

Next I got another idea. I could have the player's Head, Arms and Legs to be different classes and each of them drawing its own texture, respectively. So I can swap between different armor/helmet sprites for each of the body parts. But that would seem pretty complex to implement... or not?

Could I have a code example on how you would do this? Which path you would take if you are in my stead? Single Player class or different body parts classes? If the latter, how would you hook them so that it all looks like a single sprite?


texts:
Hello Game Development SE!

I'm crawling my way through OpenGL with the hopes of creating a simple and very lightweight game engine. I view the project as a learning experience that might make a little money in the end, but will be fun either way.

So far I've used GLFW to gain some basic I/O, a window (with a oh so fancy F11 fullscreen key) and of course an OpenGL context. I've also used GLEW to expose the rest of the OpenGL extensions because I'm using Windows and I want to use all of OpenGL 3.0+.

Which brings me to the scene graph. In short, I'd like to roll my own. This decision came after looking at OSG and reading a few articles on how the concept of a scene graph has become twisted, bent and broken. One such article described how scene graphs have developed as...

  Then we added in all this extra stuff, like hanging ornaments on a Christmas tree, except that some of the ornaments are nice juicy steaks and some are whole live cows.

Following the analogy, I'd like the steak, the meat of what a scene graph should be, without having to strap on piles of extra code, or any whole cows.

So with that in mind, I find myself wondering exactly what a scene graph should be and how a simple scene graph should be implemented? Here's what I have so far...

A one parent, n-children tree or DAG which...

Should keep track of game object transformations (position, rotation, scale)
Should hold render states for optimizations
Should provide a means of culling objects not within the view frustum

With the following properties...

All nodes should be treated as renderable (even if they don't render) This means they...

Should all have cull(), state() and draw() methods (return 0 if non-visible)
cull() recursively calls cull() on all children, thus generating a complete cull mesh for the entire node, and all children. Another method, hasChanged() could allow so-called static meshes to not need to have their culling geometry computed each frame. This would work such that if any node in the sub-tree has changed then all geometry down to root is rebuilt.

Render states will be held in a simple enumeration, each node will select from this enumeration an OpenGL state set that it requires and that state will be setup before draw() is called on that node. This allows for batching, all nodes of a given state set will be rendered together, then the next state set is setup and so on.
No node should directly hold geometry/shader/texture data, instead nodes should point to shared objects (perhaps managed by some singleton object like a resource manager).
Scene graphs should be able to reference other scene graphs (maybe using a proxy node) to allow situations like this, thus allowing complex multi-mesh models/objects to be copied around the scene graph without adding a ton of data.

I'm hoping to get some valuable feedback on my current design. Is it missing functionality? Is there a vastly better way/design pattern? Am I missing some larger concept that will be necessary to include in this design for a somewhat simple 3D game? Etc.

Thanks, -Cody


texts: Drawing cube map and texture array on NVidia cards doesn't work

texts:
I have small problem with shadow maps preview. After binding shadow framebuffer I bind proper texture to store depth in it and then render the whole scene. When I read that values in shader to calculate shadows everything works as I expect on every tested computers. But when I want draw this textures on 2D quads I have it working only on AMD cards. On NVidia all I have is white empty fields. This happens only with cube maps and array texture.

Here is screen:

Creating framebuffer:

if(!_s_buffer)glGenFramebuffers(1, &_s_buffer);
    glBindFramebuffer(GL_DRAW_FRAMEBUFFER, _s_buffer);

glFramebufferTexture(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, _depth.get(), 0); // set anything to framebuffer to avoid "framebuffer incomplete" error

glDrawBuffer(GL_NONE);
glReadBuffer(GL_NONE);

glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);

Could the problem be caused by using one framebuffer for cube map and array texture and switch between them in code (one time depth attachment is cube map - glFramebufferTexture2D with textarget set to proper cube map face - and another time it is array texture - glFramebufferTextureLayer).

Could you help me with this? I'm looking for a solution but without results. Maybe you met with this kind of problem. If more code is need I can post it.


texts:
I've looked in forums, the doc, and the code, and I'm thinking this isn't currently possible, but maybe I'm missing something, so just to be sure: is there a way to set a group as child of and actor? or, in other words, how do I create a hierarchy of actors?

I'm trying to make sorta of a strategic game, and I have things like "empires", "kingdoms", ""cities", "buildings", "people", "objects", and I thought initially that maybe would be a good idea make these things actors. But I can't find anything like addActor inside Actor class, or addGroup, it seems there is no way for "kingdoms" to have"cities", for "cities" to have "buildings", for actors to have child actors or child groups.


texts: Textures in build duplicated, despite they're packed into atlases

texts:
I have a simple SpriteAtlas: "UIAtlas" which is located in the Resources folder.
It points to a folder "UIAtlas" which contains my menu textures.
All of my batching is working perfectly, everything is being batched, because of the atlas.
When I build an iOS version, in the Editor.log I can see this:

Build Report
Uncompressed usage by category:
Textures 299.5 mb (30%)
Meshes 0.0kb (0%)
...
Used Assets and files from the Resources folder, sorted by uncompressed size:
16.0 mb 1.6% Built-in Texture2D: sactx-2048x2048-Uncompressed-UIAtlas-312aba98
...
345.3 kb 0.1% Assets/Resources/UIAtlas/medal.png
... more entries like this ...

Please notice that this texture (medal.png), along with the other textures belongs to this atlas, which is already included in the build-executable.
I feel this is wrong.
If I pack things, they should be packed into that texture and only that 2048x2048 texture should be in the build, right?
What's wrong here?


texts: Is it a good or bad thing to allow hot-loading of changes of game rules without official updates and restarts of server and clients?

texts: I’m working on such feature for my project that we allow the game designer to tweak game rules, from small things like item prices to bigger like probability for different randomizations,  while the game is running, and the changes immediately get pushed to server and client in code by just reassigning variable references in code at runtime. There are some doubts in the team from wide range of concerns such that doing so might cause a limbo period of overlapped old and new rules as different variables gets picked up at different concurrent sessions at different phases(such game rules are read-only), and possible interrupted player experiences. Can anyone know or have similar experiences share your insights? Thanks!!


texts: How to optimize two-pass operations on an array with Unity Coroutines

texts:
I am working on simulating vacuum decompression in a 2D top down environment.
I have 2 2-dimensional arrays: one that stores the pressure at a location, and one that stores the vector of fluid flow.

The algorithm looks likes this:

private void Flow()
{
    Diffuse();
    Vectorize();
}

private void Vectorize()
{
    for(int x=0;x<xRange;x++)
    {
        for(int y=0;y<yRange;y++)
        {
            float myPressure= pressure[x,y];
            [...]
            Vector2 flowVector=calculate_the_resultant_vector_from_the_pressure_differentials //O(1) op
            [...]
            vector[x,y]=flowVector;
        }
    }
}

private void Diffuse()
{
    for(int x=0;x<xRange;x++)
    {
        for(int y=0;y<yRange;y++)
        {
            float myPressure= pressure[x,y];
            [...]
            float newPressure=calculate_the_new_pressure_from_the_pressure_differentials //O(1) op
            [...]
            pressure[x,y]=newPressure;
        }
    }
}

The problem is that as the area of the simulation space increases, the performance continues to drop off as the iteration steps block the update loop.

I want to convert these to Coroutines in such a way that both yield but more or less maintain a lockstep appearance. Since flow is dependent on pressure differential, and pressure differential is partially dependent on flow, if an order has to be enforced, then Diffuse should take precedence.

My initial attempt followed the following form:

IEnumerable Flow()
{
    StartCoroutine(Diffuse());
    yield return null;
    StartCoroutine(Vectorize());
}

IEnumerable Vectorize()
{
    for(int x=0;x<xRange;x++)
    {
        for(int y=0;y<yRange;y++)
        {
            float myPressure= pressure[x,y];
            [...]
            Vector2 flowVector=calculate_the_resultant_vector_from_the_pressure_differentials //O(1) op
            [...]
            vector[x,y]=flowVector;
            yield return null;
        }
    }
}

IEnumerable Diffuse()
{
    for(int x=0;x<xRange;x++)
    {
        for(int y=0;y<yRange;y++)
        {
            float myPressure= pressure[x,y];
            [...]
            float newPressure=calculate_the_new_pressure_from_the_pressure_differentials //O(1) op
            [...]
            pressure[x,y]=newPressure;
            yield return null;
        }
    }
}

This tended to cause a jittery simulation. Even on a small 20x20 simulation field, there was noticeable difference between the first and second solutions.

Are there any tricks to coroutines that will allow a more lockstep simulation that scales well? Any suggestions on optimization is welcomed as well.


texts: Unity how to have a ghost 3d game object

texts:
I want to have a 3d game object (player) who converts to ghost.

That means that the user must not collide with other players, but must not pass walls, trees, and must take care about terrain height levels (I mean, I can't put it as kinematic and remove the collider because the Vector3.MoveTowards which moves the player will ignore the height dimension and will pass the mountains, etc)

My was thinking about tagging the players and in some way try to skip the collider between them.

Any idea? Thanks


texts: Using add_force and add_torque to turn a RigidBody2D

texts:
Godot Scene tree
Scene (Node2D)
- RigidBody2D (Parent of Sprite and CollisionShape2D initially points to X direction/90 degrees)
-- Camera2D

When I use apply_force() with ui_up key, the Vehicle moves correctly and remains in motion. However when I use apply_torque_impulse() (such as ui_right) it turns but, then the Vehicle is moving/slipping sideways instead of towards the new direction. If I stop the motion by reversing the thrust, then start again it moves correctly in that new direction.
Seems I have to do some vector math math on the value of torque but I am not sure what.
extends RigidBody2D
var thrust = Vector2(0, 100)
var torque = 1024
var cot=Vector2(0,0)
var speed: int
var direction: int
func _ready():
    set_physics_process(true)
    set_process_input(true)
    can_sleep=false
    speed=0
    direction=0
func _integrate_forces(state: Physics2DDirectBodyState):
    if Input.is_action_just_pressed("ui_down"):
        speed -= 1
        add_force(cot, thrust.rotated(rotation))
    if Input.is_action_just_pressed("ui_up"):
        speed += 1
        add_force(cot, -thrust.rotated(rotation))
    if Input.is_action_just_pressed("ui_right"):
        direction += 1
        apply_torque_impulse(torque)
    if Input.is_action_just_pressed("ui_left"):
        direction -= 1
        apply_torque_impulse(-torque)


texts:
When trying to compile the following HLSL:

Texture2DArray gShadowmap : register(TEXTURE_REGISTER_DEPTH);
SamplerState gShadowmapSampler : register(SAMPLER_REGISTER_DEPTH);

// ...

float3 projCoords = (float3)mul(gSplitVPMatrices[index], worldPos);
float viewDepth = projCoords.z - DEPTH_BIAS;
projCoords.z = float(index);
float visibilty = gShadowmap.SampleCmp(gShadowmapSampler, projCoords, viewDepth).r;

visual studio gives me:

error X3013: 'SampleCmp': no matching 3 parameter intrinsic method
error X3013: Possible intrinsic methods are:
error X3013: Texture2DArray<float4>.SampleCmp(SamplerComparisonState, float3|half3|min10float3|min16float3, float1|half1|min10float1|min16float1)
error X3013: Texture2DArray<float4>.SampleCmp(SamplerComparisonState, float3|half3|min10float3|min16float3, float1|half1|min10float1|min16float1, int2)
error X3013: Texture2DArray<float4>.SampleCmp(SamplerComparisonState, float3|half3|min10float3|min16float3, float1|half1|min10float1|min16float1, int2, float1|half1|min10float1|min16float1)
error X3013: Texture2DArray<float4>.SampleCmp(SamplerComparisonState, float3|half3|min10float3|min16float3, float1|half1|min10float1|min16float1, int2, float1|half1|min10float1|min16float1, out uint status)

I believe I match the first method, so why is this?


texts: How many OpenGL programs should I use to render multiple objects?

texts:
My scene has multiple objects in it. (Let's say 3 cubes, 1 cylinder, 8 spheres.) I assume I should create a vertex shader for each. How many programs should I have?

Alternatives:

One program per object
One program for all cubes and another for all spheres (assuming they use the same shaders)
One large program for everything

What is the correct approach?


texts: Can I create a remix of a song & incorporate it into my game music?

texts:
DJs frequently remix eachothers work and use as they please. Can I as a programmer do similar - remix a song I like and embed it in a game I create without royalty/copyright issues?

Disclaimer: answers will not be considered legal advice, this is just a hypothetical discussion :)


texts: How do I calculate the distance between a point and a rotated rectangle?

texts:
This question is similar to another one about axis-aligned rectangles. However, I specifically want to calculate this for rotated rectangles.

I have a rectangle with a (cx, cy) for the center point and a width, and height, and a (x, y) for the test point, as well as a θ for the angle of rotation.

What's the fastest way to determine the distance between that point, and the nearest edge of the rectangle? If the point is inside the rectangle, the distance should be zero.

I believe that there is going to be only a small change to the equation in the linked question, but I have no idea what it might be.


texts: What is the design rationale behind hard content that's limited to only a couple attempts per week?

texts:
There is currently a lot of discussion in the World of Warcraft playerbase about a recently added feature: Horrific Visions. Visions are personal areas you can enter alone or with a handful of players and have 5 objectives with increasing difficulty plus additional difficulty options. The details aren't that important, but the core is that these Visions require careful planning of resources and time if you want to progress the harder difficulties, both during the visions themselves and in how you earn the right to complete a Vision. In return for completing these Visions, you can earn increasingly better gear based on difficulty (though repeated gear rewards decline in quality) as well as upgrades for an item you need against the final bosses of the raid that came in the same patch.

Now, usually in games that have really hard content you're supposed to defeat, there is no limit in how many attempts you can do, or the limit is sufficiently high that it makes no real difference. However, this isn't the case in Visions. Visions require you to buy an item to make an attempt, and this item is so costly that even if you log in every day and do all the content that rewards the items you need to buy this item, you can at most earn 4 copies of the item per week. There is also incentive to save these tokens for later weeks because later upgrades require you to complete increasingly more runs, which you can speed up by not using additional tokens in weeks where you don't need them.

This is what many people see as the biggest problem with these Visions. They're hard content, but you have only a couple attempts per week and you need to make them count. So there isn't really a safe way to practise them so you can learn how they work and what the best way to do them is. If you mess up and you don't do enough to earn the upgrade token mentioned above, it's a huge potential loss and you fall behind other players who did manage to complete them.

I'm trying to understand possible design rationale behind this. I don't usually come across this design element in games, and I can't even remember another game with similar design, especially for such a core feature of the content update. in other hard game content, Soulsborne games don't really restrict you in attempts, and Roguelikes actually are built around immediately starting anew when you fail, again without real limitations. AFAIK neither genre really limits you in how often you can try them. And it has been years since Blizzard last put a hard limit on how many attempts you were allowed for the hardest content, especially such a low amount.

What can be potential design rationale behind putting hard content behind a restrictive attempt limit?


texts: How to scale objects and tiles without doubling view port in gamemaker

texts: How do I scale up tiles and sprites without acully making the view port larger than the acual view? I know that I can just scale up the images and the tileset but there must better alternative right? The reason why I dont want to make the port bigger is because then I get this kind of "pixel perfect" behaviour so 1 pixel on the image is one pixel on the screen (So it looks kind of choppy). I'm thinking I can use the draw event if there's no other alternative but how would I do that with the tileset?


texts: Circular soft body? Matter.js or other js engine?

texts:
I am using Matter.js physics in an attempt to create soft bodies. I was able to create a body like this:

However I am not sure if this is the "soft body" I want. It is true that this body is not entirely rigid and has that bouncy feel when it collides and gets dragged. I was looking for a body that shares similarities with a gelly. This image might visually help explaining the concept:

I was wondering how these type of bodies can be made. Is it the same as the as matter.js soft body but with a very specific type of properties? I can only get the body to be kind of rigid-squared and not as moldable and circular as I would like it to be.

I am also interesting in manipulating the physics body with in-game interactions which would increase or decrease the physics body size which leads me once more to the conclusion that the type of body that I want must be quite moldable.

Can matter.js handle this or do I have to change the physics engine? Any solutions to approach this?

NOTE: I am using Phaser.js for some in-game components but matter.js physics for physics manipulation because I believe Phaser integrated Physics can't simulate this type of complex body.

Thanks

EDIT: It is very similar to this https://stackoverflow.com/questions/18298329/box2d-roll-soft-body-ball?rq=1. I just need to do that with a js engine I guess. Is there any?