texts: Elegantly simulating NPC movement in inactive areas

texts:
My AI is utility-driven in a similar pattern to The Sims, where all unique behavior is coded into interactable objects, and the only thing an NPC does is decide which object they wish to use, path to it, and activate it. This is deceptively powerful, as I can extend nearly any desired behavior by creating a novel object and shaping constraints leading to its selection.

The challenge I'm having with this approach is giving the illusion that NPCs are moving around when the player isn't nearby. The game runs a 24/7 clock and seeks to have each NPC go through the motions of maintaining a regular schedule: going to work, going to bed, and randomly doing weird things in their free time to preserve the illusion of unpredictability. This is implemented with a dict(float time, Appointment appointment), which acts as a global behavior queue and is called every time the in-game clock changes to teleport each AI who has an appointment to use an object to that object's position. This works well enough for prototyping other systems, but it isn't very convincing: you never see NPCs moving through the world, and when you're familiar with a few specific characters it becomes very obvious that they're teleporting around when you can't see them.

Is there a better way to simulate movement around a world with a large number of NPCs, or am I better off keeping my current queue-oriented behavior system and writing an entirely different system to fake movement? My optimal endpoint would be a system that can order NPCs to be at any location, at any time, and trust them to move there in a convincing way, but I worry I'm putting too much detail into a simulation that could fake the same behavior more convincingly with a simpler solution.


texts:
my code looks something like this:

        graphicsDevice.Clear(Color.Black);
        spriteBatch.Begin();
        spriteBatch.Draw(contentLoader.VerticalGradient, tileSafe, null, Color.DarkGreen, 0, Vector2.Zero, SpriteEffects.None, 0.5f);

// snip a lot, including drawing stuff on the sprite batch.

        // create a new sprite batch (for snipping)
        var initialViewport = InitialBatch.GraphicsDevice.Viewport;
        InitialBatch.GraphicsDevice.Viewport = new Viewport(displayRectangle);
        var newBatch = new SpriteBatch(InitialBatch.GraphicsDevice);
        newBatch.Begin();

// draw stuff on the new batch

        newBatch.End();
        InitialBatch.GraphicsDevice.Viewport = initialViewport;

// more stuff on the original batch

        spriteBatch.End();

My problem is the third line of code I just added. I want to have a "background" on what I'm drawing (so it's not just black). So I draw it first.

Before I added that third line, everything worked great. But when I added it, everything drawn on the new/inner batch doesn't get displayed. If I draw it all on the normal sprite batch, it gets drawn (but doesn't get snipped properly), if I remove the drawing of the new texture, then the inner spritebatch works fine.

Additional things I've tried

I've tried moving the depth of the "background" texture, and when I do, it either makes the background disappear, or it makes the inner sprite batch stuff disappear. I want both.

Is there any way I can get both? Am I making sense? Is this inner sprite batch thing just crazy? I thought I used a standard example to do snipping, but maybe I got lucky and stumbled upon something crazy that just happens to work?


texts: Write colors with alphablending but don't write into the alpha channel

texts:
I am using XNA 4.0, hence DX9 and HLSL. I have a RenderTarget2D "MAIN" that I want to add semi-transparent objects "TRANS" to. I want them to blend with MAIN using the TRANS's alpha and inverseAlpha BUT I want to preserve information kept in the MAIN's alpha channel.

If I simply use BlendState.AlphaBlend, MAIN's alpha channel becomes 1 everywhere where TRANS is written. I know there is a property in the BlendState class that prevents writing to color channels Is there an option that prevents writing to alpha?

Thanks.


texts: enemy behavior with boundary to change direction

texts:
I'm doing space shooter kind of game, the logic is to reflect the enemy if it hits the boundary. With my logic, sometimes enemy behaves like flickering instead of changing the velocity. It's like trapped in the boundary and checking for if loops.
This is my code for velocity changing:

if(this->enemyPos.x>14)
{
   this->enemyVel.x = -this->enemyVel.x;
}

if(this->enemyPos.x<-14)
{
   this->enemyVel.x = -this->enemyVel.x;
}

How can I get around this? Its going out of boundary and don't know where to go and after sometimes its coming into field. I know whats the problem is, I dont know how to get around this problem.


texts:
I have an FBO with only 16-bit depth attachment:

glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, w, h, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, nullptr);

I render something to it, so now I have a depth texture with 16-bit precision. What is the best way to update this texture on the GPU (while maintaining precision), before passing it to the shader that will actually use it?

For example, let's say I want to update depth texture so that for every texel at (u,v), if u < 0.5 then the resulting texel would be equal to min between texel at (u,v) and (u+0.5, v). Value is unchanged otherwise.

The only way to do this that I can see is to create second FBO with similar depth attachment, and render to it while reading from 1st FBO's depth texture. During this render pass I can write updated values to 2nd FBO's texture through gl_FragDepth.

Is there a better way to do this? Can I avoid having 2 FBOs and update depth texture in-place, or is it considered a feedback loop and thus undefined behavior?


texts: How to set "useGravity" for Rigidbody to entities in Unity

texts:
For the position you can use this:
[Inject] private ComponentDataFromEntity<Position> _position;

But cant use it for Rigidbody. How to access the parameters for Rigidbody for entities?


texts:
Is it possible to somehow change the collider points to match sprites during the animation in Unity?
I am using the Unity built in animtion recording feature. I would like to change the points of some of my colliders as animation goes, while at the same time I am changing the respective sprites. I was not able to find any solutions so far.
Any ideas how I could do that?
I have a few attempts to overcome the problem.

Create a few game objects with the different preset points for the colliders. The solution will work. But it is crazy hard to develop and maintain resources wise. I will have to spend an immense amount of time creating a separate game object with a collider for each frame. And also the maintenance will be very lame. Because I will need to add a wrapper around all the places where I access collider. So that the wrapper would return the currently enabled collider.

I can buy the 2DColliderGen. But I do not want to spend money on that. And also it is not completely what I am looking for, because even with it I will have significant difficulties developing my animations, maintaining my game and extending it.


texts: What is the format of DXGI_FORMAT_D24_UNORM_S8_UINT?

texts:
I'm trying to read the values in a depth texture of type DXGI_FORMAT_D24_UNORM_S8_UINT.

I know this means "24 bits for depth, 8 bits for stencil" "A 32-bit z-buffer format that supports 24 bits for depth and 8 bits for stencil.", but how do you interpret those 24 bits?

It's clearly not going to be a 32-bit int, and it's not going to be a 32-bit float.  If it is an integer value, how "far away" is a value of "1" in the depth texture?


texts: How can one replicate the 'Quake Disruptor' of Wipeout XL/2097?

texts:
Following my previous question, I am wondering how one can achieve the same effect under Unity?

The effect in action

https://youtu.be/kzmmLeCwL0g?t=790

Description of the effect

When you fire the Quake Disruptor weapon, it creates a sine wave that mimics an earth quake, it happens over the next track sections forward to the player ship as you can see on the small video. This results in instant-damage and slowdown to the ships that are caught in the quake.

Technical challenges

Deforming the mesh

The function for generating a quake-like wave to apply to each section of the track mesh is easy, e.g. a Gaussian filter will probably be good enough:

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

Applying the deformation to mesh

This is where it starts to get trickier, a track is made out of sections that have few faces, each face being nothing more than a quad.

Here you can see three sections and their faces (wall, track, track, wall):

The challenge in here is how to apply the deformation and yet being able to check collisions against the track (remember that we can't use a mesh collider since it'll be updated in real-time).

I first thought that subdividing the mesh using tessellation would be needed to apply smooth deformations, hence my previous question. However, if you look closely at the video they simply move either edge of faces according to where they're against the 'quake' function being applied to the track mesh.

Here's a link to a video with the best quality, around 13 mins 10 secs:

https://archive.org/details/PSX_Longplay_243_Wipeout_2097

We're getting closer but we still need to be able to check for collisions.

Being able to still collide against the track

This is the big question mark, since we cannot update a mesh collider in real-time as it's a CPU hog, I really have no idea on how to address this part of the problem.

This also leads to another problem, since we cannot use a mesh collider, how are physics are going to be handled, by writing a physics system from scratch ?

Question

How can such effect be achieved under Unity, if possible at all?

PS You will want to remember that the PS1 had a 33Mhz CPU and certainly no mesh collider like the one we can find in Unity, yet they achieved to do it. For sure there is a trick involved but I couldn't figure it out.


texts: Real-time MMO: how should authoritative server update client position

texts:
I'm trying to build a real-time MMO game. I'm using Phaser for FE and Node.js + socket.io for BE. I have read all the tutorials like http://www.gabrielgambetta.com/client-side-prediction-server-reconciliation.html and so on.

Different players might have different FPS, this is how I update position on the client:

const data = {
  down: this.cursors.down.isDown,
  timestamp: Date.now()
};

var deltaTime = (data.timestamp - this.lastTimestamp) / 1000;
if (data.down) {
    player.position.y += speed * deltaTime;
    socket.emit('input', data);
}

This ensures speed is FPS independent (every player is moving with the same speed).

The server is running a tick at 60 FPS. This method is processing saved inputs from players.
How should the server correct player positions? It doesn't know their delta times. It can't use server's delta time since it would be always around 0.016 and it doesn't reflect player's update interval.

tick() {
    var now = Date.now();
    var serverDelta = (now - this.prevTimestamp) / 1000;
    this.prevTimestamp = now;

    for (var player of players) {
        player.update();
    }
}

player.update() {
    for (input in savedInputs) {
          player.y += input.down * speed;
    }
}


texts: Using name and 3d models of real product

texts:
I'm making tycoon game where you manage your shop. I'm not 3d modeler and purchase most of assets. I managed to find all 3d assets required for making game. All are having license to allow use for commercial usage. My question is can I use those model who are clearly modeled after their real world product in my game? Even though license for each of them permits me.
I know,I can't use their real name like for example I will change nintendo switch to ginmendo ditch or apple to mapple. I'm even planning to slightly modify each asset in 3d modeling software. will that work? Can I use them in my game ?


texts: Building a flexible GLFW Event handling system (for beginners)

texts:
The 2017 Thread "How to improve my input handling in GLFW?" is brilliant!  Exactly my question and what seems like some great solutions.

However "Tyyppi_77" is hard for me to understand as a beginner.  For starters:

1) how is addBinding called and when in the flow?  Can you describe what the parameter Callback% callback is and its purpose?

I'll stop there for now. Ty!

class Window
{
public:
    using Callback = std::function<void()>;

    void addBinding(int key, const Callback& callback)
    {
        m_Callbacks[key].push_back(callback);
    }

    void onKeyPress(int key)
    {
        for (Callback& callback : m_Callbacks[key])
        {
            callback();
        }
    }
private:
    std::map<int, std::vector<Callback>> m_Callbacks;
};


texts: Unity Rotation - Object is rotating on Z, but should be rotating on X

texts:
I've been working on a project where I have a cube. When swiped left, the cube will rotate 90 degrees the left, and then when swiped right, the cube will rotate 90 degrees to the right. I have this area working fine.

However, when i go to swipe up and down (To rotate the cube 90 forwards) it becomes slightly unstuck. If the rotation of the object is (0, 0, 0), it works fine. But if I, for example, rotate once to the left and then tried rotate fowards, the cube will correctly rotate left, but then the forward rotation will rotate on the Z axis and just spin the cube (So the face looks like its moving in right in a clockwise direction).

Here is the code:

public Transform rotateAround;
public float rotateSpeed;

bool isRotating;
Touch touchOn;
Touch touchEnd;

float changeX, changeY;

// Update is called once per frame
void Update()
{
    if (Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Began)
    {
        touchOn = Input.GetTouch(0);
    }

    if (Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Moved)
    {
        touchEnd = Input.GetTouch(0);
        var difference = touchOn.deltaPosition - touchEnd.deltaPosition;

        changeX = (touchOn.position.x - touchEnd.position.x);
        changeY = (touchOn.position.y - touchEnd.position.y);

        Debug.Log("Changes: x: " + changeX + " y: " + changeY);

        if (changeX > 25f)
        {
            StartCoroutine(Rotate(transform, rotateAround, -Vector3.up, 90, rotateSpeed));
        }
        else if (changeX < -25f)
        {
            StartCoroutine(Rotate(transform, rotateAround, Vector3.up, 90, rotateSpeed));
        }

        if (changeY > 25f)
        {
            StartCoroutine(Rotate(transform, rotateAround, Vector3.left, 90, rotateSpeed));
        }
        else if (changeY < -25)
        {
            StartCoroutine(Rotate(transform, rotateAround, -Vector3.left, 90, rotateSpeed));
        }
    }
}

public IEnumerator Rotate(Transform thisTransform, Transform otherTransform, Vector3 rotateAxis, float degrees, float totalTime)
{
    if (!isRotating)
    {
        isRotating = true;

        Quaternion startRotation = thisTransform.localRotation;
        Vector3 startPosition = thisTransform.position;

        transform.RotateAround(otherTransform.position, rotateAxis, degrees);

        Quaternion endRotation = thisTransform.rotation;
        Vector3 endPosition = thisTransform.position;

        thisTransform.rotation = startRotation;
        thisTransform.position = startPosition;

        float rate = degrees / totalTime;

        for (float i = 0.0f; i < degrees; i += Time.deltaTime * rate)
        {
            yield return null;
            thisTransform.RotateAround(otherTransform.position, rotateAxis, Time.deltaTime * rate);
        }

        thisTransform.rotation = endRotation;
        thisTransform.position = endPosition;
        isRotating = false;
    }
}

Both the camera and the cube start with rotations of 0, 0, 0. The script is placed on the camera, with the rotateAround transform object been set as a cube.

Any help would be appreciated!


texts: Multiple ( V- / I- ) Buffers, is it sane?

texts:
Currently I am developing an RTS game using XNA ( / ANX.Framework ).
There is one thing bothers me. I am not sure in what way or how to organise Buffers.
Should I use a new Vertexbuffer for any object ( e.g. a Char, a Table, an model ) or is it better to use ONE HUGE/ BIG Buffer to store any geometry in?

I am still new to 3D Programming though I finished yet couple games using DirectX 9.

Well, I hope this question qin't a duplicate and I appreciate any answer leading me into the right direction.


texts: How can I detect a perfect passageway for collision detection?

texts:
The problem is when I move diagonal it moves fractions of units and therefore my coordinates might be a fraction of a unit say (40,400) might be actually (40.12,400.40) but another problem is my pink square might be moving really fast. Below is a screenshot where you can see I can make it past a pixel perfect passageway with my pink square but the other passageway with the white square is very difficult if not impossible to make it through (I have by zooming in and moving REALLY slow but sometimes it impossible for the reasons listed above) Suppose in the example above I am holding the up and left arrows how can I make it so the pink square slides across the yellow rectangle and detects it can move upward and begins to move up?

The code I am using right now looks like this

float d45 = (float) (1 / Math.sqrt(2));
moveX = -d45;
moveY = d45;
moveX = moveX * t * speed;
moveY = moveY * t * speed;
        for (Stuff s : collidables) {
            if (overlaps(s, moveX, 0)) {
                collidedX.add(s);
                x += moveX > 0 ? s.x - width - x : s.x + s.width - x;
            }
        }
        if (collidedX.size < 1) {
            x += moveX;
        }
        for (Stuff s : collidables) {
            if (overlaps(s, 0, moveY)) {
                collidedY.add(s);
                y += moveY > 0 ? s.y - height - y : s.y + s.height - y;
            }
        }
        if (collidedY.size < 1) {
            y += moveY;
        }

I check for collision twice once on the Y axis and another on the X axis so that it can still slide to the left even if you are pushing the up and left arrow. The problem is it skips over the 100 unit passage to the left of the picture above. If I create a passage that is 110 units wide it will slide up fine but this isn't really cool because I like how it looks where it slides perfectly. Any ideas?


texts:
I have been trying to implement some lag compensation techniques for a real-time game, I've found some good resources online, but I don't think I fully understand the server-side part of the problem.

The game is a simple 2D game, where the player moves an entity around the map. There will be other entities with their own behavior that are controlled by the server, but I made it so that their movement can be easily interpolated. The player input is quite simple: an analog stick and some commands (pick target, loot objective, etc.). The game runs at a fixed 10 TPS (it's on mobile and it's not that action packed, 10 TPS will suffice). The client will send the input state every tick (even if no input is present, like the analog stick is in the default position).

It is worth mentioning that only one player is connected at the same time, so in a way this is not multiplayer, but I need to run this on the server as well to prevent cheating.

I understand client-side prediction and that's quite straightforward to implement. I am struggling with the server-side part. As far as I can see I have 3 options:

The server waits for the input from the client then computes the new game state and sends it to the client. This is a viable option only because there is only one player.
The server runs the game loop waiting up to 100ms (10 TPS -> 100ms / tick) for an input. If it gets one, it will be taken into consideration when computing the next state, otherwise it will be discarded. If an input arrives after the tick was done, it will be discarded. If an input arrives during this timespan, but the tick numbers don't match (client send input for tick 5, but server is at tick 7) it will be also discarded.
The server runs the game loop waiting up to 100ms (10 TPS -> 100ms / tick) for an input. If it gets one, it will be taken into consideration when computing the next state, otherwise it will be discarded. In this case it will not care if the input is not for the current tick, it will apply it anyways.

Option 1 is the easiest to implement and will be more consistent. The biggest issue with this is that I believe it's easy to cheat. Since the server is waiting for input, the player might be able to "pause" the game, analyze the situation then dispatch the action, basically allowing a cheating player to play in slow-motion. The client-side reconciliation in this case seems easy, when the player moves, it will move instantly on the screen and when it received the updated state from the server it will do it's reconciliation.

Option 2 is a tad harder to implemented (not by much though), but it will be unplayable (literally, the player won't be able to move) if their ping is higher than 100ms.

Option 3 has the same complexity as Option 2. It will work with pings higher than 100ms but it will most probably lead to some frustration on the player's side since their inputs will not arrive in time.

Is there a better way to do this? What are your thoughts?


texts: Bad to learn XNA without an amazing foundation on C#?

texts:
I've been going though Head First C#, and enjoying it's style of teaching.
But I'm into this as a hobby for now, and I'm itching to learn more about games, so I've been diving into Learning XNA 4.0 as well.

Is this a bad idea? Is my lack of C# gonna harm adapting it? 'cause as of now, it feels much more rewarding.
Between that and http://rbwhitaker.wikidot.com/2d-tutorials, I've been having more "fun" drawing sprites and animations than making calculators.


texts: How to use a buffer in GLSL to do a LUT-lookup?

texts:
I am currently on a medical application which needs different kinds (up to totally individual) lookup tables (LUT) for image display. And this done with 10bit finish. So it is most of the time required to use 16-bit gray scale pixels.

I chose to use modern OpenGL and thus I'll want the lookup to happen in a GLSL shader program.

I had a try in uploading a 1D-Tedture (R16) using sampler1D to do the lookup as such:

        uniform sampler2D tex;
        uniform sampler1D lutData;
        in vec2 fragTexCoord;
        out vec4 finalColor;
        void main()
        {
            float primaryLvl = texture(tex, fragTexCoord);
            // index image 'color' in Lut-Texture
            float red = texture(lutData, primaryLvl);
            finalColor = vec4(red, red, red, 1.0);
        }

It works about as expected - however Textures (also 1D aparently) are limited to 8192 in size (on my machine). So the requirement for full range 16-bit images is not met.

For this above test I upload my images as R16 (for me it is gray) - normalized float 0-1.0.

Would it be feasible to upload a buffer (arbitrary data) and do the lookup there?
How would I do this (Syntax)?

And will my current pixel format interfere with my idea so I have to upload it as R16_INT instead. Or can (and should) I convert it in the shader from Normalized to Int (how is this done)?

Thanks


texts: Effecient finding of long-range spotting targets

texts:
I'm creating a top-down 2d strategy game, with a square grid map.
So far, I've used Bresenham's line drawing algorithm in a circle to determine what's in LOS of each unit, and then targedt one of the targets in the circle.
Now I find that this limits my units to shoot only at targets that they see. I want to extend my targeting algorithm to target any other unit in range of my weapon, even if they're out of sight range of this given unit, if they're "spotted" by another friendly unit. In other words, I want to enable usage of weapons with ranges longer than sight range.
Is there a better way than iterating over all sighted units and computing range and LOSto each of them?


texts: How to communicate with LibGDX HTML5 app?

texts:
I'd like to have a HTML form send data to a LibGDX game deployed as HTML5. Ideally as a form in HTML as part of the same page that contains the LibGDX div/canvas, and use the form to set up some data that I can pass into the game, probably using Javascript.

Is this or any other method of sending data to the LibGDX app (when deployed as HTML5) possible?


texts:
I'm trying to implement a multithreaded game loop. I already did that but had to use a few locks for that, which ruined the performance. After researching a bit I came up with this idea:

Instead of splitting the engines subsystems into different threads (e.g. physics, animation), all subsystems run on all threads. So when we got four CPUs, four threads are created, with each thread having one loop for all subsystems. So the single-core game loop is copied on all four threads.
These game loops are controlled by one other loop, which sends messages (or 'jobs', 'tasks') to one of these threads (depending on their usage) according to user-input or scripts. This could be done with a double buffered command buffer.

Only the rendering loop is alone in a thread for maximum rendering performance.
Now I'm thinking of the best way to communicate with the rendering loop. The best idea I could come up with is to again use a command buffer and swap it when the rendering loop is complete. That way the rendering loop doesn't have to wait for any of the loops and can go on rendering. If the game loop hasn't finished when the rendering loop swapped the buffer, all commands after that will be executed in the next frame of the rendering loop. To make sure that all objects will be drawn even if the game loop hasn't finished, the rendering loop holds all objects that will be drawn and draws them until it gets the command to stop drawing them.

My goal is to make the engine scalable to cpu numbers and make it to use all cores. Is this a way to do that? What is the best approach to this and how are modern engines handling this?


texts:
For some reason, I am unable to test my android program because of this error.
Here are some pictures of the errors. This error is not allowing me to test my app on my test Android device, I have tried uninstalling and reinstalling, checking if it is acatually the root folder, everything, PLEASE HELP!

1st error

CommandInvokationFailure: Unable to list target platforms. Please make sure the android sdk path is correct.
C:/Users/jayso/AppData/Local/Android/sdk\tools\bin\avdmanager.bat list target -c

stderr[

]
stdout[

ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation.
]
exit code: 1
UnityEditor.Android.Command.WaitForProgramToRun (UnityEditor.Utils.Program p, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.Android.Command.Run (System.Diagnostics.ProcessStartInfo psi, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.Android.AndroidSDKTools.RunAndroidSdkTool (System.String toolName, System.String arguments, Boolean updateCommand, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.Android.AndroidSDKTools.ListTargetPlatforms (UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit)
UnityEditor.Android.AndroidSDKTools.GetTopAndroidPlatformAvailable (UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit)
UnityEditor.Android.PostProcessor.Tasks.CheckAndroidSDK+SDKPlatformDetector.GetVersion (UnityEditor.Android.AndroidSDKTools sdkTools)
UnityEditor.Android.PostProcessor.Tasks.CheckAndroidSDK+SDKComponentDetector.Detect (UnityEditor.Android.AndroidSDKTools sdkTools, System.Version minVersion, UnityEditor.Android.PostProcessor.ProgressHandler onProgress)
UnityEditor.Android.PostProcessor.Tasks.CheckAndroidSDK.EnsureSDKComponentVersion (System.Version minVersion, UnityEditor.Android.PostProcessor.Tasks.SDKComponentDetector detector)
UnityEditor.Android.PostProcessor.Tasks.CheckAndroidSDK.EnsureSDKComponentVersion (Int32 minVersion, UnityEditor.Android.PostProcessor.Tasks.SDKComponentDetector detector)
UnityEditor.Android.PostProcessor.Tasks.CheckAndroidSDK.Execute (UnityEditor.Android.PostProcessor.PostProcessorContext context)
UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context)
UnityEditor.BuildPlayerWindow:BuildPlayerAndRun()

2nd Error

Error building Player: CommandInvokationFailure: Unable to list target platforms. Please make sure the android sdk path is correct.
C:/Users/jayso/AppData/Local/Android/sdk\tools\bin\avdmanager.bat list target -c

stderr[

]
stdout[

ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation.
]
exit code: 1


texts: Setting up Payout on the Microsoft App Hub

texts:
I am a Windows Phone 7 developer from India. I want to set up the Payout option on the App Hub for the Paid apps I release.

What's the procedure? Do I have to physically mail the W-8 form to Microsoft? Any other things I should know about?

Can I release a paid app now and set up the payout later, in a month or so?


texts:
Is there a way to build an apk faster? (by disabling some shader compilation, for example Hidden/Post FX/Uber Shader takes most of the build time)

p.s. Yes I know about Unity Remote and use it - this time I need exactly Build and Run.


texts: Frame rate slowing down after publishing XNA game in VB.NET

texts:
I will get to the main question later but I just want to give the backstory here first.
I program a game in XNA using VB.NET. As I'm testing the game in debug it works at a certain speed (spritemovement, animations etc.). After I publish the game and install it on my other computer (which is newer), the game slows down considerably.
To investigate that problem I used FPS code. It showed 75 on debug and 60 after installed. I have thus programmed the entire game for running at 75. To try to solve that problem I incorporated this:

TargetElapsedTime = TimeSpan.FromSeconds(1.0F / 75.0F)
IsFixedTimeStep = True

Now after trying to publish again the game actually ran smoothly at 75fps on the newer computer, but there was a catch: when I turn to fullscreen the game again slows down. However now without showing the lower fps. So the fps is still showing 75 but the game apparently runs at 60.

I've looked around for answers and find that I can possibly maximize the window (borderless) without making it fullscreen, and could perhaps solve the problem that way. However all the code suggested are in C# and I can't get it to work.

How can I either get a borderless maximized window to work with VB.NET, or in any other way solve my FPS issue?

Thank's for any help on this issue!


texts: Bitmap font engine: When is color modulation not supported?

texts:
I am developing a bitmap font renderer for a 2D game using SDL 2.  (If it matters, I'm using Debian 8 "jessie".)  I had planned on storing the glyphs as a grayscale image, translating gray levels to alpha at load time.  I realized I would want to draw text in more than one color.  I had planned on coloring the rendered glyphs using SDL_SetTextureColorMod(glyphstex, r, g, b), with as a white texture. But the documentation for SDL_SetTextureColorMod states that this may not always work:

  Color modulation is not always supported by the renderer; it will return -1 if color modulation is not supported.

In what cases is color modulation likely to be unsupported?  In other words, how likely am I to need a fallback method in case the automatically chosen renderer does not support color modulation?  Or is it better to render entire lines of text using software rendering and then somehow efficiently convert gray to alpha later?  Or is it better to trace each glyph in FontForge in order to convert the bitmap font to an outline font for use with SDL_TTF instead of trying to make my own bitmap font renderer?


texts: Unreal Engine: Is it possible to animate inside unreal engine?

texts: I have a skeleton mesh and want to slightly tweak it. Is there a way to do this natively in Unreal Engine instead of resorting to a 3D program?


texts:
I've searched around the Internet, and eventually read a suggested article, "Fix your Timestep!". In accordance with the article, I came up with an update method, but I still have problems. Whenever I instantiate more objects, in my scene, I get much slower physical interaction. I've fixed other sub-systems, that they were wasting cycles during the update process, and I've tracked my physics performance drop to this point. I think the way I'm updating my physics is somehow wrong, because I'm using a fixed timing of 1.0 / 60.0 for my Box2D engine.

What are the mistakes I'm making in my update process? What is the correct way to update a physics frame rate? Here is my code:

void Core::Update()
{
    // Input
    this->cInput->Update();

    // Physics
    this->cPhysics->Update();

    // Keep frame rate
    static const double desiredTime = 1.0 / 60.0;
    static double currentTime = (double)(GetTickCount());
    static double accumulator = 0.0;

    double newTime = (double)(GetTickCount());
    double frameTime = newTime - currentTime;

    if(frameTime > 0.25){ frameTime = 0.25; }
    currentTime = newTime;

    accumulator += frameTime;

    while(accumulator >= desiredTime)
    {
        // Input
        this->cInput->Update();

        // Physics
        this->cPhysics->Update(desiredTime);

        // Scripts
        this->cScripts->Update();

        accumulator -= desiredTime;
    }

I've read that you shouldn't tie your physics frame rate to the render frame rate, so I use this->cPhysics->Update();. I've used my previous approach, but with a slight change; I'm not sure if what I'm doing is right, but it solved my performance issue. First, I changed currentTime to get time in milliseconds, instead of seconds. At the end, I've moved all of my update code to a time step loop, except for the renderers update. I still do not know if this is the correct way to go.


texts: how do I instantiate a prefab that adds to the score text in c#?

texts:
Hello I'm working on a game with random generation, a dungeon crawler of sorts. i need to be able to have an object that when instantiated, adds to the score(the goal is to find all of them as the dungeon is created around you)this is the script for the orb/cube.`

public Text score;
public int scores;

// Use this for initialization
void Start () {
    scores ++ ;

    score.text = scores.ToString();
}
public void Update()
{
    score.text = scores.ToString();
}

public void OnMouseDown()
{
    Destroy(gameObject);

    scores--;
}

`

when an object is added it won't add to the score.


texts: Can you offset the horizontal flip in SpriteEffects XNA?

texts:
As the title suggests I need to know if there is a way to offset the SpriteEffects.FlipHorizontally component in the XNA draw method. My reason for this is the sprite I am attempting to flip is not centered, the result is that the sprite does not rotate as expected and causes unexpected collisions when flipping. I have the alternative of redoing all the textures in the sprite sheet to centre them up however I'm wondering if there is also a quick  solution that can be added into the code?

My tests so far have shown that the origin of the texture seems to have no effect on where it is flipped otherwise I would just offset my origin and gone with that.


texts: How do I create a half-ortho half-perspective projection matrix

texts:
I've been trying to make a formula for the projection matrix where your vertical axis is projected orthographically but your horizontal axis will have perspective to it.
So the view frustum would look like this:

I studied how the formulae of orthographic projection and perspective projection and how they where achieved. And tried to modify those to try to reach projection I wanted. It seemed to me it wasn't possible to have one axis scale to Z and the other not (or to have them scale at a different factor).
It it possible to reach the perspective I want? If so what would the projection matrix look like?


texts: Slow uniform array in shader causing FPS drop

texts:
I'm trying to use an uniform array of matrices in my compute shader. However, it's really slow. I've narrowed it down to this lines of code:

uniform mat4 someMatrixArray[64];
...
vec4 result = vec4(0);
for (int i = 0; i < 2048; i++) {
    result += someMatrixArray[i%64][0] * 0.01;
}

When not accessing someMatrixArray I get 700+ fps. When accessing it, I have 10 fps. Anybody has an idea what could cause this? Could it be a driver issue?

I already tried to unroll the loops (via #pragma optionNV (unroll all)) but that didn't help. I'm using a GTX670 with the latest drivers on windows 7.

Edit:

The generated assembly for the inner loop is:

MAD.F R0.xyz, c[196], {0.0099999998, 0, 0, 0}.x, R0;


texts: How can I create a contrail effect for a spaceship in motion?

texts: I am curious how I could create an effect similar to the ship's tail in the following picture:


texts: Peer-to-peer hostless competitive games of chance?

texts:
I'm wondering - have any games been ever created that are:

peer-to-peer without one peer being designated as host
competitive (not cooperative, players play against one another)
provably fair (there is no possibility of any player cheating)
Don't give any player more information than they need (for example, not revealing other players' secrets even to the running applications)

An example of such a game would be a poker game where each player and their games would only be able to know their own hand, but not the hands of other players without relying on any of them being the host of the game. I know there are a few games out there that are provably fair, but all that I know exist in a server-client configuration.


texts: Should game logic update per second or per frame?

texts:
I'm trying to wrap my head around how and when to update an entities position.

My game loop updates logic at 25 FPS and renders at 50-60 (Depending on the computer hardware).

So lets say I'm moving an object from 0 to 75 over a course of 100ms. In my update logic, should I update the position based on a per frame value or a per second value?

I was doing the math, and came up with and interesting find.

Since the update function updates at a rate of 25 fps, this means that it will be called at 40ms, 80ms and 120ms.

And the render function updates faster at a rate of 60 fps (for the sake of argument), which means it will be called at 16, 32, 48, 64, 80, 96, and 112ms

So if you line up all of these events on a timeline you'll notice that at the 6th render (96ms) the value of our position would be 72. And on the 7th render, the position would be 75.

Then the update function would be called at 120ms and would notice that the value is 75, but the current time is 20ms over what it should be.

Now I know that 20ms isn't much, but how do you compensate in collisions, physics, and AI for this? Should I instead update my values per frame instead of per millisecond?


texts: In a grid based system, where users can build their own walls to create buildings, how do you determine which parts are indoors?

texts:
I've looked around for an algorithm to solve this problem, but I can't seem to find anything.

In a game I am working on, data is held in a grid. Certain squares within that grid can be set as walls, so that the user can create buildings.  What I am wondering is how could I write an algorithm to determine which parts of the grid were indoors, that is to say, within a building, and which parts are outdoors. Thank you in advance for any advice.


texts: How can I have more values in array on X axis than Y axis in my tilemap?


texts: How to create a line renderer with end point as the mouse position, but with a fixed direction

texts:
I have two objects with a line going from one to the other, like this:

I want to create another line with a starting point one of the objects and an end point the mouse position, however still facing the second object, which will look like the first line is filling up to where the mouse is.

For example, I want to connect the blue shape with the green shape, so I move my mouse from one to the other. The game finds the nearest white line from the cursor and creates another line on top of it that follows my cursor, like this:

The current script is this. It draws a line from the origin shape to the mouse position, but it doesn't stay on only one direction and instead moves where my mouse goes:

public class SelectionLine : MonoBehaviour {
private LineRenderer lineRenderer;

private void Awake() {
    lineRenderer = GetComponent<LineRenderer>();
}

private void Update() {
    if (ShapeSelection.instance.selectedShape != null && ShapeSelection.instance.draggingFinger != null) {
        var originPosition = ShapeSelection.instance.selectedShape.transform.position;
        var destinationPosition = ShapeSelection.instance.draggingFinger.ScreenPosition;

        lineRenderer.SetPosition(0, new Vector2(originPosition.x, originPosition.y));
        lineRenderer.SetPosition(1, new Vector3(ShapeSelection.instance.draggingFinger.GetWorldPosition(1f).x, ShapeSelection.instance.draggingFinger.GetWorldPosition(1f).y, 0));
    }
}

}

There is no way (as far as I know) to set a direction of a line renderer in Unity, so how can I achieve this?


texts: Unity3D: Storyboard-esq animation - a beginners question

texts:
As part of an interactive book I'm developing in Unity3D, I'm attempting to make an introductory scene that consists of moving lots of objects at different times - usually when another animation has completed.

For example, some trees (sprites) move down the page, which starts some text moving in and cloud sprites to appear and start to move across the page, then some text begins to scroll from the bottom to the top of the page, while some audio beings to play.

Currently, I've made a script that can move a series of clouds from left to right, or right to left across a background sprite given a speed (note: I'm not using any of the animation tools, simple C# scripting to move the objects on a loop).

Within Unity3D, what is the recommended approach to achieve this?

My thoughts are:

Create a series of scripts that waits for n seconds (where n is the duration a desired 'animation'), and then start another - with somekind of 'master' or 'controller' script to manage the timeline.
Somehow use the animation tooling built into Unity3D, although I don't think that this what they were indented for...
Find a plugin that can help me create the scene and trigger animation/ scripts either on an event (animation finished) or after a specific time.

I've been using Unity3D for about 2 weeks now, so I'm certainly at the (pre?)-beginner level, I do however have over a decade of C# experience, so I'm comfortable with the scripting aspect.

Thanks in-advance,
Kieron


texts: Marching cubes leaving holes in the mesh

texts:
Hi I'm trying to reproduce GPU Gems 3 chapter 1 (Generating Complex Procedural Terrains Using the GPU) and so far I managed the basics... Now I'm betting some strange output.

I started with the suggested -ws.y to generate a plane. Then when I moved to the noise I noticed some holes in the mesh. But unlike this previous question.

The noise mesh:

So I decided to try something more simple, 3 tubes:
x^2+y^2-2

x^2+z^2-2

y^2+z^2-2

I would assume there is some problem with the z axis. But I can seem to figure out what.
My function to get the triangles vertex positions also seems ok...

Vector3 vertexAlongEdge(int edge, Voxel v){
    Vector3 result=new Vector3(0,0,0);

    Vector3 p1=v.vertexes[edges [edge, 0]];
    Vector3 p2=v.vertexes[edges [edge, 1]];
    float v1 = density (p1);
    float v2 = density (p2);
    if (Mathf.Abs (isoLevel - v1) < 0.00001)
        return p1;
    if (Mathf.Abs (isoLevel - v2) < 0.00001)
        return p2;
    if (Mathf.Abs (v1 - v2) < 0.00001)
        return p1;

    float m = Mathf.Abs((isoLevel - v1) / (v1 - v2));
    result.x = p1.x + m * (p2.x - p1.x);
    result.y = p1.y + m * (p2.y - p1.y);
    result.z = p1.z + m * (p2.z - p1.z);

    return result;
}

The only thing I can think of right now is an error in my table with the edges for each case.
Please help.


texts:
I was testing a cool 3D Scene Graph Library called iSGL3D. Since I found some functions called alpha culling for displaying partly hidden objects (making the ones in front transparent). I was wondering if it's possible to also do dynamic occlusion culling.

I know there are several descriptions for that like View Frustum Culling, Hidden Surface Detection, Hidden Surface Removal, but I can't find anything with google or on their homepage.


texts:
So, I've been obsessing over the video game Life Is Strange for the past few weeks (rightfully so, its a wonderful game) and I've been putting together a list of what makes it compelling to play. I got to the art style, as it obviously isn't realistic but not too unrealistic. I was trying to put it together myself but when I google search life is strange art style, all that shows up is fan art that doesn't well reflect it. I want to know what style of texture painting they used to give it that semi-realistic feel. How can I replicate it on my own in photoshop for my own game?

Sorry if I misplaced this question in this community, I just didn't feel right posting in graphic design.


texts:
What is a good way of implementing a RTS selection box for tiles on a grid? I'm making a game with some similarities to Evil Genius, the building in particular. In that game you click one place, drag the cursor somewhere else and something similar to the GIF below shows.

To do so a grid and a way of translating mousePosition to the correct cell is needed. Then a set of for loops (one for x and one for y) for executing the necessary action on each cell. My main problem is accounting for the direction of dragging, and in particular when shrinking. My current solution (hastebin here) is rather crude, and I would like a more elegant solution for a more civilized age. Hopefully someone else can think of a easier way of accounting for drag direction, I surely can't.

Any help appreciated.


texts: How can I find the offset rotation and position between two objects in 3D?

texts:
I have two objects in 3 dimensions, one of them (Child) is attached to the other one (Parent) using the offset between them (XYZ - position and rotation).
Using the Vector3 library, how can I find that Child offsets from the Parent?

Further explanation: let's say we have the parent at position X:0 Y:0 Z:0 with rotations RX:0 RY:0 RZ:0, and there is an attached Child to it with the offset X:10 Y:10 Z:10, RX:90 RY:45 RZ:90 (which is what I want to know). Supposedly, I had the Parent with a different position and rotation, how can I get the offset between it and the Child (which in this case, it should be X:10 Y:10 Z:10, RX:90 RY:45 RZ:90) (in another word, I want the Child position and rotation as the Parent is the center of the map)

I've tried simple math and some other ways on the internet but with no success, since I'm pretty bad at calculating rotations (since vector3 libraries are pretty identical, so as Math libraries, any language should be fine).


texts: Are delayed abilities bad in turn-based strategy games?

texts:
In my PvP turn-based strategy, one of the balancing mechanisms for separating stronger from weaker abilities is their "delay", which is the number of turns it will take to actually execute that ability, from when it was commanded. For example, if you cast an ability with delay = 1, that unit won't use it until the start of your next turn. Most abilities have delay = 0, meaning it's used right when the command is given. It is clear when a unit is "casting" a delayed ability; they have an ongoing casting animation, there are tick marks above their head to count how many turns left for casting, and when you click on them, you see which tiles are targeted.

It's similar to "casting time" in Final Fantasy Tactics.

It serves several purposes in my game. For one thing, I need to balance stronger vs weaker abilities somehow, and there's already a lot of other resources to keep track of (action points, gold, etc). I don't want to clutter the game with more resources, such as mana on individual units. Units can have "cooldown" (number of turns where they can't be used) after being used, so moving units into enemy territory with cooldown can be dangerous, because they're vulnerable to the more powerful "delay" abilities. Finally, some of them can just be used as a deterrent, such as casting a large AoE delayed ability to say "don't come into this territory".

However, I read this article about Final Fantasy Tactics. It's an interview with a developer of a new indie game inspired by FFT, who was also a dev in FFT. Basically he says that casting time won't be in the new game, and was only in FFT because of technical limitations (the game needed time to load the graphics of certain spells). Also, I notice that it hasn't appeared in any of the later Tactics games by Square, nor in many other tactical games that are self-confessed "clones" of FFT (Fell Seal, for example). I basically haven't seen delayed abilities in any tactical turn-based game since FFT.

I also noticed, when playing the prototype of my game with some friends, that they were annoyed that some abilities didn't execute right away, even though it was advertised in their details that they have delay.

These things make me wonder if delay is an inherently bad mechanic, and that there's a good reason developers have been avoiding it since FFT. Perhaps it just feels bad or clunky on the side of the user, and reduces their overall gaming experience.

I have a few alternatives in mind. But my question is, are delayed abilities in turn-based strategies generally a bad mechanic?


texts:
In my cocos2d app I have a CCSprite moving on the screen but it moves off the screen. How can I prevent the CCSprite from moving off the screen?

Thanks


texts: GPU (render time) increase if screen size increase

texts:
i create a simple 2d scene in unity 2017.3.1f1
I changed the size (height and width) in the Game View and proflie to see how it affects the rendering.. (below photo)

I saw that the rendering time increases by increasing size, and now if this happens when playing the game on a different resolution android phone, each The higher the resolution of the phone, the more likely it is to get gpu bound !???
And i do not understand Cpu graph in the two situations in above photo(lower GPU ---> higher CPU !!!)
I tested my game on the "huawei mate 10 lite"(android device) with a resolution of 1080 x 2160 and it looks like there is a lot of rendering time.(a simple scene with only 5 sprite renderer)
(unity dosen't show GPU profiling when game run on android device and we can't check these...)
I did all the optimizations I heard, like:
DynamicBatching, Sprite Atlas , Quality Setting , sprite Texture Comprestion Override for Android..
What can be done to ensure that rendering time does not exceed a specified limit on different phones ??


texts:
I have read through and tried several approaches to changing the background color of a JButton with a buffered image, but I am consistently getting the same results. I am using a 2D array of ImageIcons, some with file names such as:
ImageIcon blackRook1 = new ImageIcon("ChessPiece/Chess_rdt60.png");

the png's I am using do not fill the entire square, just the actual chess piece
and others with BufferedImages such as:
ImageIcon space = new ImageIcon(new BufferedImage(64, 64, BufferedImage.TYPE_INT_ARGB));

I am then looping through chessBoardSquares, which is an empty 8x8 2D array of JButtons, with:
Insets buttonMargin = new Insets(0, 0, 0, 0);
for(int i = 0; i < chessBoardSquares.length; i++) {
      for(int j = 0; j < chessBoardSquares[i].length; j++) {
        JButton b = new JButton();
        b.setMargin(buttonMargin); // Insets object
        ImageIcon icon = this.chessPieces[i][j]; // 2D array of ImageIcons
        BufferedImage bi = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);[![enter image description here][1]][1]

        Graphics2D g = bi.createGraphics();

        //determine color of graphic and jbutton background
        int colorDeterminator = j + i;
        if(colorDeterminator % 2 == 0) {
          // System.out.println("Getting here and coloring white");
          b.setBackground(Color.WHITE);
          g.setColor(Color.WHITE); // I have also tried with this line commented out
        } else {
          // System.out.println("Getting here and coloring black");
          b.setBackground(Color.BLACK);
          g.setColor(Color.BLACK);
        }
        g.fillRect(0, 0, bi.getWidth(), bi.getHeight());

        icon.paintIcon(null, g, 0, 0);
        g.dispose();
        b.setOpaque(true);
        b.setIcon(icon);

the if statement using color determinator has definitely run as the print statements have executed
I keep getting the look of the attached image which, while it is a bit trippy, isn't what I want as I am aiming for the whole square to be filled in around the image. (For those that cannot see the image, the edges of the squares are black and white, but the majority of each square is filled white, which I believed is where the BufferedImage is.) Thank you for your help!


texts: Optimizing the economy of a resource management game

texts:
I am an amateur game designer. I am designing a resource management game involving real money. This is my first time designing such a game. I explain the design and mechanics below. I need feedback from experienced game designers regarding:
i) The sustainability of the core economic loop of this game,
ii) Concrete suggestions to de-risk or fine-tune it (if you can think of any)

My game is about digging up treasure. Treasure is real $$$ players can cash out. The objective of the game is to make as much money as possible.
Players utilize digging machines (excavators) to unearth treasure. The attributes of these digging machines are:

Digging prowess: Most machines are mediocre diggers. I.e. they unearth small treasure. A few rare machines can dig up really big treasure. And then there are other types in between these two extremes.
Scarcity: Only a finite number of machines are available in this game world.
Transparency: Machines' visual design varies in accordance to their digging prowess. I.e. players can easily spot which machine is better than the rest.

Main mechanics:
When a new player joins this game, they utilize real $$$ to buy one or multiple such machines. Once bought, each machine can either be:

Stored away (unused), or

Put to work. Note that when a machine accumulates 1 hour of digging time, it unearths treasure. The amount unearthed is always proportional to the machine's digging prowess.

Putting machines to work has an upside and a downside:

Upside: Machines that are put to work unearth treasure (actual $$$ players can claim).

Downside: Working machines can be forcefully bought by another player (for the machine's current value + 5% profit). No permission is needed. This permanently increases the value of the machine. Which means, if you want to snatch it back, you pay a further 5% increment on top of everything.

Storing machines away has an upside and a downside:

Upside: Nobody can forcefully buy them from the player.

Downside: They don't help the player earn anything.

How do we finance the treasure-finds?
There is a pool of money in the back-end that finances each and every treasure-finding. We finance this pool in two ways:

The first time a digging machine is bought, 90% of the proceeds are routed to this pool (10% are pocketed by the game developer).

I earlier mentioned that whenever a machine is forcefully bought, a 5% profit is paid by the buyer to the unwitting seller. We route 10% of that profit to the treasure pool, 10% to the game developer, and 80% to the unwitting seller of the machine.

It would be great to get feedback from experienced game designers regarding the economic viability of the game's core loop. How do we:

Make it sustainable?
What are the economic risks?
How can they be quantified?
Are there any risk-minimization tactics we can bake in?


texts: How to reverse or create a group sprites pinned to other objects on a specific pattern.

texts:
Hey guy i am creating a game, where i am facing some problem.

I am creating a sprite, SpriteT on runtime with a rope effect like snake with proper instances. Also am creating Text object pinned on the rope style sprites with instances and need to handle those sprites objects with text instances.

I gave the leadsprite 8 directions where other families are attached to leadsprite.

Now i want is when i rotate the leadsprite to 90 and then to 180 that is top left movement. I need is to compare the instances of equal positions of sprite Whenever i do this the system never compares each value of sprites. i don't know how to compare the elements of one single array that is definately instances to each other's position record and if they match i want to destroy the sprites objects.

this includes i think there must be some pattern now i need to reverse the remaining spriteT to the Leadsprite on the same pattern.. This is where i am lacking whenever i do this

  // On Destroyed
    OnObjectDestroyed() {
     // This contain let 10 number of sprite to attached with the center of one next sprite.
         SpriteTObjectFamily.setPositionTowardsObject(ImagePoint0);
    }

I have just started and a Noob. Please help this is actually doing in Construct2. Any help would be great. Thanks in Advance!


texts:
I would like to simulate very simple hair in a 2D environment, and will need to be able to "brush" the hair.

What I want to do:  A 2D character is facing squarely towards the player.  The player can then brush the character's hair.  Think of a little girl brushing her doll's hair into different styles.

In my preliminary Google searches, I found many 3D, super-optimized hair simulations for tens of thousands of hairs, which are far more complicated than I need.  I only need 100-500 hairs, and they only need to react to "brushing" by the player.

How might I do this?


texts: Loading player position from file but player object not at right position sometimes

texts:
In my current project I am developing a game saving system and I have encountered a problem where in some cases when I save the game and re-load it the player will not be loaded in at the correct position.

I've printed the position that is loaded in from file to the console to see if it's being changed and it's not.

Is there anything i'm not seeing?

For reference here's the two methods I use when loading the game:

    public void LoadData() {
    if (File.Exists(filename)) {
        byte[] soupBackIn = File.ReadAllBytes(filename);
        string jsonFromFile = encryption.Decrypt(soupBackIn, JSON_ENCRYPTION_KEY);
        copy = JsonUtility.FromJson<SaveData>(jsonFromFile);
        print(copy.playerPosition);
        DataToLoad();
    }
}

private void DataToLoad() {
    player.transform.position = copy.playerPosition;
    player.transform.rotation = copy.playerRot;
    player.playerHealth = copy.playerHealth;
    player.agility = copy.agility;
    player.attack = copy.attack;
    player.defense = copy.defense;
    player.strength = copy.strength;

    for (int i = 0; i < copy.inventory.Count; i++) {
        inv.AddItem(copy.inventory[i].id);
    }
}


texts: Euler Angles of Any Great Circle from hit.point of a sphere

texts: How do you get the Euler Angles of Euler Angles of Any Great Circle that surrounds the raycast hit.point of a sphere?


texts: Tips for implementing MMO quest mechanics?

texts:
What tools, patterns, or best practices would you recommend to implement the quest mechanics given below listed requirements?

I am talking about software architecture (how generic should you be) and choices for object wiring, event subscription, and representation of conditions. Mentioning of tools / libraries you have successfully used are welcome.
Edit: If you are using scripting, what setup do you recommend?

Requirements:

simple 2D mmo(rpg)
all the game data, including quests, is stored in a relational database
any event in the game could trigger a new quest for players or advancement of existing quests
a quest can have an arbitrary number of conditions that must be met before the quest is available to players
a quest can consist of an arbitrary number of sub-quests / steps with arbitrary conditions
quests would range from simple:

talk to A - kill 5 B - talk to A - permanently increase health
to quite involved:

use item in area X - go to area Y - a bot will spawn - kill bot without taking more than 10% damage - bot drops item - pick up item - portal unlocks - deliver item to J behind the portal - receive gold and experience - allow to pass portal once more - lock portal for this player
level instances are a possibility (players can complete certain quests in teams or isolation which will spawn the level location just for those participants)
Quests should preferably be manageable using a world editor without scripting or programming knowledge (Edit: not advocating against scripting in general though)
I assume C++ as the language of implementation

I was thinking that if I could combine any chain of events and conditions we could model more complex and thus possibly more engaging quests.
I experimented with rolling my own ECA (Events-Conditions-Actions) engine but that might be overkill. It has been particularly difficult to model generic conditions without using any sort of scripting.


texts: Camera looking around with mouse - Unity, C#

texts:
I am building a script in C# for camera logic in Unity, the camera is supposed to follow the player (a 3rd person character) around and the user should be able to look around using the mouse, so far everything works fine (the following logic and looking around on the horizontal axis) the problem is I can't get the camera to move along the vertical axis, left and right are fine but up and down are not working.

This is the C# script:

public class PlayerFollow : MonoBehaviour
{
    public Transform PlayerTransform;

    private Vector3 _cameraOffset;

    [Range(0.01f, 1.0f)]
    public float SmoothFactor = 0.5f;

    public bool LookAtPlayer = false;

    public bool RotateAroundPlayer = true;

    public bool RotateMiddleMouseButton = true;

    public float RotationsSpeed = 5.0f;

    public float CameraPitchMin = 1.5f;

    public float CameraPitchMax = 6.5f;

    // Use this for initialization
    void Start()
    {
        _cameraOffset = transform.position - PlayerTransform.position;
    }

    private bool IsRotateActive
    {
        get
        {
            if (!RotateAroundPlayer)
                return false;

            if (!RotateMiddleMouseButton)
                return true;

            if (RotateMiddleMouseButton && Input.GetMouseButton(2))
                return true;

            return false;
        }
    }

    // LateUpdate is called after Update methods
    void LateUpdate()
    {
        if (IsRotateActive)
        {

            float h = Input.GetAxis("Mouse X") * RotationsSpeed;
            float v = Input.GetAxis("Mouse Y") * RotationsSpeed;

            Quaternion camTurnAngle = Quaternion.AngleAxis(h, Vector3.up);

            Quaternion camTurnAngleY = Quaternion.AngleAxis(v, Vector3.up);

            Vector3 newCameraOffset = camTurnAngle * camTurnAngleY * _cameraOffset;

            // Limit camera pitch
            if (newCameraOffset.y < CameraPitchMin || newCameraOffset.y > CameraPitchMax)
            {
                newCameraOffset = camTurnAngle * _cameraOffset;
            }

            _cameraOffset = newCameraOffset;

        }

        Vector3 newPos = PlayerTransform.position + _cameraOffset;

        transform.position = Vector3.Slerp(transform.position, newPos, SmoothFactor);

        if (LookAtPlayer || RotateAroundPlayer)
            transform.LookAt(PlayerTransform);
    }
}


texts: Converting coordinate systems to/from an isometric game world

texts:
I have tried searching and reading for an answer, but the information I could dig up either didn't fit what I need or was in the form akin to "Just multiply the vectors with the inverse matrix of.." which to my brain (unfortunately) makes just as much sense as someone speaking Mandarin.

The plan is to use requestAnimationFrame and canvas for the drawing, and WebSockets for the communication. I already have a fair grasp of requestAnimationFrame and canvas, and some hacked together code for a php WebSockets server with support for most of the currently-in-use drafts. This is a project for fun and learning so please, no comments on how silly it is to write server software in php

The main hurdle arises when I try to implement movement. I have code for drawing a map both as staggered and diamond shaped. I even had click-to-walk type movement implemented, but I hit a wall when it came time to implement collision detection.

See, my player exists in the coordinate system of the canvas, along with mouse events etc. What I did was draw the character sprite in the middle of the canvas, and animate the offset of the map by the difference between the center of the canvas and a clicked point. Thing is, I would like to keep my "world" (e.g. map, player, objects/entities) in memory as a regular grid map, and just have everything drawn with isometric skewing. This would make implementing collision detection very simple.

As it is right now, adding 32px to the players x-coordinate doesn't move him along the maps x-axis but rather that of the canvas. If increasing the player's x moved him along the maps x-axis then as I said, implementing collision detection would be as simple as checking whether the next tile along that axis is blocking or not, and update my x-position based on that.

Short question is: given the player's x- and y-coordinates, how do I calculate the appropriate map offset so that increasing either coordinate will move the player along the appropriate "in-game" axis?

Thanks, and a link to my hacked together initial test: http://dev.plastbox.org/isoengine/ It's continually being modified though, so it might not work at all every now and then.


texts:
I'm trying to get a grip on mipmaps with OpenGL. I believe I understand the concept, but when trying to have OpenGL generate them I wonder how it determines how many mipmaps to generate?

Here's what I'm running with right now to initialize a 2d texture:

    glGenTextures(1, &mTexture);
    glBindTexture(GL_TEXTURE_2D, mTexture);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA , textureWidth, textureHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, &textureData[0]);
    glGenerateMipmap(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, 0);

Nowhere do I specify how many mipmap levels to generate. How many mipmaps are generated in this case? Where do you specify this number?

I've also seen another technique from http://www.opengl.org/wiki/Common_Mistakes where you use glTexStorage2D to specify all the mipmaps levels instead - but how many levels can you specify and what is a reasonable number for quality?


texts: How can I pass messages from multiple components to another?

texts:
I want to start with an (easy) Entity Component System. I have a question regarding the messaging between Components.

Let's say I have a RenderComponent. This component needs 2 integer values x and y and probably a Sprite to render.
Now I have 3 other Components:

TransformComponent with 5 doubles: x, y, width, height and rotation.
MovementComponent with 2 doubles: velX and velY.
AnimationComponent with an array of Sprites.

Now I want to render my Entity.

How do I collect the Data from the different Components to render my Sprite?
All these informations have to enter the RenderingComponent at the same time.
Does someone have an idea on how to accomplish an efficient ECS?


texts: Component System - Editor Data Management

texts:
I'm trying to construct an editor in C# that exposes game components to IronPython, so it may create the game object definitions to be used within the editor:

C# Exposes the components to the python script (Spatial, Movement, SpriteView, etc.)
IronPython creates the game object definitions (or templates) by attaching components to a game object.

At the startup of the editor:

The Python script is loaded with all of the game object definitions.
Tools are updated with the new objects (availability for painting).

The problem I'm having lies when I'm saving and opening the editor data:

When saving, I use C# to serialize all of the constructed game objects (including the game object definitions generated from python) to a file.
When opening, I use C# to deserialize the data.  - Since the Python script is not synchronized with the serialized components, I will run into a big problem when I change anything in the script.

One solution I had was to only serialize the definition name of a game object, therefore when I deserialize my data I will have to do a lookup for the target definition (created by the script) and simply clone it. But, it still will not be entirely in sync with the editor data (some data will be changed on each game object like for example the position (note when I say game object I do not mean the definition)).

Another solution might be to use a database and save out all of my editor data to it (perhaps using the entity database in C#). I'm not entirely sure if this will solve my problem.

Any help would be appreciated, thanks!


texts: HLSL Pixel Shader - Color depending on condition

texts:
I am new to shaders and HLSL so bare with me on this one.

I have a 2D tile map in my game and want to create a mini-map, at first I was just copying all the data from one sprite batch to another and rendering it in a smaller camera. This obviously has a performance issue.

So I want to make a mini-map that is composed of coloured pixels depending on what is in that particular cell.

I have a basic shader going at the moment that converts tex coordinates to pixel position but now I need a way to determine what color to set it. My instant decision was to simply pass in a 2d array of colors and grab the color using the x and y coordinate of the pixel, this crashed lol.

Here is what I have so far for the shader:

sampler s0;

// The width and height of the texture being sampled
int width, height;

float4 PixelShaderFunction(float2 coords : TEXCOORD0) : COLOR0
{
    float4 color = tex2D(s0, coords);
    // Covert the tex coordinates to pixel coordinates
    int2 tc = int2(width * coords.x, height * coords.y);

    // Here I need to do some sort of check or something?

    return color;
}

technique Technique1
{
    pass Pass1
    {
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}

How can I pass the color data to the pixel shader so it knows what color to set each pixel? I already know how to pass data but not sure how I can represent that data to pass it.

My map is every changing and units are moving around constantly, so the data will be passed in almost every frame.


texts: Unexpected results during collisions in Unity

texts:
I've got a basic car-based game I'm starting in Unity.  Currently the scene has only a floor, a car (player-controlled), and one building.

Bumping into the building at low to medium speeds works as expected.  When getting the car up to max speed and smashing into the building, though, weird results happen.

Originally, the car was being pushed through the floor and falling off the map.  I changed the floor from a plane to a cube that was stretched to be broad and flat (scale 2 height), and that helped.  Now the car seems to clip right through the building at top speed, sometimes flipping itself into the air when it emerges.

So what gives?

The car and building are both imported .fbx models and both have box colliders stretched to the outer bounds of the models.  The car has a rigid body with gravity.  The building used to have a rigid body, but I removed it once I realized it was making the building fly into the air on impact (which was definitely not what I wanted).

Here are the relevant parts of the movement code:

  bool key_up = false;
  float top_speed = 1f;
  float current_speed = 0f;
  float acceleration = .01f;

  void Update ()
    {
    if (Input.GetKeyDown (KeyCode.UpArrow) && !key_up) key_up = true;
    if (Input.GetKeyUp (KeyCode.UpArrow) && key_up) key_up = false;

    if (key_up)
      {
      if (current_speed < top_speed) current_speed += acceleration;
      }

    else
      {
      if (current_speed > -.1f && current_speed < .1f) current_speed = 0f;
      if (current_speed != 0f) current_speed = current_speed * 0.9f;
      }

    transform.Translate (0f, 0f, current_speed);
    }

Update:

After switching the camera to a fixed position (rather than following the car), I've gotten better observations.  The car will clip right through at any speed if I keep pushing forward.  There's initial resistance from the collision detection and some stuttering from the car, but it always breaks through and then flips into the air on its way out.

I've added the following function to the car code:

void OnCollisionEnter (Collision collision_info)
  {
  current_speed = 0f;
  }

current_speed is what's being used to translate the car forward each frame.  This has slowed the bug down, but the car always eventually pushes through if I hold down the gas long enough.  It looks as if Unity's collision detection isn't moving the car back far enough on each frame that the car is colliding.  Must I handle that portion on my own?


texts: Regarding static collision resolution between two circles

texts:
I have some code that resolves the positions of two circles when they collide:
float fDist = sqrtf((c2->m_pos.x - c1->m_pos.x) * (c2->m_pos.x - c1->m_pos.x) + (c2->m_pos.y - c1->m_pos.y) * (c2->m_pos.y - c1->m_pos.y));
float fOverlap = 0.5f * (fDist - c1->m_radius - c2->m_radius);

c1->m_pos.x -= fOverlap * (c1->m_pos.x - c2->m_pos.x) / fDist;
c1->m_pos.y -= fOverlap * (c1->m_pos.y - c2->m_pos.y) / fDist;

c2->m_pos.x += fOverlap * (c1->m_pos.x - c2->m_pos.x) / fDist;
c2->m_pos.y += fOverlap * (c1->m_pos.y - c2->m_pos.y) / fDist;

However, I'm having the issue that, on large numbers of simulated circles, as the program "detection rate" slows down, fDist approaches (or even becomes) 0. As a result, the circles in question are blasted off into infinity, rather than "glide" apart from each other as I intend on doing. Is there an alternative method of achieving this effect? Or does my simulation simply run too slowly?
For more context, I am following javidx9's tutorial on circle collisions.


texts:
The Sprites/Default shader multiplies the color with the provided tint, while I need to add it instead.
I fixed this copying the shader (taken from here) and simply changing the line

return tex2D(_MainTex, IN.texcoord) * IN.color;

to

return tex2D(_MainTex, IN.texcoord) + IN.color;

Is this the right approach, or there was a better one? (which uses something like inheritance, as opposite to copy-pasting)

Also, is this legal? I assume they allow you to use it at will, but technically there's no licence attached to the shader, so I'm not sure. Maybe that's covered somewhere in the Unity license?


texts: How to draw a Minecraft-like world with Open GL

texts:
I recently completed the this Open GL tutorial. The tutorial shows how to set up a window and shaders, and teaches you how to draw a single cube in the middle of the screen, which all makes sense to me (I think).

I'd like to make just a simple flat world made of cubes like Minecraft, but I have no idea how to turn my single giant cube into a bunch of smaller cubes, or how to get the smaller cubes to be arranged in the proper way.

Mostly what doesn't make sense to me is the coordinate system being from 1 to -1 and trying to draw a bunch of cubes in that space. Is there a way to adjust that coordinate space to be more world-like, where each unit of coordinate space is roughly equivalent to a meter or something?


texts: using lua in kobold2d to control parameters

texts:
Is there a tutorial on using LUA in Kobold2d?

I want to know if its possible to use it to control the game behavior (like max speed decrease of timer, and bonus points) by uploading a new script to the app.

I found this link in the FAQ:

http://www.kobold2d.com/pages/viewpage.action?pageId=917888

but it does not mention if I can replace the lua script from within the game, and reload it, is that possible?  Should i just have a parameter file instead that i can download and replace?


texts: How to test Google Play Multiplayer locally

texts:
I'm building a simple HTML5 game and I need to implement multiplayer without sharing the game on Google Play.

I'm using CocoonJS's multiplayer api.

How can I test Google Play Multiplayer locally? Do I really have to use websockets instead?


texts:
I have a basic physics body system (incomplete/very basic; as collision resolution and detection are not implemented, just mass, position, velocity, acceleration, force and impulse).

I implemented position, velocity, acceleration, force and impulse as described in Game Coding Complete 3rd. Ed. by Mike "Mr. Mike" McShaffrty et al. specifically Chapter 15: Collision and Simple Physics by Jeff Lake which is: (paraphrasing from text and code, US copyright law and all that.)

  Gravity is a Force.

  Application of a Force vector adds it to a std::list of forces.

  Application of an Impulse vector adds it to a std::list of impulses.

  Upon calling Update on the physics body:

  Add all forces and all impulses together (F).
  Clear the impulses list.
  Set acceleration to (F / mass)
  Set velocity to (velocity + (acceleration * deltaTime))
  Set position to (position + (velocity * deltaTime))

(See code below)

The problem I'm having is when gravity is applied as a force the list grows linearly...forever. Eventually it overcomes any attempt to directly set the position of an object to the point that A) The object is always affected by gravity no matter if or how fast the position is changed (clamping to the screen is a good example) B) The list grows so large that the system implodes and chugs. C) If, before the system implodes, the object is stopped at a specific position, the acceleration due to gravity continually increases making it ever harder to change the acceleration/velocity/position of the object (specifically applying an impulse or force upwards).

If I change the noted line in GravityHandler to elem->ApplyImpulse(deltaG); it works satisfactorily but is this correct or am I missing something?

My implementation according to his example:

RigidBody and its state:

void State::ApplyImpulse(const Vector2D& impulse) {
    _impulse.push_back(impulse);
}

void State::ApplyForce(const Vector2D& force) {
    _forces.push_back(force);
}

//RigidBody is a `friend` of State.
void RigidBody::ApplyForce(const Vector2D& force) {
    _curState.ApplyForce(force);
}
void RigidBody::ApplyImpulse(const Vector2D& impulse) {
    _curState.ApplyImpulse(impulse);
}

GravityHandler:

void GravityHandler::Update(double deltaTime) {

    class UpdateObject {
    public:
        UpdateObject(double deltaTime) : _deltaTime(deltaTime) { };
        void operator() (RigidBody* elem) {
            double mass = elem->GetMass();
            if(Math::IsEqual(mass, 0.0)) return;

            double gxm = elem->GetXGravityModifier();
            double gym = elem->GetYGravityModifier();

            Vector2D deltaG(_GRAVITY_VALUE.GetX() * gxm * mass * _deltaTime, _GRAVITY_VALUE.GetY() * gym * mass * _deltaTime);
            elem->ApplyForce(deltaG); //The problem seems to be here.
        };
    private:
        double _deltaTime;
    };

    _accumulator += deltaTime;
    if(_accumulator < (1.0 / 60.0)) return;
    _accumulator -= deltaTime;
    if(!_isActive) return;
    std::for_each(_subscribers->begin(), _subscribers->end(), UpdateObject(deltaTime));
}

RigidBody:

void RigidBody::Update(double deltaTime) {

    double mass = GetMass();
    //If static body, do nothing.
    if(Math::IsEqual(mass, 0.0)) return;

    Vector2D F;
    F += std::accumulate(_curState._forces.begin(), _curState._forces.end(), Vector2D());
    F += std::accumulate(_curState._impulses.begin(), _curState._impulses.end(), Vector2D());
    _curState._impulses.clear();
    SetAcceleration(F / mass);
    SetVelocity(GetVelocity() + GetAcceleration() * deltaTime);
    SetPosition(GetPosition() + GetVelocity() * deltaTime);

}


texts:
Mass is one of the basic scalar quantities, which is required in most rigid body physics calculations.

In a game, does every moving object have mass defined in the code, or is it allotted by the rendered objects size? Size should not be the only solution, though, since density also comes into play.

For example how does the physics engine handle mass in the Frostbite engine used in "Battlefield 3"?


texts:
I have a 2D matrix; each of its elements describes a homogenous coordinate in 3D wave (the values of wave coordinates are changed in time). The wave rendering is done with texture. I need to make an integration for the wave.

Does anyone have a clue? And another question; will the texture have any impact on integral calculation?
p.s maybe i can do this using opengl?


texts:
I have a collision detection and its working fine, the problem is, that whenever my "bird" is hitting a "cloud", the cloud dissapers and i get some points. The same happens for the "sol" which it should, but not with the clouds.

How can this be changed ? ive tryed a lot, but can seem to figger it out.

Collision Code

- (void)update:(ccTime)dt {
    bird.position = ccpAdd(bird.position, skyVelocity);

    NSMutableArray *projectilesToDelete = [[NSMutableArray alloc] init];
    for (CCSprite *bird in _projectiles) {
        bird.anchorPoint = ccp(0, 0);
        CGRect absoluteBox = CGRectMake(bird.position.x, bird.position.y, [bird boundingBox].size.width, [bird boundingBox].size.height);

        NSMutableArray *targetsToDelete = [[NSMutableArray alloc] init];
        for (CCSprite *cloudSprite in _targets) {
            cloudSprite.anchorPoint = ccp(0, 0);
            CGRect absoluteBox = CGRectMake(cloudSprite.position.x, cloudSprite.position.y, [cloudSprite boundingBox].size.width, [cloudSprite boundingBox].size.height);

            if (CGRectIntersectsRect([bird boundingBox], [cloudSprite boundingBox])) {
                [targetsToDelete addObject:cloudSprite];

            }
        }

        for (CCSprite *solSprite in _targets) {
            solSprite.anchorPoint = ccp(0, 0);
            CGRect absoluteBox = CGRectMake(solSprite.position.x, solSprite.position.y, [solSprite boundingBox].size.width, [solSprite boundingBox].size.height);

            if (CGRectIntersectsRect([bird boundingBox], [solSprite boundingBox])) {
                [targetsToDelete addObject:solSprite];
                score += 50/2;
                [scoreLabel setString:[NSString stringWithFormat:@"%d", score]];
            }
        }

        // NÅR SKYEN BLIVER RAMT AF FUGLEN
        for (CCSprite *cloudSprite in targetsToDelete) {
            //[_targets removeObject:cloudSprite];
            //[self removeChild:cloudSprite cleanup:YES];
        }

        // NÅR SOLEN BLIVER RAMT AF FUGLEN
        for (CCSprite *solSprite in targetsToDelete) {
            [_targets removeObject:solSprite];
            [self removeChild:solSprite cleanup:YES];

        }

        if (targetsToDelete.count > 0) {
            [projectilesToDelete addObject:bird];
        }
        [targetsToDelete release];
    }

    // NÅR FUGLEN BLIVER RAMT AF ALT ANDET
    for (CCSprite *bird in projectilesToDelete) {
        //[_projectiles removeObject:bird];
        //[self removeChild:bird cleanup:YES];
    }
    [projectilesToDelete release];

}


texts:
I want to make the grass swing/shake whenever the player walk through it. Like shown in this gif Grass Swing Effect from this article.

I know I have to move the x coordinates of the vertices factored by y coordinates. But I'm not sure how to implement it?


texts: Dual marching squares/cubes - divide or do not divide a node?

texts:
In the marching squares/cubes algorithm, how is it decided if a node in the quadtree/octree will be divided further (into 2^dimension nodes)?

I read about this heuristic that uses a trilinear interpolation to decide if an octree needs to be divided further for not.

It is not clear what the line represents and against what it's tested.


texts: Handling character with world object collision in libgdx and bullet

texts:
I am using libgdx and bullet for my 3d mmo project. I have been able to detect collisions using a collision world with collision objects. This was working fine for things like detecting players hitting each other but I was having problems handling players hitting walls or other world objects.

After some searching I came across rigid bodies and the dynamics world. This seemed like it would solve my issue but once I got my objects converted over to rigid bodies my collision handler is no longer detecting collisions and the player is still going through walls.

I would like to not have to handle the low level details of players not going through walls but I would still like to be able to manually handle collisions of collision objects for things like spells or weapons. What is the best way to go about this? I am also seeing different bullet objects like static, kinematic, dynamic, but I am not sure which is best for my situation. I also am thinking that part of my problem may be that I am translating my character every update instead of updating its velocity.

What is the best setup for accomplishing this?


texts: How can I apply setActive to a UI element after an animation finishes?

texts:
I have an object animation which plays on the opening of a scene. When the animation is over I want the UI slider to be setActive - allowing the user to rotate the object. I have both these elements in place and working individually - just can't quite work out how to go about combining them.

Any help or advice about what approach I should take is much appreciated.

The animation was created in Maya.


texts:
I have a script in which I defined different functions for each button and assign them their appropriate functions. I defined if statements for them and now I want every button to play it's music when if is true. in OnClick I assigned the script but it didn't work and when I added AudioSurce to it under play () function, it played my sound on button click not when if was true. here is my script;

public class MainMenu3 : MonoBehaviour {

    [SerializeField] Button WhitePlane;
    [SerializeField] GameObject wood1;

    public static int chnum;
    public bool isPlanesold;

void Start () {

        PlayerPrefs.SetString ("BluePlane", "on");
        if (PlayerPrefs.GetString ("WhitePlane") == "on") {
            wood1.SetActive (false);
        }

        UIManager2.coin_score = PlayerPrefs.GetInt ("Score");
        isPlanesold = PlayerPrefs.GetInt ("isPlanesold") == 0 ? false:true;
}

public void BuyWhitePlane () {

        if (PlayerPrefs.GetString ("WhitePlane") == "on") {
            PlayerPrefs.SetInt ("isPlanesold", 1);
            chnum = 2;
            PlayerPrefs.Save ();
            SceneManager.LoadScene ("Menu2");
        } else if (UIManager2.coin_score >= 1) {
            this.GetComponent<AudioSource> ().Play ();
            PlayerPrefs.SetInt ("isPlanesold", 1);
            chnum = 2;
            PlayerPrefs.SetInt ("Score", UIManager2.coin_score--);
            PlayerPrefs.SetInt ("Score", UIManager2.coin_score);
            PlayerPrefs.Save ();
            PlayerPrefs.SetString ("WhitePlane", "on");
            SceneManager.LoadScene ("Menu2");

            }
        else
        {
            Debug.Log ("You Don't Have The Score");

        }
}


texts: Unity3D Resize texture without corruption

texts:
I am currently working on a solution to make my game look very pixelated, like Doom or Quake. But there is a big problem.

I'm using Unity Personal.

I render my camera to a 1920x1080 texture, then I try to use Texture2D.Resize on it, then render it back to the screen using ScaleMode.StretchToFill.

But the problem is that the texture seems to corrupt when I use Texture2D.Resize on it.

And here is my current code:
using UnityEngine;
using System.Collections;

public class PixelRenderer : MonoBehaviour {

    Texture2D texture;

    // Use this for initialization
    void Start () {
        texture = new Texture2D(256, 256, TextureFormat.ARGB32, false);
    }

    // Update is called once per frame
    void OnPostRender() {
        texture = new Texture2D(Screen.width, Screen.height, TextureFormat.ARGB32, false);
        texture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
        texture.Apply();
        texture.Resize(256, 256);
    }

    void OnGUI() {
        GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), texture, ScaleMode.StretchToFill);
    }
}

Is there something that I'm missing here? Or am I doing something wrong?


texts: Unity3D WWW get HTML displayed in browser

texts:
I currently have in a web page, on a localhost server, some information that I want to use in Unity. My problem is that this information are stored in some js variables.

I tried to use the WWW class in a coroutine, but I only get the html source code. Is there a way to get the value of this variables inside Unity Editor ?

Thanks !


texts: Sequencing / triggering messages based on conditions in an adventure game

texts:
I've been struggling conceptualizing the best way to make a level flow with dialog and help hints changing as you play etc.

Imagine your goal is to make this one screen 'adventure' game, where you leave your house for work, but along the way, you realize you cannot find your keys to leave the house (and drive to work), also the door handle has fallen out of your door again!

Here is the structure of the story as I see it and how I'd break it down for a game. But what data types would you use, and how would you send messages to the dialog classes telling them to display the lines of text in the correct timing and order?

items:
metal bar - floor
door handle - floor
keys - down sofa

bools:
hasFoundKeys
hasFoundDoorHandle
hasFoundBar

dialog flow:
1. "Well I better get to work now."
2. "Oh damn, I can't find my keys." [when trying door]
3. "Ooh whats this" [said when keys found / other items found]
4. "Oh great, the door handle fell out again" [when trying door, but now have keys]
5. "You need that little metal bar thing before the handle works" [trying door before using metal bar on door]
6. "I cant turn that with my bare hands" [trying door without handle but with metal bar in door]

The text at the bottom would be the exact string I'd want to pop up, the timing for each one is described in the [] brackets.


texts:
i was wondering what are the best practices for restarting the game, say for example in a platformer game when you die the game restarts and you have to reposition all the characters or reset the traps or what have you.

I thought two ways for doing this:

1) You have some level or scene manager that has a reference to all the things that should react to a game state change ,for example when restarting level, you would tell every character to reposition itself or something like that.

2) You have events. Every character or entity will subscribe to this level manager to an event like "OnLevelRestart" using delegates or function pointers, then when the manager restarts the level, it would trigger the event and all the ones who have subscribed to that event, will be informed and reset their own state.

The first approach seems more flexible because i have a reference to those objects, and i can send other kind of messages to them. so if in the future i want to do something different with those objects i already have the ability to do so.
Now the second approach is...there, seems of course less flexible than the first option, but apart from that i don't have anything against it. The good thing is that the manager doesn't need to know all the objects that need to reset, so i can create new entities and register to those events ( and from this perspective, it seems flexible too).

Im concerned about the scalability and maintainability of those options in the future. Is there a "best practice" for doing this ? or is just "whatever fits yout project" ? Thanks.

My sincere apologies if this question doesn't meet the requirements to be asked on this site.


texts: Procedural Dungeon Generation Connect Rooms With Passageways

texts:
I've been working on a simple procedural generation class which currently places rooms on a x, y grid and selects a starting room. Each room needs to be connected with passageways so the player will be able to access them. The part that I am having issues with is how to actually connect the rooms.

There's a number of algorithms I've seen online, but I am unsure how to implement most of them.

As for my implementation of placing the rooms, the code tries placing them randomly on the grid until I get the desired density of rooms. After each room is placed, it is added to a list which stores the dimensions of the room. A room is them randomly selected to be the starting room.

Edit

Here's an example of the generated dungeons (the room with the "S" is the starting room):

Preferably, the rooms should be connected with their nearest neighbor. I'm not sure what the best way to go about this is.


texts:
I'm using GLEW 1.13.0, (GLUT), SDL2 and OpenGL 3.3 core.

#include <GL/glew.h>
#include <GL/glut.h>

int main(int argc, char* args[]){
  Engine::init(); // Initializes SDL_GL_* attributes

  glutInit(&argc, args); // Don't know if needed
  glewExperimental = GL_TRUE;
  glewInit();

  WINDOW["main"] = new Window("Test", {800, 600}, false, true);

  GLfloat vertices[] ={
    -0.5f, -0.5f, 0.0f,
    0.5f, -0.5f, 0.0f,
    0.0f, 0.5f, 0.0f
  };
  GLuint VBO[1];
  glGenBuffers(1, VBO); // Here my program crashes as glGenBuffers is NULL
  glBindBuffer(GL_ARRAY_BUFFER, VBO[0]);
  glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

  ...
}


texts: Map editor undo function - Not actually setting values to tiles

texts:
I'm currently attempting to implement an undo/redo function for my map editor for a tile-based 2D platformer game made with XNA. I've found a lot of resources online about this and decided to try to write my own code for it to gain a better understanding of how it works.

My issue is when I pass the my tile's information into a stored "Action" and change the data within the newly created Action, it does not actually change the data in my tiles.

Below is the Action struct and the UndoBuffer class where I modify the tile's data based on the stored actions that I created elsewhere:

public struct Action
{
    public object[] StoredItem { get; set; }
    public object[] ModifiedItem { get; set; }
}

public class UndoBuffer
{
    private readonly List<Action> _undoBuffer;
    private readonly List<Action> _redoBuffer;

    public UndoBuffer()
    {
        _undoBuffer = new List<Action>();
        _redoBuffer = new List<Action>();
    }

    public void StoreAction(object[] storedItem, object[] modifiedItem)
    {
        var action = new Action {StoredItem = storedItem, ModifiedItem = modifiedItem};

        _undoBuffer.Insert(0, action);
    }

    public void Undo()
    {
        if (_undoBuffer.Count == 0) return;

        _redoBuffer.Insert(0, new Action {ModifiedItem = _undoBuffer[0].ModifiedItem, StoredItem = _undoBuffer[0].StoredItem});

        for (int i = 0; i < _undoBuffer[0].StoredItem.Count(); i++)
        {
            Action tempAction = _undoBuffer[0];
            tempAction.ModifiedItem[i] = tempAction.StoredItem[i];
            _undoBuffer[0] = tempAction;
        }

        _undoBuffer.RemoveAt(0);
    }
}

Here's how I'm passing the data in to the class above:

private void ReplaceTile(Tile oldTile, TileInfo tileInfo, bool storeAction = true)
{
    int tileX = (int)oldTile.Position.X / Tile.Width, tileY = (int)oldTile.Position.Y / Tile.Height;
    if (tileX < 0 || tileY < 0 || tileY >= _tileData.Tiles.Count || tileX >= _tileData.Tiles[tileY].Count) return;

    var storedTiles = new ArrayList();
    var modifiedTiles = new ArrayList();

    if (storeAction)
        storedTiles.Add(_tileData.Tiles[tileY][tileX].TileInfo);

    _tileData.Tiles[tileY][tileX].TileInfo = tileInfo;

    if (storeAction)
    {
        modifiedTiles.Add(_tileData.Tiles[tileY][tileX].TileInfo);
        _undoBuffer.StoreAction(storedTiles.ToArray(), modifiedTiles.ToArray());
    }

    _saved = false;
}

And here is the actual Tile class and its TileInfo struct:

public struct TileInfo
{
    public string ViewName;
    public int Frame;
    public TileCollision Collision;
    public CollisionType CollisionType;
    public TileProperty TileProperty;
    public SpriteEffects Effects;
    public Color TileColor;
    public float Rotation;
    public float Layer;
}

[Serializable]
public class Tile
{
    public TileInfo TileInfo;
    public Vector2 Position;

    public const int Width = 8;
    public const int Height = 8;

    public static readonly Vector2 Size = new Vector2(Width, Height);

    public Tile CreateTile(TileInfo tileInfo, Vector2 position)
    {
        var tile = new Tile
        {
            TileInfo = tileInfo,
            Position = position
        };

        return tile;
    }
}

So essentially, I just need the UndoBuffer class to actually change the data within the TileInfo structs that are passed into it, and not change a boxed copy of them.