texts: How does the following code generate a full screen quad?

texts:
How does this

struct Output
{
    float4 position_cs : SV_POSITION;
    float2 texcoord : TEXCOORD;
};

Output main(uint id: SV_VertexID)
{
    Output output;
    output.texcoord = float2((id << 1) & 2, id & 2);
    output.position_cs = float4(output.texcoord * float2(2, -2) + float2(-1, 1), 0, 1);
    return output;
}

and this

pImmediateContext->VSSetShader(fxaaVS, ..., ...);
pImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
pImmediateContext->Draw(3, 0);

generate a Full Screen Quad?

It has only three vertices b(provided quad has 4 vertices)
the positions produced are also not like a (half of a) quad.

Looking at this, i might be confused between a quad and a full screen triangle.


texts: Increase animation speed according to the swipe speed in unity for Android

texts:
I have the animation done through Maya and brought the FBX file to unity. Here is my code to calculate the speed of the swipe:

Vector2 speedMeasuredInScreenWidthsPerSecond =(Input.touches[0].deltaPosition / Screen.width) *     Input.touches[0].deltaTime;

Now I wanted to take speedMeasuredInScreenWidthsPerSecond and use it to increase the animation speed accordingly like this:

animation["gmeChaAnimMiddle"].speed=Mathf.Round(speedMeasuredInScreenWidthsPerSecond);

However, this results in an error that I need to convert Vector2 to float.

So how do I overcome it?


texts: draw a box with transparent background (outline) in unity

texts:
I am trying to draw an outline (a transparent box with colored border essentially)

I have the following code adapted from here

void OnGUI(){
    GUI.Box (new Rect (10,10,200,30), "Object", InitStyles(new Color( 0f, 0f, 0f, 0.0f )));
}
private GUIStyle InitStyles(Color color){
    GUIStyle currentStyle = null;
    if( currentStyle == null ){
        currentStyle = new GUIStyle (GUI.skin.box );
        currentStyle.normal.background = MakeTex( 2, 2, color );
    }
    return currentStyle;
}

private Texture2D MakeTex( int width, int height, Color col ){
    Color[] pix = new Color[width * height];
    for( int i = 0; i < pix.Length; ++i ){
        pix[ i ] = col;
    }
    Texture2D result = new Texture2D( width, height );
    result.SetPixels( pix );
    result.Apply();
    return result;
}

This is getting rid of the border along with the background color.

Is there a better way to do this?


texts: Set value in an array[3], that the sum of all three values is always 1.0

texts:
So I'm working on a Civ like game right now and want to have a setting how taxes are split in gold income, science and luxury goods.

private double[] rate = new double[] { 0.4, 0.6, 0.0 };

now I wanted to add a methode to change one of the values to a higher or lower value but maintain the overall sum of 1.0 (100%)
but I'm stuck here with how to take or add values evenly from the other two rates

    public void setRate (int index, double r) {
    if (r < 0.0) {
        throw new IllegalArgumentException("Invalid Rate");
    }

    double diff = r - rate[index];
    if (diff > 0) {

        // ?

    } else if (diff < 0) {

        // ?

    }
    rate[index] = r;
}

EDIT for amitp:

public void setRate (int index, double r) {
    if (rate[index] = 1.0) {
         for (int i = 0; i < 3; i++) {
              if (i != index) {
                  rate[i] = (rate[index] - r) / 2;
             }
        }
    } else {
        for (int i = 0; i < 3; i++) {
            if (i != index) {
                rate[i] = rate[i] * (1.0 - r) / (1.0 - rate[index]);
            }
        rate[index] = r;
        }
    }


texts: Actors with multiple Textures - class Hierarchy?

texts:
In my 2D side-scroller game I have a bunch of actors being drawn, each of which has a single, non-animated Texture (a png image). These actors all inherit from a base GameActor class.

I want to add some more NPC's (e.g. tanks or cannons) that have one texture that doesn't move (the base) and another that rotates to shoot at things (the gun / barrel). How should I structure my Actor class hierarchy so as to allow for this? Should I refactor my base Actor class to allow for N textures? Or should I create a brand new sort of Actor for things that need > 1 texture (and then have to manage these actors separately from 'regular' actors)? Or is there a better approach I can't see?

Thus far I've been opting to keep things as simple as possible (KISS, right?), but am not sure how to proceed.

Any pointers greatly appreciated.


texts: How can one implement hot-swappable C++ modules?

texts:
Fast iteration times are key to developing games, much more so than fancy graphics and engines with truckloads of features in my opinion.  No wonder many small developers choose scripting languages.

The Unity 3D way of being able to pause a game and modify assets AND code, then continue and have the changes take effect immediately is absolutely great for this.  My question is, has anybody implemented a similar system on C++ game engines?

I have heard that some really super high end engines do, but I am more interested in finding out if there is a way to do it in a home-grown engine or game.

Obviously there would be tradeoffs, and I can't imagine that you can just recompile your code while the game is paused, have it reloaded and working under every circumstance or every platform.

But perhaps it's possible for AI programming and simple level logic modules.  It's not as if I want to do that in any project in the short (or long term), but I was curious.


texts: My issue is when I exit the game the lives and scores still appears in my game menu so how do I clear them after I quit the game and get back to the menu?


texts:
I am making a TV remote app for a specific android device (the Pixel XL, 1440x2560 resolution). However, when I put the app on my phone, it truncates most of the app.

Here's what it should look like:

Here's what it ends up looking like:

My game is forced in portrait, and I want to keep it that way.
I have tried rotating the canvas, but that does nothing. The Android app also seems to ignore the main camera; I think it is just using the canvas.

I tried many different things, including changing the scaling and setting the anchors.  None of this had any effect. I have even set the editor Game window to the target resolution, but it appears to work via the editor.

Why is Unity ignoring my camera on Android?


texts:
I have 4 angles, left, right, top & bottom. These angles are in degrees. They define the angle between the forward vector and the corresponding side. I am trying to use these to calculate the required values for Perseective Off Centre function found here http://docs.unity3d.com/Documentation/ScriptReference/Camera-projectionMatrix.html
I tried doing
 (near plane-far plane) * Tan(angle)
But that didn't give the correct results.


texts: Unity sprites are no longer batched after the object rotates/moves

texts:
With Unity 5 and access to the profiler, I'm running our game through some stress tests so I can find where our performance issues are.

While testing having 1024 units on the screen with 4 selection box corners each I ran into an odd problem. When I select all the units, 4096 selection box objects come into existence, my draw calls go from ~25 to 50 with 50 batches. Now when I tell the units to move, they rotate and the number of batches climbs up to 2090 and the draw calls climb to 2090 and stay there even after the units stop rotating or moving.

If I then reselect all the units, the selection boxes are destroyed and re-instantiated (I know, not the best way) and the batches and draw calls go back down to 50 from 2090.

What is causing this, and how would I go about fixing it?

After Selecting All Units

After having them rotate and move

After Re-selecting Them All


texts: Need help in tracking down memory leak in Unity standalone game

texts:
I'm experiencing a memory leak in my Unity game. If the game sits idly (no new game objects are being created in the scene), Windows Task Manager will show the memory of the .exe slowly rising.

I've attached the Unity profiler and the memory profiler stays completely flat with no new objects being created and its reported memory numbers don't rise. Thus, I assumed it must be from garbage allocations each frame somewhere. So I check the CPU profiler and there were a few scripts that were showing a few bytes of GC Alloc, most of which I've fixed. However, the memory leak appears to still be present.

I've gone as far as systematically removing objects from the scene to see if the memory leak stops, but that hasn't proven fruitful.

What's the next step to take to track this down? What other tools can I use?

I'm also noticing that the amount of memory being released between scene changes isn't great (very little in fact, even after requesting a GC collect). I'm hoping this is related to the memory leak during the scene though.


texts:
I set up my character to be modular, by following the UE4 docs.
I used the code at the bottom of the page to implement mesh merging functionality.
It does work well, I can merge meshes runtime.
I use this to add clothes to my characters.
Just wondering, if there is a way to take off clothes, by unmerging stuff:
Something like:

store added clothes in a TArray or something
then call a function to remove the desired cloth from the array

Of course, I would like to do it at runtime...


texts: Pygame's sprite.collide_circle() missing several frames of head-on collision

texts:
I've spent hours trying to figure why my collision detection was so crappy, with sprites visibly ovellaping for several frames, when I noticed the culprit could be pygame's detection callback pygame.sprite.collide_circle().

I've stripped down the code and created a simple demo, and results were surprising: collide_circle() still returns False for several frames after its sibling collide_rect() correctly detects a collision and returns True.

Here is the code:

import pygame

RED   = (255,   0,   0)
GREEN = (  0, 255,   0)
BLUE  = (  0,   0, 255)
BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)

SCREEN_SIZE = (800, 600)
FPS = 60
BG_COLOR = BLUE

class Ball(pygame.sprite.Sprite):
    def __init__(self, color=WHITE, radius=10, position=[], velocity=[]):
        super(Ball, self).__init__()

        self.color = color
        self.radius = radius
        self.position = list(position) or [0, 0]
        self.velocity = list(velocity) or [0, 0]
        self.bounds = (screen.get_size()[0] - self.radius,
                       screen.get_size()[1] - self.radius)

        self.image = pygame.Surface(2*[self.radius*2])
        self.rect = self.image.get_rect()
        pygame.draw.circle(self.image, self.color, 2*(self.radius,), self.radius)

    def update(self, dt=1./FPS):
        super(Ball, self).update()

        for i in [0, 1]:
            self.position[i] += self.velocity[i] * dt

            if self.position[i] < self.radius:
                self.position[i] = self.radius
                self.velocity[i] *= -1

            elif self.position[i] > self.bounds[i]:
                self.position[i] = self.bounds[i]
                self.velocity[i] *= -1

        self.rect.center = self.position

pygame.init()

screen = pygame.display.set_mode(SCREEN_SIZE)
clock = pygame.time.Clock()

background = pygame.Surface(screen.get_size())
background.fill(BG_COLOR)
screen.blit(background, (0,0))

balls = pygame.sprite.Group()
balls.add(Ball(color=RED,   radius=100, position=[  0, 300], velocity=[ 100, 0]))
balls.add(Ball(color=GREEN, radius=100, position=[700, 300], velocity=[-100, 0]))

done = False
while not done:
    for event in pygame.event.get():
        if (event.type == pygame.QUIT or
            event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
            done = True

    balls.update()
    if pygame.sprite.collide_rect(*balls):
        collision = pygame.sprite.collide_circle(*balls)
        print collision
        if collision:
            for ball in balls:
                ball.velocity[0] *= -1

    balls.clear(screen, background)
    balls.draw(screen)
    pygame.display.update()
    clock.tick(FPS)

pygame.quit()

And the output:

False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
True
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False

That's 17 frames of overlap before collide_circle() realizes that hey, there's a collision there! Even at 60 FPS that's huge.

The balls are almost halfway through each other, and this behavior seems to be velocity independent: if I change the balls' speed or the FPS, the visual result (halfway overlap) remains, but for fewer frames.

So, my question is: is this a pygame bug? Or did I completely misunderstood how detection works?


texts: Decomposing a concave mesh into a set of convex meshes

texts:
I'd like to be able to decompose a concave mesh into a set of convex meshes for 2 reasons:

Transparent rendering
Physics shapes

Is there an algorithm that takes a set of triangles (concave) as input and outputs a number of sets of triangles (convex)?  I'd like it to not fill in the holes between parts of the original mesh.

I've already come across a small idea: find all the concave edges, and split the meshes along the edge loops.  Am I on the right track?  How could I implement this?


texts: Get the player front position at specific distance

texts:
The simple way to get player front position at specific distance

     Vectro3 forward = player.transform.forward * distance;
     Vector3 newPlayerFronPosition= player.transform.position + new Vector3(forward.x, forward.y, forward.z);
     newPlayerFronPosition= new Vector3(newPlayerFronPosition.x, newPlayerFronPosition.y - 4f, newPlayerFronPosition.z);
     navigationCanvas.transform.position = newPlayerFronPosition;
     navigationCanvas.transform.rotation = camRotationToWatch.transform.rotation;

its actually working fine but the problem is as my player move up or down the navCanvas become appear ver near to my player. How to mainitain spcific distance all the time.?? that no matter player look above or down the navcanvas display at specfic distance.(position)

disatnceUICam = Vector3.Distance(newPlayerFronPosition, player.transform.position);

I also logged the distance and surprisingly it the distance is changing when i am moving up or down. its changing from 6 to 12 as i am looking up to down.


texts:
I'm trying to do binary operations with integers in the hlsl code. For example:

int n = 10 & 15;

Binary value of 10 = 1010 and Binary value of 15 = 1111.

With this, n = 10, because (1010 & 1111) = 1010. This is what I need, but if I declare the int values before, I get an error. For example:

int n1 = 10;
int n2 = 15;
int n = n1 & n2;

this shows the error: "error X3535: Bitwise operations not supported on legacy targets."

I made this simple code to help understanding, because I have no idea what is causing this.

I already tried to change the variables type to uint, but the error remains.

I'm using deferred lighting in xna and I want to store the emissive light intensity together with the specular power.


texts:
I am working on a match 3 game where the number of matched cells matters

  (if you match 3 then they just get removed, if you match exactly 4
  then something happens, and if you match more than 4 then something
  else happens)

Basically this image sums it up :

cells in the green frame should match and disappear, the ones in the red shouldn't.
Could anyone please help me out, am kinda stacked on how to tackle this.
Thank you

Edit
Thank you all for your help! flood-fill was the right thing to do, i made a good progress and faced a different problem, please check the new thread


texts: How to ensure new players aren't blocked from the leaderboards?

texts:
There is a simple word game, where players score points for each game they play. It creates a global chart, ranking players by their score.
The problem is that when a new player comes into the game, there are already old players occupying the chart top. Even if they are no longer active players.
To smooth this inequity, we introduced a super game that happens once a day and is stuffed with multiple bonuses like easier extra time, score x5 multiplication, and some others. It offers upward mobility, allowing players to get to the top if they play long enough.
Now I am thinking of another mechanism. What if all scores are subject to a little inflation, like 0.1% a day? It will affect the "poor" just a little bit and "score-fat cats" are going to be stripped of their score a bit harder. But not too much also.
I am trying to think forward on how such a mechanism could affect players' motivation, and if there some commonly used alternatives to fighting the issue?
P.S. Another idea is to reset the leaderboard at midnight on New Year's Eve, keeping a global all-time leaderboard available but just for historical purposes.
Deleting players after a certain long enough period of inactivity (like a year) is also a considered option. Another option is to reset a score if a player is inactive for a certain period of time (like half a year), but keep their profile. If the player decides to resume playing, all new games are bound to the same existing profile, but the score is counted only for games after a date when activity is restored.


texts:
Hi I am trying to create a game where there are different types of zombies. I decided to create a base class for the zombies that includes methods for moving and flipping characters and then I have individual classes for each type of zombie where I will modify things like health and damage.

I made it so the zombie prefab I put in the game has a script that inherits from the Zombie class but when I run the game nothing in the Zombie.cs script is run.

Anyway, here are my classes:

Zombie.cs

public class Zombie : MonoBehaviour {

    //zombie goes after this target
    Transform targetPlayer;

    //Zombie Rigid Body
    Rigidbody2D zombieRB;

    //The speed the zombie will move
    public float moveSpeed;

    //Used for flipping zombie based on which way it is going
    bool facingRight = true;

    // Use this for initialization
    void Start () {

        zombieRB = GetComponent <Rigidbody2D> ();

        //This finds the player object to follow it
        targetPlayer = GameObject.FindGameObjectWithTag ("Player").transform;
    }

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

        //Checks zombies position in comparison to player to see where it should move.
        if (transform.position.x < targetPlayer.position.x) {
            //zombie to the left of target go right

            if (!facingRight) { //Check if needs flipping
                flipZombie ();
            }

            zombieRB.velocity = new Vector2 (moveSpeed, zombieRB.velocity.y);

        } else {
            //zombie to the right of target go left

            if (facingRight) { //Check if needs flipping
                flipZombie ();
            }

            zombieRB.velocity = new Vector2 (moveSpeed * -1, zombieRB.velocity.y);
        }

    }

    /// <summary>
    /// Flips the zombie when moving
    /// </summary>
    void flipZombie() {
        facingRight = !facingRight;
        Vector3 theScale = transform.localScale;
        theScale.x *= -1;
        transform.localScale = theScale;
    }
}

And then I have a pulserZombie.cs but there is nothing in it but the inheritance:

public class pulserMovement : Zombie {

Here is my image of the prefab I have:


texts: How do multiple render targets get rendered onto the back buffer(s) then screen?

texts:
I'm using DX11. I understand how render targets are created, set, and why they are used, but I am really unsure how this all plays together with presenting it to the screen.

Does the GPU automatically flatten all render targets onto the back buffer, and how does this work with multiple back buffers?

If I were to have multiple render-targets for deferred rendering, or some customized post processing shader (using a ping-pong model) how do multiple render targets get presented accordingly?  I assume I have to set the final render-target used to be presented to the screen. But I am not sure.


texts: What are the most common splines you will find in game development?

texts:
List here the most common splines found in game development, how many points the method needs to interpolate a curve, and how can you build a data type that allows you to get an interpolation of the curve points. Examples: Bezier curves, B-Splines, Cubic Splines, etc.

P.S.: I'm putting this as a community wiki so we can list all kinds of spline interpolation.


texts: What problems could occur if you make use of both the MonoGame API and the underlying graphics API?

texts:
What kinds of problems could one run into if they were making a game with MonoGame and started making calls to the underlying graphics API as well?

For example, if I wanted to do something in a MonoGame project that MonoGame didn't necessarily support, or I just couldn't find the proper documentation / example for but I could find an example of how to do it in OpenTK, am I setting myself up for trouble if I implement it using OpenTK directly while using the MonoGame API everywhere else? Specifically I'm looking to find out if there are any big issues that are known that might result of this and not something obscure that will happen in very rare cases.

I tried doing a little research via Google and the GD.SE site itself and I couldn't find much. Maybe MonoGame has really covered most of its bases, but what if I manually wanted to work around one of it's outstanding issues or a feature that is not yet implemented?

If so what sort of problems might arise and are there any ways to help mitigate these issues?


texts:
I am having an extremely hard time understanding smooth 3D collision. I have spent a month trying to figure out the math and still cannot get perfect collision detection that perform the same way as in games such as Quake.

I've resorted to a virtual 2D rectangle collision model applied to 3D plane, but it's full of bugs and doesn't handle slopes. It seems that very complex math is required like matrices and vectors. There are lots of tutorials online but they are full of mathematical symbols and it's impossible for a math novice like me to understand it, I also don't have time to go through a mathematics basics from the beginning. Is it possible to do collision without vectors or matrices or a guide somewhere that can explain in non mathematical terms how to implement smooth collision? How can a nonmathematician overcome 3D math?


texts:
This is a question about a passage from this article:

  I suggest having every game object exist within a single giant array.
  This keeps game objects together in memory, and even though deletion
  of a game object is of O(n) complexity, that O(n) operation traverses
  an array, and usually will turn out to be unnoticeable. A custom
  vector or array class can be created that avoids the O(n) operation
  entirely by taking the element at the end, and placing it into the
  deleted slot.

I'm trying to understand what kind of operation the author is talking about. If I'm getting the overall point correctly, it's that accessing elements that are closer together in memory is faster, so therefor it's desirable to reorder the array such that there aren't any holes left when a game object is deleted.

If that is what the author means, then how is it possible to implement? This is what I'm imagining:

void Factory::addObject(const std::string name) {
    objects.push_back(new GameObject(name));

void Facrory::removeObject(const std::string name) {
    for(auto itr = objects.begin(); itr != objects.end()) {
        GameObject* obj = *itr;
        if(obj->name == name) {
            delete obj;
            // grab GameObject from end
            GameObject* endObj = objects.back();
            objects.erase(--m_objects.end());
            itr = objects.insert(itr, endObj);
        // else increment itr and continue

But that can't be right because just rearranging the pointers doesn't change how the memory is organized. So the author must be talking about something I don't understand about memory management.

My question is:
Have I misunderstood what the author meant? If not, then please explain how the author is suggesting the rearrangement is supposed to be done.


texts: Monogame - Problem with lighting 3d mesh

texts:
I am having an issue with lighting my 3d icosphere. For some reason,the lighting appears to be coming from the correct direction  (+X, -Y, -Z) but it also appears to be coming from (-X,+Y,+Z) and I have no idea why. I am not very well versed in 3D in Monogame yet, can anyone point me in the right direction of what is going on here?

EDIT:

The code for the shader

VertexToPixel ColoredVS(float4 inPos : POSITION, float3 inNormal : NORMAL, float4 inColor : COLOR)
{
    VertexToPixel Output = (VertexToPixel)0;
    float4x4 preViewProjection = mul(View, Projection);
    float4x4 preWorldViewProjection = mul(World, preViewProjection);

    Output.Position = mul(inPos, preWorldViewProjection);
    Output.Color = inColor;

    float3 Normal = normalize(mul(normalize(inNormal), World));
    Output.LightingFactor = 1;
    if (xEnableLighting)
        Output.LightingFactor = dot(Normal, -xLightDirection);

    return Output;
}

PixelToFrame ColoredPS(VertexToPixel PSIn)
{
    PixelToFrame Output = (PixelToFrame)0;

    Output.Color = PSIn.Color;
    Output.Color.rgb *= saturate(PSIn.LightingFactor) + xAmbient;

    return Output;
}

And this is for calculating normals

            for (int i = 0; i < Vertices.Length; i++)
                Vertices[i].Normal = new Vector3(0, 0, 0);

            for (int i = 0; i < Indices.Length; i += 3)
            {
                Vector3 p1 = Vertices[Indices[i]].Position;
                Vector3 p2 = Vertices[Indices[i + 1]].Position;
                Vector3 p3 = Vertices[Indices[i + 2]].Position;

                Vector3 v1 = p2 - p1;
                Vector3 v2 = p3 - p1;
                Vector3 normal = Vector3.Cross(v1, v2);

                normal.Normalize();

                Vertices[Indices[i]].Normal += normal;
                Vertices[Indices[i + 1]].Normal += normal;
                Vertices[Indices[i + 2]].Normal += normal;
            }

            for (int i = 0; i < Vertices.Length; i++)
                Vertices[i].Normal.Normalize();


texts: DirectX 10 - dimension of vertices passed to vertex shader

texts:
I'm trying to learn DirectX programming.
Looking at different tutorials there is something about vertices that I find a bit confusing.

I know that DirectX uses vertices with four elements (x, y, z, w).
I saw many tutorials (example http://msdn.microsoft.com/en-us/library/ff729721(v=VS.85).aspx) passing XMFLOAT3 as vertices positions omitting the w component.

How does this works?
Assuming that passing XMFLOAT3 or XMFLOAT4 doesn't change DirectX behavior (true?) should I set the w to 1 in the vertex shader or does DirectX assume it to be 1 by default?


texts: Architecture for scaling a large 2D MMORPG world vs player load

texts:
I want to make 2D MMORPG in a post-apocalyptic world.
I would like to make the game world seamless and big, with big battles for the players. Something similar is in Eve Online (in 3D), but I do not like the fact that during major battles time in EVE slows down. All this due to the limitations of the game. I thought, what if we come up with a new architecture to handle large player numbers in one region without slowing down? I had the following idea:
Server cluster Quadtree
The whole world is one big quadtree. And each quadrant of the tree is processed by a separate server.

If a big battle is coming, the quadtree subdivides, and the number of servers in the battle region increases automatically.
Can this strategy work at all?
How do you handle conflicts in this world?
I think that everything will be built using ECS (EnTT). Each server should have a connection to the servers nearby tell them information if, for example, I shoot a player while I am in server 1 and they are in server 2.
Perhaps you see some other problems with the implementation of such an architecture?


texts: Can I legally use movie sounds for game production?

texts:
Can I legally use short sounds from movies, like a door closing, in my game?
Is there a way for others know from where the sounds came from originally? Does it matter if I apply audio editing to the sample?


texts: Godot - Quaternion slerp is altering initial rotation of an object

texts:
I have a player that shoots a rocket. If the rocket has a target, I use a quaternion slerp to make it home in on that target. Free firing the rocket goes directly forwards as expected. Setting a tracking_speed of 1 homes directly towards the target as expected. But for some reason if I set tracking_speed to less than 1, the rocket's initial direction becomes (0 0, 1) no matter where the ship is pointing and then proceeds to rotate towards the target. Code below.
var transformed_rotation:Transform = global_transform.looking_at(target.global_transform.origin, Vector3.UP)
var new_rotation:Quat = Quat(global_transform.basis).slerp(transformed_rotation.basis, tracking_speed)

set_global_transform(Transform(new_rotation, global_transform.origin))


texts: Blurry UI when using Screen Space Camera

texts: I am using Screen-Space Camera as a render mode on canvas but the Textmeshpro text and other UI elements are looking blurry around edges. I think it might be due to canvas scaler setting. After changing plane distance or making canvas child of camera problem still exist.Following is the result I am getting in unity and Canvas settings.


texts: Why don't raytracing algorithms include the speed of light?

texts:
From what I understand about ray-tracing, it is instantaneous in its speed from the light source to the user. Is there a type of ray-tracing where the "rays" move at the speed of light or are affected by gravity? Such methods would be useful in simulating large scale systems (like planets).

Also, can the same method be applied to sound?


texts:
I think im on good way to grasp the complete concept of simple hard-edged shadowmapping!
The thing i find the hardest to grasp though is about the individual shadow-render for each light...

Since the example shadowmap-textures i have looked at are normal textures with a width and height as any other texture and does not cover the entire area around the light but only the area within a normal view-frustum i cannot help but wonder if it is about rendering a shadowmap for each light AND object with the camera centered on the object in each render?

I think it feels weird since this would create an exponential growth in the number of shadowmaps used in proportion to lights and objects.

I've had a hard time finding information on the subject and simply find it confusing...

So my question basicly is if this is how it works or if im missing something else?

By the way, if this question is confusing it might be because i have mostly learned this from the perspective of deferred shading but i dont think that should make much of a difference, right?

If you would use code-examples to explain something i would appreciate C# syntax by the way...


texts:
I am trying to render a 3D cube in the R programming language, and add a texture to each cube face.
So far I have this code that draws the cube:
library('rgl'); library('magrittr')

cube <- function(x=0,y=0,z=0, bordered=TRUE, filled = TRUE, lwd=2, scale=1, fillcol = gray(.95),bordercol ='black', ...)
{
     mycube <- cube3d()
     mycube$vb[4,] <- mycube$vb[4,]/scale*2

     for (i in 1:length(x)) {
        if (bordered) {
            bcube <- mycube bcube$material$lwd <- lwd
            bcube$material$front <- 'line' bcube$material$back <- 'line'
            bcube %>% translate3d(x[i], y[i], z[i]) %>% shade3d
        }
        if (filled) {
            fcube <- mycube fcube$vb[4,] <- fcube$vb[4,]*1.01
            fcube$material$col <- fillcol
            fcube %>% translate3d(x[i], y[i], z[i]) %>% shade3d
        }
    }
}

But I need help adding a texture to each face. How can I do that?


texts: Enemy collision detection with movie clips

texts:
I have created multiple movieclips with animations within them.  It is an obstacle avoidance game and I cannot seem to be able to get my enemies to contact my playableCharacter. The enemies I have created are each embedded on certain levels of my game. I have created an array, enemiesArray to have each of my enemies placed within it. Here is the code for that:

//step 1: make sure array exists
if(enemiesArray!=null && enemiesArray.length!=0)
{
    //step 2: check all enemies against villain
    for(var i:int = 0;i < enemiesArray.length; i++)
    {
        //step 3: check for collision
        if(villain.hitTestObject(enemiesArray[i]))
        {
            //step 4: do stuff
            trace("HIT!");
            removeChild(enemiesArray[i]);
            enemiesArray.splice(i,1);

            removeChild(villain);
            villain = null;
        }
    }
}

What I am unsure of is whether or not my enemiesArray is actually holding the movieclips I have suggested. If it was, this code would be tracing back a "HIT" for every time I ran into an enemy and would kill my character. It is not doing that however.

I am thinking I have to push my movieclips into my array but I don't know how to do that or where for that matter.

Any and all help would be much appreciated.


texts: How can I create a folder on Android device, download from ftp-server video and save it there?


texts: Why are my scene's depth values not being written to my DepthStencilView?

texts:
I'm rendering to a depth map in order to use it as a shader resource view, but when I sample the depth map in my shader, the red component has a value of 1 while all other channels have a value of 0.

The Texture2D I use to create the DepthStencilView is bound with the D3D11_BIND_DEPTH_STENCIL | D3D11_BIND_SHADER_RESOURCE flags, the DepthStencilView has the DXGI_FORMAT_D32_FLOAT format, and the ShaderResourceView's format is D3D11_SRV_DIMENSION_TEXTURE2D.

I'm setting the depth map render target, then i'm drawing my scene, and once that is done, I'm the back buffer render target and depth stencil are set on the output merger, and I'm using the depth map shader resource view as a texture in my shader, but the depth value in the red channel is constantly 1.
I'm not getting any runtime errors from D3D, and no compile time warning or anything.

I'm not sure what I'm missing here at all. I have the impression the depth value is always being set to 1.

I have not set any depth/stencil states, and AFAICT depth writing is enabled by default. The geometry is being rendered correctly so I'm pretty sure depth writing is enabled.

The device is created with the appropriate debug flags;

#if defined(DEBUG) || defined(_DEBUG)
    deviceFlags |= D3D11_CREATE_DEVICE_DEBUG | D3D11_RLDO_DETAIL;
#endif

This is how I create my depth map. I've omitted error checking for the sake of brevity

D3D11_TEXTURE2D_DESC td;

td.Width     = width;
td.Height    = height;
td.MipLevels = 1;
td.ArraySize = 1;
td.Format    = DXGI_FORMAT_R32_TYPELESS;
td.SampleDesc.Count   = 1;
td.SampleDesc.Quality = 0;
td.Usage          = D3D11_USAGE_DEFAULT;
td.BindFlags      = D3D11_BIND_DEPTH_STENCIL | D3D11_BIND_SHADER_RESOURCE;
td.CPUAccessFlags = 0;
td.MiscFlags      = 0;
_device->CreateTexture2D(&texDesc, 0, &this->_depthMap);

D3D11_DEPTH_STENCIL_VIEW_DESC dsvd;
ZeroMemory(&dsvd, sizeof(dsvd));
dsvd.Format = DXGI_FORMAT_D32_FLOAT;
dsvd.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
dsvd.Texture2D.MipSlice = 0;
_device->CreateDepthStencilView(this->_depthMap, &dsvd, &this->_dmapDSV);

D3D11_SHADER_RESOURCE_VIEW_DESC srvd;
srvd.Format = DXGI_FORMAT_R32_FLOAT;
srvd.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvd.Texture2D.MipLevels = texDesc.MipLevels;
srvd.Texture2D.MostDetailedMip = 0;
_device->CreateShaderResourceView(this->_depthMap, &srvd, &this->_dmapSRV);


texts:
I want the player to be able to save his score when she makes it into top 10 of high scores. Upon success, player will be asked for a name to submit. This does not need to be unique per player. I just want a basic global score board available for everyone who plays the game via web player (from github.io page of the project).
When searched for how to keep high scores, I came across PlayerPrefs.

On Web players, PlayerPrefs are stored in binary files in the following locations:

Mac OS X: ~/Library/Preferences/Unity/WebPlayerPrefs
Windows: %APPDATA%\Unity\WebPlayerPrefs

As far as I understood, the results are kept in local machine and won't be same for everyone.
So it's good for keeping track of your own score, locally.
As a placeholder in the current version of the game, I keep the scores in a local .txt file in the project directory. Can I succeed with this approach and use the github.io server to maintain a global scoreboard or do I necessarily need a database to achieve this goal?


texts: Average points per second in a world editing game

texts:
I am making an online single-player game (open beta here) with a huge emphasis on content creation and world design (sort of like Super Mario Maker or Little Big Planet but more designed for adventure or "short story" games).  The default gameplay style is a sort of Zelda-esque action RPG but it can also handle things like platformers or arcade-style shooters.  "Worlds" can vary greatly in scope, from a single short hallway to basically a full game.

In order to tie all of these diverse worlds together and make travel between them meaningful, I am using a universal currency (called Sparks) that world builders can use as collectibles and give as rewards for defeating enemies or completing challenges, and can also be used to purchase items and so on.  To prevent their abuse and discourage boring "spark farming" worlds, the amount of sparks a player can take from a world is capped based on the amount of time they spent in that world, and the world builder is rewarded for another player exploring their world based on how close the player gets to obtaining a certain percentage of that cap, encouraging them to make it easy to obtain around that amount, and possible for a skilled player to acquire more (making it worthwhile for players to replay their world in order to master it) but not exceeding the cap.

Right now, the cap is one spark per second, and the "ideal average ratio" is one fifth of that.  However, one point every five seconds seems far too low and unrewarding for most kinds of games, especially fast-paced arcade-style worlds where it is not uncommon to beat more than one basic enemy or pick up multiple collectibles per second.  However, setting the cap too high can make spark collection feel meaningless since their total value just looks like "a big number".

I have done some searching for advice or writing on typical scoring rates for different game genres or even the psychological impact of using different scoring methods.  I know that some old arcade games would add a few zeros to their score system to make things feel more rewarding but beyond that I could find very little writing on the subject.  What is a typical "points per second" value that feels rewarding and can work for a large number of possible genres?


texts: How should I track real-time resource generation in a client-server scenario?

texts:
I am currently building a game that has a "City" entity.  These cities generate and consume resources such as food variably over a period of time.  I need to be able query the server often to find exactly how much food the city at any given point.  These queries can take place  multiple times per minute.  There could also be 400,000 cities to track at a given time.

How would you handle tracking these resources?  Would you do it in real time, keeping an instance of the city in memory on the server, with some sort of a snapshot in time of the resources, then computing the growth/consumption from that snapshot time for subsequent queries?  Would you work exclusively with a database, using a similar "snapshoting" scheme?  Maybe a mixture of the 2, caching recently queried cities in memory for a period of time?

There is also a lot of other data that each city needs to track.  A player can queue units to build in a barrack.  The armies available in the city will need to be updated as units complete.

I'm interested in everyone's input on where/when/how you'd manage the real time data.


texts: Calculate corner rotation to fit between 2 waypoints

texts:
I'm currently working on a system where I create a linear path by spawning waypoints, but i'm struggling to figure out how to compute the rotation needed to render the corner waypoints correctly.

if I rotate it towards (nextSegment.Coordinate - myCoordinate) it almost seems correct, most corners are behaving how I want.

but you can see the first 2 corners, and one near the end are incorrect.

if I rotate it towards (prevSegment.Coordinate - myCoordinate) it solves the rotation for the incorrect segments in the previous solution.

I know the coordinate of the next cell, and the previous cell and the cell i'm trying to rotate.

But then the other segments are incorrect. I cannot figure out the pattern on how to decide which segment to rotate towards. Any ideas?


texts:
When calling alDeleteEffects to destroy an effect, is it necessary to first remove it from any auxiliary slots that it may be active in?

I know first removing a buffer from a source is necessary, which makes sense, but I saw no mention of it in the Effects Extension Guide to indicate either way for effects. It seems that effects are more of a state change rather than used actively like a buffer, as any parameter changes require resetting the effect in the slot, so I am leaning towards "no", but wanted to be sure.


texts:
I'm trying to make a quad sphere based on an article, which shows results like this:

I can generate a cube correctly:

But when I convert all the points according to this formula (from the page linked above):

    x = x * sqrtf(1.0 - (y*y/2.0) - (z*z/2.0) + (y*y*z*z/3.0));
    y = y * sqrtf(1.0 - (z*z/2.0) - (x*x/2.0) + (z*z*x*x/3.0));
    z = z * sqrtf(1.0 - (x*x/2.0) - (y*y/2.0) + (x*x*y*y/3.0));

My sphere looks like this:

As you can see, the edges of the cube still poke out too far. The cube ranges from -1 to +1 on all axes, like the article says.

Any ideas what is wrong?


texts: Navigating an AI that shouldn't take the shortest path but the scenic route instead (e.g. fish)

texts:
I'm working on a sidescrolling game with an underwater "fish-like" AI that has some goals (interacting at various locations) and things to avoid (player).

Started of with a Navmesh and simple straight line navigation but since algos like A* always take the shortest path what ends up happening just doesn't look good.

To solve this, I thought I could add some random area penalties to the navigation nodes (currently a grid). I generated these penalties using perlin noise, which did curve the path, but the effect is very minor, because again A* does not like to deviate from a straight line even with big penalties. If you make them too big, it's gonna act like obstacles, which isn't very usable either.

So the question is - how do I achieve something like this?

Thanks


texts: Best client/server architecture for a mobile management game?

texts:
For the past year I have worked on a small company that develops a traditional browser based strategy game, of the likes of Travian or Ogame, but using a more interactive approach like Tribal Wars 2.

The game is made in a simple php server without frameworks and a simple mysql database, and all of the game happens in a single static page that is changed through ajax calls and has a map made in pixi.js. The automatic updates are delivered to the client side through polling the server which then queries some specific database tables made for the purpose for changes.

While this approach is solid and works, it has 2 big problems:

Having a mobile app is increasingly more important and there are not enough resources for having two separate codebases. Having a app which is simply a wrapped webview is also not a solution because the performance of a really complex page with a giant webgl map is, while usable, really subpar;
Polling the server for changes creates a lot of programing challanges that make some simple tasks really complicated and creates a lot of convoluted code if we dont want to hurt the game performance, as we are not going make dozens of database queries every 5 seconds.

I want to start developing a game idea that I have that is basically inserted in the same genre and which is going to be, at least initially, mobile only. The real problem here is that after reading a lot on the internet, I am confused on what should be a good client/server architecture for me to start prototyping in a way that I do not run in the problems mentioned above.

Basically, above all, I want the server to be able to know which page/screen/state is each client looking at, and be able to send them messages when another client changes something on that specific screen. It would also be nice if the solution is something lightweight on the server side to be able to scale a little.

Client side I was thinking about Unity because of being cross platform, of all the environment around it (ads, analytics, a lot of support and answers on the internet), and because I have previous development experience with it.

Server side is the real question.

Simple http calls will not work and so PHP is out of the equation.
I have though about using node.js with socket.io to use websockets solving the polling problem. Is this a good idea? Would it be better to store the game state in a relational or nosql database in this case? Would this work on unstable mobile conections?
Lots of people seem to use a c# and sockets for unity. Would this be overkill in this situation? Taking this approach how would the data be stored? would it be feasible with a linux server or would I need a windows server? Would this work on unstable mobile conections?
Don't know, I'm open to suggestions.

tl:dr: I want to make a mobile management game in unity but am confused what to choose for the server side architecture considering that I want the server to be ablose to send a message to the client without the client asking for it. Is there anything I should take in account?

Sorry for the broad question and thanks for the help.


texts: Libgdx: api fadein() and fadeout() methods are switched?

texts:
I've been trying to create a white-screen fade effect for my libgdx game.

When I run the following code with fadeOut = false, nothing happens (white-screen does not appear because alpha is 0). When fadeOut = true, it works (fades out) until the actors alpha is down to 0.5f, then it rebounds and starts fading in. No clue why.

    if(fadeOut){
        map.setColor(new Color(1, 1, 1, 1));
        addAction(Actions.fadeOut(duration));
    }else{
        map.setColor(new Color(1, 1, 1, 0));
        addAction(Actions.fadeIn(duration));
    }

When I run the exact same code but switch the starting alpha's like this:

if(fadeOut){
        map.setColor(new Color(1, 1, 1, 0)); //notice this is 0 now
        addAction(Actions.fadeOut(duration));
    }else{
        map.setColor(new Color(1, 1, 1, 1)); // notice this is 1 now
        addAction(Actions.fadeIn(duration));
    }

When I run this code with fadeOut = false, nothing happens (screen is all white though, because starting alpha is 1). When fadeOut = true, it actually fades in. sigh...

Here's the draw method i'm running, but I doubt there's an issue there.

@Override
public void draw(Batch batch, float parentAlpha){
    batch.draw(texture, 0, 0);

    //Get the current color of the actor
    batch.setColor(getColor());

    act(Gdx.graphics.getDeltaTime());

}

I really don't know why this is happening, any insight would be valuable.

Thanks!

Edit:
Here's the full code I'm using to call the fades:

I have a "StartScreen" object that gets initialized (and contains the stage), and this piece of code is in it's constructor:

fade = new Fade((int)GdxGame.getWidth(), (int)GdxGame.getWidth(), Color.WHITE, fadeOut, duration);
stage.addActor(fade);

In the same StartScreen class, I have the following code to draw the stage:

@Override
public void render() {
    super.render();
    stage.draw();
}//end render

The following code then calls the "Fade" objects constructor which has the code mentioned above:

public Fade(int width, int height, Color color, boolean fadeOut, float duration){

    this.fadeIn = fadeOut;
    this.duration = duration;

    Pixmap map = new Pixmap(width, height, Pixmap.Format.RGBA8888);

    if(fadeOut){
        map.setColor(new Color(1, 1, 1, 1));
        addAction(Actions.fadeOut(duration));
    }else{
        map.setColor(new Color(1, 1, 1, 0));
        addAction(Actions.fadeIn(duration));
    }

    map.fillRectangle(0, 0, width, height);

    texture = new Texture(map);

    map.dispose();
}

Update: Changing the alpha with this line:

map.setColor(new Color(1, 1, 1, alpha)); to 0.2f or 0.7f works fine. Though that's because it's changing the alpha of the pixmap (and later becomes the texture)- which leads me into investigation of whether fadeOut or fadeIn change the texture's alpha or something else...


texts: Handling Events & User Event Limits In Pygame

texts:
I am trying to make a vertical shoot em up using Python and Pygame. In order to handle timing, such as when certain enemies come out and other stage events, I've been using pygame.time.set_timer().

For example, to start spawning simple enemies, I would do the following:

First setup a USEREVENT:

SPWNGRUNT = pygame.USEREVENT + 0

Then in the main loop, check for events:

for event in pygame.event.get():
    if event.type == self.SPWNGRUNT:
        spawnGrunt()

Then at some point, trigger the event on a timer:

pygame.time.set_timer(SPWNGRUNT, 600)

However, I have quickly ran out of these USEREVENTS. I eventually get the below error:

ValueError: Event id must be between NOEVENT(0) and NUMEVENTS(32)

My questions are this. Is there a way around this? Also, is there maybe a better way of managing timing and events that I am not seeing?


texts: How can I use a display as a background in unity?

texts:
I have a dancing game that I am trying to make and I have a stage where a character dances and a script to switch cameras inside that stage.
What I am trying to do is set those cameras to display 2 and use that display as a background for the place where the game actually takes place.
Is there a way to do that?


texts: Technical term for the border that appears around the screen, usually in response to low health?

texts: This had a strange term but I can't remember what it's called and it's difficult to search for.


texts: Career in game development move: hone developper skills, go indie, or a mix?

texts:
Question

When you have a current stable job as a developer in another field, what is the best course of action to enter the game industry?

Wait (indefinitely?) for an opportunity to sell your skills to an
already established game studio (aiming at the ones with a wide
employee base).
Go indie and start making games with a few artist friends, living on
your savings.
The middle road: try to find a company that will hire you in your
current sector part-time, and use the rest of the week to start an
indie game project.

Some extra background information

I am currently employed as a software developer, working on banking-related systems. While this pays decently, it's not a very glamorous occupation, and I often wish I would be working on more creative projects. Sadly, my limited free time leaves me with little opportunities to take side projects.

I'm now at a turning point of my career, as I'm about to switch companies. I'm wondering if I shouldn't use this opportunity to start my own (indie game) thing.

Being hired by an established game studio is difficult, as I'm a good software developer in my current field, with some experience in management, but my experience does not translate well to the gaming industry (little knowledge of the tools specific to that sector). I would have to go back in terms of salary and responsibilities, and this would both mean not keeping my current lifestyle, and give up on the team management side for a while. Both things I'd rather not do.

If you happen to be working in the game development field (big studios, editors, or indie), and started as a software developer in another sector, I would very much like to know about your experience.


texts: How can I solve the problem of attacking being disadvantageous in TBS due to entering the range of enemy attacks?

texts:
I noticed this thing in Age of Wonders I some time ago, but I can imagine this problem popping up in any other game system where units with equal attack range spend their move points on either moving in range or attacking.

In this game, both sides start far away from each other, not being able to hit each other. They have to spend a couple of turns advancing. At some moment it happens that one player moves their units closer to the enemy units to be able to attack them, but also ends up in the opponent's attacks' range, getting damaged before being able to attack themself. Not very good!

Sometimes it is acceptable and intended, like if I attack an army of cavalry with an army of archers, my opponent is essentially allowed a free attack because cavalry can usually move further than archer's shooting range. But if both armies have equal ranges, the game can turn into a stalemate, because nobody wants to move forward and be hit first. Getting the first strike is so important that it overshadows a strong unit stats advantage.

Even the AI knows to abuse it, waiting for an infinite amount of time before the player attacks. While it is easy to counter this as a player against AI by flanking the enemy ranks in such a way that only one of their units gets in range of many my units and the enemy is forced to advance, a real player could just back off with this unit and wait for me to fully advance, getting hit severely and likely even losing my upper hand if I had one.

Thus, it feels like an example of very bad design. How do I design TBS combat in a similar system so that it is not completely disadvantageous to move in and attack unless you have a range advantage?

The only possible solution that I see is making the ranges more different, so it is less probable to see units with similar attack ranges, but even in that case such a situation r still not impossible. I am sure that some more elegant solutions exist. So, what are they?


texts: My player sprite get stuck to walls while moving along

texts:
Hello,

My player sprite is moving along the wall (not even diagonal, just straight down) and get randomly blocked in the corner of some walls. By blocked, I mean that the Y movement is stopped.
If I move him away from the wall, he might not be blocked again by the same wall and get blocked at some other walls, always at a corner.

The walls are all the same sprite and are of the same size.

I use 2D Box Colliders for the walls. The player sprite has a Box Collider 2D and a RigidBody 2D. I am not using any physics codes, I would just like to make it work with the built-in Unity physics.

I move the player by adjusting the velocity of the rigidbody according to Input:

RigidBody2D rb = GetComponent<Rigidbody2D>();
float horizontal = Input.GetAxisRaw ("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector2 movement = new Vector2(horizontal, vertical).normalized *speed * Time.deltaTime;
this.rb.velocity = movement;

The player is set like this:

Do you have any idea why it behaves like this and how I could fix it?

Thanks for your help.


texts: How can I find multiple starting areas on a procedural map?

texts:
I'm using perlin noise to generate a 2d map, with ground types and natural resources.

When you start a new game I need to place your town hall as well as your opponents in such a way they are on grassland and near natural resources.

For an oversimplification, I have a 2d array of integers where a block of 0s and a couple 1s would be great for starting but anything lower than a 0 would be bad. How can I isolate a few blocks of what I'm looking for, ideally with a distance threshold so town halls aren't next to each other.

How does civilization do this for example?


texts: How do modern game engines handle many shadow casting lights?

texts:
This is a very general question, and not aimed at any particular language or graphics API; I am more interested in the theories & algorithms behind the solutions.

I'm reasonably familiar with the basic idea behind shadow mapping:

Each spotlight and directional light requires a rendering pass to generate it's shadow map, and each point light requires 6 such passes, prior to any lighting calculations.

Such a potentially large number of rendering passes could quite easily have a substantial negative impact on performance and texture bandwidth, so how do modern game engines deal with this problem, especially in the case with deferred rendering systems, where many lights are involved?

Consider the following scenario:

A scene contains a reasonable amount of geometry, spread out over a "level". That level has a certain number (let's say 20, for brevity) stationary point lights dotted around the level. The player can place lights around the level too, and carries a torch (spotlight).

The rendering system uses the deferred shading model, given the potentially high number of lights in the scene.

How does the renderer decide which lights to render shadowmaps for?
Of those lights, during the "light pass", how is that variable number of shadow maps handled dynamically, bearing in mind that they could be 2d textures (spots and directional), or cube maps (points)?

Do graphics API's have the capability to support shaders with arrays of maps/lights, or would the shadow maps require a single discrete lighting pass for each individual light?


texts: Why did the old 3D games have "jittery" graphics?

texts: I've been playing "MediEvil", lately, and it got me wondering: what causes some of the old 3D games to have "flowing" graphics, when moving? It's present in games like "Final Fantasy VII", "MediEvil", and I remember "Dungeon Keeper 2" having the same thing in zoom mode. However, examples like "Quake 2" didn't have this "issue", and it's just as old. The resolution doesn't seem to be the problem, everything is rendered perfectly fine when you stand still. Is the game refreshing slowly, or is it something to do with buffering?


texts: How can I get my Flash game to scale to all mobile device screen sizes?

texts: I want my application to automatically scale its size depending on the screen size. I want my application to fit any screen size automatically. I am making my application for mobile devices, how can I do this? I am fairly new at flash so please make it a bit simple!


texts: OpenGL using quaternion to rotate camera to avoid gimbal lock

texts:
I read in many sources about using quaternion to avoid gimbal lock but I can't apply this practically in my code, so I have a camera class I want to rotate it with mouse so I have Euler angles Pitch and Yaw, I have a camQuat qauaternion to store the rotation quaternion each frame, so I have the initCamera method which initialize the camera:

void Camera::initCamera(glm::vec3& pos, glm::vec3& center, GLfloat yaw, GLfloat pitch) {
    view = glm::translate(view, center - pos);
    camQuat = glm::quat(glm::vec3(glm::radians(pitch), glm::radians(yaw), 0.0));
    camQuat = glm::normalize(camQuat);
    glm::mat4 rot = glm::mat4_cast(camQuat);
    view = view * rot;
    view = glm::translate(view, pos - center);
}

then each frame I update the camera by this method

void Camera::rotate(GLfloat xoffset, GLfloat yoffset, glm::vec3& c) {
    xoffset *= this->mouseSensitivity;
    yoffset *= this->mouseSensitivity;
    view = glm::translate(view, c);
    glm::quat q(glm::vec3(glm::radians(yoffset), glm::radians(xoffset), 0.0f));
    q = glm::normalize(q);
    glm::quat temp(q);
    q = q * camQuat * glm::conjugate(q);
    camQuat = temp;
    glm::mat4 rot = glm::mat4_cast(q);
    view = view * rot;
    view = glm::translate(view, -c);
}

this makes the rotation but with gimbal look, what is the bug in my code or what is the right way to use quaternion to prevent the gimbal look?

Edit: the first image is the normal camera FPS the rotation should be around the x and y axis only (No Rolling), once I rotate around any axis (as I read until the angle becomes 90) the gimbal lock appear and the camera begins to roll around z like the second image.
enter image description here

Solution: due to DMGregory link below this code works fine:

void Camera::rotate(GLfloat xoffset, GLfloat yoffset, glm::vec3& c, GLboolean constrainpitch) {
    xoffset *= this->mouseSensitivity;
    yoffset *= this->mouseSensitivity;
    glm::quat Qx(glm::angleAxis(glm::radians(yoffset), glm::vec3(1.0f, 0.0f, 0.0f)));
    glm::quat Qy(glm::angleAxis(glm::radians(xoffset), glm::vec3(0.0f, 1.0f, 0.0f)));
    glm::mat4 rotX = glm::mat4_cast(Qx);
    glm::mat4 rotY = glm::mat4_cast(Qy);
    view = glm::translate(view, c);
    view = rotX * view;
    view = view * rotY;
    view = glm::translate(view, -c);
}

I get the quaternion for both x and y then post multiply the QX by the view matrix then pre multiply the QY by the view matrix, the idea is rotating pitch globally and yaw locally to avoid unwanted creeping roll.


texts: How to interpolate colors around the spectrum of hues?

texts:
I wanted to generate a 7 segment display whose color brightness varies with time, this can be done by just using linear relationship.
Color activeColour2 = new Color(1, DateTime.Now.Millisecond*0.001f, DateTime.Now.Millisecond*0.001f);

So in 1 complete second, it produce color in the range of (1,0,0) to (1,1,1) as in the code below:
using System;
using UnityEngine;

public class ClockDigit2 : MonoBehaviour
{
    static readonly bool[,] SEGMENT_IS_ACTIVE = new bool[,] {

        {true,  true,  true,  true,  true,  true,  false}, // 0
        {false, true,  true,  false, false, false, false}, // 1
        {true,  true,  false, true,  true,  false, true }, // 2
        {true,  true,  true,  true,  false, false, true }, // 3
        {false, true,  true,  false, false, true,  true }, // 4
        {true,  false, true,  true,  false, true,  true }, // 5
        {true,  false, true,  true,  true,  true,  true }, // 6
        {true,  true,  true,  false, false, false, false}, // 7
        {true,  true,  true,  true,  true,  true,  true }, // 8
        {true,  true,  true,  true,  false, true,  true }  // 9
    };

    public Color32 inactiveColour = Color.black;

    public SpriteRenderer[] segments = new SpriteRenderer[7];

    public void Display(int number)
    {
        Color activeColour2 = new Color(1, DateTime.Now.Millisecond*0.001f, DateTime.Now.Millisecond*0.001f);
        var digit = number % 10;
        if (digit < 0) digit *= -1;

        for (int i = 0; i < 7; i++)
        {
            if (SEGMENT_IS_ACTIVE[digit, i])
            {
                segments[i].color = activeColour2;
            }
            else
            {
                segments[i].color = inactiveColour;
            }
        }

    }

    void Update()
    {
        Display(DateTime.Now.Second);
    }
}

However, now I want to interpolate through all the colors in the circle above over 1 second.
I don't know how to express this as a formula for R, G, and B. The RGB value is not linear relationship: as you spin the selected color in the chart, you can notice the RGBA components vary together in a nonlinear form.
I considered using Lagrangian interpolation. However, this will not be accurate or might fail greatly because if you take a reference point at the circle and assume in 1sec, it made a complete revolution, you will notice there is a certain period of time where the RGB value is constant along the path: either 0 and 1.
So is there any method to get a formula that perfectly fits the color chart with respect to time?


texts: How to add lighting to a 2D Tile-based game in JavaFX?

texts:
I'm making a 2D roguelike tile-based game with Java and JavaFX.  I'm currently working on adding lighting and darkness to the dungeon, but whenever I try running it, it takes a very long time to load, and it eventually gives an out of memory error.

Here is Lighting.java:

package sample;

import static sample.World.worlds;

public class Lighting {
    public static void calculateLighting(int wn, int skyLighting) {
        Block[][][] world = worlds[wn];
        for (int z = 0; z < worlds[Player.cw][0][0].length; z++) {
            for (int y = 0; y < worlds[Player.cw][0].length; y++) {
                for (int x = 0; x < worlds[Player.cw].length; x++) {
                    Block b = world[x][y][z];
                    b.light = skyLighting;
                    if (b.embID == 1) { //test if a block has a torch attached to it
                        for (int distance = 0; distance <= 15; distance++) {
                            for (int x1 = x - distance; x1 < x + distance; x1++) {
                                for (int y1 = y - distance; y1 < y + distance; y1++) {
                                    for (int z1 = 0; z1 < worlds[Player.cw][0][0].length; z1++) {
                                        try {
                                            world[x1][y1][z1].light += 1;
                                        } catch (ArrayIndexOutOfBoundsException ignored) {

                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        for (int z = 0; z < worlds[Player.cw][0][0].length; z++) {
            for (int y = 0; y < worlds[Player.cw][0].length; y++) {
                for (int x = 0; x < worlds[Player.cw].length; x++) {
                    Block b = world[x][y][z];
                    if (b.light > 15) {
                        b.light = 15;

                        //If your number X falls between A and B, and you would like Y to fall between C and D, you can apply the following linear transform:
                        //Y = (X-A)/(B-A) * (D-C) + C
                        //https://stackoverflow.com/questions/345187/math-mapping-numbers
                        //(worlds[Player.cw][x][y][z].light-0)/(15-0) * (1-0.5) + 0.5
                        if (b.sprite != null) {
                            b.sprite = ImgManip.darken(b.sprite, (worlds[Player.cw][x][y][z].light) / (15d) * (1 - 0.5) + 0.5);
                        }
                    }
                }
            }
        }
    }
}

What this is doing is that it first finds torches in the world, and then increases the brightness of each block around it, depending on how far away the torch is.  Then, it takes each block's sprite and makes it darker with the darken() method.  This is what is causing it to take so long. When I just comment that out, it performs just fine, but the lighting isn't there.

Here is the darken() method:

public static Image darken(Image image, double amount) {
        PixelReader pixelReader = image.getPixelReader();
        WritableImage writableImage =
                new WritableImage(
                        (int)image.getWidth(),
                        (int)image.getHeight());
        PixelWriter pixelWriter = writableImage.getPixelWriter();

        for(int y=0; y<image.getHeight(); y++){
            for(int x=0; x<image.getWidth(); x++){
                Color color = pixelReader.getColor(x, y);

                color = color.deriveColor(0,-amount/2d,-amount,0);

                pixelWriter.setColor(x, y, color);
            }
        }
        return writableImage;
    }
```


texts: Lighting doesn't work properly in WebGL build only at one place

texts:
So I have a 2d game where a player walks around the level (top view) with a flashlight in front of him. Everything works fine in the editor, however whenever I build it for WebGL and test it in my browser, one room only one, has a problem with lighting, and as I walk in different parts of the room lighting changes in a weird way, and the floor is blinking in the first half of the room, as well as the flashlight is barely visible (if at all).

Here's how it looks in the editor and is supposed to look like:

And here's a few screenshots from the web build:

P.S. Everything works fine in a standalone build.

Also there seems to be no problem when I disable the 4 lights (the whole room works fine), these are the lights (the ones that look like from a window):


texts: Google Play Game Services real-time multiplayer secure game data architecture

texts: Is it secure to allow all game clients in a multiplayer game session to store sensitive opponent player data which should be revealed in the UI only upon a certain action (e.g. enemy building type only revealed after the player has hit the building) to save network traffic? Clients could then calculate public ("visible to them") information to render on the UI on their own after the action has taken place (without the need for a response from the server providing the type of building which was destroyed in this example). Or is this approach too insecure, provided Android app data can be compromised revealing sensitive opponent information, which otherwise would only be revealed on demand while progressing through the game session?


texts:
I have an animation and I modified some rotations of some bones in the animation at a certain frame. What I want to do is how to make the animation in the next couple of frames interpolate smoothly so that the changes I made looks smooth?
Like for example, if I have an animation of a game object, and in frame number 100 it rotated 90 degree in the x-direction. So now frame 100 has a modified rotation angle of the object, but frame 101 has the original animation. I want to smooth the rotation so that the transition of the obect from the modified frame back to the original animation looks smooth.


texts: How to avoid ai hands or any body part going inside wall or ground? (Unreal Engine4)

texts: Whenever my character get killed near wall his hands or any body part its goes through the wall making it look like half of the hands front of wall and another half through back. but i dont like it.. i want it look like modern game where if i killed him near wall it should be realistic where his body part should change posistion according to it. like lifiting his hand because he cant put his hands through wall and also i made a little mistake in my death animation making the hands below the ground so whenever he get killed his hands go through ground.. so how to make this work?


texts: Algorithm to modify a color to make it less similar than background

texts:
I'm creating a demo of 20 balls bouncing each other, with a background filled with a solid color. Color for each ball is chosen randomly with randint(0, 255) for each R, G, B tuple component.

Problem is some balls end up with a color that is very similar to background, making them hard to see. I would like to avoid that, either by rolling another color if the chosen one is too similar (within a given threshold), or by moving it away from the background color.

How to calculate a similarity index to use as a threshold? Or how to transform a color to make it, say, less blue-ish?

Obvious disclaimer: I know nothing about color theory, so I don't know if the above concepts even exists!

I'm coding in python, but I'm looking for concepts and strategies, so pseudo-code is fine (or just the theory).

EDIT:

To clarify a few points:

Each ball have its own random color. I'd like them to remain as random as possible, and to explore as much as possible of the color space (be it RGB or HSV, pygame accepts both formats for defining color)
I'd just like to avoid each color of being "too close" to background. Problem is not just about hue: I'm perfectly OK with a light-blue ball against a dark-blue background (or a "full-blue" against a "white-ish" blue, etc)
For now, I don't care if a ball ends up with a color similar (or even identical) to another ball. Avoiding that is a bonus, but it's a minor issue.
Background color is a constant, single RGB color. For now I'm using "basic" blue (0, 0, 255), but I'm not settled with that. So consider the background to be of an arbitrary color (with arbitrary hue, brightness, saturation, etc).

EDIT2:

TL,DR version: Just give a way to create X random colors so that none "fades in too much" against a background of arbitrary (but single and constant) color


texts: What exactly are sprites and entities and what are the differences between the two?

texts:
Well I was looking at a few game based tutorials, as well as articles. I found out about two terms:
Entities and Sprites. Now they seem related but different, what is each and how are they the same and/or different?
I have some basic ideas already:

An entity is an item/thing/object/person any object that can be interacted with in the world.

A sprite is like an entity, but usually for NPCs/players/monsters.

Or a sprite can be the name of a picture assigned to a specific entity.

Do I have the right idea or are sprites and entities something completely different?


texts: Recreating Common "Glowing Pillar" Effect in UE4

texts:
I've noticed a common "glowing pillar beacon" effect in a few games lately (Overwatch, Fortnite, etc). The effect provides a translucent glowing beam pointing upwards that tapers off towards the top and fades out.

I'm attempting to recreate the effect and was wondering if this is some form of particle emitter and what is involved in the effect?

Thanks!

Examples:


texts: What's the rationale for different coordinates systems?

texts:
Could someone explain to me why Blender and other 3D modeling apps switch axes?

If I export model with Blender, then exporters do following things for the same model:

The 3DS format applies this transform matrix:

     [ 1.0, 0.0, 0.0, 0.0 ],
     [ 0.0, 0.0, -1.0, 0.0 ],
     [ 0.0, 1.0, 0.0, 0.0 ],
     [ 0.0, 0.0, 0.0, 1.0 ]

The Collada format applies this transform matrix:

     [ 1.0, 0.0, 0.0, 0.0 ],
     [ 0.0, 0.0, -1.0, 0.0 ],
     [ 0.0, 1.0, 0.0, 0.0 ],
     [ 0.0, 0.0, 0.0, 1.0 ]

The OBJ format (default) transforms axes just like a transform matrix was applied, but OBJ format (Forward Y, Up Z) gives the original values that I see in Blender. The PLY format also does nothing and I get same values I see in Blender.

PS

Question was edited. I do not ask why there are different coordinate systems.
I understand that.

I do not understand why Blender and other switch axis silently when model is exported.

People in comments say:

It is easy to fix model after export
There are people who needs that.

Actually I never seen these people and if it easy to fix then it is more easy to switch axis for those who really need that switch.

I would love to hear someone who say that axis switch is important and he/she needs in real work (not in theory)


texts: Turning a game into a server-client game

texts:
I'm redoing a game i wrote in XNA to Unity. The XNA game was the client to a server I wrote as a console application.

How does Unity work with a server exactly, and how do you set that up?


texts: Creating an OpenGL FPS camera: I have the position and orientation vectors, now what?

texts:
I have been struggling to create a first person camera in OpenGL ES 2.0 without using gluLookAt(). I grab the camera's orientation vectors (the way it's looking) from the current modelview matrix, and use that to calculate the new forward/backward (Z) translation value. I then calculate the strafe (X) value from the dot product of Z and Y (which is always 1.0). So, I have all the information I need to create a view matrix, but how do I do that without using gluLookAt? Almost all the examples I've seen use gluLookAt, but no such function exists in OpenGL ES 2.0. Besides, one of the moderators on cprogramming.com mentioned that gluLookAt is not appropriate for FPS cameras:

http://cboard.cprogramming.com/game-programming/135390-how-properly-move-strafe-yaw-pitch-camera-opengl-glut-using-glulookat.html

I am really confused by all the conflicting information I'm getting. I just want to create a first person camera that goes forward (W,S keys), side-to-side (A,D keys) and rotates around its center (Y axis only), Wolfenstein style.

Here's more-or-less my existing code:

vec4 cur_look,dir_move,dir_strafe,cam_pos;
mat4 mat_modelview,mat_rot,mat_temp;
float lr; //left/right keypress increment value
float ud; //up/down keypress increment value

//grab current camera orientation (look at) from the modelview matrix
cur_look[0] = mat_modelview[8];
cur_look[1] = mat_modelview[9];
cur_look[2] = mat_modelview[10];
cur_look[3] = mat_modelview[11];

//rotate the direction vector using the rotation matrix
mat4_identity(mat_rot);
mat4_identity(mat_temp);
mat4_rotate_Y(mat_rot,mat_temp,lr); //create rotation matrix

//multiply the current direction vector by the rotation
//matrix and place the result in dir_move
mat4_mul_vec4(dir_move, mat_rot, cur_look);

//normalize the fwd/back direction vector
vec4_norm(dir_move,dir_move);

//calculate strafe vector using cross product of Z and Y
vec4_cross(dir_strafe,dir_move,(vec4){0.0,1.0,0.0,0.0});

//normalize strafe vector
vec4_norm(dir_strafe,dir_strafe);

//detect key input

//FWD/BACK
if(key_pressed == 'w'){
    cam_pos[2] += (dir_move[2] * -INPUT_SENS_Z); //z
}
if(key_pressed == 's'){
    cam_pos[2] += (dir_move[2] * INPUT_SENS_Z); //z
}

//ROTATION
if(key_pressed == LEFT_ARROW){
    lr += INPUT_SENS_ROT;
}
if(key_pressed == RIGHT_ARROW){
    lr +=  -INPUT_SENS_ROT;
}

//build new modelview matrix
mat4_identity(mat_modelview);

//multiply modelview matrix by rotation matrix
mat4_mul(mat_modelview,mat_modelview,mat_rot);

//create translation matrix
mat4_translate(mat_tran,-cam_pos[0], 0.0, -cam_pos[2]);
//multiple modelview matrix by translation matrix
mat4_mul(mat_modelview,mat_modelview,mat_tran);

//update uniforms and draw scene using glDrawArrays()
glUniformMatrix4fv(loc_modelview, 1, GL_FALSE, mat_modelview);

Any help on this would be much appreciated!


texts: How do you send game data from/to server?

texts:
Recently I've learned about running my clients and servers on separate threads than main, and I was able to send string data back and forth, open/close sockets, etc.

Now I'm curious: How do I send gameobject data (transform, variables, actions, etc.) between server and client? I understand how you turn data into bytes with GetBytes() and then into strings with GetString(), but how do you deal with any other data types, like Gameobjects, or Transforms?

I have tried changing everything to strings, then bytes, then back to strings, but I honestly don't even know where to start otherwise, as this seems excessive and wrong.

Important information I almost forgot to mention:

I am not using the unity built in networking tools, as this is for my own education.
I'm using a Udp server and client, all coded in C#, currently using MonoBehaviour(which I can remove if necessary)
Being it's all c# Udp, I'm using UdpClient and Sockets.

Thanks in advance for any help, if more information is needed to clarify anything feel free to ask!


texts: How to handle Entity Initialisation and Destruction

texts:
I've been using the ECS pattern for a while now and, as the complexity of the game increased, I started having issues with the timing of the entity initialisation and destruction code.

I'll use the Physics as the example, but the same principles apply to most other aspects as well.

First a few definitions:

PhysicsModule - the low level physics system (usually an external library like box2d) - has no idea about ECS
PhysicsSystem - an ECS system - works as an iterface between the low-level module and the rest of the ECS
EntityWorld - the object responsible for creating and destroying entities and associating them to Systems

For example, a typical scenario goes like this:

1) An Entity gets created from external data (Transform, ShapeData, CollidableData)
2) The data has to be registered with the PhysicsModule (using ShapeData and CollidableData)
3) Every frame, the PhysicsSystem asks the PhysicsModule for the position of the related object and updates the Transform. Repeat for a while.
4) The Entity gets destroyed in another System far a way
5) The PhysicsModule needs to be told to remove the associated physics object

The problematic steps are 2) and 5).
I can think of two ways of handling this.

Have the PhysicsSystem handle the lifecycle.

Pros:

the logic is encapsulated in one System

Cons:

the PhysicsSystem needs to know about the init data (ShapeData, CollidableData) which is useless after the initial registration with the PhysicsModule
the EntityWorld has to keep track which entities were freshly added or removed from a system to notify it about them
the destruction of the entity has to be delayed in order for its components to still be accessible in the same frame
this approach often causes long chains of events (spanning a couple of frames) which are difficult to follow

In order to make this work, the main loop always ends up being a complete mess to make sure particular inits, updates and destroys are done in the correct order.

Have one place for all the init and destruction code.

Pros:

the init data is not used beyond the initial registration
the init / destroy code is in one place
all the cleanup can be done in one frame in the correct order

Cons:

this essentially becomes the God Object and knows about everything in the game
the whole thing probably becomes very cluttered with all the possible permutations
the destruction of the entity has to be delayed in order for its components to still be accessible in the same frame

At the moment my game evolved into the first solution and I'm having quite a few issues so I'm thinking about trying another approach. The second one I mentioned seems a bit better, but it does involve a God Object and from my experience that is a bad way of doing things.

Also, I took a look at various ECS implementations and noticed that some of them have methods to notify systems that entities were added/removed to them and some of them don't - so there's obviously various approaches to this.

My question is - Is there another way of handling Entity Initialisation and Destruction without resorting to either the God Object or the God Loop?


texts:
I'd like to implement a trail (like the white circles in Angry Birds) that chase my sprite. I already used CCMotionStreak, but the trail texture is "stretched" instead.

Anyone has an idea how to make this?


texts: Are weapon names or pictures copyrighted/licensed?

texts: Will I get a copyright strike or something if I use a picture of a weapon and the name of it? (e.g. a shop where you can buy guns, AK-47 with the pic)


texts:
Why do people use this:

public void set(Vector2 v) {
    this.vector2 = v.cpy();
}

insted of just using:

public void set(Vector2 v) {
    this.vector2 = v;
}

What I don't know that I should know?


texts:
Hey all, you may remember me asking a question regarding a snake game I was creating about two weeks ago.

Well I'm quite far now into making the game (thanks to a brilliant tutorial I found). But I've come across the error described named above.

So heres my problem;

I have a SnakeFood class that has a method called "Reposition". In the game1 class I have a method called "UpdateInGame" which calls the reposition method to load an orange that spawns in a random place every second.

My latest piece of code changed the reposition method to allow the snake I have on the screen to not be overlapped by the orange that randomly spawns.

Now I get the error (in full):

Error   1   Inconsistent accessibility: parameter type 'TheMathsSnakeGame.Snake' is less accessible than method 'TheMathsSnakeGame.SnakeFood.Reposition(TheMathsSnakeGame.Snake)'   C:\Users\Tom\Documents\Visual Studio 2008\Projects\TheMathsSnakeGame\TheMathsSnakeGame\SnakeFood.cs 33  21  TheMathsSnakeGame

I understand what the errors trying to tell me but having changed the accessiblity of the methods, I still can't get it to work.

Sorry about the longwinded question.

Thanks in advance :)

Edit: Code I'm using

 (Game1 Class)
private void UpdateInGame(GameTime gameTime)
    {
        //Calls the oranges "reposition" method every second
        if (gameTime.TotalGameTime.Milliseconds % 1000 == 0)
            orange.Reposition(sidney);
        sidney.Update(gameTime);
    }

(SnakeFood Class)
 public void Reposition(Snake snake)
    {
        do
        {
            position = new Point(rand.Next(Grid.maxHeight),     rand.Next(Grid.maxWidth));
        } while (snake.IsBodyOnPoint(position));
    }


texts: Collision stickyness problem on multiple inputs

texts:
I've been trying for a couple of days to solve an issue I'm having with top-down 2D collisions, whenever I collide with tiles that have adjacent collidable tiles my player sticks to the wall, If I collide right or left I can't move up or down, the same for the Y axis, I can't move left or right when colliding from the top or bottom. Here's a picture to represent my issue a bit better:

The gray boxes represent the collision area.

Here is my code:

            Rectangle tileRect = new Rectangle((int)tile.Position.X, (int)tile.Position.Y, tile.SourceRect.Width, tile.SourceRect.Height);
            Vector2 temporaryPlayerPosition = player.Sprite.Position - player.Velocity;
            if (player.CollisionBox.Intersects(tileRect))
            {
                if ((player.CollisionBox.Right >= tileRect.Left && player.CollisionBox.Right < tileRect.Right) ||
                    (player.CollisionBox.Left <= tileRect.Right && player.CollisionBox.Right > tileRect.Left))
                {
                    player.CollisionBox.X = (int)temporaryPlayerPosition.X;
                    player.Sprite.Position.X = temporaryPlayerPosition.X;
                }
                if ((player.CollisionBox.Bottom >= tileRect.Top && player.CollisionBox.Bottom < tileRect.Bottom) ||
                    (player.CollisionBox.Top <= tileRect.Bottom && player.CollisionBox.Top > tileRect.Top))
                {
                    player.CollisionBox.Y = (int)temporaryPlayerPosition.Y;
                    player.Sprite.Position.Y = temporaryPlayerPosition.Y;
                }
            }

If anyone could point me to the right direction I would be grateful!! Thanks again!

EDIT!!!

I changed my whole collision code so it does a forward check before handling the displacemente of the sprite, I still have the stickyness issue though. This is the new code:

Rectangle forwardCollision = new Rectangle((int)(player.CurrentPos.X + (player.Velocity.X*4)), (int)(player.CurrentPos.Y + (player.Velocity.Y*4)), player.Sprite.SourceRect.Width, player.Sprite.SourceRect.Height);
player.CanRunX = player.CanRunY = true;
foreach (TmxTile tile in tileList)
{
    tile.Update(gameTime);
    Rectangle tileRect = new Rectangle((int)tile.Position.X, (int)tile.Position.Y, tile.SourceRect.Width, tile.SourceRect.Height);
    if (forwardCollision.Intersects(tileRect) && SolidTileIds.Contains(tile.Id))
    {
        if (player.Velocity.X != 0)
            player.CanRunX = false;
        if (player.Velocity.Y != 0)
            player.CanRunY = false;
    }
}
foreach(DebugRectangle rectangle in rectangleList)
{
    rectangle.Update(gameTime);
}

if (player.CanRunX)
    player.Sprite.Position.X += player.Velocity.X;
else
    player.Sprite.Position.X -= player.Velocity.X;
if (player.CanRunY)
    player.Sprite.Position.Y += player.Velocity.Y;
else
    player.Sprite.Position.Y -= player.Velocity.Y;

player.CurrentPos = player.Sprite.Position;
player.CollisionBox.X = (int)player.Sprite.Position.X;
player.CollisionBox.Y = (int)player.Sprite.Position.Y;
player.DebugRectangle.Position.X = forwardCollision.X;
player.DebugRectangle.Position.Y = forwardCollision.Y;


texts: Making a way to fight monsters in my clicker game

texts:
I want a working next and previous button for killing monsters http://prntscr.com/o375y7 http://prntscr.com/o37609   Im new to this concept so i don't know how to go about doing this.

html code(all i have so far)

 <button onclick="Fight()" id="Fightbtn" >Fight</button> Rat &nbsp; Hp:10

&#8249;
&#8250;

The "Rat" in the middle of the button stuff should be like "span id="currentenemy" span" just didnt know how to set up my switch statement or array to be able to switch between current enemy, hp and damage from clicking the next button. if someone can help me set it up id appreciate it. never used this concept before.

I expect after my program is running for the next button to be by itself disabled until you kill a rat 10 times then it becomes enabled then after you click it for the enemy to change and hp to change(damage to) then the previous arrow will become unhidden. But my actual output i can't get this to work.


texts: How to play a sound only one time in XNA?

texts:
I'm using a sound when a key is pressed, like a fire. But despite that I'm pressing the key for just a short moment, the sound is playing so many times. I guess it's because of the Update method that updates it all 60 times per second.

Is there a way to play the sound only one time, until I press the next time? I also have the same problems with sprites when they hit the border a short "bang" sound is played, but it dosen't sounds like it should do! I guess it playes to many times!?

Help id preciated to solve this! Thanks!

if (keyboardState.IsKeyDown(Keys.Space))
{
code play sound and activate a sprite
}


texts: remove sudden upward & downward jerk from camera

texts:
I have a scene with low poly assets & NavMesh enabled for character navigation. When player climbs the bridge there's a sudden upward jerk in camera. Also, when the player comes down, there's a downward jerk in Camera.

I want the camera movement to be smooth so it appears as if the y-axis of the camera is floating like a drone. Below is my script that I'm using

public class FollowCamera : MonoBehaviour {

float MIN_X = -26.72f;
float MAX_X = 34f;
float MIN_Z = -6.22f;
float MAX_Z = 47.6f;
float MAX_Y = 15f;
float MIN_Y = 0.6f;

public float startYPositionOfCamera;

// The target we are following
public Transform target;
// The distance in the x-z plane to the target
public float distance = 10.0f;
// the height we want the camera to be above the target
public float height = 5.0f;
// How much we
public float heightDamping = 2f;
public float rotationDamping = 3.0f;

[AddComponentMenu("Camera-Control/Smooth Follow")]

void Start()
{
    startYPositionOfCamera = transform.position.y;
}

void LateUpdate()
{
    // Early out if we don't have a target
    if (!target) return;

    // Calculate the current rotation angles
    float wantedRotationAngle = target.eulerAngles.y;
    float wantedHeight = target.position.y + height;

    float currentRotationAngle = transform.eulerAngles.y;
    float currentHeight = transform.position.y;

    // Damp the rotation around the y-axis
    currentRotationAngle = Mathf.LerpAngle(currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);

    // Damp the height
    currentHeight = Mathf.Lerp(currentHeight, wantedHeight, heightDamping * Time.deltaTime);

    // Convert the angle into a rotation
    var currentRotation = Quaternion.Euler(0, currentRotationAngle, 0);

    // Set the position of the camera on the x-z plane to:
    // distance meters behind the target
    transform.position = target.position;
    transform.position -= currentRotation * Vector3.forward * distance;

    // Set the height of the camera
    transform.position = new Vector3(transform.position.x, currentHeight, transform.position.z);

    // Always look at the target
    transform.LookAt(target);

    // Clamp the position of camera so it doesn't go back of mountains
    transform.position = new Vector3(
            Mathf.Clamp(transform.position.x, MIN_X, MAX_X),
            Mathf.Clamp(transform.position.y, MIN_Y, MAX_Y),
            Mathf.Clamp(transform.position.z, MIN_Z, MAX_Z)
        );
}

}


texts: Box2dWeb: setting velocity of bodies using events

texts:
I would like to move a kinematic box by pressing the down arrow. As is noted by the console logs, the keydown actually does change the box's velocity... but for reasons beyond my grasp it still doesn't move.

Note that if you place the SetLinearVelocity() call in a spot where it runs immediately, the box will move, but if it is in a setTimeout, or as in my example, called from an event, the box stays frozen despite its y velocity property changing to 1.

I created the simplest example I could to show my problem.

Note: I am using the latest release of Box2dWeb

//std variables
     var   b2Vec2 = Box2D.Common.Math.b2Vec2
        ,   b2BodyDef = Box2D.Dynamics.b2BodyDef
        ,   b2Body = Box2D.Dynamics.b2Body
        ,   b2FixtureDef = Box2D.Dynamics.b2FixtureDef
        ,   b2Fixture = Box2D.Dynamics.b2Fixture
        ,   b2World = Box2D.Dynamics.b2World
        ,   b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape
        ,   b2DebugDraw = Box2D.Dynamics.b2DebugDraw;

//create world and gravity
     var world = new b2World(
           new b2Vec2(0, 10)
        ,  true
     );

//fixture defs
     var fixDef = new b2FixtureDef;
     fixDef.density = 1.0;
     fixDef.friction = 0.5;
     fixDef.restitution = .2;

//body defs
     var bodyDef = new b2BodyDef;
     fixDef.shape = new b2PolygonShape;
     fixDef.shape.SetAsBox(2,2);
     bodyDef.type = b2Body.b2_kinematicBody;
     bodyDef.position.x = 3;
     bodyDef.position.y = 0;

//body and fixture creation
     var body1 = world.CreateBody(bodyDef);
     body1.CreateFixture(fixDef);

//"Before" console log
     console.log("Claimed velocity before down is pressed: " + body1.GetLinearVelocity().y);

//Listener and keycode switch for intended velocity change
     window.addEventListener("keydown", onKeyDown, false);
     function onKeyDown(e) {
        switch(e.keyCode) {
            case 40://down
                body1.SetLinearVelocity(new b2Vec2(0,1));
                console.log("Claimed velocity after down is pressed: " + body1.GetLinearVelocity().y);
        }
     }

//debug drawing
     var debugDraw = new b2DebugDraw();
        debugDraw.SetSprite(document.getElementById("canvas").getContext("2d"));
        debugDraw.SetDrawScale(30.0);
        debugDraw.SetFillAlpha(0.5);
        debugDraw.SetLineThickness(1.0);
        debugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit);
        world.SetDebugDraw(debugDraw);

     window.setInterval(update, 1000 / 60);

//loop
     function update() {
        world.Step(1 / 60, 10, 10);
        world.DrawDebugData();
        world.ClearForces();
     }


texts: How to rotate an object to a specific transform?

texts: I am working on a car racing game and there are some times when the car rotates and ends up on its roof. On those situations I want the car to respawn on the same location. What can I do to rotate it so the car ends up on its wheels?


texts: Understanding DeviceContext and Shaders in Direct3D/SlimDX

texts:
I've been working through this tutorial about drawing triangles with SlimDX, and while it works, I've been trying to structure my program differently than in the tutorial.

The tutorial just has everything in the main method, I'm trying to separate components into their own classes. But I'm not sure where certain components belong: namely, contexts and shaders.

The tutorial (as it's just rendering one triangle) has one device, one swapchain, one device context and one set of shaders. intuition says that there is only one device/swapchain for one game, but with contexts I don't know.

I made a Triangle class and put the vertex stuff in there. Should it also create a context? Should it load its own shaders? Or should I pass some global context and shaders to the triangle class when it is constructed? Or pass the shaders and construct a new context?

I'm just getting started with 3D programming, so in addition to answering this question, if anyone knows of a tutorial or article or something about the larger-scale structure of a game, I'd be interested in seeing that as well.


texts: How to store the progress of multiple users

texts:
When I start my game, it displays a level menu, and When I select a level, it's gonna create a game corresponding to the level and  I can play.
Now I'd like to store the progress of each user, implementing something like this but I don't know where to start.

public class Game {

    private Level level;
    // Each level are stored in a txt file,
    // the class Level read and load the file.

    public Game(Level level) {
        this.level = level;
    }

// Other methods.. such as Undo, restart etc...

}

I have created a login system in a class called User where it stores the data in a map.

And I need a class that link them so I created a new class but I'm not sure what kind of method it should contain  :

public class MoveTheBlock{

    private User currentUser;

    public MoveTheBlock() {

    }

}


texts: Do you really have to sync Physics over the network?

texts:
Let's say you want to create a 2D game where a character can shoot a bullet. You have the same code running on the Client and Server (JavaScript so it's exactly the same code).

If the client and the server create the same bullet instance at the same tick X, with the same position, direction and velocity, is it safe to assume that the bullet will end on the same place on both the server and the client? Does the server need to send back the exact position at which the bullet collided, or can the client just predict that as it uses the same physics and same bullet initial data.

Can the bullet hit the target on a different tick, or at a different position on the server from the client? My initial thought is that this shouldn't happen, but could this happen because of a different CPU architecture or a different JavaScript engine?


texts: Algorithm for generating levels for shooting game

texts: I have a shooting game made in Java. It's based on time, i.e you have to shoot the objects before the time runs out. Everything is working fine, except that I'm trying to implement an algorithm to generate levels. I implemented one that increases the number of game objects and increase their speed, but I don't know how to give the player an appropriate time based on these factors to provide an appropriate challenge for the player.