texts: Security-minded design patterns / paradigm for client/server application

texts:
I am working on a client/server application and am starting to take it from proof-of-concept to actual implementation.  The client is an Android application and the server is in PHP.  In similar applications, I'd always simply created a PHP class with appropriate MySQL calls to return JSON objects.

This particular application is a game where clients will end up interacting with each other.  My goal is to start with a good basis for security so that I can avoid issues in the future such as duping or other scamming techniques.  Obviously, good separation of client and server is one of the keys.  Normally I would move to an MVC approach, however it has been suggested that a more RESTful design (e.g., here) would be more secure (or at least a better approach), but I don't really see the benefit other than using a different paradigm.

My question then is twofold.  For a client/server application where clients may need to interact/chat/trade, what is a proper paradigm / design pattern to base a server on.  Second, is a RESTful design necessary in this case, or is it a programmer's preference?

Edit: I may have had a misunderstanding of REST, and have done some more reading.  A more precise question for this community, then, would be what should I build into my API at the outset of development to ensure that I don't run into security issues involving user interactions.  For example, say that two users indicate that they wish to trade.  My current approach would be for User1 to send the trade request to the server, which then delivers it to User2.  Each selects the items to be traded, and that information is passed between each client to the server, which then notifies the opposite client as to the details of the trade.  Upon acceptance from each client (either no time limit or a fairly longish time limit...this is not a real-time game), the server then swaps whatever database entries make up the particular inventory selection between the appropriate users.

A second example would simply be a client/server interaction.  Assuming that I am limiting client actions to be Attack MonsterA or Defend or Attack MonsterB (in the form of buttons), do I need to consider much from a security perspective other than validating that the client can in fact perform whichever action has been sent?


texts: Implementing Geometry Instancing in DirectX

texts:
I have a project that I'm doing in Managed DirectX (DX9) where I want to render lots of grass. My current method (many draw calls) is slow, but I've heard Geometry Instancing can fix that.

I know that I have to have one vertex buffer to store the vertices that will drawn multiple times. I know that I need another vertex buffer to store the transformations (from what I've seen you can only have one additional vertex buffer). So should the second vertex buffer store transformation matrices? I tried coding this, but when I want to create a new vertex buffer one of the required parameters is vertexFormat, but I can't supply a vertex format since this is a matrix.

I also wanted to try to have the second vertex buffer store the translation values as Vector3, but how do I tell DirectX that the values in the second vertex buffer are to be used as translation values? Secondly, I also need rotation values. Do I store these in a third vertex buffer?

Basically, I want to use geometry instancing to draw multiple instances of a  quad that are rotated and translated.


texts: Problem modifying GameObject in list of GameObjects Unity

texts:
So I've been working on a little project that involves Valve's "Portal" style portals, the type where you can seamlessly see what's on the other side and walk through. I've run into a problem when it comes to teleporting an object to it's new location upon hitting the portal. I have a List<GameObject> that contains all the objects that are in close enough range to feasibly travel through the portal, but when I try to modify the transform.position of one of these GameObjects, nothing happens, no error messages.
So I've been going through my script line by line and writing little dummy functions to test different parts of it to see where the problem lies, and everything seems to work up until I index the list and try to modify a value, nothing happens. So was thinking that perhaps the List doesn't actually contain a reference to the GameObject in the scene, but simply a copy of the GameObject's data at the time it was passed into the list. So I checked this by making the list public so that I see it in the inspector, and when I click on an item in the list it highlights that same GameObject in the hierarchy, which suggests it is actually a reference. See bellow...

I am at a loss as to what's happening here and would really appreciate if anyone could offer a suggestion, Here is the dummy function where I try to arbitrarily modify the GameObject data from the List...
        if (Input.GetKeyDown("k"))
        {
            for (int i = 0; i < trackedTravelersObjects.Count; i++)
            {
                trackedTravelersObjects[i].transform.position += new Vector3(0, 30, 0);
                Debug.Log("K");
            }
        }

You'll notice a Debug.Log("k"), this is just to check that the code is actually being called, which it is.
Thanks.


texts: Use arrow keys to navigate between specific toggles, not all UI elements

texts:
I'm making a game where the player needs to select a object out of three and navigates between then with the arrows of the keyboard, and I'm using toggles to make this system.
But the problem is that when I hit play, the navigation mixes the toggles with some other UI elements I dont want to include in the navigation, like sliders and buttons.
How can I lock the navigation for just these three toggles?
I also want to make the navigation switch between these toggles and another three toggles in the middle of the game. How would I change my navigation via script?


texts:
I am searching for a way to create and integrate cinematic in a simple 2D game with XNA for Windows Phone.
I don't know if the best way is to create an animation with sprite and commonly process to animate them... or Is it possible to create the animation with an external tool and read it from the code.

Thanks for your help


texts: What technologies are required for 3D game development?

texts:
I want to make a racing game like Need for speed. And I want to start from very start.
Please tell me the skills, technologies that one should posses while making it.

I am beginner in game development, Although I have good programming skills. I am ready to learn. Please also recommend few good books.

Thanks in advance.

Updated: I am interested in making PC games and I have no intention in making my career in gaming. Also no 2D games, just full-fledged 3D games. Here I don't think like creating a games like pacman or mario are gonna help me. if they, then please pardon me.

Updated: Why should I learn 2D game development? I want to develop a 3D game.


texts: Field of view determination with partially opaque cells

texts:
I'm currently implementing the field of view of a player in a 2D-grid based game. I've chosen a standard ray tracing algorithm because he really fits the features needed in my game.
However, the cells aren't just opaques or transparents. They can be "partially opaques", which means that they decrease the length of the line of the sight more than the others (we don't see as far in water than in the air!). Concretely, the player has a given "vision potential", and each cell has a "vision cost". For each cell crosses by the ray during the ray tracing, I decrease the vision. When it hits zero, I stop the ray.
Things are OK here. But this algorithm leads to some artefacts, as described in the last part of this document:

Ok, we have thrown rays all aroung our @, flagging each cell as visible. When we move aroung the dungeon, we notice some artifacts appearing on some walls, especially when the @ is near the wall.
Since we stop the ray as soon as it reaches a wall, when the ray is almost parallel to the wall, there may be some missing wall cells in the resulting potential visible set. [...] The issue is due to the fact that the ray should keep going until it reaches the other side of the wall and not stop on the first cell. But this is not possible since we have only a boolean 'lightThrough' information  and not the wall orientation.
Fortunately, there is a trivial trick which will allow us to remove those artifacts without adding more information on the cell. It is based on a simple observation : if the player sees a ground cell, he sees the wall behind it. [...]
Thus, our post-processing algorithm consist of :

loop through all cells of the visible map.

if the current cell is a hidden wall and is directly behind a visible ground cell (depending on the region the current cell is in), we can flag it as visible.

The result : on the left, the PVS [potential visible set] without the post-processing step. The yellow arrows show the missing cells. On the right, the PVS with the post-processing step.

The document suggests a post-process treatment, but it obviously doesn't work in my situation. What can I do instead?


texts:
I'm new to this site as well as new in game development, so I need to get a great start for it. Can anybody tell me from where I should start and some books or link are appreciable.
What are the prerequisites to start game programming in java?
I already knows the concepts of java.


texts: Legal issues around forming an international game dev team

texts:
A friend and I have been wanting to collaborate on a mobile app game. It's a 'start small but dream big' kind of venture, where neither of us has much experience, but we're hoping that if we succeed, we could build on it and become a proper full-time game dev studio in the future.

The main issue here is that we're both from different countries, and neither of us wants to risk personal liability in releasing a game without having first formed a LLC. I know the odds of ACTUALLY being personally sued for damages are very low, but it's just not a risk that we want to take.

There seem to be a lot of problems with forming a LLC when both people are in different countries, though. There are multiple laws against having a co-founder, director, or even an employee being someone from a different country.

How do game dev teams or studios consisting of people all around the world get around this problem?


texts: How to only detect Actor and not background

texts:
I'm making a game where I have buttons on a stage, but the background also acts as a "button". But when I press on one of the existing actors on the stage, it also registers a click in the background in addition to the click on the button. How can I fix this?

Inside constructor

button = new ImageButton(getDrawable(new Texture("PlayUp.jpg"))); //only using one image atm
button.setSize(150, 134);
button.setPosition(camera.position.x, camera.position.y);
stage = new Stage(viewport);
        Gdx.input.setInputProcessor(stage);
        stage.addListener(new ClickListener(){
            @Override
            public void clicked(InputEvent event, float x, float y) {
                System.out.println("Background touched");

            }
        });
        button.addListener(new InputListener() {
            @Override
            public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
                return true;
            }

            @Override
            public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
                System.out.println("Button touched");
            }
        });
        stage.addActor(button);

part of render() method

@Override
    public void render(float delta) {
        Gdx.gl.glClearColor(1, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    tapCatch.batch.setProjectionMatrix(camera.combined);
    tapCatch.batch.begin();

    stage.act(delta);
    stage.draw();

    tapCatch.batch.end();

}


texts:
I'm a relatively new programmer attempting to create a simple 2d fighter for fun using the SFML 2 library.  As a game with interaction dependent on what the character is doing, using a state system seems to be the way to go.  I've been trying to incorporate a finite state machine.  My question is, what is the best way to go about this?  Currently I have something like this:

switch (playerstate)
{
case idle:
    if (!onGround)
    {
        playerstate = fall;
    }
    else if (sf::Keyboard::isKeyPressed(controls.Up))
    {
        moveUp();
        playerstate = air;
    }
    else if (sf::Keyboard::isKeyPressed(controls.Down))
    {
        playerstate = crouch;
    }
    else if (sf::Keyboard::isKeyPressed(controls.Right))
    {
        moveRight();
        playerstate = dash;
    }
    else if (sf::Keyboard::isKeyPressed(controls.Left))
    {
        moveLeft();
        playerstate = dash;
    }
    else
    {
        decelOnGround();
    }
    break;
case dash:
    if (!onGround)
    {
        playerstate = fall;
    }
    else if (sf::Keyboard::isKeyPressed(controls.Up))
    {
        moveUp();
        playerstate = air;
    }
    else if (sf::Keyboard::isKeyPressed(controls.Down))
    {
        playerstate = crouch;
    }
    else if (sf::Keyboard::isKeyPressed(controls.Right))
    {
        moveRight();
    }
    else if (sf::Keyboard::isKeyPressed(controls.Left))
    {
        moveLeft();
    }
    else
    {
        decelOnGround();
        playerstate = idle;
    }
    break;
case air:
    if (onGround)
    {
        playerstate = idle;
    }
    else if (sf::Keyboard::isKeyPressed(controls.Up))
    {
        // if numOfJumps > 0, moveUp();
    }
    else if (sf::Keyboard::isKeyPressed(controls.Down))
    {
        fastFall();
    }
    else if (sf::Keyboard::isKeyPressed(controls.Right))
    {
        moveRight();
    }
    else if (sf::Keyboard::isKeyPressed(controls.Left))
    {
        moveLeft();
    }
    break;
case fall:
    if (onGround)
    {
        playerstate = idle;
    }
    else if (sf::Keyboard::isKeyPressed(controls.Down))
    {
        fastFall();
    }
    break;
case crouch:
    if (sf::Keyboard::isKeyPressed(controls.Up))
    {
        moveUp();
        playerstate = air;
    }
    else if (sf::Keyboard::isKeyPressed(controls.Down))
    {
        decelOnGround();
        playerstate = crouch;
    }
    else if (sf::Keyboard::isKeyPressed(controls.Right))
    {
        moveRight();
        playerstate = dash;
    }
    else if (sf::Keyboard::isKeyPressed(controls.Left))
    {
        moveLeft();
        playerstate = dash;
    }
    else
    {
        playerstate = idle;
    }
    break;
default:
    std::cout << "ERROR\n";
}

Which as you can see, there is a lot of repetition and a lot of code.  I haven't even incorporated using different attacks yet (I'm going to have a variety of these).  Am I approaching this the wrong way?  Should I instead have each control be a case instead and branch from there?  Any help is appreciated!


texts: Why does Unity let you install iOS Build Support on Windows?

texts: When installing Unity on a Windows machine, you are allowed to select "iOS Build Support" as one of the components to install. However, it is not possible to make an iOS build from Windows. Why is this package available on Windows? What does it offer?


texts:
On starting the game, a basic startmenu should load. startScreenUI is the background image, and startUI is the buttons for "play" and "exit".

I set Time.timescale to zero in Awake() so that the time would initially be set to zero.

However, the game just plays behind the start screen as normal.

My PauseMenu scripts runs perfectly, pausing the game etc.

My MoveEnemy scripts controls the movement of a wall that moves back and forth between the scene. It moves fine, on pause it stops moving. I should add that the Wall is kinematic and used gravity.

I do not understand why the initial time.Timescale is not set to zero upon starting the game and the game runs normally behind the start screen.

My code for the StartMenu:

using UnityEngine;
using System.Collections;

public class StartMenu : MonoBehaviour
{

public GameObject startUI;
public GameObject startScreenUI;
public PauseMenu otherscript;

  private void Awake() {
    otherscript.enabled = false;
    startUI.SetActive(true);
    startScreenUI.SetActive(true);
    Time.timeScale = 0;
  }

  private void Start() {
    startUI.SetActive(true);
    startScreenUI.SetActive(true);
    Time.timeScale = 0;
  }

  public void Play() {
    startUI.SetActive(false);
    startScreenUI.SetActive(false);
    Time.timeScale = 1;
  }

  public void Quit() {
    Application.Quit();
  }
}

This is my code for the Moving of the Enemy Walls:

using UnityEngine;
using System.Collections;

public class MoveEnemy : MonoBehaviour {
  public Vector3 pos1 = new Vector3 (-7.6f, 1.1f, 7f);
  private Vector3 pos2 = new Vector3(7.6f, 1.1f, 7f);
  public float speed = 1.0f;

  // get StartMenu for bool of startUI

  public StartMenu otherScript;

  // get PlayerController for bool of "dead" to reset the static component manually
  // resets the position of the wall

  void Awake() {
    transform.position = pos1;
  }

  // moves object from pos1 to pos 2
  void Update () {
    transform.position = Vector3.Lerp(pos1, pos2, Mathf.PingPong(Time.time * speed, 1.0f));
  }
}

using the Awake() function was a troubleshooting attempt I heard worked to reset the position of the walls upon restart. But as my game does not restart properly, I do not know if this works fully yet.

and finally this is my code for the Pause Menu that actually works:

using UnityEngine;
using System.Collections;

public class PauseMenu : MonoBehaviour {

  public GameObject pauseUI;
  private bool paused = false;

  void Start() {
  }

  void Update() {
    if(Input.GetButtonDown("Pause")) {
      paused = !paused;
    }

    if(paused) {
      pauseUI.SetActive(true);
      Time.timeScale = 0;
    }

    if(!paused) {
      pauseUI.SetActive(false);
      Time.timeScale = 1;
    }
  }

  public void Resume() {
    paused = false;
  }

  public void Restart() {
  }

  public void MainMenu() {
    Application.LoadLevel(0);
  }

  public void Quit() {
    Application.Quit();
  }
}

Initially I wondered if the problem was associated with the PauseMenu's timescale function interfering with the timescale set on the startMenu, but on disabling the PauseUI completely the game still ran behind the start screen.

Can anyone think of a quick fix to this? I have been troubleshooting for a while and not really getting anywhere.


texts: How do "community patches" for commercial games work?

texts:
For a lot of games, mostly role-playing games (Gothic 3, Oblivion, Skyrim, Titan Quest to name a few), there exist community patches. So, patches that are made by the communities, not by the developers.

How does this work? Most commercial games are not open source.

How can someone without source code access provide a patch?


texts: Is this aiming mechanic usable in a third-person top-down game?

texts:
Long story short: I've switched to a third person - top down perspective. The camera is fixed and looks down at the player. How can I implement 3d aiming ? The player needs to aim left and right as well as up and down.

details:
I've ditched the first person perspective in my current project - I wouldn't call it a game yet, it's more of a test-case. Instead I'd prefer a third person perspective with the user looking down at the player (slightly tilted to the back). The implementation is no problem, the aiming system is. Although the player will be rarely armed there will be situations where he's allowed to return fire.

This is more complicated than it sounds since the player needs to aim up and down. I hope you can envision my problem. In an ego shooter moving the mouse let's the player look up/down and left/right . In a top/down game the mouse points in the direction the player is moving. I'm currently casting a ray from the camera and the player looks at the first collision point of that ray. That means to aim at an enemy the player just needs to hover the mouse over him. Not very comfortable, no skill required at all.

I've thought about this: The player is always centered on the screen, the mouse 2d coordinates are computed to a 2d vector that is used as the player's viewing direction. This way he couldn't look up or down but then again that's only visuals the camera wouldn't be moved in any case. In order to shoot the player presses the right mouse button. The mouse movement is now mapped to the player just as in any common shooter. Mouse up -> look up. Mouse left -> turn left. Don't misunderstand me: I don't intend to move the camera only the player charaTo show the player where he's aiming I then draw a line to his target (or a cone for less precise weapons).

What are possible pitfalls ? Have you done something like this and can tell me if it's usable ? I've never played a game that worked this way and just wonder if it's a good idea

UPDATE: I've accepted an answer but of course I'm still interested in other options. If you've got a good idea that fits here I'd highly appreciate it.


texts: Keystone Correction using 3D-Points of Kinect

texts:
With XNA, I am displaying a simple rectangle which is projected onto the floor. The projector can be placed at an arbitrary position. Obviously, the projected rectangle gets distorted according to the projectors position and angle. A Kinect scans the floor looking for the four corners.
Now my goal is to transform the original rectangle such that the projection is no longer distorted by basically pre-warping the rectangle.

My first approach was to do everything in 2D: First compute a perspective transformation (using OpenCV's warpPerspective()) from the scanned points to the internal rectangle's points und apply the inverse to the rectangle. This seemed to work but was too slow as it couldn't be rendered on the GPU.

The second approach was to do everything in 3D in order to use XNA's rendering features. First, I would display a plane, scan its corners with Kinect and map the received 3D-Points to the original plane. Theoretically, I could apply the inverse of the perspective transformation to the plane, as I did in the 2D-approach. However, since XNA works with a view and projection matrix, I can't just call a function such as warpPerspective() and get the desired result. I would need to compute the new parameters for the camera's view and projection matrix.

Question: Is it possible to compute these parameters and split them into two matrices (view and projection)? If not, is there another approach I could use?


texts: pre-load new scene in unity async but don't show it

texts: I have a top down dungeon crawler in 3D where I show one room at a time. Each room is it's own unity scene. Each room has an exit point that when clicked I fade the screen, load a new scene and then fade in the screen. What I'd like to do, but not sure how, is to pre-load the next possible scenes (note the S, there will be 2 but could be more. 2 because it's the next room or the previous if the player decides to go back) while in one scene. I know the scenes that are possible to get to, but how can I pre-load but not show them and because there is more than 2, I assume if they go in one direction, there is a pre-loaded one that I need to unload. Overall I want to do this to make a faster/smoother transition between rooms, but I want the one room at a time for artistic style.


texts: Why is my enemy object shaking in my AI code?

texts:
My script here is attached to an 'enemy' object. My enemy walks to certain "points" if the player is far away from him. If the player gets close to him, the enemy follows the player. The problem is that after chasing the player, when he escapes, the enemy should walk back to the "points".

Now I see the enemy object shaking and walking far away from the expected direction?!

public class enemyscript: MonoBehaviour {

    public Transform target;
    public Transform[] waypoint; // points
    NavMeshAgent ePath;
    private int farPoint = 0;
    public float elife = 100f,distance,look_range = 20.0f;

    // Use this for initialization
    void Start () {
        ePath = GetComponent<NavMeshAgent>();
        ePath.speed = 2;
    }

    // Update is called once per frame
    void Update () {
        distance = Vector3.Distance(gameObject.transform.position, target.transform.position);

        if (ePath.remainingDistance < 0.5f)
        {
            nextpoint();
        }

        if (distance < look_range)
        {
            attack();
        }
    }

    void attack() {
        ePath.SetDestination(target.position);
        ePath.speed = 6;
    }

    void nextpoint() {
        if (waypoint.Length == 0)
            return;
        ePath.destination = waypoint[farPoint].position;
        farPoint = Random.Range(0, waypoint.Length);
        ePath.speed = 2;
    }
}


texts: How do i get effect when gems come together in godot?

texts:
I'm create gems puzzle game, In my game there is requirement that 2x2 matrix gem will group and then it will convert in power gem. check below image.

I'm new in game development, so anyone can point me out ? any suggestion or link will be helpfull.

Thank you


texts:
I need to move  clipping plane of OpenGL and begin the clipping from that position.
The default location of clipping plane is (0,0,0), so if my model is far enough from the center of coordinate system it immediately disappears, as I begin the clipping, cause it appears in the half clipped by the plane that just moved from (0,0,0) point. So what I need is :

Create a clipping plane
Translate it to the point I want (normally it's near model surface I want to clip)
Begin the clipping from that point and not from (0,0,0).

How can I achieve my goal ?


texts: Only affect pixels in buffer with alpha 0

texts:
I'm working on a transition effect where I have a texture and simply draw that as a pattern to my buffer. Here is a demo, use "e" to start the effect again.
This looks fine but it won't work if the texture has pixels with alpha 0 < x < 1.

This is the texture I used in my demo ( zoomed ):

As you can see the edges are rough and full on opaque. If I do use a texture with softer edges the pixels with alpha will just smear the black away. How can I achieve the effect of pixels in my texture with an alpha of 0 < x 1 to only affect pixels with alpha 0 in my buffer?


texts: How can I achieve a 'warm' scene in Unity using post processing effects?

texts:
I've recently fallen inlove with this Cozy Tavern scene by Beholder, and am looking to replicate it's feel the best I can in unity as a learning exercise.

A lot of the scene's depth is added through lighting, and post processing effects. The lighting is simple enough to where I think I can reasonably replicate it with some trial/error using different lights, however the post-processing is where I get a bit lost.

It's clear that there are a few different effects going on, one of which being the increase in saturation, and a limited depth of field.

My guess is that I would need to write a few different shaders (or rather one?) to add these effects? Any input as to how I could achieve similar results would be greatly appreciated.

No Post Processing:

With Post Processing:


texts: Best way to implement mouse-based movement in MMOG

texts:
I want to design an MMO where players click the destination they want to walk to
with their mouse and the character moves there, similar to Runescape in this manner.

I think it should be easier than keyboard movement since the client can simply send the server the destination each time the player clicks on a destination.

The main thing I'm trying to decide is what to do when there are obstacles in the way.
It's no problem to implement a simple path-finding solution on the client,
the question is if the server will do path-finding as well, since it'll probably take
too much Computation power from the server.

What I though is that when there is an obstacle the client will send only the
first coordinate it plans to go to and then when he gets there he'll send the next coordinate automatically.

For example if there is a rock in the way the character will decide on a route that is made of two destinations so it goes around the rock and when it arrives at the first destination it sends the next coordinate.

That way if the player changes destination is the middle he won't send unnecessary information.

Is this a good way to implement it and is there a standard way MMOGs usually do it?

EDIT: I should also mention that the server will make sure all movements are legal and there aren't any walls in the way etc. In the way I wrote it should be quite easy since all movements will be sent in straight lines so the server will just check there aren't any obstacles along that line.


texts: How not to show ads to paid customers when I decided to make it free?

texts:
I am planning to publish a paid game built with Unity. After a while I will update the game as free and will start showing ads. But I do not want my first paid customers to see the ads after installing update? How can I manage this?

Game will be both on App Store and Google Play.

Thanks


texts:
Is there a way to play videos with LibGDX?

I want to put a video as my splash screen in Android, but I dont want to use the Android SDK, because I am using LibGDX and I am almost finished :/


texts:
I'm working on a game in XNA 4 and I recently switched to a deferred shading implementation following this guide.  A strange white outline is showing up on my models now and I'm not sure whats causing this.  I thought maybe it was a lack of precision on the normal render target or the depth render target but increasing them to 64 bits (Rgba64) instead of 32 (Color) didn't help.  I also thought it might be some problem with the specular calculation so I tried setting the specular to 0 but that didn't help either.  Debugging the pixel in PIX shows the diffuse value is being calculated as nearly white for that pixel.  Any ideas?  I included a picture of the problem below, it's easier to see it at full size.

Pixel Shader:

float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    input.ScreenPosition.xy /= input.ScreenPosition.w;

    float2 texCoord = 0.5f * (float2(input.ScreenPosition.x, -input.ScreenPosition.y) + 1) - halfPixel;

    float4 normalData = tex2D(normalSampler, texCoord);

    //Transform normal back into [-1, 1] range
    float3 normal = normalize(2.0f * normalData.xyz - 1.0f);

    float specularPower = normalData.a;
    float specularHardness = tex2D(colorSampler, texCoord).a * 255;
    float depthVal = tex2D(depthSampler, texCoord).r;

    //Compute screen-space position
    float4 position = float4(input.ScreenPosition.xy, depthVal, 1.0f);

    //Transform to world space
    position = mul(position, InvertViewProjection);
    position /= position.w;

    //Surface-to-light vector
    float3 lightVector = lightPosition - position;

    float3 projectedTexCoords = position - lightPosition;
    projectedTexCoords = mul(projectedTexCoords, float3x3(
                            float3(-1, 0, 0),
                            float3(0, 1, 0),
                            float3(0, 0, 1)));

    float distanceToLight = length(lightVector) / lightRadius;
    float shadow = ShadowContribution(projectedTexCoords, distanceToLight);

    float attenuation = saturate(1.0f - distanceToLight);

    lightVector = normalize(lightVector);

    //Compute diffuse light
    float normalDotLight = max(0, dot(normal, lightVector));
    float3 diffuseLight = normalDotLight * Color.rgb;

    float3 reflectionVector = normalize(reflect(-lightVector, normal));
    float3 directionToCamera = normalize(cameraPosition - position);
    float specularLight = specularPower * pow(saturate(dot(reflectionVector, directionToCamera)), specularHardness);

    return shadow * attenuation * lightIntensity * float4(diffuseLight.rgb, specularLight);
}

Edit: Sorry about the JPG, stackexchange's uploader did that on its own.  Roy T:  I did actually reference your XNA4 conversion of the tutorial for the parts that changed from XNA3.  Since I didn't make any big changes to the code I thought maybe this bug existed in the original but was just impossible to see with so many lights all moving around, so I removed all but one light and the bug showed up again (look near the lizard's elbow)

Here are the GBuffer contents for my scene:

Color Buffer:

Depth Buffer:

Normal Buffer:

Final Render:

Edit2:

I'm starting to suspect the problem is CombineFinal.fx when it samples the color map.  This is the computation for a properly colored pixel right next to a white pixel:

diffuseColor        : (0.435, 0.447, 0.412)
diffuseLight        : (1.000, 1.000, 0.902)
light               : (1.000, 1.000, 0.902, 0.000)
PixelShaderFunction : (0.435, 0.447, 0.371, 1.000)
specularLight       : 0.000

And this is the output from an improperly colored white pixel directly next to it:

diffuseColor        : (0.824, 0.792, 0.741)
diffuseLight        : (1.000, 1.000, 0.902)
light               : (1.000, 1.000, 0.902, 0.000)
PixelShaderFunction : (0.824, 0.792, 0.669, 1.000)
specularLight       : 0.000

The diffuseColor is the only difference, and this color is taken directly from the color map.  Perhaps there is a slight error in the computation of the texture coordinate to sample from?

Lighting Pass:


texts:
I am making an fps that uses a raycast for shooting. I used some suggestions taken from a few reddit pages, but it's mostly my own code. It was working properly, until I noticed that when you shot up above the enemy, it still registered as a hit. Does anyone know why this might be happening? code:
func use_weapon():
Raycast.force_raycast_update()
if Raycast.is_colliding():
    var collider = Raycast.get_collider()
    if collider:
        if collider.has_method("takedamage"):
            collider.takedamage(10)


texts: 2D Physics: storing previous position vs storing velocity

texts:
I saw a number of 2d game tutorials and books where previous position of an object was stored in state instead of velocity vector. Velocity is then calculated each frame as a difference between positions.

What are the advantages of that method?


texts: Issue picking the closest vector in a unique circumstance

texts:
I have a list of targets that can be picked depending on the magnitude from the vector created using:

  for(int i = 0; i < targetQueue.Count; i++) //2 loops to cycle through targets
            {
                for(int j = 0; j < targetQueue.Count; j++)
                {   //if two targets are the same, then skip them
                    if(targetQueue[i] != targetQueue [j])
                    {
                        //getting the direction using the source and destination vectors
                        Vector3 iDir = targetQueue[i].transform.position - transform.position;
                        Vector3 jDir = targetQueue[j].transform.position - transform.position;

                        //comparing i with j, if i is less than target at j then match found
                        if(iDir.magnitude < jDir.magnitude)
                        { //LockedTarget is a gameobject to show what target the turret is locked on to
                            LockedTarget = targetQueue[i]; //if match found then set locked target to target at i
                            break;
                        }
                    }
                 }
             }

This code compares every target to each other, however it does this twice, once on each side( target[i] becomes target[j]). When the magnitude is compared, if the target[i] is smaller, then this is now the locked target as this target is closer to the turret.

This works every time except for one instance and I can't figure out why its happening here:

When both targets are inside the collider, the target on the right should still be highlighted, yet I get the target that is farther away being selected, this also occurs with more than two targets, with even stranger results. These being that the original target chosen for 'DEADLOCK' what i'm calling it, stays locked. Even when I move the other targets above, below, left and to the right of it.

This only occurs with this target, i've tried with 2 other targets (south of the turret) and it works as intended by properly switching based on size of magnitude of the direction vector between the target and the source.

I have ruled out the possibility being that it is an issue to do with adding target's to the gameobject list as it works everywhere else. When measuring the lengths of the magnitudes, the wrong target is chosen as the locked target. It does show that the closest target on the images does actually have the smallest vector magnitude.

UPDATE: the magnitudes of the vectors are increasing and decreasing by tiny amounts, 1 to 2 for a major movement. this makes sense as its worldPos.
What doesn't make sense is the target on the right having a magnitude of 49 and the target above having a magnitude of 82, when according to world space they are pretty close to eachother.

Can anyone help me with this issue? its been driving me nuts for days.

It must be to do with the magnitudes of the direction vectors not being calculated properly.


texts: How can I avoid applying textures to a fragment in a shader when the surface normal is (0, 1, 0)?

texts:
I have a small GLSL shader with a vertex shader and a fragment shader. I want to avoid applying textures to faces that have a normal equal to (0, 1, 0). Is this possible? These are my shaders:

Vertex:

#version 120

varying vec2 UV;
varying vec3 normal;

void main()
{
  UV = gl_MultiTexCoord0;
  gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
  normal = gl_Normal;
}

Fragment:

#version 120

varying vec2 UV;
uniform sampler2D diffuseMap;

void main(void)
{
  gl_FragColor = texture(diffuseMap, UV);
}


texts:
I have a problem: I working on a simple game and want to use some GUI (think of simple input for player name, etc). I've googled a lot of GUIs that can be used with SDL, but:

Most of them are using OpenGL while I'm using SDL2 render system. Docs say I can't mix these two, so I need to render GUI in a separate window. I know I can make it borderless and always-on-top, but I still need to manage this as a separate window (e.g. if main window moves, I need to move the gui window, etc, basically, I need to implement the childing myself). That makes me sad.
Those few which are using SDL as render (without OpenGL) either abandoned / unfinished / can't be compiled / etc or I can't figure out how to mix them with my rendering.

What I want to achieve: to render GUI in some place on the screen (think of a sidebar) and game stuff on the rest of the screen. Like:

SDL_Window* w = ...;
SDL_Renderer * r = ...;

while(running)
{
    renderGui(r, 0, 0, 100, 100); // Minimap located at 0,0 of size 100
    renderGameScreen(r, 100, 100, 100, 100); // Rest of the game located at 100, 100
}

Is there a way to do that? How GUI supposed to be used in alongside the SDL? May be my design is broken.

Sorry, I'm completely novice and may mix the things. Thanks.

Update:

Thanks for your answers. Quick update: I've tried so far:

nanogui-sdl - it uses opengl context, I was not able to mix it with SDL 2d render: it either flickers (because opengl and sdl fight for the screen and over-drawing the contents) or just draws the either thing: ui or game screen. Moreover, it crashes on some controls (like color-picker) and significantly affects rendering time (it drops 2-3 times when I add nanogui rendering with a couple of basic widgets)
nuklear - the same thing as with nanogui
I was not able to compile ToT KiWi - there are some syntax error (like #elsif instead of #else if or #elif so I'm not ever sure it can be compiled at all).

I'm going to try: imgui, kiss and gwen (gwork).

In the end, I can switch my drawing to opengl (fortunately I need some basic primitives, like circles, rectangles, triangles, etc, nothing complex) if I can't find a UI to work with SDL 2d render.

Update 2:

Sorry for not selecting the answer - was very busy during the week. I marked answer as accepted. I also tried to upvote both answers, since they are both useful, but I don't have enough reputation to do that. Thanks.

For those who wondering is I solve the problem: yes, kind of. I've switched over to SFML. I really like SDL and know it's very stable and mature, but I really need basic graphics for my pet project, so I'm OK with SFML too. It makes working with OpenGL a bit easier, so I can adopt the GUI library.


texts:
#from pygame.locals import
import pygame
import math
from time import sleep
import display_world

# class Player(pygame.sprite.Sprite):
class Player():
    x = 10
    y = 500
    speed = 10

    # stores if the player is jumping
    isjump = 0

    # force(v) up and mass m.
    v = 8
    m = 2

    def moveRight(self):
        self.x = self.x + self.speed
        # moving right

    def moveLeft(self):
        self.x = self.x - self.speed
            #moving left

    def jump(self):
        self.isjump = 1

    # Jumping
    def update(self):
        if self.isjump:
            # Calculate force(F).
            if self.v > 0:
                F = (0.5 * self.m * (self.v*self.v))
            else: F = -(0.5 * self.m * (self.v*self.v))

        # Change position
            self.y = self.y + self.y

        # Change velocity
            self.v = self.v - 1

        # If ground is reached
        if self.y >= 500:
            self.y = 500
            self.isjump = 0
            self.v = 8

class App:
    windowWidth = 800
    windowHeight = 600
    player = 0

    def __init(self):
        self._running = True
        self._display_surf = None
        self.image_surf = None
        self.player = ()

    def on_init(self):
        pygame.init()
        self.display_surf = pygame.display.set_mode((self.windowWidth, self. windowHeight), pygame.HWSURFACE)

        pygame.display.set_caption('MY FIRST GAME')
        self.running = True
        self._image_surf = pygame.image.load('small_mario.png').convert()

    def on_event(self, event):
        if event.type == QUIT:
            self._running = False

    def on_loop(self):
        pass

    def on_render(self):
        self._display_surf.fill((0,0,0))
        self._display_surf.blit(self._image_surf, (self.x, self.y))
        self.player.updatepygame.display.flip()
        sleep(0.03)

    def on_cleanup(self):
        pygame.quit()

    def on_execute(self):
        if self.on_init() == False:
            self._running = False

        while(self._running):
            pygame.event.pump()
            keys = pygame.key.get_pressed()

            if (keys[K_RIGHT]):
                self.player.moveRight()

            if (keys[K_LEFT]):
                self.player.moveRight

            if (keys[K_UP]):
                self.player.jump()

            if (keys[K_ESCAPE]):
                self._running = False

            self.on_loop()
            self.on_render()
        self.on_cleanup()


texts:
I am working at dynamic voxel engine in Unity (something like Space Engineers) where player can create object from voxels, push them, damage and split in to other object.

I store all data in 3D array, 1 mean voxel, 0 mean empty node.

So I looking for solution to break object (array). For example when I remove enough voxels object should split in to two.

00000000            00000    0000
01110110   ====>    01110    0110
01110110            01110    0110
00000000            00000    0000

In 2D example it should split like that.

I try to use BFS search but it not fast enough ;(. It works fine for small grids like 5x5x5, when I creat 5x5x50 grid it works few seconds before break arrays.

My algorithm:
1) First find empty node
2) When you find empty node start BFS from that node, collect all not empty nodes, when you cant find not empty node finish.

If break exist it will collect only one part of array so it find break, if there is no break it will return whole array.

The problem is speed of it ;/ How to make it faster?


texts: Is it possible to move buttons or other ui elements over each other dynamically in Godot?

texts:
What im trying to do is have it set up so that if the player clicks on a character their ability's will appear on the ui, but i want to use the same ui space for the other characters as well.

So is it possible to have multiple buttons in the same area and then depending on which character is selected only the buttons connected to that character appear?

Thank you in advance for the help.


texts: Is it possible to detect two different mice at the same time, and have their movements recorded seperately?

texts: I'm thinking of making a game that requires two mice to play. It needs to register the movement separately from one another. Is this possible? Or does the Windows architecture not allow for such things?


texts:
I'm making a game that needs to save total played time into file (using JSON) for comparing & resolving data conflicts between local and cloud. I will override outdated one.

Currently, I'm just adding Time.realtimeSinceStartup, but is that okay? What if the time is really, really big and couldn't be handled in Unity anymore? Could that eventually happen?

If so, what are some alternatives?


texts: Does it make a sense to use a build server in small (2-3 developer) game development team? I like the idea of continuous integration, and the team members are not in the same place, so it might not be a bad idea.


texts: Lengthen Line (bidirectional) - crossing zero line

texts:
I'm trying to lengthen a line, by a certain amount.
I want to apply the modification to both points on the line, expanding it in both directions. without moving it from it's current position (center point expansion would be acceptable, but I'n not sure how to apply it).
Exact details:
Line:
Point 1 [X = 1 , Y = 4], Point 2 [X = -1, Y = 6]
Line Normalized Vector: V = [X = -0.707106, Y = 0.707106]
Expand by: E = 1
So the result I'm looking for is
New Line = [ 1.707 , 4.707 ] ~ [ -1.707 , 6.707 ]
My problem happens when I multiply Point2[X] + ((0-V[x])*E) = - 0.292
Can someone give a SIMPLE example.  Psudo code, is great!
I know it is because I'm crossing the zero line, but I'm sure there's a better way to do this than testing if the point is greater than zero or less than zero.


texts: Unity Animator - bool transitions keep re-entering state while true

texts:
My StateMachine is triggered in a loop as long as transition boolean is true.

I have made sure my code only runs once, where I set the animation bool:

animator.SetBool("talk", true);

This does trigger the transition but the problem is that it re-triggers every frame as long as the bool is true. I had the same issue with a normal state earlier, but there I could turn off "Can transition to self" which solved it.
However a StateMachine does not have that option.

I want the animation to play until the bool is set back to false, so using a trigger would not be good here.

EDIT: For some reason it seems the "Transition duration" is the one resetting my animation. So if I change that to 3, it re-enters every 3 seconds, and so on. This seems really weird?

How do I just make sure that the animation plays until its done, then it re-enters (to choose another random talking animation from my StateMachine), as long as talk == true?


texts: glBindVertexArray very occasionally causes crash

texts: I'm writing a game in an engine of my own design. Very occasionally, and without much cause, when I come to render the post processing result to a quad, the glBindVertexArrays crashes. It actually doesn't crash on that thread, it crashes in the nVidia GPU thread on an instruction called "INT E29".. I don't know machine code very well. Anyway reading up about this, it looks like it could be something to do with putting the wrong stuff in VAOs but when this crash happens I will have rendered it for a good minute at 400+ fps already, and the VAO wouldn't ever been called other than on initialisation. Any ideas?


texts: How to make the Steam overlay work with WPF?

texts:
I have developed a game using C#+WPF and the game is currently on Steam (private branch until release). However Steam's overlay isn't working with WPF. Sometimes it tries to appear in the popups of comboboxs.

I've tried several options, the best so far was to render a black screen using SharpGL under my application :

<sharpGL:OpenGLControl
            Name="openGLControl"
            DrawFPS="False" RenderContextType="FBO" FrameRate="14"/>
<Grid Name="gridContainingMyApplication">

</Grid>

But as you can imagine this decreases the performance of the application and some effects can appear delayed (mouseover for example).

It was not a major concern until now but since we are planning on adding multiplayer we would like to find a way to make Steam's overlay work.

I know that WPF isn't the best option to create games but in our case we thought it would be. We've created a simulation game and since we have a lot of tables/stats/etc. we thought WPF was great, and excepting this overlay issue WPF seems perfect for us.

Is there a way to make Steam's overlay work with WPF ?

Thank you,


texts: What is the movement represented by this sprite animation?

texts:
Fire Emblem 7 is a sprite based game with some interesting sprite art aesthetics. For example, see this sheet of one of the main characters, Lyn:

On the last frames of the critical hit, the artist used some kind of slash effect to represent the entire motion of the sword in a single frame. It looks really appealing on video. I have two questions:

What is this effect called?
How or why did the artist arrive at that result? For example, why are those "spikes" where they are, and why is the "end" of the line fatter?


texts: 2D UI - Image with 1px border randomly gets different thickness

texts:
I created a test image that is 60 x 60 px, which has a 1px border.  I then drop that into Unity as a UI sprite image set to the same size, however the 1px border on a few sides can appear to be thicker, and this ruins the look I am going for especially when there are multiple of them.

I've tested in the editor and creating builds (testing resolutions), and the same issue in all cases.

It's easier to explain this with images.

The left screen shot is the actual size of the image in the game view.  The zoomed in image is another case where the borders change thickness, but zoomed in to make it more clearer.

I've tried various settings, always the same issue.

How can I get the image to appear exactly as it should with no changes to the borders?


texts: Voxel engine/vertexes: how to add more and more different textures during game runtime and change some of the blocks' faces?

texts:
It's difficult to ask this, but I'll try. The thing is: I asked before somethings about creating ramps and blocks with vertexes. [I'm using C#/XNA.]

Explanation: now I got a chunk that has blocks wherever I want, that automatically change "stairs" into ramps. And I love it and I thank all the people that helped me out! But I don't know how to texture it appropriately.

I could add a Texture Atlas and set the coordinates of each texture (I found the example at a project called "TechCraft Engine"), but I'd like to create separate PNG files for each texture, 'cause I'll use transparency later and I'd like that textures can be loaded during game runtime.

I'm newbie in programming, but I'm searching for solutions. All that I got for now is that I have a custom effect (FX file) created that changes colors for each time of the day. But it only has a slot for one texture file loaded. And I still can't implement it because of that.

I can't add more texture samplers to the effect 'cause it can't be done at game runtime (or can it?)

I'm using the VertexBuffers and IndexBuffers, with TriangleList primitive. For now, I can only draw with colors, without textures.

Later in my game I would like that custom textures could be added and placed on some of the block's faces. A example for this can be found in The Sims 3. There you can add textures to the game and paint the walls and objects with it. It's something like that I'd like to create, but with a loader while playing.

My question is: should I create a VertexBuffer and a IndexBuffer for each texture and separate the vertexes with each texture between them, creating a List of VertexBuffer and IndexBuffer for placing each?... Then I could draw all the vertexes of one texture at a time, change the effect's texture parameter with a different one (call the pass technique again), and set the graphics device again with the next VertexBuffer and IndexBuffer of the list, for drawing it with the TriangleList primitive.

I'd repeat it for each texture loaded. Does it work or is there any other way to do it?

Should I forget about runtime loading for now, for finding a easier solution?

I'm pretty messed with this, do you have any suggestions? Any information will help. Thank you!


texts: Can’t Load .fbx from blender to Monogame correctly

texts:
I am using pipeline.exe tool, to convert an .fbx file I made using Blender (using the default Blender 2.73a export settings) to .xnb, and then manually copy and paste it in my content directory (Is this one of the correct ways to convert it properly ?).

After watching this video https://www.youtube.com/watch?v=u7tLYMPC828 I saw that you have to convert the .fbx file that you create using blender, to a new .fbx file, using a tool called fbx converter 2013, and then use that file in the pipeline.exe tool, to produce the final .xnb file. Without doing that, I can't even see my model when drawn on the screen.

With the steps I described above, I managed to see the .xnb file on my screen but it was not exactly the original model I had made. For example:

As you can see the real model I got (after the convertion with the fbx converter 2013)  is much longer, whereas the one on the left (the one I draw in my game), is like packed in a small square.

If you are using blender, please let me know how do you import the .fbx to your Monogame project. (Or you can suggest to me another software you are using to make models and tell me your method of importing models to Monogame)

This is how I am drawing my model:

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

    Vector3 modelPosition = new Vector3(-25, 0, 0);
    float modelRotation = 0;
    float aspectRatio = graphics.GraphicsDevice.Viewport.AspectRatio;

    // Draw the model. A model can have multiple meshes, so loop.
    foreach (ModelMesh mesh in Brick.Meshes)
    {
        Vector3 cameraPosition = new Vector3(0.0f, 0.0f, 50.0f);
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.EnableDefaultLighting();
            effect.World = Matrix.CreateRotationZ(modelRotation)*
                Matrix.CreateTranslation(modelPosition);
            effect.View = Matrix.CreateLookAt(cameraPosition,
                Vector3.Zero, Vector3.Up);
            effect.Projection = Matrix.CreatePerspectiveFieldOfView(
                MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10000.0f);
        }
        // Draw the mesh, using the effects set above.
        mesh.Draw();
    }
    base.Draw(gameTime);
}

Edit: I also tried exporting to .X from blender and when i converted to .xnb, loaded the model and drew it, nothing shows up.


texts: Is it possible to have extension methods that starts coroutines? Id like to have an extension method for the GameObject that checks if itself has a renderer and a material and then lerps the color to a target color.


texts: How can I generate a texture that looks like left-over tea leaves?

texts:
We are working on a project for iPhone and Windows Phone 7 where we'd like to be able to generate tea leaves at the bottom of a cup. It doesn't have to look photo-realistic, and actually cartoon-y is ok.

What sort of techniques should we research to accomplish this? Are there any libraries (preferably in C, but we can translate) that would be helpful?

Here are some samples pulled from a Google Image search


texts: What is the standard C# / Windows Forms game loop?

texts:
When writing a game in C# that uses plain-old Windows Forms and some graphics API wrapper like SlimDX or OpenTK, how should the main game loop be structured?

A canonical Windows Forms application has an entry point that looks like

public static void Main () {
  Application.Run(new MainForm());
}

and while one can accomplish some of what is neccessary by hooking the various events of the Form class, those events don't provide an obvious place to put the bits of code to perform constant periodic updates to game logic objects or to begin and end a render frame.

What technique should such a game use to achieve something akin to the canonical

while(!done) {
  update();
  render();
}

game loop, and to do with minimal performance and GC impact?


texts:
I'm preparing a 2d game.
I'm working with particles, the problem is my particle is displaying on the obstacle and also a problem with level text see the reference image:

and the second issue is when I run my game on mobile then below some space left?

canvas : screen space camera and render camera->main camera.
Background RectTransform (stretch->stretch).

Canvas Inspector:

Particle Inspector:

Obstacle Inspector:


texts: Silly question about perspective correct texture mapping

texts:
OK, I'll admit, the math on a perspective projection matrix is quite hairy for me, but I get the general gist of it: morph the object so that it looks... perspective-ish.

But there is one thing which I really don't get it: if I send the textcoord for a vertex to a "smooth out fTexCoord" varying variable, how is that interpolation affected by either the clip space coordinates (x,y,z,w), where w actually has a value !=1 or a naive implementation without the w component? Is the interpolation happening in clip space?

I mean, I understand WHY half a quad texture looks squished at the diagonal if looked from a perspective type of camera, because one triangle is morphed and it's texture coordinates just fill a smaller area than the triangle which is closer to the camera.

What I don't understand is how clip space avoids thats. I mean, isn't the fTexCoord just interpolated based on the distance against the tree verts? And if I can give naive gl_Position values, and OK clip space gl_Position values, and they occupy the same space in... space, how can the perspective correct texture mapping help that?


texts:
I am creating an endless runner with a flying character.

I want to lock any movement in the x axis so that the character object can only move up and down but still move forward through the scene. I have looked into freezing axes and joints, but this stops the forward movement.

Is it possible to edit the below to lock the x axis for character movement only, or is there a setting where i can apply this?

using UnityEngine;
using System.Collections;

public class moveupdown : MonoBehaviour {
    public Vector2 velocity;
    public float uservelocity;
    public Rigidbody2D rb2D;

    void Start() {
        rb2D = GetComponent<Rigidbody2D>();
    }

    void FixedUpdate() {

        if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Moved) {
            Vector2 touchDeltaPosition = Input.GetTouch (0).deltaPosition;

            rb2D.MovePosition (rb2D.position + touchDeltaPosition * Time.fixedDeltaTime / uservelocity);

        }
    }
}


texts: What methods exist to implement a 2D looping world?

texts:
I would like to know what other methods exist to implement a 2D wrapping world.

I know the simple modulo solution (ObjectPosition % MapSize) but that doesn't really fulfills my requirements. My issue with this easy solution that it only works on points and not on objects.

I was trying to clone / duplicate my objects and make them visible on both sides of the level that way but it doesn't really works out with box2d physics. So i am thinking if there is any other solution?

I would like to make my game world a truly looping cylindrical world, but i don't know what other methods exist to implement such a thing in 2D.


texts: Why doesn't my computer paddle move in my Pong game?

texts:
I'm making a pong game and I can't figure out why the computerPaddle won't move up or down when it's supposed to to hit the ball automatically!

Please help me.

Here's code:

<html>
<h3>- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PONG- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -</h3>

<canvas id="gameCanvas" width="800" height="600"></canvas>

<script>
var canvas;
var canvasContext;
var ballX = 50;
var ballY = 50;
var ballSpeedX = 11;
var ballSpeedY = 5;

var playerPaddleY = 240;
var computerPaddleY = 240;
const paddleHeight = 120;
const paddleThickness = 12;

function calculateMousePos(evt) {
    var rect = canvas.getBoundingClientRect();
    var root = document.documentElement;
    var mouseX = evt.clientX - rect.left - root.scrollLeft;
    var mouseY = evt.clientY - rect.top - root.scrollTop;
    return {
        x: mouseX,
        y: mouseY
    };

}

window.onload = function() {

    canvas = document.getElementById('gameCanvas');
    canvasContext = canvas.getContext('2d');

    var framesPerSecond = 30;

    setInterval(function() {
        moveEverything();
        drawEverything();
    }, 1000 / framesPerSecond);

    canvas.addEventListener('mousemove',
        function(evt) {
            var mousePos = calculateMousePos(evt);
            playerPaddleY = mousePos.y - (paddleHeight / 2);
        });

}

function ballReset() {
    ballX = canvas.width / 2;
    ballY = canvas.height / 2;
    ballSpeedX = -ballSpeedX;

}

function computerMovement() {
    if (computerPaddleY < ballY) {
        computerPaddleY += 5;
    } else {
        computerPaddleY -= 5;
    }
}

function moveEverything() {

    ballX += ballSpeedX;
    ballY += ballSpeedY;

    if (ballX > canvas.width) {
        if (ballY > computerPaddleY && ballY < computerPaddleY + paddleHeight) {
            ballSpeedX = -ballSpeedX;
        } else {
            ballReset();
        }
    }

    if (ballX < 0) {
        if (ballY > playerPaddleY && ballY < playerPaddleY + paddleHeight) {
            ballSpeedX = -ballSpeedX;
        } else {
            ballReset();
        }

    }

    if (ballY > canvas.height) {
        ballSpeedY = -ballSpeedY;
    }

    if (ballY < 0) {
        ballSpeedY = -ballSpeedY;
    }

}

function drawEverything() {

    canvasContext.fillStyle = 'black';
    canvasContext.fillRect(0, 0, canvas.width, canvas.height);
    canvasContext.fillStyle = 'white';
    canvasContext.fillRect(2, playerPaddleY, paddleThickness, paddleHeight); //
    player

    canvasContext.fillRect(786, computerPaddleY, paddleThickness, 120);
    //computer player

    canvasContext.beginPath();
    canvasContext.arc(ballX, ballY, 12, 0, Math.PI * 2, true); //ball
    canvasContext.fill();

}

</script>

</html>


texts: Why do most games require you to patch them after downloading, instead of rolling the patches into the installer?

texts: When I download a video game from the publisher's website, it typically needs to update itself several times before I can play it. Why can't the developer simply put the patched version of the game up for download? I assume there must be technical problems with this, but what are they?


texts: Collision resolution - Character walking on ascendent ground

texts:
I don't know if the solution to this problem is quite straight-foward but I really don't know how to handle collision resolution on a game where the player walks on an ascendent floor which is not flat. How can the player position itself on the y axis depend on the ground x and z (opengl coords)? What if the floor's slope is too much and the player can't go up, how do you handle that?

I don't need any code, just a simple explanation would be great.


texts: Unreal Engine - spawning actor from content browser

texts:
What is best way to spawn Actor from UFactory ?
I am trying to create custom asset based on AActor:
UObject * UMyActorAssetFactory::FactoryCreateNew(UClass * InClass, UObject * InParent, FName InName, EObjectFlags Flags, UObject * Context, FFeedbackContext * Warn)
{
    return NewObject<AMyActorAsset>(InParent, InClass, InName, Flags);
}

Now I can create MyActorAsset. But when I try to open it, it fails because of missing world.
Is there any way to access editor world, or do I need to create new instance of world and supply that one?
Thanks.


texts: How to handle realtime random movement with client side prediction

texts:
I'm building a realtime multiplayer game that runs the same 'physics' loop on client and server. I'm using a steering behavior 'wander' that is essential random movement. The client and server generate different Random numbers when running the wander algorithms.

I'm wondering how I can keep a naturally random looking movement but use some constant that will insure the client and server come to the same conclusion.


texts: Generate islands/continents with simplex noise

texts:
Managed to get something like this using a simplexnoise port i made from the original javacode to php:

Used some tips from other post:

Understanding Perlin Noise

basically, lowered the frequency to get more flat terrain.

Now, how could i foce the map to be a huge Pangea? If i manualy set for example, if (x < 5) set height = 0 (water), when i normalize all the map to 0...1 the value 0 get higher (as my simplexnoise function returns -1 1). If i force it to -9999, does not work either.

Has to me something elegant to sneak into the height generation code to make the borderline squares, water.

With MDP algorithm i could seed the sides of the map to -500 for example and then pretty coast would be made, but with simplex/perlin does not seem the case as i can not enter pre-seeded cells with artificial heights.

Any tips?


texts: Difference between texture arrays and multiple single textures?

texts:
I've just learnt that DirectX 10 and above have a feature called "texture arrays". Which, basically, is just a normal array of textures (shader resources) which in a shader is declared like:

Texture2D myTextures[2];

What I've been using so far is 2 multiple separate textures:

Texture2D myFirstTexture;
Texture2D mySecondTexture;

Is there any practical (performance, memory etc...) difference between the two?


texts: why are my 2d game objects passing through each other?

texts: So I've been looking around for a while and can't seem to find an answer for this. I am trying to make a game where you stack shapes as high as possible. I have an OnMouseDrag script so I can grab a shape and put it on top of another. but for some reason when I'm dragging a shape, the shapes will just pass right through each other and glitch and start spinning excessively and also passes through other colliders such as the box colliders 2d on both sides of the screen. If anyone could help me I would very much appreciate it. Thank you.


texts: Determining a sensible gear-like hierarchy for a series of connected objects

texts:
I would like a series of objects to behave in similar manner to a series of connected gears.

This means that each black object in the diagram below will rotate at a speed based on the ratio of their radius compared to their parent's radius.

The problem is how can I determine a sensible parent child hierarchy algorithmically?

Is there a tried and tested mathematical procedure for such a task?


texts: How to start the game at the same time across two phones?

texts:
I am trying to synchronize two devices so that they can start the game at the same time.

The mechanism that I've thought about is that I would use the phones' time and set the intervals at, for example, ten seconds each. Then, when the start button is clicked, it will start the game on the beginning of the next interval. So, as long as the start buttons on both devices are clicked in a short time frame of each other, the game should start at the same time.

For the game, near perfect synchronization is important.

Will this work? I am assuming that every phone receives a timestamp from a single source, so that internal clocks are at the same time.

If that doesn't work, what is an alternative/better solution to offline multi-device synchronization?


texts:
I'm trying to make a 2D car driving game in Unity and I'm having problems with my code.

I am able to move forward,backward,turn left/right using arrow key from my present code

using UnityEngine;
using System.Collections;

public class CarControll : MonoBehaviour {

// Use this for initialization
float speedForce = 15f;
float torqueForce = -200f;
float driftFactorSticky = 0.9f;
float driftFactorSlippy = 1;
float maxStickyVelocity = 2.5f;
float minSlippyVelocity = 1.5f;

bool move=false;
public bool forwardArrow=false;
public bool backwardArrow=false;

public bool rightTurn=false;
// Use this for initialization
void Start () {

}

void Update() {

    move=true;
}

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

    Rigidbody2D rb = GetComponent<Rigidbody2D>();

    float driftFactor = driftFactorSticky;
    if(RightVelocity().magnitude > maxStickyVelocity) {
        driftFactor = driftFactorSlippy;
    }

    rb.velocity = ForwardVelocity() + RightVelocity()*driftFactor;

    if( Input.GetButton("Accelerate") || Input.GetButtonDown("Forward") || Input.GetKeyDown(KeyCode.UpArrow)) {
        Debug.Log ("Uparrow....................................................");
        rb.AddForce( transform.up * 20);

    }

    if( forwardArrow==true) {

        rb.AddForce(transform.up*0.5f);
    }

    if(backwardArrow==true) {

    rb.AddForce( transform.up * -speedForce/25f );
    }

    if(Input.GetButton("Brakes") || Input.GetButton("Backword") || Input.GetKeyDown(KeyCode.DownArrow)) {

        rb.AddForce( transform.up * -speedForce/2f );
    }

        float tf = Mathf.Lerp (0, torqueForce, rb.velocity.magnitude / 2);
        rb.angularVelocity = Input.GetAxis ("Horizontal") * tf;

}

Vector2 ForwardVelocity() {

    return transform.up * Vector2.Dot( GetComponent<Rigidbody2D>().velocity, transform.up );
}

Vector2 RightVelocity() {

    return transform.right * Vector2.Dot( GetComponent<Rigidbody2D>().velocity, transform.right );
}

public void MoveForward()  //forward button
{
    forwardArrow = true;
    backwardArrow = false;
}

public void MoveBackward() backward button
{
    backwardArrow = true;
    forwardArrow = false;
}

public void RightTurn()  //right button
{

    rightTurn = true;
}

}

I have added four button(Forward,backward,right,left).Now I need to move the car using this button. The car is moving Forward,backward using the button but when Press the right/left button the car is not Turing left/right while move.But its working perfectly on key press.Can anyboady help solving this issue


texts: Is it better to track rotation with a vector or a float?

texts:
In XNA, you can see that to draw a rotated sprite with SpriteBatch, you'll need a float describing the angle in radians.

I'm used to making games in OpenGL. I just want a rapid prototyping environment in XNA, but I'm a little lost. It's my preference to always use Vectors to store my rotation, to do vector math, et cetera.

So my question is: in XNA, is better to keep a vector for your rotations, and each frame transform to a float angle, or just keep the float angle itself? If I prefer the vector, what would be my drawbacks compared to just using a float?


texts: How to check if the bottom side of one object touches the top side of another object?

texts:
How can I check if the bottom side of one object touches the top side of another object? Like on the image:

I tried this:
foreach (tile t in tiles)
        {
            foreach (tile t2 in tiles)
            {
                if (t != t2)
                {
                    if (t.rect.Intersects(t2.rect))
                    {
                        if (t.rect.Center.Y < t2.rect.Center.Y)
                        {
                            kill_tiles_list.Add(t2);
                            kill_tiles_list.Add(t);
                        }
                    }
                }
            }
        }
    }

It will work to tell me that there has been a collision, but it will not tell me about which parts collided.


texts: How to create simple physics for a group of balloons colliding in the screen (2D)

texts:
The game is 2D, how can I make simple physics for a group of balloons colliding in the screen.

What I need is the balloons not to overlap and to bounce when they reach the limits of the screen or other balloons.

Should I use something like box2d or is there a simple algorithm to do something like this?


texts: (Java) Trying to animate an arraylist of coins with a (working) animation class

texts:
I have a coin class which takes in an integer numOfCoinsand an enum LayoutType, which can be linear or curved. A linear layout displays the coins in a straight line one after the other - we'll work with this since the method is small and straight forward.

My constructor looks like this:

public Coin(float xPos, float yPos, int numOfCoins, LayoutType layout) {
        setType(ObjectType.COIN);
        coinList = new ArrayList<Coin>(); // arraylist of coins
        setPos(xPos, yPos); // set starting position of coin(s)
        if (layout == LayoutType.LINEAR)) {
            linearLayout(); // display coins in a straight line
        } else if (layout == LayoutType.CURVE{
            curveLayout();
        }

}

And my linearLayout() method looks like this

public void linearLayout() {
        //draw numOfCoins amount of coins in a straight line
        for (int i = 0; i < numOfCoins; i++) {
            Coin coin = new Coin(xPos, yPos);
            coinList.add(coin);
            xPos += 50; // place coins 50 pixels apart
        }
}

I have a working animation class and a spritesheet for the coins - however, the way I have modelled my coins is in such a way that 1 coin object can contain numOfCoins amount of coins, so I can't just directly call the animation in the draw method.

The class' draw() method is in an abstract class GameObject which Coin extends. It looks like this:

public void draw(SpriteBatch batch) {
    // if the object is a coin iterate through the list of coins
    // and draw the sprites, if it isn't a coin, simply draw the objects sprite
    if (type == ObjectType.COIN) {
        for (Coin coin : getCoinList()) {
            coin.getCoinList().draw(batch);
        }
    } else {
        sprite.draw(batch);
    }
}

This draw() method is called in World.render().

How would I create an animation using my Animatorclass for each coin if I have 6 coins in a straight line for instance? I can't seem to find a way. Highly grateful for any help, thanks.


texts: Bejeweled-like game, managing different gem/powerup behaviors?

texts:
In general, what I am asking is, given any game where a game element can look/behave/affect-other-elements one way under one set of conditions, and look/behave/affect-other-elements a different way under another, and there are many such conditions, what is the best approach to developing this flexibility into the core? (with one aim being to keep the game "fresh" by introducing variation on the game-play during the life of a game...)

Specifically,
In a Match 3 game, a valid move involves swapping a pair of adjacent tiles so that three-identical-tiles in a row are formed. The identical tiles are removed from the grid and replaced by those above them. New spaces (on top) on the grid are now filled with new tiles. This is the standard behavior. Richer Match-3 games, such as Bejweled, offer modified behavior based on the same mechanic when a player matches 4 tiles-in-row resulting in retention of the one tile that was swapped, and triggering alternative animations, sounds, scoring, etc. And yet still, 5-in-a-row, and cross-patterns, "power-up" tiles behave in very different ways and affect neighboring tiles in alternative ways as well.

ANY pointers for good practices here would be highly appreciated.


texts: Tower defense endless levels logic sprite kit

texts: I am making a tower defense game for iOS using Sprite Kit. I would like for my game to support an endless number of levels, like in Bloons TD 5. What approach should I take to implement this?


texts: Why does my GLSL 1.20 shader not work with an OpenGL 4.0 driver?

texts:
I'm just starting out with OpenGL on Linux. In order to write future-proof code, I explicitly wrote code for OpenGL 4.0 Core Profile in the first place, thus the shaders are GLSL 4.0.

That worked fine on a recent notebook with an AMD graphics card using the fglrx driver, which supports OpenGL 4.0. I then tried to run this code on another box with an Intel card, whose driver only supports OpenGL 2.1. That failed, obviously.

I then rewrote the shaders in GLSL 1.20, without changing the C++ code at all. Now it works on the Intel box, but on the AMD notebook, it displays nothing (except for glClearColor).

That confuses me. The code checks glGetError() periodically, so an error in the shader compilation would have been caught.

My only idea would have been that I accidentally created a GL 4 core context (instead of a compatibility context) on the AMD box, but the context is created by SDL 1.2, which (says the documentation) can create compatiblity contexts only.

Can anyone see what the problem is, or give hints on how to debug this? For reference, I'm attaching all shaders. (They're pretty trivial; as I said, I'm just starting.)

#version 120 (vertex shader)
uniform mat4 ModelMatrix;
uniform mat4 ViewMatrix;
uniform mat4 ProjectionMatrix;
attribute vec4 in_Color;
attribute vec4 in_Position;
varying vec4 pass_Color;
void main(void) {
    gl_Position = (ProjectionMatrix * ViewMatrix * ModelMatrix) * in_Position;
    pass_Color = in_Color;
}

#version 400 (vertex shader)
layout(location=0) in vec4 in_Position;
layout(location=1) in vec4 in_Color;
out vec4 ex_Color;
uniform mat4 ModelMatrix;
uniform mat4 ViewMatrix;
uniform mat4 ProjectionMatrix;
void main(void) {
    gl_Position = (ProjectionMatrix * ViewMatrix * ModelMatrix) * in_Position;
    ex_Color = in_Color;
}

#version 120 (fragment shader)
varying vec4 pass_Color;
void main(void) {
    gl_FragColor = pass_Color;
}

#version 400 (fragment shader)
in vec4 ex_Color;
out vec4 out_Color;
void main(void) {
    out_Color = ex_Color;
}


texts:
When player is walking on terrrain, around him Unity is rendering shadow coming from directional light.

But after some radius in the distance, shadows are not rendered.

Only when player walks close to some prefab, shadow is being drawn.

This is not very realistic. I would like that shadows are visible in the distance as in real terrain.

How to fix that ?


texts: How can I make a beveled edge with bump mapping?

texts:
I say bump mapping for lack of a better term, but that may not be what I need. I'm trying to make my corners of various objects look bevelled as opposed to square:

I can't just create a physical bevel on all the edges (performance concerns), and I can't just apply soft shading (I want a hard, but beveled, edge), so I'm trying to figure out if there's a way with shaders / bump mapping to apply a beveled / tapered look to sharp edges to give them a bit of a blunt feel, or even appear to actually be tapered sharply rather than just blunt, but either way is fine.

How can I make an edge tapered / blunt with bump mapping / shaders?


texts: How can I implement jumping in a 2D game using bounding box collision?

texts:
Problem:
I'm trying to implement basic jumping to my 2D game engine, but have failed several times.
Basically what I've done so far is disabling gravity and using a separate function moving the player upwards. The problem with this is that it looks really bad.

I've checked a lot of threads about this, and found one way that should work.
This is by simply adding another force going upwards against gravity. This force should be greater than gravity, but should decrease until the force of gravity is greater again.

The problem is that I am unable to implement it.

My code is written in Javascript and uses html5 canvas for rendering.
Note! This code is only a part of the whole engine.
As for variables:
c_objects - array with all objects the player can collide with
player - object literal with position, width, movement speed, velocity, and the velocity multiplier.

Pseudo-code is good for me, but i'd love an answer in JS.

Code:

// physics module collision
function collision(obj_1, obj_2) {
    var collision = Boolean(
        obj_1.x <= (obj_2.x + obj_2.width)
        && obj_2.x <= (obj_1.x + obj_1.width)
        && obj_1.y <= (obj_2.y + obj_2.height)
        && obj_2.y <= (obj_1.y + obj_1.height)
    );

    // return position booleans
    return {
        collision: collision,
    };
};

function movement(x, y) {
    new_pos.x = player.x + x;
    new_pos.y = player.y + y;
    // check collision for all objects in collision array
    var index;
    var collisions = new Array();
    for (index = 0; index < c_objects.length; ++index) {
        var new_collision = engine.collision(new_pos, c_objects[index]);
        collisions[index] = new_collision.collision;
    }
    var it_collides = collisions.indexOf(true) >= 0;
    if (it_collides == false) {
            player.x += x;
            player.y += y;
    }
}

// velocity & gravity module for adding gravity to an object
function gravity(modifier) {
    if (player.gravity == true) {
        var x = 0;
        var y = 0;
        x = 0;
        y = +(player.velocity * modifier);
        engine.movement(x, y);

        if (player.velocity <= 450) {
            player.velocity = (player.velocity * player.velocity_m);
        }
        else {
            velocity = 450;
        }
    }
};


texts:
I'm working in a team of three people on a 2D game, and Unity recently has been messing up the fileID on many sprites:

-  m_Sprite: {fileID: 21300000, guid: 6186fa4d068aae8418d9520f658d1ee6, type: 3}
+  m_Sprite: {fileID: 21300002, guid: 6186fa4d068aae8418d9520f658d1ee6, type: 3}

The guid stays the same, but the fileID changes, and the sprite goes missing. If one member fixes it, it becomes broken for one or both the others.

What can we do to fix that?

"reimport" didn't work. Prefabbing them didn't work. Deleting the whole project and re-downloading it didn't work either.

We are using 4.6.0f3, and before that we were using 4.6.0b17 IIRC. "Force Text" is already selected.

Here's .gitignore:

Build/
Design/

# project trashable
obj
Temp
*.tmproj
*.csproj
*.unityproj
*.sln
*.suo
*.user
*.pidb
*.userprefs
*.link
*.pyc

# library trashable
Library/cache/*
Library/shadercache/*
Library/metadata/*
Library/previews/*
Library/ScriptAssemblies/*
Library/*.log
Library/ShaderCache.db
Library/ShaderCache
Library/shadercompiler-1.log

# various
AnnotationManager
AssetImportState
AssetServerCacheV3
AssetVersioning.db
AudioManager.asset
BuildPlayer.prefs
BuildSettings.asset
CurrentLayout.dwlt
CurrentMaximizeLayout.dwlt
DynamicsManager.asset
EditorUserBuildSettings.asset
FailedAssetImports.txt
InspectorExpandedItems.asset
MonoManager.asset
NetworkManager.asset
ScriptMapper
assetDatabase3
assetservercachev3
expandedItems
guidmapper
CurrentMaximizeLayout.dwlt

I've just noticed I also have a global gitignore, which the others might not have:

*~
.DS_Store

I'm wondering if such a thing mess up the fileIDs? I.e. if someone has a DS_Store file and someone else does not, can this be a problem?

(btw what's the point of fileIDs, if there already are guids? Doesn't they defeat the purpose of having guids in the first place?)


texts: How to get UV coordinates for sphere (Cylindrical Projection)

texts:
I have created one sphere and I want to map onto it a texture map. But I want first to project my map texture to cylinder and then to sphere.

So I want to create a function which takes as parameter a 3D point from sphere and calculate a uv coordinate of this point using cylindrical coordinates. My guess is that I have to transform the spherical coordinates to cylindrical but I am not sure.

Is this possible and how can I implement it ?


texts: Character animation in physics-simulated environment

texts:
What are the standard solutions for animating characters in physics-simulated environments?

Let me explain what I mean - in most games characters are pretty much excluded from physics simulation - there are no forces acting on specific body parts (only gravity for the whole character) and limbs are forced to go into positions specified in key frames of animation... which in turn may produce infinite forces on the limbs and we know real muscles have limited strength...

What I want is character animation based on simulated muscles with plausible limitations - so character walking into a 1 T stone won't move it, or if he gets hit with a fast flying brick he would realistically fall (and brick won't just bounce like from the wall, whit character standing still like nothing happened).

Are there libraries that can do that? Maybe free ones for 2D simulations?


texts: sprite array problem with initialization

texts:
I have a problem with my Sprites. I'm trying to create a lot of Sprites. However, I got a problem in that I have several grass tiles and I don't want to do this

grass1 = new Sprite...;
grass2 = new Sprite..;

The problem is I make an array of Sprites say Sprite[] grass = new Sprite[7]; I don't know how I would intialize them. I need to put

for(int i=0; i<grass.length;i++){
        grass[i] = new Sprite(16,0,i,SpriteSheet.tiles);
    }

Somewhere, however I get an error saying you have to put it in a bracket. I get a syntax error. I'm thinking that I should put it into the constructor so I have

    public Sprite(){
    for(int i=0; i<grass.length;i++){
            grass[i] = new Sprite(16,0,i,SpriteSheet.tiles);
         }
    }

However, I think that is bad for memory. I don't know how to solve this. I think I need to use an array list. Maybe, create an array list of grass and then add elements in it.

   public class Sprite {
        public final int SIZE;
        private int x;
        private int y;
        public int[] pixels;
        private SpriteSheet sheet;

        public static Sprite[] grass = new Sprite[7];
        for(int i=0; i<grass.length;i++){
            grass[i] = new Sprite(16,0,i,SpriteSheet.tiles);
        }

        public static Sprite voidTile = new Sprite(16,0xffffff);

        public static Sprite player_up = new Sprite(32,0,5, SpriteSheet.tiles);
        public static Sprite player_back = new Sprite(32,2,5, SpriteSheet.tiles);
        public static Sprite player_right = new Sprite(32,1,5, SpriteSheet.tiles);
        public static Sprite player_left = new Sprite(32,3,5, SpriteSheet.tiles);

        public static Sprite player_up1 = new Sprite(32,0,6, SpriteSheet.tiles);
        public static Sprite player_back1 = new Sprite(32,2,6, SpriteSheet.tiles);
        public static Sprite player_right1 = new Sprite(32,1,6, SpriteSheet.tiles);
        public static Sprite player_left1 = new Sprite(32,3,6, SpriteSheet.tiles);

        public static Sprite player_up2 = new Sprite(32,0,7, SpriteSheet.tiles);
        public static Sprite player_back2 = new Sprite(32,2,7, SpriteSheet.tiles);
        public static Sprite player_right2 = new Sprite(32,1,7, SpriteSheet.tiles);
        public static Sprite player_left2 = new Sprite(32,3,7, SpriteSheet.tiles);

        public Sprite(int size, int x, int y, SpriteSheet sheet){
            this.SIZE=size;
            pixels = new int[SIZE*SIZE];
            this.x=x*SIZE;
            this.y=y*SIZE;
            this.sheet = sheet;
            load();
        }

        public Sprite(int size, int colour){
            SIZE=size;
            pixels= new int[size*size];
            setColour(colour);
        }

        private void setColour(int colour) {
            for(int i=0; i<SIZE*SIZE; i++){
                pixels[i]=colour;
            }
        }

        private void load() {
            for(int y=0; y<SIZE; y++){
                for(int x=0; x<SIZE; x++){
                    pixels[x+y*SIZE]=sheet.pixels[(this.x+x)+(this.y+y)*sheet.SIZE];
                }
            }

        }

    }


texts: Flexible alternatives to many many small polymorphic classes (for use as properties or messages or events) C++

texts:
There are two classes in my game that are really useful, but slowly becoming a pain. Message and Property (property is essentially a component).

They both derive from a base class and contain a static id so that systems can only pay attention to the ones they want to. It's working out very well... except...

I'm constantly making new message types and property types as I extend my game. Each time I need to write 2 files (hpp and cpp) and a ton of boilerplate to get essentially an classID and one or two standard data types or a pointer.

It's starting to make playing around and testing out new ideas a real chore. I wish when I want to create a new message or property type, I want to be able to just type something like

ShootableProperty:  int gunType, float shotspeed;

ItemCollectedMessage:  int itemType;

instead of creating a header and cpp file, writing a constructor, including the parent class, etc etc.

It's around 20 - 40 lines (including include guards, and everything) just to do what logically is 1 or 2 lines in my mind.

Is there some programming pattern to get around this?

What about with scripting (which I know nothing of)... is there a way to define a bunch of classes that are almost the same?

Here is exactly what one class looks like:

// Velocity.h

#ifndef VELOCITY_H_
#define VELOCITY_H_

#include "Properties.h"

#include <SFML/System/Vector2.hpp>

namespace LaB
{
namespace P
{

class Velocity: public LaB::Property
{
public:
    static const PropertyID id;

    Velocity(float vx = 0.0, float vy = 0.0)
    : velocity(vx,vy) {}
    Velocity(sf::Vector2f v) : velocity(v) {};

    sf::Vector2f velocity;
};

} /* namespace P */
} /* namespace LaB */
#endif /* LaB::P_VELOCITY_H_ */

// Velocity.cpp

#include "Properties/Velocity.h"

namespace LaB
{
namespace P
{

const PropertyID Velocity::id = Property::registerID();

} /* namespace P */
} /* namespace LaB */

All of that just for a 2D Vector and an ID saying to expect a 2D vector.  (Granted, some properties have more complicated elements, but it's the same idea)


texts:
I've been trying to add boundaries to my space game.

I've been following this tutorial with a sphere instead of a cube, but every time I start the game and move or rotate my ship it appears outside the sphere, as shown in the image:

The ship has a collider and a characterController.

Could anybody tell me what I'm doing wrong here? Thanks!


texts: Does the Windows 10 Game Bar have an an API that I, as a developer, can hook into and as such make a product that starts alongside all games that support the game bar (say, a parental control interface)?


texts: When scene loaded up, Position player at a start point. (Unity2D)

texts:
If pointName and player.startPoint are true, shown by the inspector, why doesn't the player's position go to the start point with a pointName of "ToNeighborhood". Note: The code runs if pointName == player.startPoint. It isn't running even when they both contain the same string shown by the inspector

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerStartPoint : MonoBehaviour {

    private PlayerController player;
    private CameraController theCamera;

    public string pointName;

    // Use this for initialization
    void Start () {
        player = FindObjectOfType<PlayerController>();
        theCamera = FindObjectOfType<CameraController>();
        if (pointName == player.startPoint)
        {
            Debug.Log("Changing");
            player.transform.position = gameObject.transform.position;
            theCamera.transform.position = new Vector3(transform.position.x, transform.position.y, theCamera.transform.position.z);
        }

     }

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

    }
}


texts: How do I dynamically set a WheelJoint's anchor points?

texts:
I've created a car in RUBE and imported it into my game. The game has a tuning menu, allowing the ride height of the car to be adjusted with a slider.

I can't work out how to change the position of the WheelJoint relative to the car body. The result I'm looking for is as if I had changed the anchorA Y-value in RUBE. I thought this would be equivalent, but it isn't:

    car.rearWheelJoint.getAnchorA().set(xvalue,yvalue);

I've tried instead creating a whole new jointdef:

        WheelJointDef d = new WheelJointDef();

        d.initialize(car.rearWheelJoint.getBodyA(), car.rearWheelJoint.getBodyB(),
                car.rearWheelJoint.getAnchorA().add(0,(val-100)*0.01f),
                car.rearWheelJoint.getAnchorB());

        car.rearWheelJoint = (WheelJoint) game.world.createJoint(d);

...but I think this is messing up the pointer to the wheel joint.

How can I do this?


texts: samplerCube for point light shadow map has dark corners relative to screen aspect ratio / size?

texts:
I almost have point light shadows working but the corner of the samplerCube that I use for the shadow map has corners that get darker depending on the main camera. Is this something to do with a transform into a different space somewhere? I followed learn-opengls tutorial on this and they don't seem to have this issue or it just didn't come up in their simple example.

Here a YouTube video of the problem because it is kinda hard to explain... https://youtu.be/FXpwgyJh1ZA

That shows the depth map sampler not the shadows by the way.

This also happens when the radius is almost 0 and the cube map is completely white.

float PointLightShadow(
    vec3 NegL, // FragWorldPos - pointLights[i].Position
    float R)   // radius of light
{
    if (mat_hasShadowMap2 == 0) {
        return 1.0f;
    }

    float closestDepth = texture(mat_shadowMap2, NegL).r;
    float currentDepth = length(NegL);

    float bias = 0.05;
    float shadow = R * closestDepth > currentDepth - bias ? 1.0 : 0.0;

    return closestDepth; // for this example
}

Sending light position to shader

...
m_lightData.PointLights[i].Position = lights[i]->Position(); // setting in world space
...

and for the FragWorldPos

...
out vec3 FragWorldPos;
...
vec4 worldPos = model * vec4(vert, 1);
FragWorldPos  = worldPos.xyz;
...

and then the fragment shader has a matching in variable.

I think like 99% of this is working, I just don't understand why the cube map seems to have these dark corners. They change aspect by changing the screen also suggesting that they are in some type of camera space, but I don't see where that would happen. Let me know if you need more context for the code snippets, these are the only important parts I think though.


texts: How can I communicate between libGDXand the Android Studio Java files?

texts:
The reason I'm asking is because I wanted to create a game and I know I could use Scene2D to create the UI but as far as menus go I wanted to use the tools in android studio to at least create a menu that would lead to the game screen.

They say you should try to do everything in libgdx but how would I go on about trying to accomplish this task?


texts: Unity setting rectTransform on an UI Image with a Vector3, do I need to convert coords?

texts:
I am trying to build a menu with a cursor.  I created the menu and that in the unity UICamera on the canvas.  It looks great.  I want the cursor to move so what I did was move the cursor by hand and record the values at each location I want the cursor to possibly be (see attached).  The problem is later when I try to set the value to these via this:

pauseCursor.rectTransform.position = new Vector3 (-45f, -80.6f, 0);

It fails and looking in the inspector again the x,y values are like 300, 800 or something.  I am guessing I need a conversion I just am not sure where or how.
Do I get the Ui camera reference and use the WorldToScreen?


texts: Best way to connect multiplayer users with each other (matchmaking) on a low powered server?

texts:
OK so I am using unity to make a multiplayer game, but I'm not sure how to connect players with each other over the internet.

Unlike other questions, this isn't a general problem of working out how to do UPnp or using unity's matchmaking server. My issue is that my server that I would use is a simple low powered pc (running normal windows 10, no idea how to use windows server).

I think it is powerful enough to match players with each other, but not to host more than one or two actual games.

The other issue is that I have a residential internet connection with a dynamic ip that changes every few months. However the speed should be ok (150Mb/s download, 20Mb/s download).

Also, I'm not planning to spend money on a monthly basis for a server (like unity's matchmaking service) as I plan to spend as little as possible (So far I've paid £12 to Microsoft for a dev account and I've received a £200 voucher from them so my current spending is -£189!)

So my question is should I use my server (would it work), are there any online services that are very cheap to use, or is there another way to make this work?

Only other thing is I could use the free 20 users at once on unity's matchmaking, but would this limit be too small?

EDIT:
just for information, my game is a simple tank shooter. I was thinking about limiting the amount of tanks in a game somewhere around 8-20. The bullets in my game are physical objects with rigidbodys and they move at a slower speed (if you've ever played tank trouble, it looks like that). The world is in 3D. There is a potential for there to be up to a hundred bullets in a scene at once at the worst.
After hosting a LAN world with 7 players connected for about 20-30 minutes, windows reports the data usage being around 3-4MB.