texts: How do I simulate the Doppler effect in a game?

texts:
I am trying to simulate the Doppler effect in a game (a car racing game). I am not using a specific sound library that simulates the effect; I only have a callback function where I mix the data.
I already figured out how to change frequency of a sample in the mixer function.
What I don't know is how much the frequency should change, depending on player and emitter position and velocity.
Here is what I have in the game:
//player
vec3 p.pos;
vec3 p.vel;

//emitter
vec3 e.pos;
vec3 e.vel;

According to Wikipedia, the relation between emitted frequency and observed frequency is given by:
 float f = (c + vr) / (c + vs) * fo

where c is a constant, the velocity of waves in the medium (typically a big number), and vs and vr are source and receiver velocities relative to medium.
So I guess:
float vr = p.vel.length; //player speed
float vs = e.vel.length; //emitter speed

However, I think this is wrong. It won't produce any change in frequency (for example) if vr = 0 (player doesn't move) and the emitter has constant speed, then vr and vs won't change (while they should).
Maybe should I calculate the velocity of the player relatively to the velocity of the emitter, like this?:
relative_speed = distance(p.pos + p.vel, e.pos + e.vel) -
distance(p.pos, e.pos);

Then how should vr and vs be found?

Wikipedia gives another formula to simulate the effect of a vehicle when that vehicle passes by the observer:
 vr = vs * cos(theta);

 //theta is angle between observer and emitter
 //theta = atan2(e.pos.y-p.pos.y, e.pos.x-p.pos.x);?

However, this formula supposes that the receiver doesn't move, which is not the case here. If the player and the emitter move at same speed (or with a small difference), there should be no Doppler effect. This function is also specific to one case, I suppose the final formula should be the same no mater the situation.

EDIT: I'm trying to find a correct formula, using SkimFlux's post:
vr,r = vr.vel * cos(shortest_angle_between ( vr.vel , vs.pos - vr.pos));
vs,r = vs.vel * cos(shortest_angle_between ( vs.vel , vr.pos - vs.pos));

//is there a easier/faster way to find them out?
//note: vr.vel and vs.vel are vectors, the green and red arrows in SkimFlux's picture.

EDIT 2:
For those interested, here is final formula:
vec2 dist = vs.pos - vr.pos;

vr,r = dotproduct(vr.vel, dist) / length(dist)
vs,r = dotproduct(vs.vel, dist) / length(dist)

It uses vector projection:

Then vr,s and vs,r should be injected into the first Wikipedia formula:

I tested it and it works successfully, providing great results.


texts: UE 4.25.3 - can't make layered animations to work

texts:
I want to make my character's upper body animations not connected to the lower body. For example, I have this set of animations:
Running
Jumping
Crouching
Kick
Sliding
Idle with sword
Sword attack
I need the idle with sword and sword attack animations override upperbody for every other animation, but the slide and kick. So, I want my character to hold his hand with the sword in front and do sword attack even while running and jumping.
I tried using layered animation like in every tutorial on Youtube. I created the upperbody slot, created a montage for my desired upperbody animation, added the Layered blend per bone node in the animBP and set the bone there, but it doesn't work. I don't know if I've missed something.


texts: Adding a time-delay without changing the function signature

texts:
I have written a simple generic implementation of the BFS algorithm, which I intend to use in several places in my Unity game. A simplified version of the class is:

class BFS {
     public abstract void OnNewNodeDiscovered(Node node);

     public void FindPath(Node start, Node end) {
         // Implementation of the algorithm.
         // Calls OnNewNodeDiscovered whenever a new node is discovered.
     }
}

I added the method OnNewNodeDiscovered so that users of this class can do custom actions, such as logging, changing the colors of things in the scene, etc., during the algorithm.

This works fine, but now I want to create a sub-class which also, in the function OnNewNodeDiscovered, adds a time-delay, so that the progress of the algorithm can be displayed to the player. The problem is that, the only way I know for adding a time delay in Unity is to convert the function to a coroutine, which returns IEnumerator, and then "yield return new WaitForSecods(delay)".  But this breaks my design of having a generic OnNewNodeDiscovered function.

My quesion is: is there an alternative way to add a time-delay inside a function that will be called from Unity? Can't I just say something like "sleep(duration)" to sleep for the specified duration and return later to the next statement point, without having to change the return type to IEnumerator?


texts: When is transform width in code not equal to the transform width in inspector?

texts:
I've come across a strange case in Unity's UI where the width of a RectTransform isn't the same as what is being reported. I have a transform which is 50 by 50 with no scaling, it is a root object of the canvas yet when I use the information that I get from the transform in code to draw from the bottom left edge of the transform to the top right it doesn't reach all the way!

Gizmos.color = Color.red;
Vector2 pos = new Vector2(transform.position.x, transform.position.y);
Gizmos.DrawLine(pos - transform.sizeDelta, pos + transform.sizeDelta);

Vector3[] corners = new Vector3[4];
transform.GetWorldCorners(corners);

Gizmos.color = Color.magenta;
Gizmos.DrawLine(corners[3], corners[0]);
Gizmos.DrawLine(corners[0], corners[1]);
Gizmos.DrawLine(corners[1], corners[2]);
Gizmos.DrawLine(corners[2], corners[3]);

The first section should draw a line from the bottom left to the top right according to what the transform reports are the width and height however they don't reach across the entire transform. Using GetWorldCorners the actual corners can be found and drawn around, with that data you can extract that the actual width is 60 (150.2 - 30.2 = 120 / 2 = 60)!

Why? Is this a bug or an I missing something obvious here?


texts: Multiple small UDP packets vs One big constant UPD packet

texts:
I'm making a MMO Bullet Hell game on Game Maker Studio 2 with a node.js server and I'm already able to receive and send information through UDP connections. I NEED to keep the server as fast as possible on the response to avoid lag to players since on this genre lag means death in most of the cases.
My main problem is: I need to get the ping/ms of the clients on the server and other informations (such as player data) from the client to the server. I'm currently dividing the two, so i send a "ping/pong" packet from the server to the client to get the ping/ms and every time something inside the player data is modified on the client it sends the information to the server on a JSON.
Now to the question: Should I put all the data on a big JSON and send to the server constantly or should i keep my current model and send a packet to get the ms and other packets to send and receive data?
Keep in mind that when my player is moving it'll send a bunch of data packets to the server whilst the ping function is running.


texts: Unity3D multiple objects user rectangle selection

texts:
I wish to allow the user to select multiple units by click and drag as most RTS do. The issue I have is that the tutorials are either in 2D or only use the transform.position such as this one.
Using the transform.position will work for most cases but will not allow the user to select easily as selecting the head or feet of a unit will not work in this instance. It also means I have to do an other script using raycasts for single click selections as it is almost impossible to get the single point of the transform.position with one click.
How can I do a proper rectangle selection for a 3D game? By looking at 3D RTS games I own, I noticed that they use a simplified hitbox (usually a cube or capsule).


texts: CCG Design - How to define text descriptions

texts:
I'm designing a CCG/TCG game (with the Kotlin language), and I am looking for advice regarding the text of the cards.

First of all, here is an example of one card, defined in XML:

  <card name="Sample Card"
        type="event"
        image="tex-event"
        metalCost="1"
        energyCost="1">
        <text>
            Whenever you destroy a creature, you will gain 3 energy.

            Your stronghold does not produce energy.
        </text>
        <traits>
            <trait name="ScavengeResOnDestroy" type="energy" amount="3"/>
            <trait name="ResFlux" target="self"/>
        </traits>
    </card>

ScavengeResOnDestroy, and ResFlux are direct mappings to class names.
Scavenge refers to the first line in the text, and ResFlux to the second.

Before I go on and design a whole lot of cards this way (then again maybe this issue would become a lot clearer AFTER I would design some more cards..) Should I attempt to tie/"hard"-code the text descriptions into the Trait-classes?

The thing is, I find it quite hard problem to "generate" the text for a Trait..
For example ScavengeResOnDestroy could have several targets:

Self (Whenever you destroy a creature...)
Opponent (Whenever an opponent destroys a creature...)
Both (Whenever a player destroys a creature...)

And to complicate things even further, I could very well see a possibility to modify ScavengeResOnDestroy, like so:

Whenever you destroy a creature you do not control..
Whenever an opponent destroys any creature..."

Now I haven't done much research on the topic yet... but I guess I'd need to build some kind of "sentence generator" (I don't know the correct term)?

Do you think I should stick with simply defining the text for each card, as in the example, or possibly, under the <trait>? And perhaps generate the text only for the simplest traits? Something else?


texts: How to allow free download of a paid game to specific users

texts:
if I am a game developer, how can I allow some selected users to download it for free? The options I am aware of are the following:

Use the built-in functionalities of play store and iTunes connect. This is not an option for me because they restricts the number of coupons I can create
Use some deep linking framework to unlock paid features for users coming from some specific link. This could be an options, but it can means the need of too many changes to my codebase

Are there any other options than these?

Thank you


texts: Problem importing Blender materials into Unity via FBX

texts:
I've created a simply low poly house in Blender (2.92) that I have imported into Unity as an FBX. Materials (simple colours) are all set up in Blender.
Initially this was all working fine. Colours all came across correctly (bit dark, but they always seem to do that), but now all of a sudden I am finding that in some cases the material for object A is applied to object B and the material for B applied to A, and so on. Most are fine, but not all (eg the window frames - meant to be white, are coming out dark wood, and the sills - meant to be dark wood, are coming out white.
The only thing that appears to have changed between working OK, and not working, is that I started to apply different colours to different faces of the walls for different rooms. However, the walls themselves are fine, all the right colours in the right places, it is just some other bits as above - and those bits were previously OK.
I've read there are issues in importing complex textures from Blender, but these are nothing complicated, just plain colours. Everything looks fine in Blender. What I do before creating the FBX is join most of the objects together in Blender with CTRL-J to minimise the number of objects going across, but again, this was all fine up to now.
I'd be grateful for any suggestions. I don't really want to have to reapply all material in Unity if I can avoid it.
UPDATE:
Having exported all the objects separately, the wrong ones actually have the wrong material assigned. For instance a window frame has material WindowSill assigned. It is the right colour for WindowSill - it just isn't meant to be that material at all, it is meant to be WindowFrame, and in Blender, that is what shows up as assigned.


texts: Tube model imported from Blender getting stretched vertically when rendering

texts:
I'm actually working on a 3D game engine with OpenGL 4 and C++. The problem is that, I don't know why, my geometry isn't well renderered except for primitives.

At the right you can see a cube, it is rendered as intended.
At the center you can see a mesh that I've made in blender, it is not rendered as intended, at the left you can see my mesh rendered as intended BUT I did tweak the Z-Scale (and I should not do that)

So to be short : My mesh are not rendered well proportionned.

I verified coordinates of each vertices in blender and my project : they're same.

I don't know if there is a problem with my matrices, the only thing I know is that problem appears only on the Z-Axis (Z is up).

Everything let me think that somewhere a number is rounded but I can't see where

I leave here some code, which might be helpful :

Mesh Rendering Code :

void RD_Mesh::render(RenderMode rndrMode) {
    if (rndrMode == RenderMode::Filled) {
        glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
    }
    else {
        glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
    }

    //m_shader->useShader();
    m_mat->BindMaterial();

    glm::mat4 mdl = glm::mat4(1.0f); //Declaring Model Matrix

    glm::mat4 translate = glm::mat4(1.0f);
    glm::mat4 scale = glm::mat4(1.0f);
    glm::mat4 rotation = glm::mat4(1.0f);

    //Position
    translate = glm::translate(translate, glm::vec3(m_position.getX(), m_position.getY(), m_position.getZ()));

    //Scale
    scale = glm::scale(scale, glm::vec3(m_scale.getX(), m_scale.getY(), m_scale.getZ()));

    //Rotation
    rotation = glm::rotate(rotation, glm::radians(m_rotation.getX()), glm::vec3(1.0f, 0.0f, 0.0f));
    rotation = glm::rotate(rotation, glm::radians(m_rotation.getY()), glm::vec3(0.0f, 1.0f, 0.0f));
    rotation = glm::rotate(rotation, glm::radians(m_rotation.getZ()), glm::vec3(0.0f, 0.0f, 1.0f));

    mdl = translate * rotation * scale;

    m_shader->SetMatrix("model", mdl);

    glBindVertexArray(VAO);
    glDrawElements(GL_TRIANGLES, RAWindices.size(), GL_UNSIGNED_INT, 0);
    glBindVertexArray(0);
}

Camera code :

void RD_Camera::SetupCamera() {
    projection = glm::perspective(glm::radians(FOV), (float)m_rndr->getWindowWidth() / m_rndr->getWindowHeigh(), m_near, m_far); //Projection matrix

    view = glm::lookAt(glm::vec3(m_pos.getX(), m_pos.getY(), m_pos.getZ()), glm::vec3(m_subject.getX(), m_subject.getY(), m_subject.getZ()), glm::vec3(0.0f, 0.0f, 1.0f)); //View matrix

    m_rndr->GetCurrentShader()->SetMatrix("projection", projection);
    m_rndr->GetCurrentShader()->SetMatrix("view", view);
    m_rndr->GetCurrentShader()->SetVec3("CamPos", m_pos);
}

My Vertex Shader:

#version 450 core

layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aNormal;

out vec3 Normal;
out vec3 FragPos;

uniform mat4 projection;
uniform mat4 view;
uniform mat4 model;

void main()
{
    gl_Position = projection * view * model * vec4(aPos, 1.0);

    Normal = normalize(mat3(transpose(inverse(model))) * aNormal);
    FragPos = vec3(model * vec4(aPos, 1.0));
}


texts:
Playing Game Dev Tycoon I noticed they rename all the console and company brands ever so slightly. Is something like this done in parody or to avoid copyright?

For example Nintendo is Ninvento and has the consoles name TES (Super TES, TES 64 etc.)

In many pokemon games (I know they are licensed by nintendo though) they make direct references to consoles.

My question is, can you make a game and directly reference Sony Playstation or SNES etc?


texts: SDL surface inside another GUI component?

texts: Is there a way to host an SDL surface inside another GUI component so that SDL is not at the top-level? For instance, could I put an SDL surface inside a Java JPanel or other widget?


texts:
I want to count the number of particles (yellow balls) that hit the cube. When a particle hits the cube object, it must disappear.

This script is attached to the particle system:

    int P_ball = 0;

    void OnParticleCollision(GameObject other) {
       if (other.CompareTag("cube"))
       {
           P_ball = P_ball + 1;
           Debug.Log("Particles : " + P_ball );
       }
}


texts:
Can a Component.gameObject be null in Unity? If it can what can cause it to be null?

The context for the question is a NullReferenceException I got from the users, which specifies only method, but not line in which it occurred.

So, I suspect that there may were conditions which cause Component.gameObject to be null.


texts: In unity's GameObject class, there are a few default data members. When we add a component to the game object, light for example, where exactly does it get added? Does it become a part of the GameObject class?


texts: Cocos2d sprite's parent not reflecting true scale value

texts:
I am encountering issues with determining a CCSprite's parent node's scale value.

In my game I have a class that extends CCLayer and scales itself based on game triggers. Certain child sprites of this CCLayer have mathematical calculations that become inaccurate once I scale the parent CCLayer. For instance, I have a tank sprite that needs to determine its firing point within the parent node.

Whenever I scale the layer and ask the layer for its scale values, they are accurate. However, when I poll the sprites contained within the layer for their parent's scale values, they always appear as one.

// From within the sprite
CCLOG(@"ChildSprite-> Parent's scale values are scaleX: %f, scaleY: %f",
      self.parent.scaleX, self.parent.scaleY); // Outputs 1.0,1.0

// From within the layer
CCLOG(@"Layer-> ScaleX : %f, ScaleY: %f , SCALE: %f",
      self.scaleX, self.scaleY,     self.scale); // Output is 0.80,0.80

Could anyone explain to me why this is the case? I don't understand why these values are different. Maybe I don't understand the inner design of Cocos2d fully. Any help is appreciated.


texts: Fitting 3D points representing bones to a BVH animation file

texts:
I am developing a motion capture animation system and I want my data to be stored within a BVH file. At the moment I have measured the size of the actor so I can create the hierarchy of the BVH file. I also have points in 3D representing the relative positions and orientations of the middle of certain bones such as the lower leg, foot e.t.c.

I was wondering what the best approach would be to map the bones into the BVH motion frames. I have to take into account slight inaccuracies in the 3D positions, for instance the foot might be plotted in 3D space 1cm off the actual location in the realworld.

Furthermore I was wondering how to recover lost 3D points. For instance if I have the left foot and left thigh, is it possible to recover the estimated position of the left shin?

Any help would be greatly appreciated.

Thanks


texts: The XNA redistributable isn't in the prerequisites list; how do I include it when publishing?

texts:
So I created a small project in XNA 4.0, and wanted to try and publish it, and so I did.
Yet when attempting to install it on a different computer it didn't seem to work.

I've read and studied about how the process of publishing works, and I saw someone in a different thread asking the same question as me, then I realized that
inside the prerequisites list which is in PROJECT -> PROPERTIES -> Publish,
the XNA redistributable wasn't there therefore it wasn't checked, and when attempting to install it on a different computer they needed to install redistributable on their own
to make it work.

Any idea why isn't the redistributable in the list? Maybe this isn't even
the problem and if that's case any ideas of what IS the problem? Thanks ahead.


texts: How can I achieve simulated fluid surface deformation in a bottle?

texts:
I'd like to mimic this effect seen in Half Life: Alyx:

I can't figure out what is going on here, people say "it is just a shader effect it isn't simulating anything", but I don't think that is true at all, it appears to be doing some sort of surface only fluid dynamics, but I'd have no idea what technique is actually used underneath.

My best guess is that

each object has a "origin" plane associated with each bottle that "exists" outside of the bottle and always fixed to some origin relative to the bottle
then waves ala gerstener waves are generated via movement somehow
the surface is raymarched only within bottle geometry
when below the surface additional ray marching is done for bubbles which are generated via potentially 4D noise, or a set number of bubbles are generated then rendered as round sprites or independently of noise
foam is generated based on a uniform value that is passed in that determines the "shakey" ness of the bottle, which makes values closer to the fluid surface more opaque and white.
fluid volumetric opacity doesn't necessarily have to be raymarched, but would likely be with the rest of this stuff being raymarched.  Using beers law to attenuate light based on distance and density through fluid.

But I'm really not understanding how the plausibly physically correct surface deformation is happening. How would I do something similar? I've seen some other posts that just have the surface wobble, but if you look in the video, it is more than just surface wobble, there is actual surface deformation.


texts: How can I improve performance when looping and comparing values on dictionaries?

texts:
On my quest to creating 0 garbage when procedurally generating points I've stumbled upon a performance issue when comparing values to another values stored inside Dictionaries.

Initially I used lists and arrays but I recently revisited the code in order to avoid any garbage generation. Also I decided to use Dictionaries instead of Arrays/Lists because it seems useful to access a certain Key in a Dictionary.

I use Dictionaries in the following way:

Each key is a mesh in my game
Each value is an array of vertices or triangles
Every array contains hundreds of vertices or triangles

Dictionary<int, Vector3[]> exampleVerticesDictionary;
Dictionary<int, int[]> exampleTrianglesDictionary;

My procedural system does the following:

1. Takes an initial random value (int or float).
2. Loops through all the items in the arrays of the 1st Dictionary.
3. If the value matches any value on any of the arrays, continue on the next loop.*
4. Loops through all the items in the arrays of the 2nd Dictionary.
5. If the initial value matches again, continue on next loop.
6. Loops through all the items in the arrays of the 3rd Dictionary.
7. If the initial value matches again, create a 3D point.

I access and compare items in Dictionaries in the following way:

if (exampleVerticesDictionary[key][index] == 1)

The problem: It causes noticeable performance spikes. The profiler indicates it's caused by the numerous calls (tens of thousands) to these methods:

  Dictionary.get_Item()
      GenericEqualityComparer.Equals()
          Int32.Equals()
      GenericEqualityComparer.Equals()
          Int32.GetHashCode()

The questions:

Why does the performance drop so much when using Dictionaries to make those comparisons?
Am I just better off using Arrays of Arrays instead of Dictionaries of Arrays?
Should I be using other way of accessing and comparing items in Dictionaries?

Thanks in advance! Coding is not my strong suit and I'm kinda lost with this issue...


texts:
I'm using java and I do pixel-by-pixel rendering (a pixel array from an ARGB BufferedImage). So a color is 0xAARRGGBB. Now how can I render a transparent color? I guess that I should manipulate the existing pixel and not overwrite it. I can make color addition simply:

public static int additiveColor(int c1, int c2) {
        int red = (c1 & 0x00ff0000) + (c2 & 0x00ff0000);
        int grn = (c1 & 0x0000ff00) + (c2 & 0x0000ff00);
        int blu = (c1 & 0x000000ff) + (c2 & 0x000000ff);
        return 0xff000000 + (red > 0x00ff0000 ? 0x00ff0000 : red) + (grn > 0x0000ff00 ? 0x0000ff00 : grn) + (blu > 0x000000ff ? 0x000000ff : blu);
    }

So to set a pixel to a sum of two colors I just do this:

pixels[i] = additiveColor(c1, c2);

How can I do transparency?


texts: When is Micromanagment in games considered fun/boring?

texts:
Some players (typically the developer types, but not exclusively) love to control intricate aspects of a game (typically a simulation game) such as how long traffic lights take, how much to tax certain citizens (in sim city style games) when to change gear (in a racing game) exactly what an AI should do etc...

But how far should a developer go to implement micromanagement, when does it stop becoming fun? It would be rather tedious to connect each building to the water, and electrical grid for example in sim city. Whereas issuing city ordinances is considered engaging to the player.


texts:
I want to implement a mipmap filter in my 3D game, so that textures which are located far away are using a lower resolution than the original.
For the shader I'm using hlsl version 4_0_level_9_1 or 4_0 depends on which one I will get this running.
I have tried this:

texture Texture;
sampler diffuseSampler = sampler_state
{
    Texture = (Texture);
    MAGFILTER = ANISOTROPIC;
    MINFILTER = ANISOTROPIC;
    MIPFILTER = ANISOTROPIC;
    AddressU = Wrap;
    AddressV = Wrap;
};
[...]
Color PixelShaderFunctionTex(VertexShaderOutputTex input)
{
    return tex2Dlod(diffuseSampler, float4(input.TexCoord, 0.0, 0.0));
}

in vs_4_0 it still uses the full-res texture.
And in vs_4_0_level_9_1 it won't even compile: "texlod not supported on this target"

I could manually generate the downscaled textures, but there must be a way to only input one texture and let hlsl do the rest.

In short:
How to apply the mipmap filter in hlsl?


texts: Is there a way where I can make the script restore its condition to that before I hit play? Should I create a new copy of the original script every time instead?


texts: When the player collides with an entity, the player can no longer move

texts:
Here is my collision code, any ideas on how I can improve it to fix the problem?

    public void collide(Entity entity){
    if(x + width >= entity.x && x <= entity.x + entity.width && y + height >= entity.y && y <= entity.y + entity.height){
        setShouldCollide(true);
    }else{
        setShouldCollide(false);
    }
}


texts: Google turn based multiplayer automatch criteria

texts:
I've set up a multiplayer game using Google's turn-based API.  I now want to put some qualifiers on auto-matching and am racking my brain on how to solve this issue...

I'm using GetVariant() to distinguish between the Lite and Pro versions of my game.  That's easy enough.  Other than that I want to have several parameters that can be varied.  As a restricted example, let's say there are three difficulty levels and two types of game.  I want the players to be able to either specify which they want or to leave the option completely open (and before it's pointed out, I realise that the more specific the qualifiers, the longer it might take to get a match).

It seems that setting the exclusiveBitMask in the createAutoMatchCriteria function call could be the solution (and, indeed, I can't see anything else at all that might be useful in this task).

I thought that the game type could be specified in the lower two bits and the difficulty level could be specified using the next three bits.  Essentially, the bit mask would mask out the difficulty levels and game types that the player isn't interested in.  So, looking at the lower 5 bits of exclusiveBitMask we would have

011 10 - difficulty 3, game type 1
101 10 - difficulty 2, game type 1
110 01 - difficulty 1, game type 2

And the difficulty level (for example) could be left open by not masking any of the difficulty bits

000 10 - any difficulty level, game type 1

This works fine (in theory) so long as one player specifies the type of game he wants and the other players all leave their options open.  It's likely that most players will select "quick match" which defaults the settings to "any" so that might not be such a problem.  (If two players specify the same difficulty, for example, the exclusive bits will prevent a match.  If two players specify differing game types, they will actually be given a match, but that can be overcome by using three bits to specify the game type).

But this system would require every player to join the match before it can actually commence which isn't ideal.  It could be that one player has specified the type of game he wants, one player has specified the difficulty level he wants and three players have left all options open.  We can't initialise the game until we have all players ready and know what choices each of them has made.

So this brings me to the crux of the problem.  Without each player taking an empty turn to pass their information on to the next, how can I determine what exlusiveBitMask each has used?  I was hoping that exclusiveBitMask might be modified by a logical OR operation after each player joins and that this would be available via getAutoMatchCriteria but this isn't the case.

So, the questions I have...

1) This method isn't nice but it's the only one that seems remotely viable for specifying game types (and being able to leave some options open in the specification).  Is there a nicer, cleaner method available?

2) If no other method is available, are there any suggestions as to how to overcome the caveats and identify each player's specification without every player having to run an empty turn at the beginning of a game to pass the information on?


texts:
I'm working on a Unity project, and what I'm doing is creating a new scene. In my new scene, I want add some prefabs that there aren't in the project folders, but I can see them in another scene.

So in my new scene I have only few prefabs, and I don't know how to add the prefabs that are present in the other scenes. Is there a way to do it?


texts: translation and rotating at the same time and waiting before animation?

texts:
I am having difficulties here. I want to move my character with the buttons and I want the character to rotate wherever he is going.

Also I want to play an animation when there is no keys pressed. I am able to do that but I want the animation to play after 10 seconds of no key being pressed, and only once. Than after a movement that resets and again after 10 seconds of no key the animation plays. (The animation works but it happens right after I stop pressing a key and continuously.)

IEnumerator Test()
{
    yield return new WaitForSeconds(10.0f);
}

void Update()
{
    if (Input.GetKey(KeyCode.W))
    {
        counter += Time.deltaTime;
        transform.Translate((Vector3.forward) * moveSpeed * Time.deltaTime);
        Debug.Log("Pressing W key");
    }
    if (Input.GetKey(KeyCode.S))
    {
        counter += Time.deltaTime;
        transform.Translate((Vector3.back) * moveSpeed * Time.deltaTime);
        Debug.Log("Pressing s key");
    }
    if (Input.GetKey(KeyCode.A))
    {
        counter += Time.deltaTime;
        transform.Rotate(Vector3.down * rotateSpeed);
        Debug.Log("Pressing a key");
    }
    if (Input.GetKey(KeyCode.D))
    {
        counter += Time.deltaTime;
        transform.Rotate(Vector3.up * rotateSpeed);
        Debug.Log("pressed D");
    }
    if (!Input.GetMouseButton(1))
    {
        moveSpeed = 20;
    }

    if (!Input.anyKey)
    {
        if (counter >= 2)
        {
            StartCoroutine(Test());
            anim.Play("Animation");
            counter = 0;
            Debug.Log("A key or mouse click has been detected");
        }
    }
}


texts: Why are my Mecanim animation curves not staying within the entered range?

texts:
I have an in-place animation that I added curves to (In the rigged FBX which has the animation). I created 2 float parameters in the relevant controller with the same names as the curves in the animation clip.

Now, when I get the value of the float using animator.GetFloat(), the values I get are not in the value range I entered in the curves. My range is between 0.0f and 4.0f but what I get is approximately -0.6f to 0.03f. Why is this? From what I could gather from other threads, there is some blending going on with some other curves. What is this blending? And if there is some blending happening, how can I remove that?

I'm using Unity 5.1.1.


texts: What is the cost of distributing through steam?

texts:
We are in Pre-alpha stage of a game development project and haven´t yet got reply from Valve about how it works to distribute through Steam. We need this information to do a business model with all the different costs of developing and distributing this game.

So my question is, what is the pricing structure? Do they take a per cent of our sale? If so, how much?

Thanks Felix


texts: Soccer Game only with National Team names (country names) what about player names?

texts:
Ok...this question hasn't been asked before, its very similar to some, but here's the difference:

I am making a soccer/football simulator game, that only has national teams (with no official logos) just the country names and flags.
Now, my doubt is the following...can I use real player names (that play or played on that national team?)

From what I understand if I use a player name linked to a club like Barcelona FC (not a national team) I need the right from the club and the association that club is linked to, right?
But If I am only linking the name just to a country...I might just need the permission of the actual player (that I am using his name) and not any other associations, correct?

Thanks a lot in advance!
Cheers,
Diego.


texts: How to correctly enable anti aliasing in XNA?

texts:
In my project when I add graphics.PreferMultiSampling = true; this line in the Game1 Constructor (as the msdn website suggests), anti aliasing does not enable. Any idea what I might be missing ? Here is the full code:

public Game1() : base()
{
    graphics = new GraphicsDeviceManager(this);
    graphics.PreferredBackBufferWidth = 720;  // game's width
    graphics.PreferredBackBufferHeight = 720; // game's height
    graphics.PreferMultiSampling = true;
    Content.RootDirectory = "Content";
}

protected override void LoadContent()
{
    spriteBatch = new SpriteBatch(GraphicsDevice);
    LightningSegment = Content.Load<Texture2D>("Lightning Segment");
}

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

    Matrix skew = Matrix.Identity;
    skew.M12 = (float)Math.Tan((double)Math.PI / 6);
    spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, skew *
         Matrix.CreateScale(1.5f, 3f, 1));
    spriteBatch.Draw(LightningSegment, new Vector2(200, 200), null, Color.Red, 0,
         new Vector2(0f, 300f / 2f), new Vector2(250f, 1f), SpriteEffects.None, 0f);
    spriteBatch.End();

    base.Draw(gameTime);
}


texts: Game Asset Storage: Archive vs Individual files

texts:
As I am in the process of creating a 3D c++ game and I was wondering what would be more beneficial when dealing with game assets with regards to storage. I have seen some games have a single asset file compressed with everything in it and other with lots of little compressed files.

If I had lots of individual files I would not need to load a large file at once and use up memory but the code would have to go about file seeking when the level loads to find all the correct files needed.

There is no file seeking needed when dealing with one large file, but again, what about all the assets not currently needed that would get loaded with the one file?

I could also have an asset file for each level, but then how do I deal with shared assets

This has been bothering me for a while so tell me what other advantages and disadvantages are there to either way of doing things.


texts: My rigid body controller stuck in middle of screen (unity)

texts:
Still working on my Star Fox clone and am changing up the camera a bit.

The problem I keep having is my Ship gets locked in the middle of the screen and can't move while its parent (spinMe) is still moving.

I'm working with rigidbody-ception here I have a rigidbody with in a rigidbody. Both of them move up, down, left, and right.These two are called spinMe and Ship.

In this version  the player is able to move until they reach the end of the screen.

What I'd like to do is have the camera move slightly as well to help Ship cover more of a bases and help with perception. Star Fox did this as well.

So spinMe pulls Ship around with it but for some reason that keeps Ship from moving independently while being moved around by spinMe. Only when spinMe can't move any further Ship will move.

So I guess I would like to know is why can't I get my Ship to move at the same time as spinMe.

So this is the main chunk of the code for spinMe

    Vector3 movementy = transform.TransformDirection(Vector3.up * Input.GetAxis("Vertical") * turnSpeed);
    Vector3 newPos = transform.position + movementy;
    Vector3 offset = newPos - Midpoint.position;
    transform.position = Midpoint.position + Vector3.ClampMagnitude(offset, radius);

    Vector3 movementx = transform.TransformDirection(Vector3.right * Input.GetAxis("Horizontal") * turnSpeed);
    Vector3 newPosx = transform.position + movementx;
    Vector3 offsetx = newPosx - Midpoint.position;
    transform.position = Midpoint.position + Vector3.ClampMagnitude(offsetx, radius);

And this is the movement for Ship

Vector3 pos = Camera.main.WorldToViewportPoint(transform.position);
    pos.x = Mathf.Clamp01(pos.x);
    pos.y = Mathf.Clamp01(pos.y);
    transform.position = Camera.main.ViewportToWorldPoint(pos);
   Vector3 moveDirection = new Vector3(turnSpeed * Input.GetAxis("Horizontal"),
                                       turnSpeed * Input.GetAxis("Vertical"), 0);
   moveDirection = transform.TransformDirection(moveDirection);
   rb.MovePosition(transform.position + moveDirection);

I've tried this a variety of different ways and I believe this is my best chance of getting this working.


texts:
I'm getting the most horrible glitches on multiple materials and objects. In the Unity Editor everything is fine. When building individual scenes alone it is fine. But when I build all the scenes including main menu, things like this happen.
I have no idea what I should do in terms of diagnosis since it's fine when building the scene by itself. I've had similar, seemingly undiagnosifiable, encounters with unity builds.


texts: How can I guarantee a solvable Fifteen Puzzle shuffle?

texts:
I am making a 15 Puzzle game in C# that allows the user to enter a custom row and column value up to a maximum of a 10 x 10 puzzle. I am having problems with the shuffle method.

I want to make it so the puzzle is always solvable by first creating a winning puzzle then shuffling the empty space. The problem is it is too inefficient to call every click event each time. I need a way to invoke the click event of a button adjacent to the empty space but not diagonal. I also use an invisible static button for the empty spot. The PuzzlePiece class inherits from Button. I am not too sure how to do this.

Here is what I have:

private void shuffleBoard()
    {
        //5 is just for test purposes
        for (int i = 0; i < 5; i++)
        {
            foreach (Control item in this.Controls)
            {
                if (item is PuzzlePiece)
                {
                    ((PuzzlePiece)item).PerformClick();
                }
            }
        }
    }

 void PuzzlePiece_Click(object sender, EventArgs e)
    {
        PuzzlePiece piece = (PuzzlePiece)sender;

        if (piece.Right == puzzleForm.emptyPiece.Left && piece.Top == puzzleForm.emptyPiece.Top)
        {
            movePiece(piece);
        }
        else if (piece.Left == puzzleForm.emptyPiece.Right && piece.Top == puzzleForm.emptyPiece.Top)
        {
            movePiece(piece);
        }
        else if (piece.Top == puzzleForm.emptyPiece.Bottom && piece.Left == puzzleForm.emptyPiece.Left)
        {
            movePiece(piece);
        }
        else if (piece.Bottom == puzzleForm.emptyPiece.Top && piece.Left == puzzleForm.emptyPiece.Left)
        {
            movePiece(piece);
        }
    }


texts: How to give the player the feeling of being chased by enemies and force him/her to rush

texts:
I have already asked a question about the difficulty progression in my endless runner game: How to make difficulty progression in my endless-runner game?

Now I have to decided that it is a good approach to make the following:

Camera is always drifting up, slowly, but preventing the player from idling.
If squirrels jump, the camera follows them and the spiders also update their position to be slightly below visible area. Their speed is a little bit faster than the camera's drifting speed, so the player will panic out of the fear of the spiders catching them.
Something else?

I want to make feel of constant chase by spiders and force player to run, make quick decisions and make mistakes. Player need to know exactly how close the spiders to squirrels are.

P.S: You can see earlier version of this game here: http://ludumdare.com/compo/ludum-dare-34/?action=preview&uid=66055

EDIT: The problem is that spiders are always relatively close to player and distance between them and the spiders matters. Once spiders have left the visible area, player feels safe. Firstly, spiders run with constant speed and if the player runs a little bit faster, he is always in the safe area and doesn't see any spiders.

The idea is to have player under pressure all time. The difficulty is that the visible area between the spiders and squirrels is small

FINAL DECISION: The final decision was made because of majority votes, and I suppose this answer suits for many games. But there is more than one good answer, and most of the answers are worth reading and implementing. That is what I am going to do.

Thanks everyone for your great answers!

FINAL NOTE: you can check final implementation finding released game on market - https://play.google.com/store/apps/details?id=by.Ludum.Vaverki


texts: How can I get all components of a type from a List with mixed components?

texts:
I have a list of GameObjects.  Half of these GameObjects have Component1, and the other half have Component2.  I want to get all of Component1 from the list.

So an example of my list:

var list = new List<GameObject>();
for (int i = 0; i < 10; i++)
{
    list.Add(new GameObject());
}
foreach(var go in list)
{
    if(UnityEngine.Random.Range(0.0f, 1.0f) < 0.5f)
    {
        go.AddComponent<Component1>();
    }
    else
    {
        go.AddComponent<Component2>();
    }
}

I can get all of Component2 by using LINQ as such:

var components1 = list.Where(g => g.GetComponent<Component1>()).Select(r => r.GetComponent<Component1>()).ToList();

But that is very dirty and seems repetitive.  Is there a better way to do this?


texts: How do you blend multiple colors in HSV (polar) color-space?

texts:
In RGB color space, you can do a weighted multiple-color blend by just doing:

Start with R = G = B = 0. Then we perform a blend at index i using a set of colors C, and a set of normalized weights w like so:

R += w[i] * C[i].r
G += w[i] * C[i].g
B += w[i] * C[i].b

But I'd like to interpolate the colors in the HSV color-space instead, so that saturation and brightness are uniform across the interpolation. I know I can blend saturation and brightness in the same way as above, but the HUE component is an angle around a continuous circle, since HSV is essentially a polar coordinate system.

Blending only two HSV colors makes sense to me, you just find the shortest arc around the circle and interpolate between the two hues. But when you attempt to blend more than 2 colors, it becomes a bit of a puzzle.

You have to handle anomalous cases, like 4 equally-weighted colors with a hue at 0, 90, 180, and 270 degrees. They basically cancel each other out, so any hue will do.

Any ideas would be greatly appreciated.


texts: Should a socket server and game server be separate processes?

texts:
Assume a simple standard client/server game.  For the server, is it worthwhile to have a separate process that listens for connections and messages from clients and sends the data via local sockets or stdin to another process that runs the actual game server?

The other option would be to have both things be done in a single process. Queueing incoming messages and executing them in the right order there shouldn't be a halting issue.

I am wondering if the extra resources to separate the two "activities" is actually worth it. How should I decide? I'd like to hear any pros/cons.


texts:
I have an enemy game object and an item game object.

Enemies have an ItemDrops script attached.
Items have a DisplayItemLabel script attached.

Attached to each enemy:

public class ItemDrops : MonoBehaviour
{
    public Transform itemPrefab;
    private EnemyHealth enemyHealth;

    private float originToGroundDistance;
    private Vector3 offset;

    private bool itemDropped;
    private bool numberGenerated;
    private float randomNumber;

    private ItemData itemData;
    public string nameOfDroppedItem;

    void Start()
    {
        enemyHealth = GetComponent<EnemyHealth>();

        itemData = GameObject.Find("Item Manager").GetComponent<ItemData>();
    }

    void Update()
    {
        //Initialized in Update instead of Start because enemy floats to 1.083333 on the Y-axis after some time after Start
        originToGroundDistance = transform.position.y - 0.25f;
        offset = new Vector3(0f, originToGroundDistance, 0f);

        if (enemyHealth.isDead && !itemDropped)
        {
            if (!numberGenerated)
            {
                RandomNumberGenerator();

                //Debug.Log(randomNumber);

                if (randomNumber < 1)
                {
                    SpawnItem(itemData.coin);
                }
            }
        }
    }

    private void RandomNumberGenerator()
    {
        numberGenerated = true;

        randomNumber = Random.value;
    }

    private void SpawnItem(Item item)
    {
        itemDropped = true;
        nameOfDroppedItem = item.itemName;

        Instantiate(itemPrefab, transform.position - offset, Quaternion.identity);
    }
}

Attached to each item:

public class DisplayItemLabel : MonoBehaviour
{
    private GameObject itemLabel;
    private Text itemNameText;

    void Start()
    {

        itemLabel = transform.Find("Canvas/Item Label").gameObject;
        itemNameText = itemLabel.GetComponentInChildren<Text>();

        itemNameText.text = "Item Name";

        itemLabel.SetActive(false);
    }

    void Update()
    {
        ClampLabelToItem();
    }

    private void ClampLabelToItem()
    {
        Vector3 offset = new Vector3(0f, 16f, 0f);

        Vector3 desiredPosition = Camera.main.WorldToScreenPoint(transform.position) + offset;
        itemLabel.transform.position = desiredPosition;

        itemLabel.SetActive(true);
    }
}

Item is not a child of enemy for multiple reasons I can think of. One is that enemies are destroyed when they are killed. With that said, how do I get the item to know who dropped it or get the enemy to know which item it dropped?
MY GOAL is to get itemNameText.text = "Item Name"; to say something like itemNameText.text = itemDrops.NameOfDroppedItem; but I can't use GameObject.FindGameObjectWithTag("Enemy").GetComponent<ItemDrops>(); because it won't always grab the correct enemy and thus the correct ItemDrops script.
I also can't set DisplayItemLabel.itemNameText.text = nameOfDroppedItem in the SpawnItem function because it wouldn't know which item's DisplayItemLabel script to get.

So clearly, I'm having issues with references. What should I do?


texts: Make transform.up face toward velocity while preventing transform.forward from rolling?

texts:
I have been working on a personal project that is suppose to mimic Anthem. I am using a state machine for the character controller that I intend to integrate with the Unity's Animation state machine.
I am calculating a new velocity that makes the player follow the mouse when flying, and I am making transform.up = Velocity so that the player appears to be going head first towards its velocity.
The issue is that when you start to rotate in a circular way on the xz plane, the player will start to roll and its transform.forward moves from facing towards the ground (which is what I want) to facing the sky.

The core code is in public override Update():
public class s_MechFlyt : MechStates{

  float flySpeedPercentage;

  public s_MechFlyt(in MechController Master) : base(Master){
    flySpeedPercentage = 2.5f;
  }

  public override void Update(){
    if (_Master.SprintButtonHeld){

      Quaternion Rot = Quaternion.Euler(-_Master.DMouse.y , _Master.DMouse.x , 0);

      _Master.Velocity = Rot * Vector3.forward * _Master.Stats.Speed * flySpeedPercentage;
      Vector3 Rotation = _Master.Velocity;**
      //Rotation.y = Mathf.Clamp(Rotation.z, 0, 50);
      _Master.transform.up = Vector3.Normalize(Rotation);
      //_Master.transform.rotation = Rot;

      //_Master.transform.rotation = Quaternion.RotateTowards(_Master.transform.up, _Master.Velocity, 5);

      _Master._Controller.Move(_Master.Velocity * Time.deltaTime);

      if (_Master.JumpButtonHeld){
        _Master.ChangeStates("hover");
        _Master.transform.up = Vector3.up;
      }

    }
    else{
      _Master.ChangeStates("fall");
      _Master.transform.up = Vector3.up;
    }
  }

  public override void EnterState(){
    _Master.CamController.ChangeStates("flying");
  }
}


texts: Simulation of supersonic, hypersonic flight with user defined surfaces

texts:
I want to create a small rocket-launching game, inspired by Kerbal Space Program.

Since there's nothing in orbital mechanics, that I still don't know. I decided to make this as close to reality as possible. The only moment I needed to discover is how to implement aerodynamics.

Well, this became a very problematic, since I discovered the way the fluid is simulated. My first idea was to implement small virtual aerotube, which collects data from solid object and calculates it aerodynamical properties, in dependency of its form. I want to collect this data as a part of build rocket process.

This is hard-but-possible-to-implement part, since there are lot of information of how to make incompressive fluid solvers. But rockets fly at supersonic and hypersonic speeds, so I need to discover how to calculate this forces in apropriate conditions. But, I can see, that implementing incompressive flows is a kind of almost-impossible-to-solve-problem.

So, I decided to ask a very generous question. How did those guys implemented aerodynamics in Kerbal Space Program game? And how usually people modelling it when things are getting little further than "basic understanding".

For me sub-sonic aerodynamics (in games) now seems almost clear. But trans-sonic, supersonic and hypersonic, seems like "Have no idea what to do".


texts: How to deal with events in a game with multiple players, in Unity?

texts:
As I'm developing our game I have asked myself a couple times "When we have more than 1 player, how will I ensure events from player A do not crossover to player B?"

As an example, lets say player A clicks on a unit. This publishes an event with data on the click location, the type of object it is, and the player that clicked. This can be received by lets say a selection manager script that just keeps track of what is currently selected for that player.

The problem now, is that this event is received by every player. Every player will receive this event and try and select that object, and perform various tasks along the way.

Is there a method of programming in unity to ensure that an event is only subscribed to by classes that have the same player component referenced (only the appropriate players methods will be added to the invocation list of delegates under the player)? Or will I just need to create a check at the subscribers to these events to only accept the event data if it's the same player?

ie.

if ( RClickEventArgs.Player.GetInstanceID() == player.GetInstanceID()) {}

Edit: For clarity. Here is an example event.

public delegate void RightClickHandler(string clickType, RClickEventArgs e);
public static event RightClickHandler RightClickEvent;
private void RightClick()
{
    if(Input.GetMouseButtonDown(1))
    {
        if (userInput.isMouseOnScreen && !EventSystem.current.IsPointerOverGameObject())
        {
            GameObject hitObject = inputValidations.FindHitObject();
            Vector3 hitPoint = inputValidations.FindHitPoint();
            hitPoint.z = -1;

            if (hitObject && hitPoint != ResourceManager.InvalidPosition && hitObject.name != "Ground")
            {
                RightClickEvent("Object", new RClickEventArgs(hitObject, hitPoint, player));
            }
            else if (hitObject.name == "Ground")
            {
                RightClickEvent("Ground", new RClickEventArgs(hitPoint, player));
            }
        }
    }
}

When an object is clicked an event is published with relevant info on what was clicked. There are subscribers to this event using "MouseClickEvents += YourMethodNameHere;". This works as intended. However, since two players will have the same scripts as components this creates an issue where the 2nd player's scripts also add themselves to the invocation list of player 1's delegates, and vice versa (as far as I know, I don't know how to check what is in the invocation lists). So each player receives their own events, and the events of the other player.

If I have a fundamental misunderstanding of a concept here, please let me know.


texts: In unity, making a navmesh for a tiny planet?

texts:
I'm trying to build a scene in a small planet, and baking will always give me the result on the half top of the planet. But what I want is to create a navmesh all around the small planet.

I am wondering if there is a way to convert a mesh that I well built in blender, to be a navmesh in Unity. That means using the mesh totally without baking. Or, if there is some other ways to create navmesh for my poor planet.


texts: How can I create a 2D camera with upscaling and translation?

texts:
I've computed a Viewport that is fair in size (a proper aspect ratio to the given device) and then I calculate my ScaleMatrix like so:

  scaleMatrix = Matrix.CreateScale(
        (float) GraphicsDevice.Viewport.Width/virtualWidth,
        (float) GraphicsDevice.Viewport.Width/virtualWidth,
        1f);

That by itself, works great. The game scales and everything works fine. However, I'm not trying to add translation to track my character and some things are going a bit wonky.

I'm trying to construct my full transform like so:

   _transform =
                Matrix.CreateTranslation(new Vector3(-pos.X, -pos.Y, 0))*scale
                * Matrix.CreateTranslation(new Vector3(_viewPortWidth * 0.5f, _viewPortHeight * 0.5f, 0));

Am I doing something wrong? The results are not what I expected; the position is the position of the character. Before i added the scaling code, something like this worked for translation.

Here's an image to demonstrate what I want, sorry for the excessive size:
=

Here's a screenshot of what I currently get:

I'm looking to find a way to achieve the first result with automatic scaling to the maximum viewport size.


texts: How do I stop my skeleton from playing the walking animation?

texts:
I'm trying to get a Skeleton Model to go from its walking animation to its idle animation using a bool that checks for input. Currently, in-game, the skeleton doesn't leave its walking animation and stays in it even when not walking.
Here is the code I'm using:
public class SkeletonMove : MonoBehaviour
{
    private float velocity = 5f;
    public bool _isWalking = false;
    Vector2 input;

    void Update()
    {
        GetInput();

        if (Mathf.Abs(input.x) < 1 && Mathf.Abs(input.y) < 1)
            return;

        Rotate();
        Move();
    }

    void GetInput()
    {
        input.x = Input.GetAxisRaw("Horizontal");
        input.y = Input.GetAxisRaw("Vertical");
    }

    void Move()
    {
        _controller.Move(transform.forward * velocity * Time.deltaTime);
        _anim.SetBool("Walking", _isWalking);

        if (input.x != 0 || input.y != 0)
            _isWalking = true;

        if (input.x == 0 && input.y == 0)
            _isWalking = false;
    }


texts:
I have a bit of a dilemma ...
So i setup my scene how I want it with some bits in it and now I want to move all my camera related code in to a camera class however doing so is proving to be a pain in my ass.

So in my game code (my main game class) I have ...

    protected override void Initialize()
    {
        model = new TerrainModel();
        base.Initialize();

        // Load known core components
        camera = new Camera(this, cameraPosition, new Vector3(10, 10, 10));
    }

Then in update ...

    protected override void Update(GameTime gameTime)
    {
        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            this.Exit();

        camera.Update();

        base.Update(gameTime);
    }

Then in draw ...

    protected override void Draw(GameTime gameTime)
    {
        cubeEffect.View = Matrix.CreateLookAt(cameraPosition, new Vector3(10, 10, 10), Vector3.Up);
        cubeEffect.View = camera.View;

        cubeEffect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspectRatio, 1.0f, 1000.0f);
        cubeEffect.Projection = camera.Projection;
    }

It's these draw lines that have me confused.
If i use the first pair (the lines that create the matrices there and then) it all works.

If I use the second pair (pulling the same thing from my camera class) it doesn't and i get a blank screen.

I'm only rendering a single model so there's a chance it could be pointing in the wrong direction but it seems to have done what i expect when i put breakpoints in and look at the variables.

So what have i done wrong?

Here's my camera class ...

public class Camera
{
    #region fields

    Matrix viewMatrix;
    Matrix projectionMatrix;
    Viewport viewPort;
    BoundingFrustum cameraViewableBounds;
    Vector3 currentTarget;
    Vector3 cameraPosition;

    #endregion

    #region Properties

    public Matrix Projection { get { return projectionMatrix; } }
    public Matrix View { get { return viewMatrix; } }
    public Viewport ViewPort { get { return viewPort; } }

    public Vector3 Position
    {
        get { return cameraPosition; }
        set
        {
            cameraPosition = value;
            Update();
        }
    }

    public Vector3 TargetPosition { get { return currentTarget; } }

    public bool CanSee(BoundingBox ObjectBounds)
    {
        if (cameraViewableBounds.Contains(ObjectBounds) != ContainmentType.Disjoint)
            return true;

        return false;
    }

    #endregion

    public Camera(Game game, Vector3 startingPosition, Vector3 startingTarget)
    {
        cameraPosition = startingPosition;

        // creates a new view matrix
        LookAt(startingTarget);

        viewPort = game.GraphicsDevice.Viewport;

        // Set the Projection matrix which defines how we see the scene (Field of view)
        projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, 0, 1, 10000);
    }

    #region Camera state updating

    public void Update()
    {
        viewMatrix = Matrix.CreateLookAt(cameraPosition, TargetPosition, Vector3.Up);
        cameraViewableBounds = new BoundingFrustum(viewMatrix * projectionMatrix);
    }

    public void LookAt(Vector3 target)
    {
        currentTarget = target;
        viewMatrix = Matrix.CreateLookAt(Position, TargetPosition, Vector3.Up);
    }

    #endregion
}

}

I'm sure this is something crazy simple that i've missed ... i just can't see it.

NOTE:
I have omitted a lot of code here to try and simplify my question but I'm pretty sure the rest of my code is fine because it works unless I use this new camera class, however I can provide more if its needed.


texts: Referencing multiple canvas images through script in C#

texts:
What is the best way to reference multiple Canvas Images within C# script attached to my player in Unity?

Currently I have something similar too:

public Image image;

//Finds the Image Object being referenced.
image = GameObject.Find ("Canvas/Image").GetComponent<Image> ();


texts: Better way to do AI Behavior in AS3/Flixel

texts:
I'm making a game in Flixel and I need to program an NPC. It's rapidly turning more complex than I expected. I was wondering if there are any best practices, tutorials or examples that you can refer me to, to see how this is done.

I can probably hack it together, which is what I always do, but it would be nice if I can make it maintanable and can add stuff later on.

Here's screenshot to give you an idea: The butler will be an NPC that will follow you, or guide you, and talk to you the whole time.

EDIT:
More specifically: What I have now is a long list of IF statements in the update loop of the butler (about 8 different cases), and all I have covered is his walking behavior. I want him to comment on things and sometimes switch his main behavior to be more aggresive or distant,... Is there any way to keep track of this, or is complex code with many many nested if statements the way to go?


texts:
I'm working in LWJGL and trying to implement pausing when the user presses the 'P' key. Thus far I have this:

boolean gamePaused = false;
    while(!Display.isCloseRequested()){

        if(Keyboard.isKeyDown(Keyboard.KEY_P) && !gamePaused)
            gamePaused = true;
        if(Keyboard.isKeyDown(Keyboard.KEY_P) && gamePaused)
            gamePaused = false;

        if(gamePaused){
            while(true){
                System.out.println("Game paused.");
                if(Keyboard.isKeyDown(Keyboard.KEY_P)){
                    gamePaused = false;
                    break;
                }
            }
        }
        //...game logic
    }

My problem is that it continues playing even when I press the P key.


texts:
Already posted this on another forum but I'll repost it here because I'm curious if this is a good forum for game-design questions.

I'm looking to design a player ranking system for my game. The game is similar to a racing game where you get a score for individual tracks you play (based only on your own performance). Beside the score for tracks played I want a player rank. The purpose of this player rank is to:

Make you feel like you are progressing and getting better
Encourage you to play more
Encourage you to play better and improve your skill
Be enjoyable

Another way to state it is that I want to encourage playing more levels (increasing amount of play) as well as improving skill (getting higher score). It's not necessary for the rank to actually reflect your skill. Although, I suspect some amount of accuracy is needed for the score to feel meaningful.

The only ranking system I'm familiar with is the ELO-type ranking system which I feel is lacking in some ways. Although it accurately reflect the skill of the player it has the problem of not being enjoyable in my experience - it punishes bad plays, gives no rewards for trying/experimenting with new plays. It also puts a lot of pressure on you to perform well in every game which discourages casual play.

Any ideas?

Thanks


texts: breakout game, computing optimal ricochet angle of a ball to get to a certain point

texts:
perhaps the title isn't clear so here is an explanation with a picture to better express my question

Consider the following breakout clone game

where the game is rigged to change the ricochet angle according to some parameters

Suppose the ball was to hit one of these blue bricks, finding the angle at which the ball should ricochet to go toward any point below the bricks using trigonometry should be trivial and easy.

My question however, is if we have the following setup

How would I got about finding the optimal angle to ricochet from the collision point (circled in red) to get to a certain location (green dot for example)

The path should ricochet off of multiple points to get there, obviously, I'm just not sure how to go about it.

Any math guru who can help me out? Thanks!


texts: Issues detecting if position is inside a Polygon2DCollider

texts:
I have a Polygon2DCollider set in my scene that I am using Physics2D.OverlapPoint(position, 0) to see if the set position collides with anything. Initially, the collider is stored in memory and then deactivated for future use. When I want to use it I do the following:
targetColliderObj.SetActive(true);

Collider2D collider = Physics2D.OverlapPoint(testPosition, 0);
if (collider == null || collider.tag != targetColliderObj.tag)
{
    Debug.Log("Unable to move down a floor.");
}

In the code above I activate the target gameobject for the Polygon2DCollider and check to see if the testPosition is within the collider. The collider is always null even though I am placing the testPosition inside of the collider. Also, I am checking on layer mask 0. The gameobject of the Polygon2DCollider is also on the Default layer (0).


texts:
I'm currently in the last phases of an original release for my upcoming risk game - I'm looking at making a patching system to autopatch the game.

My current concept for it is-

1: Player opens the game

2: Game checks valid serial key

3: If valid, game checks latest version

4: If newer, game prompts opening of auto patcher

5: If opened, patcher downloads version list, with all version

6: Patcher loops through list to find all newer patches and downloads all version files with links to patch data

7: Patcher checks with the website for each file, checking if downloading all patches is smaller than downloading the latest version of the file: if smaller, downloads patches; if bigger, downloads latest file

8: If smaller patch file, patcher incrementally alters file with each patch applied by each small patch file, from oldest to newest. If larger, patcher simple overwrites the file

9: Patcher asks exit/launch game so players can enjoy the game

Does this sounds like a sane way to do the patcher or will it come back and bite me later on?


texts: Trouble referencing a bone transform in Unity. (Using MakeHuman armature / configured in Avatar ok / Anim mocaps working ok))

texts:
I've seen that the bones are Transforms. And i've tried copying many examples. The armature is the standard MakeHuman one and is unchanged. It imported to Unity fine and the mocap animations work perfectly. What I need to do is make the hand a parent of my gun .

Here is what I have currently (I have tried many similar permutations):

    Transform handR;
public GameObject gunPrefab;
GameObject gun;

private void Start()
{
    rb = GetComponent<Rigidbody>();
    playerAnims = GetComponentInChildren<PlayerAnimations>();
    absoluteGround = rb.transform.position.y;
    distToGround = GetComponent<Collider>().bounds.extents.y;
    handR = transform.Find("hand_r");
    Debug.Log("handR really is: " + handR);

    gun = GameObject.Instantiate(gunPrefab);
    gun.transform.SetParent(handR);
    //gun.transform.position = handR.position;
    gun.transform.rotation = Quaternion.identity;
}

The end result of this: The gun will spawn but isnt parented to anything. And if I try to set its position using handR.position then i get null exception. Pic above shows the image where I see its called "hand_r"

One more thing of note: The bones shown in the image above , do NOT appear in the hierarchy. I have on occasion imported models with the bones included whose bone names all appear in the hierarchy - could this be the reason Unity is finding "hand_r"??? and if so whats the best way to fix that (Please done say remove the armature and make my own in Blender !! :O )

PS: I have since tried it with a new model, made in Blender with a Rigify rig. The code part "handR = transform.Find("hand_R"); -yes the rigify rig names it with capital "R". Still doesnt work, BUT THERE IS A WORKAROUND I FOUND... if I make the Transform handR public and drag it into the Inspector it all works fine! (And yes the Rigify skeleton also shows up in hierarchy!) (So if you are reading this and struggling too, DONT use the MakeHuman skeleton, use one from Blender Rigify.)

But I'm still very confused why the "Find" command doesnt find the bone


texts:
A lot of role playing games have a system where npcs scale with the player level and become stronger, on the surface it might seem genial but in most games either it doesn't change anything or it makes low levels enemies ridiculously hard to beat or sometimes impossible, like in oblivion.

I came up with the idea of making nps not scale with the level of the player but scale with stats.

For example a level 1 wolf has a base attack that deals 5% of the players maximum HP as damage with each hit, but is mitigated by defense. Therefore the attack will remain consistent in strength even when the player is max level but can be blocked by sacrificing damage to build  a lot of denfese or by becoming better at parrying attacks.

Is there any other mechanism I can implement to make the npcs stronger through all the levels without making them ridiculously invincible or giving them one hit mechanics that instantly kill the player?


texts: Is it possible to use the GPU on a mobile device to accelerate a particle physics engine?

texts:
I am interested in answers for any mobile device but I am mainly considering the iPhone and devices that run Java.

I am developing a game that relies heavily on a particle physics engine for core gameplay (not just animation effects) and have been developing/testing on a PC up to now with the intention of porting it to iPhone and/or Android.  The problem is that the particle physics engine (which I implemented myself) is still way too slow.  I can barely reach the target frame rate on a netbook and I am guessing that most phones will be worse (maybe not the iPhone but that will be expensive to port so I want to be confident that it will be worthwhile.)

I've optimized the software implementation as far as I can and now I am wondering if it is possible to accelerate it in hardware.  The GPU looks like the obvious thing to try first.

Has anyone researched this or do you know of an existing library that implements this?


texts: How can I move a polygon edge 1 unit away from the center?

texts:
Let's say I have a polygon class that is represented by a list of vector classes as vertices, like so:

 var Vector  = function(x, y) { this.x = x; this.y = y; },
     Polygon = function(vectors) { this.vertices = vectors; };

Now I make a polygon (in this case, a square) like so:

var poly = new Polygon([
    new Vector(2, 2),
    new Vector(5, 2),
    new Vector(5, 5),
    new Vector(2, 5)
]);

So, the top edge would be [poly.vertices[0], poly.vertices[1]].

I need to stretch this polygon by moving each edge away from the center of the polygon by one unit, along that edge's normal.  The following example shows the first edge, the top, moved one unit up:

The final polygon should look like this new one:

var finalPoly = new Polygon([
    new Vector(1, 1),
    new Vector(6, 1),
    new Vector(6, 6),
    new Vector(1, 6)
]);

It is important that I iterate, moving one edge at a time, because I will be doing some collision tests after moving each edge.

Here is what I tried so far (simplified for clarity), which fails triumphantly:

for(var i = 0; i < vertices.length; i++) {
    var a = vertices[i],
        b = vertices[i + 1] || vertices[0]; // in case of final vertex

    var ax = a.x,
        ay = a.y,
        bx = b.x,
        by = b.y;

    // get some new perpendicular vectors
    var a2 = new Vector(-ay, ax),
        b2 = new Vector(-by, bx);

    // make into unit vectors
    a2.convertToUnitVector();
    b2.convertToUnitVector();

    // add the new vectors to the original ones
    a.add(a2);
    b.add(b2);

    // the rest of the code, collision tests, etc.
}

This makes my polygon start slowly rotating and sliding to the left, instead of what I need.

Finally, the example shows a square, but the polygons in question could be anything.  They will always be convex, and always with vertices in clockwise order.


texts:
I have a CCSprite with a certain shape in Cocos2D and I would like to fill it with a pattern, as seen here:

I've seen a lot of examples where they fill a rectangle with a pattern, or even a dynamically-created polygon, but not another CCSprite. Is it possible to do so?
Thanks!


texts: My camera does not rotate around player in 3d open world

texts:
I want my camera to following behind the player at all times.  When the player turns to the left, I would expect the camera would move behind the player while remaining focused on the player.

My camera stays focused on the player.  However, it does not rotate to stay behind the player.

I tried following the directions from here, and here.  Neither of which seems to help.

Here's my code:

public class CameraFollow : MonoBehaviour
{

    private GameObject player;
    private GameObject mainCamera;
    private Vector3 offset;
    private float distance;
    private Vector3 playerPrevPos;
    private Vector3 playerMoveDir;

    // Use this for initialization
    private void Start()
    {
        player = GameObject.FindGameObjectWithTag("Player");
        mainCamera = GameObject.FindGameObjectWithTag("MainCamera");

        //Calculate and store the offset value by getting the distance between the player's position and camera's position.
        offset = transform.position - player.transform.position;

        distance = offset.magnitude;
        playerPrevPos = player.transform.position;
    }

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

    private void LateUpdate()
    {
        playerMoveDir = player.transform.position - playerPrevPos;

        if (playerMoveDir != Vector3.zero)
        {
            playerMoveDir.Normalize();
            transform.position = player.transform.position + offset;
            transform.LookAt(player.transform.position);
            transform.rotation = Quaternion.Lerp(transform.rotation, player.transform.rotation, Time.deltaTime * 1);

            mainCamera.transform.position = player.transform.position + offset;
            mainCamera.transform.LookAt(player.transform.position);
            mainCamera.transform.rotation = Quaternion.Lerp(transform.rotation, player.transform.rotation, Time.deltaTime * 1);

            playerPrevPos = player.transform.position;
        }
    }
}

I have done something a little different, per instructions from a online unity class.  My main camera is a subobject of a rootobject, as shown in this picture.

I have attached image of the game with the yellow line showing which way the player is facing.  The camera is facing in a different direction.

Any help would be appreciated.
Thnx
Matt

Follow-up from answers:
I cannot get either solution to work.  @alejandrodlsp solution doesn't compile (I've added a comment to the answer explaining why).  If I do not set offset on Start (aka its always 0), then the camera rotates.  The problem is that is at the feet the player and not behind like I wanted.   Once I compute offset, then the camera never rotates behind the player.


texts: Using PlayerPrefs to save audio volume throughout scenes in Unity

texts:
I have game that plays music. I have a mute toggle button that will mute my game music when you press on it, it will also un-mute it when you press it again. I'm having problems with saving the audio volume when a scene is loaded. (I tried using DontDestoryOnLoad but my mute script is attach to my main menu canvas so its saving the canvas as well, which I do not want. I find using playerprefs a lot easier). For example, when I click on my mute button, it mutes my game, I play the game, die, restart the game and the volume is being restarted as well. Even though I used playerprefs to try and solve the problem it didn't work, it still did the same thing. Anyway this is my script:

public bool mute;
public static Vector3 target;

void Start ()
{
    PlayerPrefs.GetFloat("mute");
}

void  Update()
{
    PlayerPrefs.GetFloat("mute");
}

private void Muted ()
{
    mute = !mute;
    if (mute) {
        gameObject.GetComponent<AudioSource> ().volume = 0;
        PlayerPrefs.SetFloat("mute", 0);
    }
    else
    {
        gameObject.GetComponent<AudioSource> ().volume = 1;
        PlayerPrefs.SetFloat("mute", 1);
    }
}


texts: I have a rectangle which is created by 2 triangles and it is in x-z plane, and i have object on it. Now, the normals of two triangles (face normals) are y axis i.e. (0,1,0). I want to display normals of two triangles for which i need two points to draw a line to show normal. Intuitively if i take center of a triangle as one and (0,1,0) as second point of a normal then both of the normals will converge to single point. I dont think it is correct as the normal should be exactly perpendicular to the surface. We can do a trick and take one point as a center and other by increasing y coordinate keeping x and z same, but what if we have curved surface and not a plane board? What about the cylinder made of triangles? How could we display normals as a lines of cylinder? I guess i am missing very basic concept here, please help me to understand it and tell me how to calculate the two points of normal.


texts: Dynamic Memory Allocation and Memory Management

texts:
In an average game, there are hundreds or maybe thousands of objects in the scene.
Is it completely correct to allocate memory for all objects, including gun shots (bullets), dynamically via default new()?

Should I create any memory pool for dynamic allocation, or is there no need to bother with this? What if the target platform are mobile devices?

Is there a need for a memory manager in a mobile game, please? Thank you.

Language Used: C++;
Currently developed under Windows, but planned to be ported later.


texts: Drawing an animation over an already drawn screen

texts:
I am working on a XNA WP7 card game whose basic prototype is complete. In game screen, 6 cards are displayed at a time (3 for each of the two players say 1,2 and 3).

If player A attacks one of player B's card then I want to show an animation over player B's card i.e the victim card(say a claw scratch for e.g.)

My question is how do I approach with the animation system so that I can draw an animation over a card upon certain events e.g. dead, fire, claw attack etc.

I have an attack function which detects which type of card is attacking which type of card. Depending on the type of attacker card I want to display the animation on the victim card.

Can I call animation classes function for different animations in the attack function itself without actually having to call separate draw and update functions. If so, how?

Also how do I play sound at the same time when the animation is going on?

EDIT-
Heres what I have done.

I took your advice and created an animation routine in a different class.
Here's how it works.

I have a separate Animation.cs class file (where animation occurs)
I have a wrapper class called CardAnimation which has a Dictionary object as animations with animation type as key and animation object as value.
I created a static object of CardAnimation class in Card class so that its not created every time I call animation routine.
I am calling the card's update method from another class called MAINGAMESCREEN.

Here's the flow of Update methods

MAINGAMESCREEN -> CARD -> CARDANIMATION -> ANIMATION

Animation works but it occurs very fast that I can see only first frame.
Same animation code works fine in an independent project.
 What can I do to slow it down?


texts: Do I need to roll my own polygon segmentation algorithm to automate Box2d body creation from a tile map?

texts:
Before re-inventing the wheel I figured I'd ask:

I'm working on a tile-based 2d-maze level generator for cocos2d + box2d. The idea is:

I'm using one of the well-known graph traversal algorithms to
generate a random maze.
This data gets encoded as an XML of the type that both Tiled and
cocos2d can work with.
Based on the generated maze tile data, my program should also
generate the polygonal data (vertices) that define the walls of the maze so that I can get them from, for instance, a Tiled's XML's object layer and into Box2d for defining bodies.

However, I'm at step 3 and so far, I'm thinking of solving this step with something along the lines of a flood/segmentation/magic wand algorithm. That is, from step 2 I get the graph's nodes which translate in Tiled's XML to, for instance, a 2d array where walls are marked with a number and open spaces are 0s. This is in the cvs non-compressed XML representation for instance.

So what I need to do now is sort of solve the convex-hull problem for a bunch of points (the non-zero numbers in this 2d array), but actually creating different polygons. I also need to then break any concave ploys into convex, but that can be done easiest with ear-clipping and, should I decided to get fancier, Delaunay or something.

Let me illustrate with images:

And in the next image you can see A the set's convex-hull (approximately), and B what I'm trying to achieve (concave subsets of the hull):

That is, I need to be able to distinguish separate polys. Of course, but for one, these also turn out to be concave which Box2d will not like. But like I said, I'll turn them to convex sets afterwards.

The question is, is there anything built-in or tested/tried that I could just grab and use or do I need to implement my magic wand algorithm?

I'm also open to different approaches all together.


texts: how to apply a texture to a 3d scene background?

texts:
i don't really know the exact term for that (i thought it was hdr but no...).

i want to put a texture as a background in opengl-es , and when we rotate the view , the background rotate too (obviously) but when there is translation , the background doesn't change.

like if i was inside a sphere and the texture are stick to it.

(and i don't think the sphere idea is the best way to do it).

I have certainly not explained the problem correctly , I'm sorry for that and thanks a lot if you understand me (even more if you have the answer :p)


texts:
I've googled this and haven't come up with anything. Can I create a Pac-Man game and not get in trouble with?

Like can I sell it, and be able to make money without having to pay someone else royalties?


texts:
I'm using the "Zig-Zag" approach to drawing my isometric map (as seen here https://stackoverflow.com/questions/892811/drawing-isometric-game-worlds).  Now I need to do collision detection on the irregularly shaped map.

All I need to know is how to figure out if point (x, y) is colliding with the zig-zag isometric map.


texts:
I have the following h and v blur:

Horz

  texture tex;
   sampler2D s = sampler_state {
      texture = <tex>;
   };

   int tWidth;
   int tHeight;
   float blurSize = 9.0;
   float4 ps_main(VS_OUTPUT Input) : COLOR0
   {
      float2 pxSz = float2(1.0 / tWidth,1.0 / tHeight);
      float4 outC = 0;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(-4.0 * pxSz.x * blurSize,0)) * 0.05;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(-3.0 * pxSz.x * blurSize,0)) * 0.09;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(-2.0 * pxSz.x * blurSize,0)) * 0.12;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(-pxSz.x * blurSize,0)) * 0.15;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(0,0)) * 0.16;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(pxSz.x * blurSize,0)) * 0.15;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(2.0 * pxSz.x * blurSize,0)) * 0.12;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(3.0 * pxSz.x * blurSize,0)) * 0.09;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(4.0 * pxSz.x * blurSize,0)) * 0.05;
      outC.r = 0;
      outC.g = 0;
      outC.b = 0;
      outC.a *= 0.8;
      return outC;
   }

vert

  texture tex;
   sampler2D s = sampler_state {
      texture = <tex>;
   };

   int tWidth;
   int tHeight;
   float blurSize = 9.0;
   float4 ps_main(VS_OUTPUT Input) : COLOR0
   {
      float2 pxSz = float2(1.0 / tWidth,1.0 / tHeight);
      float4 outC = 0;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(0,-4.0 * pxSz.y * blurSize)) * 0.05;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(0,-3.0 * pxSz.y * blurSize)) * 0.09;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(0,-2.0 * pxSz.y * blurSize)) * 0.12;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(0,-pxSz.y * blurSize)) * 0.15;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(0,0)) * 0.16;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(0,pxSz.y * blurSize)) * 0.15;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(0,2.0 * pxSz.y * blurSize)) * 0.12;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(0,3.0 * pxSz.y * blurSize)) * 0.09;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(0,4.0 * pxSz.y * blurSize)) * 0.05;
      outC.r = 0;
      outC.g = 0;
      outC.b = 0;
      outC.a *= 0.8;
      return outC;
   }

When the blur size is < 5, it looks like Photoshop's, but when I bring it up to make drop shadows, it starts looking like this:

Top is my game, bottom is photoshop. Notice the lines that form on mine. I think it stems from reaching the edge of the texture maybe. What could I do to make it look more like Photoshop's?

Thanks


texts:
My trigger does not detect my player.
My Trigger.cs file:
using UnityEngine;

public class Trigger : MonoBehaviour {

public Camera camera1;
public Camera camera2;
public GameObject panel;

 void OnTriggerEnter(Collider other)
{
    camera1.enabled = false;
    camera2.enabled = true;
    panel.SetActive(true);
    Debug.Log ("Entered-");
}

 void OnTriggerExit(Collider other)
{
    camera2.enabled = false;
    camera1.enabled = true;
    panel.SetActive(false);

}
private void Update()
{
    if(Input.GetKeyDown(KeyCode.DownArrow) || Input.GetKeyDown(KeyCode.S))
    {
        panel.SetActive(false);

    }
            }

}

Where I can start troubleshooting te issue?

Object on which the trigger script is sitting on.

 The solution:
-- I created two colliders, and assigned one as a collider, the other (bigger) is a trigger.  -- I also had problems with the small triggers in the scene. The triggers were to small to be detected by my main player, althought
they detected my "sphere" player object


texts: Highlighing and hit detection on a geographic game

texts:
I'm developing a geographic game where you select a country and it highlights. At first I thought about using 196 images (1 for the world, 195 for each country highlight) with the same size, and the country images would only have the country drawn and the rest is transparent. That way they'd overlap perfectly.

This design doesn't feel quite right, and it would cause trouble doing hit detection on cases where a country is inside another one.

What's the best approach for this situation?


texts: How can I prevent P2P connections from leaking player IP addresses?

texts:
There's a common issue in multiplayer PC games like the older versions of Call of Duty where any connected player in a match can easily sniff the game packets and read the IP addresses of all the connected players. This is undesirable privacy-wise.

How can I reasonably protect players from malicious actors that may use their IP for nefarious purposes?


texts: How can I avoid instantiating multiple instances of a RigidBody?

texts:
I could use a little help.

I've a state machine for an NPC that does a melee attack. The problem I'm running into is that the current code instantiates multiple instances when I only need one per cycle.

I could use some ideas.

This is the chunk of code I'm working with:

public void ChaseToAttack()
{
    _navMeshAgent.speed = 3.5f;//slow down the navAgent

    float playerDistance = Vector3.Distance(chaseTarget.position, transform.position);
    //stop navMeshAgent to begin attack sequence
    if (playerDistance <= stopAtDistance)
    {
        /// ensure enemy is always looking at player
        enemyToTarget = ((chaseTarget.position + offset) - eyes.transform.position);
        if(Physics.Raycast(eyes.position, enemyToTarget, out _hit, sightRange) && _hit.collider.CompareTag("Player"))
        {
            _navMeshAgent.Stop();
            currentState = _attackState;
            //StartCoroutine(FistTimer());
            PunchCycle();
        }
        /// ensure the enemy isn't hitting air & will always look for the player
        else
        {
            transform.Rotate(chaseTarget.position, searchTurnSpeed * Time.deltaTime, 0);
        }
        /// end look & atttack player block
    }
}

void PunchCycle()
{
    StartCoroutine(AttackCycle());
}

void PunchClone()
{
    clone = Instantiate(pfbPunch, transform.position, transform.rotation) as Rigidbody;
    clone.transform.Translate(0,1f,0);
    clone.velocity = transform.TransformDirection(0.0f,0.0f,0.125f * punchDistance);
}

IEnumerator AttackCycle()
{
    //move animation here
    AnimPunch();
    PunchClone();
    yield return new WaitForSeconds(4f);//fistTimer
    BeAlert();

}

Thanks in advance...

EDIT:

Changed the code so it would only instantiate once- but now, it will only instantiate only once even though it's still in the attack sequence.

    public void ChaseToAttack()
{
    _navMeshAgent.speed = 3.5f;//slow down the navAgent

    float playerDistance = Vector3.Distance(chaseTarget.position, transform.position);
    //stop navMeshAgent to begin attack sequence
    if (playerDistance <= stopAtDistance)
    {
        /// ensure enemy is always looking at player
        enemyToTarget = ((chaseTarget.position + offset) - eyes.transform.position);
        if(Physics.Raycast(eyes.position, enemyToTarget, out _hit, sightRange) && _hit.collider.CompareTag("Player"))
        {
            _navMeshAgent.Stop();
            currentState = _attackState;
            StartCoroutine(AttackCycle());
        }
        /// ensure the enemy isn't hitting air & will always look for the player
        else
        {
            transform.Rotate(chaseTarget.position, searchTurnSpeed * Time.deltaTime, 0);
        }
        /// end look & atttack player block
    }
}
void PunchClone()
{
    if(!didClone)
    {
        clone = Instantiate(pfbPunch, transform.position, transform.rotation) as Rigidbody;
        clone.transform.Translate(0,1f,0);
        clone.velocity = transform.TransformDirection(0.0f,0.0f,0.125f * punchDistance);
    }
    didClone = true;
}
IEnumerator AttackCycle()
{
    //move animation here
    AnimPunch();
    yield return new WaitForSeconds(0.75f);//fistTimer
    PunchClone();
}


texts: How to render a pseudo-3D view like in the game Biosys (1999)?

texts:
Biosys is a PC game released in 1999, where navigation through its environments is done by clicking an "exit" on a scene, taking the player to a new scene. The player can't move in a scene, and interaction is done by clicking a location in it. In some scenes the player can freely look around in 360 degrees by moving the mouse.

My question is, what technique could be used to render such a scene? I'm asking because that doesn't look like it's true 3D; it looks drawn as if a picture is wrapped around the player, but how would you produce and render a picture in such a way?

Here is a rare YouTube video of that game, beginning at 3:40 where the technique I'm curious about is shown.

And here's a picture of one of those environments:


texts:
I'm working on a 3D Sniper game and have finished the project. When I test it on Windows (7). It's All Fine, not even a bug. But when I take the app into android (Bluestacks App Player), my buttons and images render in Solid Black color. and my trees are Solid White. Some materials are rendering black too. You can see this in the image below

That Black Square On Top Right Corner Is A UI Button And The White Regions Are Tree And Bushes. The Black Thing In The Bottom Is A APC Tank.


texts: How do I fix the "Failed to recompile android resource files." build issue?

texts:
I've tried similar solutions I found on this website, nothing worked. There are thee errors that pop up... been banging my head for quite a while now, please help!

Also note: I updated my JDK using the download link (next to the browse option in the external preferences). Then linked it to this file, which I am lead to believe is the correct file. C:/Program Files/Java/jdk-9

Failed to compile resources with the following parameters:
-bootclasspath "C:/NVPACK/android-sdk-windows\platforms\android-24\android.jar" -d "C:\Users\Dylan\Desktop\ContentCreater\Repo\DoodlePlanes\DoodlePlanes\DoodlePlanes\Temp\StagingArea\bin\classes" -source 1.6 -target 1.6 -encoding UTF-8 "com\android\vending\billing\R.java" "com\SoloDeveloperStudio\DoodlePlane\R.java" "com\unity\purchasing\R.java" "com\unity\purchasing\googleplay\R.java"
warning: [options] source value 1.6 is obsolete and will be removed in a future release
warning: [options] target value 1.6 is obsolete and will be removed in a future release
warning: [options] To suppress warnings about obsolete options, use -Xlint:-options.
3 warnings

UnityEditor.HostView:OnGUI()

UnityException: Resource compilation failed!
Failed to recompile android resource files. See the Console for details.
UnityEditor.Android.PostProcessor.CancelPostProcess.AbortBuild (System.String title, System.String message, System.Exception ex)
UnityEditor.Android.PostProcessor.CancelPostProcess.AbortBuild (System.String title, System.String message)
UnityEditor.Android.PostProcessor.CancelPostProcess.AbortBuildPointToConsole (System.String title, System.String message)
UnityEditor.Android.PostProcessor.Tasks.BuildResources.CompileResources (UnityEditor.Android.PostProcessor.PostProcessorContext context)
UnityEditor.Android.PostProcessor.Tasks.BuildResources.Execute (UnityEditor.Android.PostProcessor.PostProcessorContext context)
UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context)
UnityEditor.Android.PostProcessAndroidPlayer.PostProcess (BuildTarget target, System.String stagingAreaData, System.String stagingArea, System.String playerPackage, System.String installPath, System.String companyName, System.String productName, BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.BuildReporting.BuildReport report)
UnityEditor.Android.AndroidBuildPostprocessor.PostProcess (BuildPostProcessArgs args)
UnityEditor.PostprocessBuildPlayer.Postprocess (BuildTargetGroup targetGroup, BuildTarget target, System.String installPath, System.String companyName, System.String productName, Int32 width, Int32 height, BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.BuildReporting.BuildReport report) (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/PostprocessBuildPlayer.cs:263)
UnityEditor.HostView:OnGUI()

UnityEditor.BuildPlayerWindow+BuildMethodException: Build failed with errors.
  at UnityEditor.BuildPlayerWindow+DefaultBuildMethods.BuildPlayer (BuildPlayerOptions options) [0x001b9] in C:\buildslave\unity\build\Editor\Mono\BuildPlayerWindowBuildMethods.cs:162
  at UnityEditor.BuildPlayerWindow.CallBuildMethods (Boolean askForBuildLocation, BuildOptions defaultBuildOptions) [0x00050] in C:\buildslave\unity\build\Editor\Mono\BuildPlayerWindowBuildMethods.cs:83
UnityEditor.HostView:OnGUI()


texts: LibGDX “EXCEPTION_ACCESS_VIOLATION” error when recreating previously disposed Box2DLights light

texts:
I just installed the Box2DLights dependency for LibGDX and I added a cave with 2 ConeLights inside. The first time I render the cave, everything works as expected. Then when I exit the cave, I make sure to dispose() all the lights. Then if I enter the cave again and try to create the same 2 ConeLights, it gives me this exception with a big error log (PasteBin added at the bottom of this post). If I don't dispose() the lights when exiting the cave, it won't crash the second time, but it will keep adding lights and it will get brighter and brighter and it's bad for performance. It doesn't matter if I use a PointLight or a ConeLight, the same exception will occur.

Everytime a map change occurs, destroyLighting() and then loadLighting() for the new map is called. The error happens when a ConeLight is created, the second time when you enter the cave (4th line in the loadLighting() method)

loadLighting():

for(MapObject o : lightingObjects) {
      EllipseMapObject circleMapObject = (EllipseMapObject) o;
      Ellipse ellipse = circleMapObject.getEllipse();
      Light light = new ConeLight(rayHandler, 60, new Color(255,225,166,1), 100, ellipse.x, ellipse.y, 90, 90);
      light.setSoftnessLength(0);
      lights.add(light);
}

destroyLighting():

for(Light light : lights) light.dispose();
lights.clear();

The error log:
https://pastebin.com/1v36aNPg