# Question
Title: How to do Chromatic Aberration on a transparent background?
I have a problem with a chromatic aberration shader effect...

If I produce the effect on a white background I get exactly what I want:

But if I do the same effect on a transparent background I get this:

In my code I use the following shader to produce the chromatic aberration effect:

```
// Chromatic Aberration

float DisplacementX = 5;
float DisplacementY = 5;

sampler TextureSampler : register(s0);

float4 main(float4 position : SV_POSITION, float4 color : COLOR0, float2 texCoord : TEXCOORD0) : COLOR0
{

// Offset the main texture coordinates.
float2 texCoord2 = float2(texCoord.x + DisplacementX, texCoord.y + DisplacementY);

float2 texCoord3 = float2(texCoord.x - DisplacementX, texCoord.y - DisplacementY);

float4 color1 = tex2D(TextureSampler, texCoord);
float4 color2 = tex2D(TextureSampler, texCoord2);
float4 color3 = tex2D(TextureSampler, texCoord3);

float alpha = color1.a + color2.a + color3.a;

// Look up into the main texture.
return float4 (color1.r, color2.g, color3.b, alpha);

}

technique RGBSplit
{

pass Pass0
{

PixelShader = compile ps_2_0 main();

}
}

```

This works great when I set the whole screen to a render target and apply the effect but I want to be able to apply this effect only to the foreground so I can choose which sprites it effects and then draw the background behind the transparent space.

My thinking so far is that I could create a white layer of the foreground image and blend it with the chromatic layer to produce the correct effect like this:

```
return float4(1, 1, 1, alpha); // Produces white version of layer

```

But I've unsuccessfully managed to blend it and I always end up with the same result as the second image.

I know this is possible because Teleglitch uses the same effect on bullets etc without effecting the background.

Perhaps someone with better blending knowledge than myself can help point me in the right direction?

# Answer
> 1 votes
I came up with a solution for this, if anyone else can think of a better way please let me know.

If I set the backbuffer of the foreground layer to white with an opacity of 99% or something like that:

```
GraphicsDevice.Clear(Color.White * 0.99f);

```

The shader will blend the foreground with the white creating the chromatic aberration like I want.

Then I pass over the final texture and remove any pixels that have transparency (which is the white background). So the new shader looks like this:

```
// Chromatic Aberration

float DisplacementX = 5;
float DisplacementY = 5;

sampler TextureSampler : register(s0);

float4 main(float4 position : SV_POSITION, float4 color : COLOR0, float2 texCoord : TEXCOORD0) : COLOR0
{

// Offset the main texture coordinates.
float2 texCoord2 = float2(texCoord.x + DisplacementX, texCoord.y + DisplacementY);

float2 texCoord3 = float2(texCoord.x - DisplacementX, texCoord.y - DisplacementY);

float4 color1 = tex2D(TextureSampler, texCoord);
float4 color2 = tex2D(TextureSampler, texCoord2);
float4 color3 = tex2D(TextureSampler, texCoord3);

float alpha = color1.a * color2.a * color3.a;

float4 finalTex = float4(color1.r, color2.g, color3.b, alpha);
if (finalTex.a <= 0.975f)
{
    clip(-1); // Abandon Pixel with transparency
}

// Look up into the main texture.
return finalTex;

}

technique RGBSplit
{

pass Pass0
{

PixelShader = compile ps_2_0 main();

}
}

```

The result means I can perform chromatic aberration on individual sprites then overlay them onto a background that doesn't use the effect.

---
Tags: c#, xna, shaders, hlsl, monogame
---


title: Is there a 'wait' function in Allegro5?

text:
# Question
Title: Is there a 'wait' function in Allegro5?
I am creating a game in allegro5 and I have come across a problem. I have a character that fires a shotgun and there needs to be a delay before he can shoot again. The code for shooting his gun is in a function called

```
fire_shotgun();

```

and I cant find a way to create a pause before he shoots again without stopping the whole game by using

```
al_rest();

```

I am wondering if there is any way to do this.

P.S. my game is running on a 60FPS timer if that is of any use.

# Answer
There are a couple of ways to approach this. One is to simply count down from the last time the gun was fired. If you have an `update` function that gets called every frame, you can do something like:

```
void update(float timeElapsed) {
    ...
    cooldown -= timeElapsed;
    ...
}

...

void fireShotgun() {
    if (cooldown <= 0) {
        createBullets();
        playSound();
        // etc...
    }
}

```

Another approach is to create a new `ALLEGRO_TIMER` that will notify you when the player is ready to fire again. This will likely be more complicated than the countdown approach.
> 5 votes

---
Tags: c++, allegro
---


# Question
Title: [opengl]get world position after rotate object by pivot
I need to rotate an object around a pivot,so I use this theory:

1. Translate the object to Pivot position
2. Rotate the object
3. Translate back the object from Pivot position

everything works fine,I can successfully rotate the object by a fixed point. but the problem is, I lose control of the world position of the object.how can I calculate the world position?

# Answer
A scene graph node typically stores this kind of information:

* Parent node (reference)
* Transform (matrix) OR ( translation (matrix) AND rotation (matrix) \[AND scale (matrix)\] )
* Children nodes (references)

To determine the final position of a node, you compute the transformation of the node, then calculate the transformation of each of the parents, in order, up to the root of the scene graph.

So you don't "lose" information, it's there and it's computed on a per-need basis.
> 0 votes

---
Tags: opengl, rotate
---


# Question
Title: Resuming a previous scene from a current scene using the Unity3D
I am building a first person shooter game using unity and I am facing the problem of resuming a scene from its current state. It would be easy to pause the scene by using the `Time.timeScale = 0.0;` within the scene itself. But I am loading a pause scene to ask whether the user wants to restart, resume or quit. But when I click on resume, it loads the scene I want, but it is totally fresh (i.e when the Ammo is supposed to be half full, it is full. Or the enemy has lost a part of his life, but then it starts with life completely full)

How do I resume the previous scene from where it left off using `SceneManager`? This could have been somewhat easy by using the `Application.loadLevel()` and making sure that application does not destroy the previously loaded state.

Here is the script I made for the pause scene.

```
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System.Collections;

public class pauseScript : MonoBehaviour {

    // Use this for initialization
    void Start () {

    }

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

    }

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

    public void restartPress()
    {
        SceneManager.LoadScene("prototype1");
    }

    public void resumePress()
    {
        SceneManager.LoadScene("prototype1");
    }
}

```

Here is the code snippet for calling the pause menu scene. and this is in another script.

```
SceneManager.LoadScene ("PauseMenu");

```

Is there anyway to save the current scene before calling the PauseMenu scene as shown in the above statement? This may be a simple enough query to you but I am completely new to game development as a whole and I am using unity for the first time, so please go easy on me.

Thanks

# Answer
> 5 votes
You can use SceneManager with `LoadSceneMode.Addtive`. By that you will be able to load another scene on your current scene.

And when you want to resume just unload Pause Scene using `UnloadScene`

```
//===============================================================================//
// Gameplay.cs
public bool _paused = false;

// Pausing Game
void PauseGame()
{
    SceneManager.LoadScene ("YOUR_PAUSE_SCENE", LoadSceneMode.Additive);
}
//===============================================================================//

//===============================================================================//
// PauseMenu.cs

// Resuming Game
void ResumeGame()
{
    Gameplay gp = FindObjectOfType<Gameplay>();
    gp._paused = false;
    SceneManager.UnloadScene ("YOUR_PAUSE_SCENE");
}
//===============================================================================//

```

**Tip:** Remove Camera from your Pause Scene as LoadingScene in Additive mode will add all your game objects of pause scene in current scene.

---
Tags: unity
---


title: Transform matrix hierarchy issue

text:
# Question
Title: Transform matrix hierarchy issue
I'm trying to implement a parent child relationship between Sprites and draw them to the screen. I'm calculating transforms by chaining transform matrices.

I'm using code from here:

```
    private void Draw(Texture2D texture, Matrix transform)
    {
        Vector2 p, s;
        float r;
        DecomposeMatrix(ref transform, out p, out r, out s);
        spriteBatch.Draw(texture, p, null, Color.White, r, new Vector2(texture.Width / 2, texture.Height / 2), s, SpriteEffects.None, 0.0f);
    }

    private static Matrix GetMatrix(Vector2 position, Vector2 scale, float rotation)
    {
        return Matrix.CreateScale(scale.X, scale.Y, 1f) * Matrix.CreateRotationZ(rotation) * Matrix.CreateTranslation(position.X, position.Y, 0f);
    }

    private static void DecomposeMatrix(ref Matrix matrix, out Vector2 position, out float rotation, out Vector2 scale)
    {
        Vector3 position3, scale3;
        Quaternion rotationQ;
        matrix.Decompose(out scale3, out rotationQ, out position3);
        Vector2 direction = Vector2.Transform(Vector2.UnitX, rotationQ);
        rotation = (float)Math.Atan2(direction.Y, direction.X);
        position = new Vector2(position3.X, position3.Y);
        scale = new Vector2(scale3.X, scale3.Y);
    }

```

And I'm drawing things like this:

```
        Matrix parentT = GetMatrix(parentPosition, parentScale, parentRotation);
        Matrix childT = GetMatrix(childPosition, childScale, childRotation);
        childT = childT * parentT;
        Draw(parent, parentT);
        Draw(child, childT);

```

This seems to be working fine except when the parent has a different scale than \[1, 1\]. For example, when the scale is \[2, 1\] and the child is rotating - the child gets scaled along the world X axis which causes it to look deformed:

The result I actually want is:

I still want the child to be affected by the parent's scale while taking the rotation into the account. I guess I could temper with the scale and apply it manually but that doesn't feel right. How to achieve this behaviour using matrices?

# Answer
Change your Methods:

First you need to scale, so your model is still at the origin, but now has the right dimension. Then rotate it so the center still lies on the origin and the side are now rotated. Then translate the object to the place you want.

what you want to do is the following:

```
matrix child = scaleChild * scaleParent * rotateChild * translateChild * rotateParent * translateParent;

```
> 2 votes

---
Tags: xna, monogame
---


title: Using bone joints

text:
# Question
Title: Using bone joints
I am trying to save bone joints to a file, and am using this format. I was wondering if anyone could clear up a few questions I have

1. why do I need to provide rotation data for the bone, if I already gave it the location?
2. How do I calculate the rotation of each axis if I have the relative location from the parent joint?

\** EDIT \**

After doing some more digging, I think that it has something to do with quaternions, so, could someone point me to a good resource on using quaternions for bone joints?

\** EDIT AGAIN \**

I think I've solved it, but I don't understand how it works. I can't seem to find any google results explaining it. I'd appreciate if anyone could send resources explaining it to me.

# Answer
> 0 votes
1. In the end, bones are just simplified sets of data that generate standard transformation matrices.

Bones have position and orientation in space, they can be scaled, they can be located anywhere and are not necessarily connected to one another. Yet, many approaches to skeletal animation skip some of those possibilities and work with simpler approach where bones could have as little as just rotation and length, or just position and rotation. Other data required to construct transformation matrix is calculated from that and assumptions (e.g. that bones always attach to parent bone, or that rotation is (0,0,0) by default).
2. There are many ways and all of them will be valid. You can set (0,0,0) rotation, or you can set it to point or the next bone in hierarchy, or something else.

From programmers point of view, Euler angles are simpler to code, but from animators point of view, Euler angles are harder to work with and require extra efforts to avoid Gimball locks.

# Answer
> 0 votes
I'll tell you what I know about quaternions so far as I'm now attempting my own 3d animation. A quaternion is a combination of a Vector and a Scaler. A Vector are real number components that can represent direction distance or,velocity(i.e. (x,y,z)). A Scaler is a magnitude(distance/length) without an angle. with these you can calculate what you need to know about a particular bones capabilities like rotation and distance.

---
Tags: 3d
---


# Question
Title: Enable and disable different component on a Gameobject
So far I am not clear how do you actually access the various components on a game object, to enable and disable them.

I have a component that has various scripts and elements, like a camera, transform, audio listener and few other custom scripts.

It is in the scene, so I try to access to it via script:

```
private GameObject _player;

_player = GameObject.Find("the_player")

```

So far so good; if I want to access for example to the camera, and enable or disable it, I can do it

```
    _player.GetComponent<Camera>().enabled = true;

```

This disable correctly the camera, or eanble it, depending from the paramenter that I pass.

Now, if I want to access my script, called "playerscript"; I can't do the same thing, since I get an error:

```
    _player.GetComponent<playerscript>().enabled = true;

```

Not sure why I get an error; I have a class that is called "playerscript", that is attached to that \_player object, but instead, VS complain.

This is the error message:

```
Error   CS0246  The type or namespace name 'playerscript' could not be found (are you missing a using directive or an assembly reference?)

```

I did try to use also GetComponentInChildren, but the result is the same.

If I have the object \_player, which hold a reference to the original game object instantiated in the scene, why I can't simply access all the elements attached to it, via GetComponent and dot notation? I believe this used to work time ago, but in Unity5 I can't get this to work.

EDIT: This is the content of the playerscript class:

```
using UnityEngine;
using System.Collections;

public class playerscript : MonoBehaviour
{
    // Use this for initialization
    void Start()
    {
        // get the instance of the button from UI manager
    }

    void OnTriggerEnter(Collider world_item)
    {
        //enable item animation
    }

    void OnTriggerExit(Collider world_item)
    {
        //disable item animation
    }
}

```

# Answer
> 1 votes
The solution came from Hamza's suggestion: close VS and start it again.

Once I did restart VS, now it is able to recognize correctly the scripts without problem.

I guess the issue is that VS get stuck sometimes, and does not see scripts created by the user, until you restart it. I will file a bug report to Microsoft to point out the issue.

If it ever happen to you; restart Unity and then launch VS double clicking on a script in Unity; which will restart VS.

---
Tags: unity, c#
---


title: Day/Night - Rotation from a sine wave

text:
# Question
Title: Day/Night - Rotation from a sine wave
I recently found this question on stack exchange with a great answer that showed how to condense game time into a sine wave, where 1 = midday and -1 = midnight

Converting time of day into a smooth day/night variable?

I've implemented this fine as far as I can tell but I'm a little confused as to how one would get a clean rotation from this to drive a directional light.

Currently I'm using arc-sine to revert the wave to radians and then converting it to degrees but I feel like this is going against the whole process of getting the sine in the first place. It doesn't actually work correctly anyway because we can't tell what side of the unit circle we're on, at least not with my current setup.

Is there a clean way for me to extract a rotation from this sine value so a sun would rotate smoothly? Thanks!

# Answer
just my impression, but are you sure that you are not over-complicating things?

Why invert the sine function at all, when you have the argument you have passed to it? That's precisely the value you are looking for, in your quest for trigonometric functions inversion...

Just either cache the sin argument somewhere before applying the function to it, or just re-create the argument. Convert it to degrees, and you are set.

Keep in mind the DRY principle: the `sin` result is useful to get right things like "ambient light" values, or to feed, for instance, a proper value to NPC agents, but it's just a derivative value. The *proper authoritative source* for the time of the day in your game, is still the double/int/whatever variable where you keep track of your game cycles/wall time, and as long as you have it, you can get from it all kind of different time *manifestations*, whether is -1/+1 for day/night, or something as complex as a quaternion keeping track of true ephemeral for the sun position.

Hope this helps!

**UPDATE** Cursory explanation of the algorithm behind time/rotation/sin, as requested in the comments.

Suppose you start with the `game time`, that is, the number of seconds within your simulation.

The sine function you use is just a mathematical construct (one of many actually) that turns your linear, ever increasing time (0 at the start of the simulation, 3600 after 1 hour of game time, 36000 after 10 hours, ecc) into a *periodic* function.

The nice thing is that if you multiply your time for a proper constant before applying the sin function, that is `2PI/day_length_in_seconds`, the result will oscillate with a period that's *exactly* with the same period of your day/night cycle, and will be, save for a time offset, 1 at noon and -1 ad midnight, and this is very useful in a number of situations, as stated in the first part of the answer, and is what you already have. But...

*The argument of sin is an angle in radians* (at least on most math libraries implementations...) and it happens to be, after a rad2deg conversion (180 x the argument / PI) and normalization (x % 360) exactly the angle you are looking for, that is 90deg at noon, -90 at midnight.

You don't need the sin function at all to compute the angle, because it's the other way around: you already have to have the angle to compute the sin function.

As for lighting, just a few tips: you can use the result of `sin` to compute the ambient light, with some rescaling/biasing, and then use the angle to put the sun into the sky and also to compute the diffuse and specular components (if you use the phong model), but first, do read a good tutorial/primer on trigonometry and get the hang of it: it's very basic stuff, and you definitely need that (and more...) for even casual game development ;-)
> 4 votes

---
Tags: mathematics, trigonometry
---


# Question
Title: Can't get Depth testing to work (cube faces shine through)
I'm making my first steps with OpenGL with LWJGL. I am currenlty constructing a... wait for it... **CUBE**. Quite creative...

Up to now i made it to three of its faces and thats where the Problems began. Sometimes its faces overlap each other. Googeling that Problem brought up **DEPTH TESTING** thing which i tried immediately unfortunately with no luck. The Problem remains the same. The faces are still "overlapping" eachother and it seems that this is somehow related to the drawing order.

Here is my complete code:

```
import org.lwjgl.LWJGLException;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;

import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.util.glu.GLU.gluPerspective;

public class Cube {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            Display.setDisplayMode(new DisplayMode(1024, 768));
            Display.create();
            Display.setVSyncEnabled(true);

        } catch (LWJGLException e) {
            e.printStackTrace();
        }

        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        gluPerspective(30f, 1024f / 768f, 0.00001f, 100);
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        glEnable(GL_3D_COLOR);
        glClearDepth(1.0f);                      // Depth Buffer Setup
        glEnable(GL_DEPTH_TEST);              // Enables Depth Testing
        //glDepthFunc(GL_ALWAYS);               // The Type Of Depth Testing To Do
        // Really Nice Perspective Calculations
        glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
        //glShadeModel(GL_SMOOTH);

        System.out.println(glGetString(GL_VERSION));

        float speed = 0.0f;
        float rotationX = 0;
        float rotationY = 0;
        float rotationZ = 0;

            while(!Display.isCloseRequested()){
                System.out.println(glGetError());
                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

                glTranslatef(0, 0, speed);

                if(Mouse.isButtonDown(0)){
                    rotationX +=1;
                }

                if(Mouse.isButtonDown(1)){
                    rotationY += 1;
                }

                if(Mouse.isButtonDown(2)){
                    rotationZ += 1;
                }

                rotationX %= 360;
                rotationY %= 360;
                rotationZ %= 360;

                glPushMatrix();
                    glTranslatef(0, 0, -50);
                    glRotatef(rotationX, 1, 0, 0);
                    glRotatef(rotationY, 0, 1, 0);
                    glRotatef(rotationZ, 0, 0, 1);
                    glBegin(GL_QUADS);

                        glColor3f(1, 0, 0);
                        //Deckel
                        glVertex3f(0, 5, 0);
                        glVertex3f(5, 5, 0);
                        glVertex3f(5, 5, -5);
                        glVertex3f(0, 5, -5);

                        glColor3f(1, 1, 1);
                        //Front
                        glVertex3f(0, 0, 0);
                        glVertex3f(5, 0, 0);
                        glVertex3f(5, 5, 0);
                        glVertex3f(0, 5, 0);

                        glColor3f(0, 1, 0);

                        glVertex3f(0, 5, -5);
                        glVertex3f(5, 5, -5);
                        glVertex3f(5, 0, -5);
                        glVertex3f(0, 0,-5);

                    glEnd();
                glPopMatrix();

                if(Keyboard.isKeyDown(Keyboard.KEY_UP)){
                    speed += 0.05f;
                }

                if(Keyboard.isKeyDown(Keyboard.KEY_DOWN)){
                    speed -= 0.05f;
                }

                Display.update();
                Display.sync(60);
            }

            Display.destroy();
    }
}

```

**If you're using the code, you can rotate the "cube" by using the three mouse buttons**

* Is there anything that i'm obviously doing wrong?
* Does this code work for anyone?
* Could this problem result from using this on Linux?, 'cause that's what i'm doing.

# Answer
> 3 votes
Sometimes using a 0 or very low value for the zNear will result in a bad depth calculation. Try using the following instead:

```
   gluPerspective(30f, 1024f / 768f, 1.0f, 100);

```

# Answer
> 1 votes
Having depth problem, I found out a topic telling to place `glEnable(GL_DEPTH_TEST);` on display function. So I played out with it, and found out that in my case it works fine as last call in init function. So putting in display function would be overdone.

Example of my init function:

```
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA|GLUT_ALPHA|GLUT_DOUBLE|GLUT_DEPTH);
glShadeModel(GL_SMOOTH);
glClearDepth(1.0f);
glDepthFunc(GL_LESS);
glDepthMask(GL_TRUE);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glEnable(GL_DEPTH_TEST); // <-- it works here; anywhere above it doesn't work

```

---
Tags: opengl, java, lwjgl
---


title: OnMouseClick not detected

text:
# Question
Title: OnMouseClick not detected
I created "main script" and in `Start()` created simple cube:

```
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.localScale = new Vector3 (1,2,1);
cube.GetComponent<Renderer>().material.color = new Color(0,0,255);
cube.AddComponent<CubeScript>();

```

and then in CubeScript I have empty `Start()` and `Update()` but in `onMouseDown()` just `Debug.Log("click detected");`

and I can never see log despite clicking on cube.. Any advice? did I missed something?

# Answer
problem actually was that I typed onMouseDown() instead of **O**nMouseDown() .. Everybody coming from Java world pay attention!!! MonoDevelop will not warn you that mathod with such a name doesn't exist, but it will just silently ignore the issue.

Thanks a lot to @Malrig & @Hasan .. There were really trying to help me and made me double check what I typed
> 2 votes

# Answer
Your cube doesn't have a collider.

Try

```
cube.AddComponent<BoxCollider>();

```

See: http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseDown.html
> 1 votes

---
Tags: unity, mouse
---


title: What is render path?

text:
# Question
Title: What is render path?
What is "render path"? Who invented this term?

I can suppose that this thing mean something one from the list below:

* The thing which shows which rendering technique should be used (e.g. forward/deffered rendering)
* Module for rendering lines and curves
* Description how shaders should be connected in mutlipass render to reach the goal of some render FX.

For what this term is stand for? Thanks

# Answer
I think it's more commonly called a history tree by 3d modelers. I've heard of render path and render tree to describe the ORDER in which render steps occur.

For an image render example: If you blur 10%, then add a sparkle light source looks different than if you do those two events in the opposite order.

In a class once taught, I showed a 3d model example where the model looks different if you start with a rectangular solid and then fillet first and hollow as the 2nd step, versus if you hollow 1st and fillet the outside second.

In the image below, you can see difference in the shape when you change the ORDER of the model render history.

Here's the terms that I think are close synonyms in 3d modeling:

* History Tree
* Model Tree
* Render Tree
* Render Path
> -1 votes

---
Tags: graphics, rendering
---


# Question
Title: How to avoid recursive and or infinity loop monogame return function
This piece of code is returning on a infinite base how to fix?

```
public GuiElement MoveElement(int x, int y)
{
    GUIRect = new Rectangle(GUIRect.X += x,GUIRect.Y += y,GUIRect.Width,GUIRect.Height);
    return MoveElement(x,y);
}

```

this is where i set the values i have in my Other class

```
        gm.Add(new GuiElement("BackGround"));

        gm.Add(new GuiElement("Play_Button").MoveElement(150, 50));

        gm.Add(new GuiElement("HighScore_Button"));

        gm.Add(new GuiElement("Quit_Button"));

```

basicly i want a to be able to move some elements using that MoveElement

it creates a infinite loop

An unhandled exception of type 'System.StackOverflowException' occurred in giftman.exe

# Answer
> 3 votes
You don't need to use recursion for this (and without a base case, you'll get an infinite loop, like you are).

Just change your method to:

```
public GuiElement MoveElement(int x, int y)
{
    GUIRect = new Rectangle(GUIRect.X += x,GUIRect.Y += y,GUIRect.Width,GUIRect.Height);
    return this;
}

```

Or better yet, add a constructor to set the position of your GuiElement, so you can just call it like this:

```
gm.Add(new GuiElement("Play_Button", 150, 50));

```

Or you can just change your `MoveElement` method to not return anything at all:

```
public void MoveElement(int x, int y)
{
    GUIRect = new Rectangle(GUIRect.X += x,GUIRect.Y += y,GUIRect.Width,GUIRect.Height);
}

```

Then when creating it you can do this:

```
GuiElement playButton = new GuiElement("Play_Button");
playButton.MoveElement(150, 50);
gm.Add(playButton);

```

---
Tags: c#, monogame
---


title: Struggling to define js sprite sheet

text:
# Question
Title: Struggling to define js sprite sheet
I've been working on this for a couple days, unable to get anything to load. Here is the whole page. Please help me find what I'm doing wrong. Right now, I'm only trying to render the first card in the upper left corner of the main canvas context.

```
<html>
  <head>
    <style>
      canvas#game-canvas {
        position: absolute;
        top: 5%;
        left: 5%;
        background: lightblue;
        height: 281px;
        width: 500px;
      }
      body {
        background: darkblue;
      }
    </style>
    <script type="text/javascript" src="jquery1_10_2_min.js"></script>
    <script>
      var canvas = document.getElementById("game-canvas");
      var context = canvas.getContext("2d");

      function cardsheet(path, frameWidth, frameHeight) {

         this.image = new Image();
         this.frameHeight = frameHeight;
         this.frameWidth = frameWidth;
         this.image.src = path;

         var card_sprites = [];
         var card_names = [
         '1d', '2d', '3d', '4d', '5d', '6d', '7d', '8d', '9d', '10d', 'Jd', 'Qd', 'Kd',
         '1h', '2h', '3h', '4h', '5h', '6h', '7h', '8h', '9h', '10h', 'Jh', 'Qh', 'Kh',
         '1s', '2s', '3s', '4s', '5s', '6s', '7s', '8s', '9s', '10s', 'Js', 'Qs', 'Ks',
         '1c', '2c', '3c', '4c', '5c', '6c', '7c', '8c', '9c', '10c', 'Jc', 'Qc', 'Kc'];

         this.image.onload = function() {
            framesPerRow = Math.floor(this.image.width / frameWidth);
            framesPerCol = Math.floor(this.image.height / frameHeight);
            k = 0;

            for (i = 0; i < framesPerRow; i++) {
              card_sprites[card_names[k] + '_canvas'] = document.createElement('canvas');
              card_sprites[card_names[k] + '_canvas'].width = frameWidth;
              card_sprites[card_names[k] + '_canvas'].height = frameHeight;
              card_sprites[card_names[k] + '_context'] = card_sprites[card_names[k] + '_canvas'].getContext('2d');
              card_sprites[card_names[k] + '_context'].drawImage(this.image, frameWidth * i, frameHeight, frameWidth, frameHeight, 0, 0, frameWidth, frameHeight);
              k++;
            }
         };
        return card_sprites;
      }

      var cards = cardsheet('small_playing_cards.png', 54, 65);
      context.drawImage(cards['1d_canvas'], 10, 10);
    </script>

  </head>
  <body>
    <canvas id="game-canvas"></canvas>
  </body>
</html>

```

UPDATE (Still not working...)

```
<script type="text/javascript" src="jquery1_10_2_min.js"></script>
<script>
$(document).ready(function() {
  var canvas = document.getElementById("game-canvas");
  var context = canvas.getContext("2d");

  var cards = cardsheet('small_playing_cards.png', 54, 65);
  context.drawImage(card_sprites_context[0], 10, 10);
});

function cardsheet(path, frameWidth, frameHeight) {

   this.image = new Image();
   this.frameHeight = frameHeight;
   this.frameWidth = frameWidth;
   this.image.src = path;

   var card_sprites_canvas = [];
   var card_sprites_context = [];
   var card_names = [
   '1d', '2d', '3d', '4d', '5d', '6d', '7d', '8d', '9d', '10d', 'Jd', 'Qd', 'Kd',
   '1h', '2h', '3h', '4h', '5h', '6h', '7h', '8h', '9h', '10h', 'Jh', 'Qh', 'Kh',
   '1s', '2s', '3s', '4s', '5s', '6s', '7s', '8s', '9s', '10s', 'Js', 'Qs', 'Ks',
   '1c', '2c', '3c', '4c', '5c', '6c', '7c', '8c', '9c', '10c', 'Jc', 'Qc', 'Kc'];

      framesPerRow = Math.floor(this.image.width / frameWidth);
      framesPerCol = Math.floor(this.image.height / frameHeight);
      k = 0;

      for (i = 0; i < framesPerRow; i++) {
        card_sprites_canvas[k] = document.createElement('canvas');
        card_sprites_canvas[k].width = frameWidth;
        card_sprites_canvas[k].height = frameHeight;
        card_sprites_context[k] = card_sprites_canvas[k].getContext('2d');
        card_sprites_context[k].drawImage(this.image, frameWidth * i, frameHeight, frameWidth, frameHeight, 0, 0, frameWidth, frameHeight);
        k++;
      }

  return card_sprites_context;
}

</script>

```

# Answer
I can see a few issues with this code. The first is that you get the `canvas` variable before it actually exists. To fix this, put all of the code outside of the `cardsheet` function into a different function, and make that function load on `window.onload = function() {outsideFunction()};`.

The second issue is to do with the card\_sprites array, as the function effectively returns nothing. This is because of the way you access the array. In order to access the first element of an array, you need to use `exampleArray[0]`, and increase 0 for each element in the array. You can see how it's nonsensical, then, to try and access `card_sprites["1d_canvas"]`

To give you an idea of how to actually use arrays, see the below code snippet:

```
for (i = 0; i < framesPerRow; i++) {
  card_sprites_canvas[i] = document.createElement('canvas');
  card_sprites_canvas[i].width = frameWidth;
  card_sprites_canvas[i].height = frameHeight;
}

```
> 0 votes

# Answer
You are referencing `card_sprites_context` in your document.ready-function, even though it's not defined at that scope. You should switch that line to `context.drawImage(cards[0], 10, 10);`.
> 0 votes

---
Tags: javascript, sprites, spritesheet
---


# Question
Title: Why are my canvas drawings larger than the actual image?
For the following page source, I've finally gotten a grip on rendering the cards. I'm puzzled why they appear about 2.5x larger on the canvas.

```
<html>
  <head>
    <style>
      canvas#game-canvas {
        position: absolute;
        top: 5%;
        left: 5%;
        background: lightblue;
        height: 281px;
        width: 500px;
      }
      body {
        background: darkblue;
      }
    </style>
    <script type="text/javascript" src="jquery1_10_2_min.js"></script>
    <script>
    // $(document).ready(function() {
      window.onload = function() {
      var canvas = document.getElementById("game-canvas");
      var context = canvas.getContext("2d");

      var cards = cardsheet('small_playing_cards.png', 50, 68);
      context.drawImage(cards[0], 10, 10);
      context.drawImage(cards[1], 50, 50);

      function cardsheet(path, frameWidth, frameHeight) {

         this.image = new Image();
         this.frameHeight = frameHeight;
         this.frameWidth = frameWidth;
         this.image.src = path;

         var card_sprites_canvas = [];
         var card_sprites_context = [];
         var card_names = [
         '1d', '2d', '3d', '4d', '5d', '6d', '7d', '8d', '9d', '10d', 'Jd', 'Qd', 'Kd',
         '1h', '2h', '3h', '4h', '5h', '6h', '7h', '8h', '9h', '10h', 'Jh', 'Qh', 'Kh',
         '1s', '2s', '3s', '4s', '5s', '6s', '7s', '8s', '9s', '10s', 'Js', 'Qs', 'Ks',
         '1c', '2c', '3c', '4c', '5c', '6c', '7c', '8c', '9c', '10c', 'Jc', 'Qc', 'Kc'];

            framesPerRow = Math.floor(this.image.width / frameWidth);
            framesPerCol = Math.floor(this.image.height / frameHeight);
            k = 0;

            for (i = 0; i < framesPerRow; i++) {
              card_sprites_canvas[k] = document.createElement('canvas');
              card_sprites_canvas[k].width = frameWidth;
              card_sprites_canvas[k].height = frameHeight;
              card_sprites_context[k] = card_sprites_canvas[k].getContext('2d');
              card_sprites_context[k].drawImage(this.image, frameWidth * k, frameHeight * 0, frameWidth, frameHeight, 0, 0, frameWidth, frameHeight);
              k++;
            }

        return card_sprites_canvas;
      }
    };

    </script>

  </head>
  <body>
    <canvas id="game-canvas"></canvas>
    <img src="small_playing_cards.png">
  </body>
</html>

```

# Answer
> 1 votes
You need to set the canvas size:

```
<body>
    <canvas id="game-canvas" width=500 height=281></canvas>
    <img src="small_playing_cards.png">
</body>

```

---
Tags: javascript, html5, html-canvas
---


# Question
Title: Dijkstra's algorithm null hypothesis pathfinding without navmesh
I am having trouble understanding how to implement dijkstra's algorithm for a path finding assignment, here's what the layout looks like:

Each node has a List of neighbours which are found using raycasting. Now the issue i am having is how to weight each node.... I understand Dijkstras maintains a list of visited nodes and an open list. I just don't understand how to weight them individually based on where i want to go.

Right now i'm weighting them all by a distance of 1. But this seems to be incredibly redundant and is going to take an extremely long time to find the shortest path because it's going to check every possibility of a paths to the endNode....

Can someone help me understand the logic of how to implement dijkstra's algorithm in this environment?

# Answer
To answer your questions one by one:

> Each node has a List of neighbours which are found using raycasting. Now the issue i am having is how to weight each node.... I understand Dijkstras maintains a list of visited nodes and an open list. I just don't understand how to weight them individually based on where i want to go

because you found those node by raycasting, in order to find the *shortest* path the weight of edges must be naturally equal to **distance**(or multiple of) between those nodes and *not* influenced by the goal node. Dijskras algorithm does not care what the goal node is - the output of the algorithm is *w-distance*(weighted distance, in your case just the "distance") from one node to *every* other.

> Right now i'm weighting them all by a distance of 1.

that is partially correct way because it is a multiple of distance between adjacent nodes - assuming they are on grid and it is not diagonal distance, which would be sqrt(2).

> But this seems to be incredibly redundant and is going to take an extremely long time to find the shortest path because it's going to check every possibility of a paths to the endNode....

Profile first, judge speed after. Dijsktra runs in ~n^2, raycasting all vs all will cast n^2 rays *and* check up *all* objects in scene each, moreover contrary to the pathfinding algorithm there is quite complicated math behind it that takes time.
To speed things up there is for example very popular A\* algorithm, however I would not be surprised if it were actually *slower* than Dijkstra for input with few number of nodes(\<1000?) just because it is more complicated algorithm.
You can imagine(very simplified!) Dijkstra as filling the map with water from start node(that does not stop until all map is full), A\* is analogy with the map tilted towards goal node.
Alternatively, you can use Floyd-Warshals algorithm which runs in n^3 and computes shortest path "all vs all". This way, you can run the computation "offline" before game is loaded, effectively reducing time to ~zero. Note: because paths are pre-computated, it will not handle moving obstacles.
> 2 votes

---
Tags: path-finding, dijkstra
---


# Question
Title: How do mobile games create simple UI components?
How are simple UI inputs typically handled in 2D mobile games? For example, text input boxes and keyboards.

It seems that many game engines do always have simple UI components. There are obvious challenges in trying to show native components when your game engine has "control" of the application.

I would be interested if anyone can share their design approach. I am most comfortable with cocos2dx and cocossharp. However I am interested in other 2d game engines and possible work arounds for showing text input boxes and keyboards.

# Answer
I can't speak for cocos2d, but since your post has a libgdx tag, I will tell you how libgdx does it.

Libgdx has the scene2d.ui widgets library that includes several useful UI components like Buttons, TextFields, Checkboxes, etc...

The best part about these widgets is that they are implemented completely within the Libgdx library (on top of OpenGL) so any widgets that you use will be cross platform.

I have found that trying to overlay native controls over your game view is quite tricky and the design is brittle. Since Libgdx's ui controls are basically clickable sprites, you can fully integrate them into your game view and make a much more elegant design.

All of these widgets are also very customizable. In Libgdx you can load a skin JSON file where you can point to assets and styles to customize the look of your UI. These skins even support nine patches.

Here's a link to libgdx's scene2d.ui page

I don't know if cocos2d has something similar, but if you decide to go with cocos2d look for a similar ui library. I would definitely go for integrated controls over native controls any day
> 1 votes

# Answer
If you are familiar with Android's UI design, and its properties, it is pretty easy to program something for yourself. So if you want to learn to design a pretty UI, study Android. It doesn't matter game UI or not. It's same thing.

I recently made a ListView. I haven't tried it yet. So it is incomplete. But there is some rules, every UI element should obey.
1. Every UI element should inherit same class.
2. Dimensions and position should be dynamic. Also it's properties. For example program your list view for one column or more. If you need a two column list then you don't need another class.
3. Instead of hardcoding, use **final** variables. For example padding, if you use a final variable for that, you can change it more easily.

Don't forget Android, design some apps, study the UI. You will get a good idea.

NOTE: Android uses dpi system instead of the traditional pixels. So it can be viewed perfectly in different screen sizes and resolutions. If you are targeting multiple resolutions on your game, your UI dimensions should be dynamic. In 4K texts cannot be at the same size as a 720p display.

I almost forgot: Listeners. When you select something in the list view, listener tells the upper class (where you used list view) that the something is selected and which one is selected. Listeners are important.
> -2 votes

---
Tags: libgdx, gui, cocos2d
---


# Question
Title: How to generate tiled delaunay triangulation mesh (delaunay triangulation within a rectangle with triangles connecting opposing edges)?
I have a nice triangulation of a square mesh. The way I do this currently is

1. generate square mesh (two triangles), from (0.,0.) to (1.,1.) (axis-aligned and normalized for simplicity)
2. add point somewhere within square (poisson disk sampling)
3. detect which triangle point falls within
4. subdivide into 3 triangles
5. iterate over all tris, perform "delaunay flips" where necessary
6. GOTO 2

This works great (a bit simplified, as there's also edge-case detection code to account for colinear points, fp precision errors, etc...).

Anyways, what I want to do now is have the edges of this square "wrap".

EDIT: Upon request, here are some illustrations to help convey my problem:

So, we have an initial set of pts:

A normal delaunay triangulation would generate something like this:

What I want is a *tessalated* delaunay triangulation. That is, what edges would have to exist to allow this to be infinitely tile-able:

An example set of edges might be like this:

Now, imagine if you left those connections, but didn't tile them. I've drawn just the "wrapping" connections for the red dot and the purple dot in green, assuming there is only one instance of each dot in view (centered around the initially displayed set of dots):

Already, it's a topological mess. But in theory, I'd expect it would work, assuming I stick to some implementation constraints.

So, the plan would be to create a mesh containing all these pts and their respective connections. I would have some offset, and move the points in the vertex shader as a modulus of that offset. That way, every point will exist as "the closest instance of that point in the infinitely tiling plane" to the offset (for example, the camera). Since all the connections are in place, I wouldn't have to mess with them, and would get infinitely-scrolling (repeating) "terrain". All the topologically-messy-wrapping connections would be "backfacing" triangles, and would be culled... right?

Edit: Ok no they would *not* necessarily be backfacing... shoot. (if the wrap of the triangle was both vertically and horizontally wrapped, it would be back to frontfacing. My best guess at a solution is to, in the vert shader, artificially lower all the pts "close" to being wrapped, so any wonky giant tri's show up way below any legitimate tris. #hack.

Ok. off to try this. Will report back with any updates...

# Answer
Ok. I did it. I'll give a brief description- if someone in the future needs more details feel free to request source.

Because it's tiled, my "non-tiled" solution for generating a delaunay mesh doesn't work. It starts by creating a 4 bounding corner points, dividing them into 2 triangles, and then adding one point at a time (each added point subdividing the triangle it is within). When tiling, you can't do this, because those 4 bounding points *are all the same point*.

So, to alleviate that, I instead create 9 internal points (at intersection of x = 0.15, 0.5, and 0.85, and y = the same). I connect them as triangles as though they were in a standard grid. But I also create backfacing triangles connecting the left side to the right, and the top side to the bottom. Then I create *front facing* triangles connecting the four corners in a square (I'll leave it as an exercise to the reader to see why this makes sense).

Once you have this basic, wrapping triangulation, you can (similar to the old method) add one point at a time, subdividing its internal triangles. The trick is that you need to do some modulus arithmetic, centered around the point you are adding, to ensure the "triangle" you're considering is in the orientation as it would be displayed (for example, if you have a triangle with two points near the top left, and one point near the bottom right, the intended orientation of that triangle is one that wraps both the vertical and horizontal axis- NOT a triangle spanning the entire mesh).

Because we started with a triangulation with each triangle's bounding area of less than (0.5,0.5), we know that no *larger* triangles will be created. So a quick test of its area is helpful in determining whether you are considering the triangle correctly.

Once you are able to do that, just add points to your own satisfaction!
> 5 votes

---
Tags: mesh, delaunay-triangulation
---


# Question
Title: Is it legal to use the game mechanics of risk if I don't use their name?
I'm currently developing an idea for a conquest-style board game similar to Risk. I was wondering if I would be legally entitles to use some game mechanics that appear in that game so long as I don't use Risk's title or logo or anything.

# Answer
> 2 votes
## Yes.

Game mechanics cannot be copyrighted, so using the Risk gameplay ideas should not be a problem. Obviously, you can't use the *name* Risk because that is trademarked.

That being said, I am not a lawyer. You should avoid copying exact rules or procedures from Risk as you risk (pun intended) running afoul of copyright issues.

# Answer
> 2 votes
**Yes**. There is no harm to use game-mechanics of any one. Even a good mechanics may become a complete genre on which world can run after for at least 6 month :)

For examples you may have a look on ZigZag, Temple Run or Subway Surfers, Air Hockey and so on...

So in short, **YES** you can.

---
Tags: game-mechanics, copyright
---


# Question
Title: Mousedown event not performing drawImage
I've been working on the basic gameplay. I'm to a point where I think it should draw a card in the quadrant clicked/tapped, but nothing is happening. I can't see what's wrong. Please help. My only clue is that this line in `mouse_down_handler`: `alert('X: ' + mouse_x + ', Y: ' + mouse_y);` isn't firing.

```
<html>
  <head>
    <style>
      canvas#game-canvas {
        position: absolute;
        top: 0%;
        left: 0%;
        background: lightblue;
      }
      body {
        background: darkblue;
      }
    </style>
    <script type="text/javascript" src="jquery1_10_2_min.js"></script>
    <script>
      var card_width = 42;
      var card_height = 63;
      var x1 = 0;
      var y1 = 0;
      var width_increment = 167; // Math.floor(canvas.width / 3);
      var height_increment = 167; //Math.floor(canvas.height / 3);
      var x2 = x1 + width_increment;
      var x3 = x2 + width_increment;
      var y2 = y1 + height_increment;
      var y3 = y2 + height_increment;

    window.onload = function() {

      document.addEventListener("mousedown", mouse_down_handler, false);

      var canvas = document.getElementById("game-canvas");
      var context = canvas.getContext("2d");

      var cards = cardsheet('small_playing_cards.png', card_width, card_height);

      function mouse_down_handler(e) {
        var mouse_x = e.clientX;
        var mouse_y = e.clientY;
        alert('X: ' + mouse_x + ', Y: ' + mouse_y);
        play_move(mouse_x, mouse_y);
      };

      function play_move(x, y) {
        // tap left col
        if (x < x2) {
          // tap left box on top
          if (y < y2) {
            play_grid(x1, y1, random_number());
          // tap left middle box
          } else if (y < y3) {
            play_grid(x1, y2, random_number());
          // tap lower left box
          } else {
            play_grid(x1, y3, random_number());
          }

          // tap in center col
        } else if (x < x3) {
          // tap top center box
          if (y < y2) {
            play_grid(x2, y1, random_number());

          // tap mid center box
          } else if (y < y3) {
            play_grid(x2, y2, random_number());

          // tap lower middle box
          } else {
            play_grid(x2, y3, random_number());

          }

          // tap right col
        } else {
          // tap top right box
          if (y < y2) {
            play_grid(x3, y1, random_number());

          // tap right middle box
          } else if (y < y3) {
            play_grid(x3, y2, random_number());

          // tap lower right box
          } else {
            play_grid(x3, y3, random_number());
          }
        }
      };

      function play_grid(x_pos, y_pos, n) {
        if (n >= 0) {
          context.drawImage(cards[n], x_pos, y_pos);
        } else {
          return false;
        }
      };

      function random_number() {
        if (cards_left > 0) {
          var number = Math.floor(Math.random() * cards_left);
          cards = cards.splice(number, 1);
          cards_left--;
          return number;
        else {
          return false;
        }
      };

      function cardsheet(path, frameWidth, frameHeight) {

         this.image = new Image();
         this.frameHeight = frameHeight;
         this.frameWidth = frameWidth;
         this.image.src = path;

         var card_sprites_canvas = [];
         var card_sprites_context = [];
         var card_names = [
         '1d', '2d', '3d', '4d', '5d', '6d', '7d', '8d', '9d', 'Xd', 'Jd', 'Qd', 'Kd',
         '1h', '2h', '3h', '4h', '5h', '6h', '7h', '8h', '9h', 'Xh', 'Jh', 'Qh', 'Kh',
         '1s', '2s', '3s', '4s', '5s', '6s', '7s', '8s', '9s', 'Xs', 'Js', 'Qs', 'Ks',
         '1c', '2c', '3c', '4c', '5c', '6c', '7c', '8c', '9c', 'Xc', 'Jc', 'Qc', 'Kc'];

            framesPerRow = 13; // Math.floor(this.image.width / frameWidth);
            framesPerCol = 4;  // Math.floor(this.image.height / frameHeight);
            k = 0;

            for (i = 0; i < framesPerRow; i++) {
              for (j = 0; j < framesPerCol; j++) {
                card_sprites_canvas[k] = document.createElement('canvas');
                card_sprites_canvas[k].width = frameWidth;
                card_sprites_canvas[k].height = frameHeight;
                card_sprites_canvas[k].face_value = card_face_value(card_names[k]);
                card_sprites_canvas[k].suit = card_suit(card_names[k])
                card_sprites_context[k] = card_sprites_canvas[k].getContext('2d');
                card_sprites_context[k].drawImage(this.image, frameWidth * i + (i * 10), frameHeight * j + (j * 9), frameWidth, frameHeight, 0, 0, frameWidth, frameHeight);
                k++;
              }
            }

        return card_sprites_canvas;
      }
      function card_face_value(card_name) {
        suit = card_name.slice(-1);
        face_value  = card_name.split(suit)[0];
        return face_value;
      }
      function card_suit(card_name) {
        suit = card_name.slice(-1);
        return suit;
      }
    };

    </script>

  </head>
  <body>
    <canvas id="game-canvas" width="500" height="500"></canvas>
    <img src="small_playing_cards.png" style="display: none;">
  </body>
</html>

```

# Answer
> 0 votes
I was missing a curly brace on line 107...

```
  function random_number() {
    if (cards_left > 0) {
      var number = Math.floor(Math.random() * cards_left);
      cards = cards.splice(number, 1);
      cards_left--;
      return number;
    // was "else {" instead of "} else {"
    } else {
      return false;
    }
  };

```

---
Tags: javascript, html-canvas
---


title: 2D Platformer AABB collision issues

text:
# Question
Title: 2D Platformer AABB collision issues
Before anyone say that this questions already has a answer, I will list all the questions I read and tried:

So, whats **my** problem? I am tring to implement a solid collision handling/response, but every time I try I fail. After fail with a lot of tile based solutions, like this one:

```
player.Y = tile.Y - player.height;

```

I am using the XNA Platformer Example as base, it is solid, but not completly. Some of the bugs is this:

This happens very often when the character is even wider than from the example. I solved it changing this line:

```
if (absDepthY < absDepthX || collision == GameMap.TileCollision.Platform)

```

To this:

```
if (absDepthY < absDepthX || collision == GameMap.TileCollision.Platform || _velocity.X == 0)

```

So, if the player isn't moving in the X axis, don't resolve it (resolve the Y axis instead). It worked very well, but it only hides the problem. After some gameplay the error is evident when you fall down and is pushed some tiles to the right. See this example from my game, I slowed down the X velocity:

I can't walk to the left and if I fall on the middle of the tiles, I'm pushed to the right. In the game the velocity isn't too slow, but as I said, it still happens. **This is the real problem.**

## Update

The problem above was solved using David's solution, now I need implement the one-way platforms. The code I have so far is this, I commented the most important parts:

```
private void HandleCollisions(Direction direction)
{
    Rectangle playerBounds = BoundingRectangle;
    int leftTile = playerBounds.Left / (int)GameMap.Instance.TileSize.X;
    int topTile = playerBounds.Top / (int)GameMap.Instance.TileSize.Y;
    int rightTile = (int)Math.Ceiling((float)playerBounds.Right / GameMap.Instance.TileSize.X) - 1;
    int bottomTile = (int)Math.Ceiling(((float)playerBounds.Bottom / GameMap.Instance.TileSize.Y)) - 1;

    _isOnGround = false;

    for (int y = topTile; y <= bottomTile; ++y)
    {
        for (int x = leftTile; x <= rightTile; ++x)
        {
            Vector2 depth;
            Rectangle tileBounds = GameMap.Instance.GetTileBounds(x, y);
            GameMap.TileCollision collision = GameMap.Instance.GetCollision(x, y);

            if (collision != GameMap.TileCollision.Passable && GameMap.Instance.TileIntersectsPlayer(playerBounds, GameMap.Instance.GetTileBounds(x, y), direction, out depth))
            {
                if (collision == GameMap.TileCollision.Platform && direction == Direction.Vertical && previousBottom < tileBounds.Top)
                {
                    // This is reachable if I fall on a platform tile only from the top!
                    _isOnGround = true;
                }

                if (collision == GameMap.TileCollision.Block || (direction == Direction.Vertical && _isOnGround))
                {
                    // The position is increased
                    Position += depth;
                    playerBounds = BoundingRectangle;
                    // But the player falls through the platform block.
                }
            }
        }
    }

    previousBottom = playerBounds.Bottom;
}

```

If I jump from bellow of the platform, when I reach the top of the tile the `_isOnGround` is set to `true`, so the condition bellow is executed and the player is supposed to be pushed to top, but he falls through the platform. I debugged and the `Position` is really increased, but it only happens **one** time. What am I doing wrong?

# Answer
The first problem where the collisions were handled wrong, were solved with this solution posted by David. Instead of solving the two axis at the same time, the solution solves each axis individually. So, instead of sum the velocity at the position and handle the collisions, I sum each velocity and handle the direction:

```
if (_velocity.Y != 0f)
{
    Position += _velocity.Y * Vector2.UnitY * elapsed;
    Position = new Vector2(Position.X, (float)Math.Round(Position.Y));
    HandleCollisions(Direction.Vertical);
}

if (_velocity.X != 0f)
{
    Position += _velocity.X * Vector2.UnitX * elapsed;
    Position = new Vector2((float)Math.Round(Position.X), Position.Y);
    HandleCollisions(Direction.Horizontal);
}

```

To solve the second problem, I need manage a way to make the one-way platformers (the ones where you can jump from bottom but stop if falls from top). To resolve this, I made just like the XNA Platformer Demo. On the begin of `HandleCollisions()`, I reseted the `_isOnGround` variable to `false`, so at the beggin of verification the player is not on the ground.

If the tile collision that is being verified through the loop is not passable and the player is intersecting it, verify if the tile collision is a Platform, if the movement is vertical (because the one-way platforms ignores the x axis), and if the previous bottom of the player is less or equal of the tile top:

```
if (collision == TileCollision.Platform && direction == Direction.Vertical && previousBottom <= tileBounds.Top)
{
    _isOnGround = true;
}

```

If so, the player is on the ground, setting `_isOnGround` to `true`. After that, I check if the tile collision is a block, if is, the player needs be pushed out from the tile, but I also verify if the player is on the ground, that means he landed on a platform, so he also need be pushed out.

```
if (collision == TileCollision.Block || (direction == Direction.Vertical && _isOnGround))
{
    Position += depth;
    playerBounds = BoundingRectangle;
}

```

Before the end of the method, I set `previousBottom = playerBounds.Bottom;`, to prepare for the next `update` loop. The full method:

```
private void HandleCollisions(Direction direction)
{
    Rectangle playerBounds = BoundingRectangle;
    int leftTile = playerBounds.Left / (int)GameMap.Instance.TileSize.X;
    int topTile = playerBounds.Top / (int)GameMap.Instance.TileSize.Y;
    int rightTile = (int)Math.Ceiling((float)playerBounds.Right / GameMap.Instance.TileSize.X) - 1;
    int bottomTile = (int)Math.Ceiling(((float)playerBounds.Bottom / GameMap.Instance.TileSize.Y)) - 1;

    _isOnGround = false;

    for (int y = topTile; y <= bottomTile; ++y)
    {
        for (int x = leftTile; x <= rightTile; ++x)
        {
            Vector2 depth;
            Rectangle tileBounds = GameMap.Instance.GetTileBounds(x, y);
            GameMap.TileCollision collision = GameMap.Instance.GetCollision(x, y);

            if (collision != GameMap.TileCollision.Passable && GameMap.Instance.TileIntersectsPlayer(playerBounds, GameMap.Instance.GetTileBounds(x, y), direction, out depth))
            {
                if (collision == GameMap.TileCollision.Platform && direction == Direction.Vertical && previousBottom <= tileBounds.Top)
                {
                    _isOnGround = true;
                }

                if (collision == GameMap.TileCollision.Block || (direction == Direction.Vertical && _isOnGround))
                {
                    Position += depth;
                    playerBounds = BoundingRectangle;
                }
            }
        }
    }

    previousBottom = playerBounds.Bottom;
}

```
> 5 votes

# Answer
If I understand correctly, your movement issue can be resolved by David's answer, but you want to implement being able to move upwards through platforms. This can be solved with an additional if statement. When you collide with a platform, check the players Y velocity and the target block type to see if you can move upwards through it. If the player's Y velocity is set above 0, or the block type cannot be moved through upwards, then resolve the collision as normal.
> 2 votes

---
Tags: c#, xna, monogame, collision-resolution
---


title: Libgdx Fine Tune Megaman Movement

text:
# Question
Title: Libgdx Fine Tune Megaman Movement
With help from my last question, I was able to fix the issue of having a stuttering effect if you keep hitting jump, while jumping.

I believe I have managed to match moving on the X axis and the physics behind jumping, but I have ran into another hurdle. I'm hoping someone might be able to point out what I am missing.

At this point, the jump looks right, but the collision logic allows Megaman to pass through the floor and stop with his head just under the floor.

EX. Before: After:

Any assistance would be greatly appreciated. I'm really exciting to be learning Libgdx. :)

Megaman.java

```
package com.mygdx.game;

import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer.Cell;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.Input.Keys;

public class Megaman extends Sprite implements InputProcessor
{
/**the movement velocity*/
private Vector2 velocity = new Vector2();

private float speed = 60 * 1.375f;

private float gravity = 0;
private float jumpV = 4.75f;
private static float GRAVITYCONST = -.25f;
private boolean canJump;
private boolean released;
private boolean movingX;
private int movingLR = 1;
private boolean jumping;

private TiledMapTileLayer collisionLayer;

public Megaman(Sprite sprite, TiledMapTileLayer collisionLayer)
{
    super(sprite);
    this.collisionLayer = collisionLayer;

}

@Override
public void draw(Batch spriteBatch)
{
    update(Gdx.graphics.getDeltaTime());
    super.draw(spriteBatch);
}

public void update(float delta)
{
    // apply gravity
            setY(getY() + gravity);

            // clamp velocity
            if(gravity < -7.0f)
                gravity = -7.0f;

            // save old position
            float oldX = getX(), oldY = getY();
            boolean collisionX = false, collisionY = false;

            // move on x
            if(movingLR == -1) // going left
                collisionX = collidesLeft();
            else if(movingLR == 1) // going right
                collisionX = collidesRight();

            // react to x collision
            if((collisionX == false) && (movingX == true)) {
                if(movingLR == -1)
                {
                    setX(getX() - 1.375f);
                }
                else if(movingLR == 1)
                {
                    setX(getX() + 1.375f);
                }
            }

            if(jumping == false){ // going down
                canJump = collidesBottom();
                collisionY = collidesBottom();
                released = collidesBottom();
            }else if(jumping == true) // going up
            {
                collisionY = collidesTop();
                setY(getY() + (jumpV += GRAVITYCONST));
            }

            // react to y collision
            if((collisionY == true) && (jumping = true)) {
                setY(oldY);
                jumpV = 4.75f;
            }
}

public Vector2 getVelocity() {
    return velocity;
}

public void setVelocity(Vector2 velocity) {
    this.velocity = velocity;
}

public float getSpeed() {
    return speed;
}

public void setSpeed(float speed) {
    this.speed = speed;
}

public float getGravity() {
    return gravity;
}

public void setGravity(float gravity) {
    this.gravity = gravity;
}

public TiledMapTileLayer getCollisionLayer() {
    return collisionLayer;
}

public void setCollisionLayer(TiledMapTileLayer collisionLayer) {
    this.collisionLayer = collisionLayer;
}

@Override
public boolean keyDown(int keycode) {
    switch (keycode)
    {
    case Keys.W:
        jumping = true;
        if(canJump) {
            canJump = false;
        }
        break;
    case Keys.A:
        //velocity.x = -speed;
        movingX = true;
        movingLR = -1;  //moving left
        break;
    case Keys.D:
        //velocity.x = speed;
        movingX = true;
        movingLR = 1;  //moving right
        break;
    }
    return true;
}

@Override
public boolean keyUp(int keycode) {
    switch (keycode)
    {
    case Keys.W:
        if (released == true)
        {
            //when W is released, set Y velocity to 0
            //velocity.y = 0;
            released = false;
            jumping = true;
        }
        break;
    case Keys.A:
    case Keys.D:
        //velocity.x = 0;
        movingX = false;
        break;
    }
    return true;
}

@Override
public boolean keyTyped(char character) {
    return false;
}

@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {

    return false;
}

@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
    return false;
}

@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
    return false;
}

@Override
public boolean mouseMoved(int screenX, int screenY) {
    return false;
}

@Override
public boolean scrolled(int amount) {
    return false;
}

private boolean isCellBlocked(float x, float y) {
    Cell cell = collisionLayer.getCell((int) (x / collisionLayer.getTileWidth()), (int) (y / collisionLayer.getTileHeight()));
    return cell != null && cell.getTile() != null && cell.getTile().getProperties().containsKey("blocked");
}

public boolean collidesRight() {
    for(float step = 0; step < getHeight(); step += collisionLayer.getTileHeight() / 2)
        if(isCellBlocked(getX() + getWidth(), getY() + step))
            return true;
    return false;
}

public boolean collidesLeft() {
    for(float step = 0; step < getHeight(); step += collisionLayer.getTileHeight() / 2)
        if(isCellBlocked(getX(), getY() + step))
            return true;
    return false;
}

public boolean collidesTop() {
    for(float step = 0; step < getWidth(); step += collisionLayer.getTileWidth() / 2)
        if(isCellBlocked(getX() + step, getY() + getHeight()))
            return true;
    return false;

}

public boolean collidesBottom() {
    for(float step = 0; step < getWidth(); step += collisionLayer.getTileWidth() / 2)
        if(isCellBlocked(getX() + step, getY()))
            return true;
    return false;
}
}

```

# Answer
> 1 votes
It seems like your problem is here:

```
public boolean collidesBottom() {
    for(float step = 0; step < getWidth(); step += collisionLayer.getTileWidth() / 2)
        if(isCellBlocked(getX() + step, getY()))
            return true;
    return false;
}

```

You only detect if the player has hit the floor when the cell inside of him is blocked. To fix this, change the code to:

```
public boolean collidesBottom() {
    for(float step = 0; step < getWidth(); step += collisionLayer.getTileWidth() / 2)
        if(isCellBlocked(getX() + step, getY() + playerHeight))
            return true;
    return false;
}

```

---
Tags: java, libgdx, physics
---


# Question
Title: how to create a play button and load game on play? Monogame
I need help with understanding how I can make my function work and load the game when pressing play.

At the moment, when I press *Play*, it won't update or missing update o knowing the button is pressed

Entier menu seperate class:

```
namespace giftman
{
    class GameMenu : Component,ILoadable,IUpdateable,IDrawable
    {
        List<GuiElement> gm = new List<GuiElement>();

        public GameMenu()
        {
            GuiElement BackGround = new GuiElement("BackGround");
            gm.Add(BackGround);
            GuiElement PlayButton = new GuiElement("Play_Button");
            gm.Add(PlayButton);
            GuiElement HighScore = new GuiElement("HighScore_Button");
            gm.Add(HighScore);
            GuiElement QuitButton = new GuiElement("Quit_Button");
            gm.Add(QuitButton);
        }

        public void LoadContent(ContentManager content)
        {
            foreach (var element in gm)
            {
                element.LoadContent(content);
                element.CenterElement(480,800);
                element.clickEvent += OnClick;
            }
            gm.Find(X => X.AssetName == "Play_Button").MoveElement(0,-120);
            gm.Find(X => X.AssetName == "HighScore_Button").MoveElement(0, -37);
            gm.Find(X => X.AssetName == "Quit_Button").MoveElement(0, 50);
        }

        public void Update()
        {
            foreach (GuiElement element in gm)
            {
                element.Update();
            }
        }

        public void Draw(SpriteBatch spriteBatch)
        {
            foreach (GuiElement element in gm)
            {
                element.Draw(spriteBatch);
            }
        }

        public void OnClick(string element)
        {
            if (element == "Play_Button")
                GameWorld.Instance.isplaypresssed = true;

            if (element == "HighScore_Button")
            {
                // Play the Game //
            }

            if (element == "Quit_Button")
                // Quit The game //
               GameWorld.Instance.Exit();
        }
    }
}

```

...and the place I load it all another class, `GameWorld`:

```
protected override void Initialize()
{
    // TODO: Add your initialization logic here
    graphics.PreferredBackBufferWidth = 800;
    graphics.PreferredBackBufferHeight = 480;
    IsMouseVisible = true;

    if (IsPlayPressed == false)
    {
        var gamemenu = new GameObject();
        //var guiElement = new GuiElement("Play_Button");
        // GameMenu and functions load here //
        gamemenu.AddComponent(new GameMenu());
        gamemenu.Update();
        // End GameMenu //

        gameObjects.Add(gamemenu);
    }

    if (isplaypresssed)
    {
        var map = new GameObject();
        var player = new GameObject();
        var player_2 = new GameObject();
        var enemy = new GameObject();
        var fruit = new GameObject();
        var gamecomponents = new GameObject();

        // Static Map Component //
        map.AddComponent(new GameMap(map, "pac_man_map", new Rectangle(0, 0, this.GraphicsDevice.Viewport.Width, this.GraphicsDevice.Viewport.Height), 0));
        // Static Map Component End//

        // Importent Systemcomponents //
        gamecomponents.AddComponent(new ScoreSystem());
        gamecomponents.AddComponent(new LifeSystem());
        // Importent Systemcomponents End//

        //Player's component //
        player.AddComponent(new SpriteRenderer(player, "Player_1", 1));
        player.GetTransform.GetPosition = new Vector2(50, 10);
        player.AddComponent(new Animator(player));
        player.AddComponent(new Player(player));
        //Player's component End//

        //Player's_2 component //
        player_2.AddComponent(new SpriteRenderer(player_2, "Player_2", 1));
        player_2.GetTransform.GetPosition = new Vector2(200, 10);
        player_2.AddComponent(new Animator(player_2));
        player_2.AddComponent(new Player_2(player_2));
        //Player's_2 component End//

        //Enemy Components //

        enemy.AddComponent(new SpriteRenderer(enemy, "GiftMan_animated3.0", 1));
        enemy.GetTransform.GetPosition = new Vector2(80, 50);

        enemy.AddComponent(new Animator(enemy));
        enemy.AddComponent(new Enemy(enemy));

        // End Enemy Components //

        fruit.AddComponent(new Fruit(fruit, "cherry", 10));

        gameObjects.Add(map);
        gameObjects.Add(gamecomponents);
        gameObjects.Add(fruit);
        gameObjects.Add(player);
        gameObjects.Add(player_2);
        gameObjects.Add(enemy);
    }

    base.Initialize();
}

```

What I need help with is understanding how I can make it change the `IsPlayPressed` to `true` and then switch to the game.

# Answer
You've got two different checks in here, at

```
    if (IsPlayPressed == false)

```

and at

```
    if (isplaypresssed)

```

Since one of these must be wrong, make sure to correct the capitalization of the wrong one.
> 0 votes

# Answer
In your gameworld class you have an initialize function. From your code it is unclear when that function is called (when do you instantiate the gameworld?).

Either way, from the looks of it the Initialize is generally only called upon creation. It appears that when it is instantiated the PressedButton boolean is set to false. By setting the boolean to true *doesn't* automatically call the function Initialize again. Thus your gameworld is never actually initialized.

You may want to look into gamestates. A gamestate mechanism is better than setting a boolean.

-edit: also ChrisUC's answer. You seem to have inconsistencies in your variable names.
> 0 votes

---
Tags: c#, monogame
---


# Question
Title: How do you create test for unity variables that are set through the [SerializeField] tag?
I need to create some tests for a bunch of variables that are initialized via the editor, So in the script they are always null and can't be set publicly.

Usually using the tag is a good way to encapsulate the code but with tests how do I check such a variable? Example:

```
public class thing
{
    [SerializeField]
    private string line;

    //constructor(s), methods, etc..

    public void setLine(string text){line = text; }
}

```

How do I check the value of the string after it is set inside a test?
(preferably without creating a getter method)

# Answer
I ended up creating a constructor for each class that i wanted to test. So for the example above it would be:

```
thing(string line)
{
    //this will be the value of a [SerializeField] variable
    this.line = line;

    //ensure that start is called just like it would in the game
    Start();
}

```

Then in a test I just initialize the class with this value. This works out well as you can integrate all the start method stuff into the initialization which saves you calling it separately within the test.
> 1 votes

# Answer
Your initial code is *initialized* through the inspector, unless you call your function in `void Update()` the value will always be null or its initial value no matter what you put in the inspector.
> 0 votes

---
Tags: unity, c#, unit-testing
---


# Question
Title: Why Does unity_LightPosition[0] Seem to Depend on Camera Position?
I'm trying to write a fairly basic shader but I keep running into lighting issues with Unity. My first problem was trying to figure out which variable stored the light's position in world space. (I'm only working with one light, at least at the moment).

I finally found something that responds to movement of my light source: `unity_LightPosition[0]`. However the shader still didn't do what I wanted it to do, so I did some debugging:

I have a basic vertex and fragment shader and what I'm currently doing in the fragment shader is:

```
float4 c = float4(0, 0, 0, 1);
float3 lp = normalize(unity_LightPosition[0]);
c.rgb = lp;
return c;

```

This should just set the color of my object to the normalized position of the light source, correct? What I see in my scene is my object changes colors when I move my camera around it (I'm not moving the light source at all, it is a separate entity). The color also seems to increase in strength as I zoom in.

To me, it seems as if unity\_LightPosition\[0\] is related to my camera's position, as well as orientation and zoom level, yet the documentation I've found says it should represent the position of the light in world space.

I tried switching to using the following:

```
float3 lp = float4(
    unity_4LightPosX0[0],
    unity_4LightPosY0[0],
    unity_4LightPosZ0[0],
    1.0
);

```

...but that only colors my object red regardless of the light's actual position.

Additionally, I've set the `LightMode` tag to `Vertex`.

It seems like simply getting the world position of the light source shouldn't be this difficult. What am I not doing correctly?

**EDIT**: I've been playing around with the camera and light position and I think that `unity_LightPosition[0]` actually puts out position in the projection space. If I place the light source in the lower-left corner of the screen, the object is black. Upper-left the object is green (0, 1), upper-right is orange (1, 1), and lower-right is red (1, 0). When I place it in the lower-left (0, 0) and move the camera in front of it, it becomes blue. This is consistent with the depth value behavior. (0, 0, \>0) would appear as blue.

Now, how to get it from projection back to world?...or should I use a different variable?

# Answer
I can give you an answer for what concern forward rendering and Cg shaders.

In the shader first pass (BasePass) Unity set uniforms value of the 1 important directional light and up to 4 vertex lights.

Base Pass (Directional per pixel light) uniforms:

* **\_WorldSpaceLightPos0** : position in world space of the first directional light
* **\_LightColor0** : color of the first directional light

The additional per vertex light orientations can be accessed using:

* **unity\_4LightPosX0** : x component of the world space positions on the 4 per vertex lights
* **unity\_4LightPosY0** : y component
* **unity\_4LightPosZ0** : z component
* **unity\_4LightAtten0** : attenuation factors

There are several references on the web suggesting using **unity\_4LightPosX0** uniform values. I don't know, maybe they work on different rendering paths. For what concern the forward base pass the uniforms above should work correctly.

I found out that 2 good ways to understand how rendering pipeline works are:

* **read** all `.gcinc` files inside unity Data/CGIncludes folder. They contains some macros and helper functions that can both help you writing shaders and show you which values are used for what (documentation often isn't enough).
* **compile** builtin surface shaders with `#pragma debug` directive. You can inspect the generated Cg code for default shaders.

---

EDIT

I'm not sure for what concern `pointlights`, but for `spotlights` Unity uses an additional render pass (`ForwardAdd`) if you want to render them per pixel. So for example if you try to access **\_LightMatrix0** or **\_WorldSpaceLightPos0** in the `ForwardBase` pass the values aren't always consistent.

So I guess that if you want to display point or spot light positions of an important light per pixel you should do that inside a second pass in the shader with the following tag: `Tags { "LightMode" = "ForwardAdd" }`. (Or alternatively manually settings uniforms values: I'm doing this for rendering both lightmaps and spotlights in a single pass shader).
> 1 votes

# Answer
I've just encountered the same issue with \_WorldSpaceLightPos0, which was sometimes (0,0,0,0) and it depended on camera (not light and not mesh) position. It turned out that I forgot to put lighting mode tag

```
Tags { "LightMode" = "ForwardBase" }

```

into my `PASS` section
> 2 votes

# Answer
**unity\_LightPosition** is in **Model-View space**. To convert it into world space you'll have to multiply it by the inverse matrix of UNITY\_MATRIX\_MV.

Here's some code that might be helpful in inverting a matrix: http://answers.unity3d.com/questions/218333/shader-inversefloat4x4-function.html

Example:

```
float4 worldLightPos = mul( inverse(UNITY_MATRIX_MV), unity_LightPosition[i]);

```

Note, that matrix inversion is a resource-intensive process, and it's better to perform it in C#/JS code, and supply to the shader via a material property.
> 1 votes

---
Tags: unity, shaders, vertex, lighting
---


title: Infinite scroll with tweens in Phaser

text:
# Question
Title: Infinite scroll with tweens in Phaser
Let's say you have a bunch of tweens running like this:

http://holbrook.no/tests/featherfall.html

Now you want to scroll them horizontally while they fall. By updating camera x, they start moving, but in the end, the camera x value will overflow. And besides, one might want to wrap some background graphics before then.

Therefore we need to periodically snap the camera back to the original position. But then the tweens will snap back too.

So the individual sprites need a transform value on top of the current tween position to correct for the camera repositioning.

I haven't found any setting in Phaser for this. Any ideas?

---

EDIT:

It's possible to work around it with keeping a global variable to keep track of the camera yanking, and adding it manually to the onUpdateCallback of the tween, and consolidating the difference with the next tween change. But the hack seems to be glitching sometimes, and I suspect it's slower than if an internal transform variable could be used. Anyway, here's the result:

http://holbrook.no/tests/featherfallscrolled.html

# Answer
(Based on input from http://www.html5gamedevs.com/topic/20539-infinite-scroll-wrapping-with-tweened-sprites/)

A suggested workaround:

I coupled it with some event signals, and came up with the following test for performance (see below for code):

http://www.holbrook.no/tests/tweencamerasync.html

You can pass a whole number on get param c to change the count, default count is 100. On my laptop browser it starts acting up on after 2000 somewhere (Linux Mint 17,1, 770 MHz cpu, 3,5G ram, firefox 44.0.2) on a 800x600px canvas.

Basically I add a signal to the world object that adds the yank difference with addAll to all DisplayObjects' x values. Then it iterates the game tween manager to update each tweened custom sprite's camera\_offset\_x variable, used for those sprites to calculate the x together with the intermediary tweened tx property (IF the isTweened is true for the sprite). The camera\_offset\_x is reset with tween onComplete.

Funnily, the game.tweens.getAll() function is undefined when no tweens exist. Expected behaviour would be that it return 0 and not just blatantly fail, no?

```
var sprite = new Array();
var spawncount;

window.onload = function() {
    game = new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.AUTO, '', {create: create, update: update});
    spawncount = parseInt(getQuery("c"));
    if (!spawncount || spawncount == 0 || spawncount === undefined || spawncount === null)
        spawncount = 100;
    else if (spawncount > 5000)
        spawncount = 5000;
};

CameraTweenGfx = function(game, x, y) {
    Phaser.Graphics.call(this, game, x, y);

    this.camera_offset_x = 0;
    this.tx = x;
    this.ty = y;

    this.update = function() {
        if (this.game.tweens.isTweening(this)) {
            this.x = this.tx - this.camera_offset_x;
            this.y = this.ty;
        }
    };
};

CameraTweenGfx.prototype = Object.create(Phaser.Graphics.prototype);
CameraTweenGfx.prototype.constructor = CameraTweenGfx;

function create() {

    game.camera.yank = function() {
        var params;

        params = {
            x: this.x,
            y: this.y
        };
        this.setPosition(0, 0);
        console.log("inside custom camera yank method");
        this.onYank.dispatch(params);
    };

    game.camera.onYank = new Phaser.Signal();
    game.camera.onYank.add(yankHandler, game.camera);

    game.onCameraYank = new Phaser.Signal();
    game.onCameraYank.add(yankHandler2, game);

    game.world.setBounds(0, 0, window.innerWidth + 100, window.innerHeight);

    for (var i = 0; i < spawncount; i++) {
        var startx;
        var starty;
        var endx;
        var endy;
        var duration;
        var color;
        var size;

        startx = game.rnd.integerInRange(10, game.width - 10);
        starty = game.rnd.integerInRange(10, game.height - 10);
        endx = game.rnd.integerInRange(10,game.width - 10);
        endy = game.rnd.integerInRange(10, game.height - 10);
        color = game.rnd.integerInRange(0, 16581375);
        duration = game.rnd.integerInRange(100, 4000);
        size = game.rnd.integerInRange(10, 20);

        sprite[i] = new CameraTweenGfx(game, startx, starty);
        game.add.existing(sprite[i]);

        sprite[i].beginFill(color);
        sprite[i].drawRect(0, 0, size, size);
        sprite[i].endFill();

        sprite[i].camera_offset_x = 0;

        game.add.tween(sprite[i]).to({
            tx: endx,
            ty: endy
        }, duration, null, true, 0, 0).onComplete.addOnce(function() {
            this.camera_offset_x = 0;
        }, sprite[i]);
    }

    poly = new Phaser.Polygon();
    poly.setTo([
        new Phaser.Point(0, game.height),
        new Phaser.Point(game.width, game.height / 2),
        new Phaser.Point(game.width, game.height),
    ]);
    var graphics = game.add.graphics(0, 0);
    graphics.beginFill(0x00FF00);
    graphics.drawPolygon(poly.points);
    graphics.endFill();
    game.world.sendToBack(graphics);

}

function update() {
    game.camera.x ++;
    if (game.camera.x > 50)
        game.camera.yank();
}

function yankHandler(params) {
    console.log("inside camera onYank handler" + this.totalInView);
    // doesn't do anything now, but maybe needed for other stuff maybe needed for other stuff
    this.game.onCameraYank.dispatch(params);
}

function yankHandler2(params) {
    console.log("inside game onCameraYank handler");
    this.world.addAll("x", -50);
    if (typeof this.tweens.getAll == "function") {
        this.tweens.getAll().forEach(function(o) {
            o.target.camera_offset_x += params.x;
        });
    }
}

// naughtly stolen from stackoverflow.com/questions/831030/how-to-get-get-request-parameters-in-javascript
function getQuery(name){
   if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
      return decodeURIComponent(name[1]);
}

```
> 1 votes

---
Tags: phaser, scrolling, tweening
---


# Question
Title: HardonCollider Error: attempt to call method 'addRectangle' (a nil value)
I want to add collision detection mechanism to my game, which is written in love2d. As i do not want to implement my own algorithm, i have found a HardonCollider library to do the heavy lifting for me.

I have followed the example code of the library but got an error even with a basic setup.

```
local hc  = require "hardoncollider"

local hero
local collider

function on_collision(dt, shape_a, shape_b, mtv_x, mtv_y)

end

function love.load(arg)
    collider = hc(100, on_collision)
    hero = collider:addRectangle(30,30,16,16)
end

```

Running this code will throw the following error message:

```
PS C:\dev\love-0.10.0-win64> Error: main.lua:12: attempt to call method 'addRectangle' (a nil value)
stack traceback:
        main.lua:12: in function 'load'
        [string "boot.lua"]:437: in function
        [C]: in function 'xpcall'

```

I have been investigating the problem, but did not find any solutions nor anybody else who faced this error.

# Answer
Answering my own question here, in case somebody else encounters this issue.

Looks like i have been reading outdated documentation & samples, according to the new docs there is no such method as `addRectangle`.

It should be:

```
collider = hc.new(100, on_collision)
hero = collider:rectangle(30,30,16,16)

```
> 2 votes

# Answer
`addRectangle` is a method of hardoncollider, not a method of the object produced from running `hc(100, on_collision)`. The correct way to do this would be:

```
function love.load(arg)
collider = hc(100, on_collision)
hero = hc:addRectangle(30,30,16,16)
end

```
> 1 votes

---
Tags: collision-detection, lua, love2d
---


title: Rotation in animation not working

text:
# Question
Title: Rotation in animation not working
I have a model of an SMG with arms exported from Blender and set to generic rig in unity import settings. I was creating an animation for this model in Unity Animation tab, it included changes in position and rotation of the individual parts like magazine and left arm and gun itself. Then when I was satisfied with how the animation worked (I saw it by pressing the play button IN THE ANIMATION TAB). My problem is that when I click play IN THE GAME TAB there is no rotation and some movement, only some parts move (but not rotate). Does anyone know what could be my problem? I am not sure what screenshots to post so tell me what you need to see and I'll add some. Thanks in advance.

# Answer
I got this to work. The problem was that I enabled "Apply root motion", when I disabled it the animation worked properly.
> 2 votes

---
Tags: unity, animation, rotation, transformation, import
---


# Question
Title: Are there any good 2D fighting game engines that can be used to make a commercial product?
I'm looking for a good 2D fighting game engine based on sprites. I really dont care much about which language that it is programmed in. Specifically I'm looking for an engine I can use for a game I can sell later and could be exportable to different systems.

Something like 2D Fighter Maker or MUGEN would be great, but that could have a product sold using the tech.

# Answer
> 1 votes
http://kokusaifightingengine.blogspot.com/

This looks pretty promising and it is build on the c# xna 4.0 This platform is very powerful when it comes to publishing content for Windows, Windows phone 7 and Xbox.

It also looks like it comes with some good editing modules for helping you get your game up and running in no time.

# Answer
> 1 votes
For Windows i would buy DarkBasic Pro from TGC (BASIC Code). You can develop 2D and 3D commercial games for Windows. DarkBasic Pro is also compatible with TGC Plug-in's

If you want cross platform 2D game development use App Game Kit (BASIC Code). App Game Kit has a website: www.appgamekit.com.

Both are available from www.thegamecreators.com .

# Answer
> 0 votes
## **java-fighting-game-engine**

*"A modular fighting game engine for the Java SE and Android platform."*

This has a well-written codebase, but the demo games included need much polish.

# Answer
> 0 votes
Unity3D is a great choice. It uses sprites. There is ton of tutorials and documentation available on this game engine so learning will be easy. In Unity the are limitless possibilities you can achieve with the scripting, there's a choice of three languages but mainly two are used JavaScript and C#. You can easily create a 2D/3D game for the web and many other platforms.

---
Tags: 2d, cross-platform
---


# Question
Title: Raycast from ScreenCenter hits object but does not return its tag
Here is my code:

```
using UnityEngine;
using System.Collections;

public class Crosshair : MonoBehaviour {
    public Camera cam;
    RaycastHit hit;
    Quaternion rot;
    // Update is called once per frame
    void Update ()
    {
        int x = Screen.width / 2;
        int y = Screen.height / 2;

        Ray ray = cam.ScreenPointToRay(new Vector3(x,y,0));
        Debug.DrawRay(ray.origin, ray.direction * 100, new Color(1f, 0.922f, 0.016f, 1f));
        rot = Quaternion.FromToRotation(Vector3.up, hit.normal);

        if (Physics.Raycast(transform.position, transform.forward, out hit))
        {
            Debug.Log("Now trying to locate enemy...");
           if(hit.transform && hit.transform.tag == "Enemy")
            {
                Debug.Log("Enemy Spotted!!");
            }
            else
            {
                Debug.Log("I tried bro...");
            }
        }

    }
}

```

as I can imagine `if(Physics.Raycast(transform.position, transform.forward, out hit))` is always false.

What am I not doing correctly?

# Answer
> 0 votes
The code works fine, what fixed the problem was clearing the cache! I've been working on this project for so many hours that it probably clogged out!

EDIT: To clear the cache I exited Unity, located my Unity's cache folder and deleted the contents. Loaded Unity up again and voila!

---
Tags: c#, unity, raycasting
---


# Question
Title: Collision between free player and tilebased map
so I'm working on some sort of platformer in javascript where the map is tilebased but the player can move freely.

Now, i have a problem with collision detection/response. It's kind of obvious what I'm trying to do, I don't want the player to walk into walls and fall into the ground so i need collision stuff.

Basic info:

* The player is the same size as the tiles
* The tiles are 8x8
* The map is stored in an array like this: \[0, 0, 0, 1, 1, 1, 0, 0, 0\]. So if the map was 3x3 there would be a horizontal line in the center.

I feel that the system that I'm using is very inefficient and there are some problems with it:

```
sides = {};

// The tiles are 8x8 wide so i divide the players position by 8 to get the current tile the players is occupying.
// The player.y * mapWidth + player.x thing gets the tile at that position in the map array
// I use Math.floor instead of round to get the tile to the left of the player
if (map[(Math.round(player.y / 8) * mapWidth) + Math.floor(player.x / 8)] == 1) {
    sides.left = true;
} else {
    sides.left = false;
}

if (sides.left) {
    // Set the players x position to exactly outside the wall.
    player.x = Math.floor((player.x / 8) - 1) * 8;
}

```

Now this works fine for walls but when you use it on the ground it works but it glitches on corners.

For example if the player half way over an edge it falls through the tile and is pushed to the side.

Is there a better way to do this and if not, how do i fix the ground collision?

# Answer
> 1 votes
You are falling through the corners because you are comparing the left side of the object to the left side of the player (or middle if that is where x is), you need to compare to the right side of the player as well to make sure you don't fall through the corner (make sure the side of the object is between the right and left side of the player).

---
Tags: javascript, tiles, collision-resolution
---