title: Lights shining through walls

text:
# Question
Title: Lights shining through walls
I'm currently having a problem with lights in Unity. They shine through walls for some reason.

Point, directional, etc. If a light is next to a wall on one side, you can see it on the floor on the other side. I believe this has something to do with culling masks or light culling.

I was wondering how I could go about culling the lights so they no longer shine through walls. Any help is greatly appreciated.

I'm on Unity 4.x Pro, so I have all the features for that.

Here's a picture of a light on one side of the wall:

And here's it shining through to the other side, which it's not supposed to do:

# Answer
> 4 votes
I managed to fix the problem, turning the shadows to Soft Shadows, setting the strength to 1, and putting a culling mask on certain objects made the light shine on the proper surfaces and not pass through anything.

# Answer
> 2 votes
I would double check on the shadows for that particular light, that's exactly what should happen in deferred rendering when you have shadows off for a point light.

# Answer
> 0 votes
I found a trick for this problem (tested just for the spotlight)! Do the following things:

1) Set the range of illumination to just reach the wall(the strength of the light on the wall will decrease).

2) Increase the intensity as you want and you will see that the light is now illuminating just the wall and don't go through

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


# Question
Title: What does this code mean in the source engine
I am working on a project in which I analyze acceleration in the Source engine. Being that I have very basic knowledge of computer science, I am not very proficient in understanding the syntax.

The code that I am having trouble with is:

mv-\>m\_vecVelocity\[i\] += accelspeed * wishdir\[i\];

I am confused as to what the " mv-\> " is. Thank you for your help in advance.

I am getting the code from here: https://github.com/ValveSoftware/source-sdk-2013/blob/56accfdb9c4abd32ae1dc26b2e4cc87898cf4dc1/sp/src/game/shared/gamemovement.cpp

line 1745

In particular I am interested in knowing what mv is and what the -\> is

# Answer
> 2 votes
It's object instance of class CMoveData. It handles movement.

This can be found from code file you posted:

```
CMoveData *pMove
mv = pMove;

```

So, `mv` is `CMoveData`

The `->` is the arrow operator. You can access class pointers using (for example) `mv->m_nPlayerHandle.Get()`. This is somewhat hard area to understand. There are couple of good answers on stackoverflow about this

Difference of pointer and reference variables

Array operator vs dot

# Answer
> 1 votes
Basically, "mv-\>" means "the following property of mv".

So, "mv-\>m\_vecVelocity" means "the vector velocity property of the movedata".

"mv" represents kinematic state of a physical object.

---
Tags: source-code, source-engine, quake3
---


# Question
Title: How to put labels at a specific point on any resolution
I am working on a project in Unity 4.6.1 and I put the label at the top:

But when I put the Scene in full view this happened:

I made a Development Build and when I select my resolution (1366x768) the label goes behind the buttons. Is there any way to put the label at a specific point no matter what resolution?

# Answer
> 1 votes
Click on the Title in your hierarchy. In the Rect transform, you can see that square in the editor. Click it, you can then set the position of the Text (Top, in you case.) After that, press Alt, and choose where to place your Anchor. (Top again). If you still don't like it, you can choose to move the Anchor manually in the Scene. Ultimately, keep the Anchor close to the object's center, so it's always well positionned.

Here is a quick animation : http://gfycat.com/HonorableAcrobaticArcticfox

---
Tags: unity, resolution, scene
---


# Question
Title: Life Counter in Greenfoot caught "Incompatible Types" exception
I need to make a life counter so that when my Actor get hit by an Enemy, his life will be decreased by 1.

I put this method in my `Actor` class:

```
private void decreaseLife() {
    Actor enemy = getOneIntersectingObject(Enemy.class);
    if (enemy != null) {
        int lastIndex = Scenario.getLifeBar().size()-1;
        Life LastLife = Scenario.getLifeBar().get(lastIndex);
        /** catch error on lastIndex --> "incompatible types" **/

        getWorld().removeObject(enemy);

        getWorld().removeObject(LastLife);
        Scenario.getLifeBar().remove(lastIndex);
    }
}

```

I used `Scenario.getLifeBar().size() - 1;` to get the last index from my `ArrayList` collection then decrease it by 1. My `LifeMax` was set to 3, so when decreased by 1 it should be returning value = 2, and be saved in `lastIndex`.

This is my code including `LifeBar` code in `Scenario` Class:

```
import greenfoot.*;
import java.util.ArrayList;

public class Scenario extends World {
    private final int LIFE_MAX = 3; //Max value of my Actor's life
    private static ArrayList LifeBar = new ArrayList();

    public Scenario() {
        super(600, 400, 1);
        prepare();}

    private void prepare() {
        prepareLifeBar(40, 30);
        // Add obj. main actor
        // Add obj.enemy
    }

    private void prepareLifeBar(int offsetX, int offsetY) {
        int spaceBetweenLife = 10;  // just to put space between image
        for (int i = 0; i < LIFE_MAX; i++) {
            Life life = new Life();
            life.setLocationX(offsetX+((life.getImage().getWidth()+spaceBetweenLife)*i) );
            nyawa.setLocatinY(offsetY);
            addObject(life, life.getLocationX(), life.getLocationY());
            LifeBar.add(life);
        }
    }

    public static ArrayList getLifeBar() {
        return LifeBar;
    }
}

```

In my `Life` class, I put some code to add attributes of `LocationX` and `LocationY` to save my `Life` actor in x and y axis.

I believe there's no other exception caught in any other class related to my life counter, yet my `lastIndex` caught an incompatible types exception.

**What's causing this exception to be thrown?**

# Answer
Apparently my arraylist elements stored as Object objects (not as Life objects). So I need to cast the element as type Life first,

I need to change this :

```
Life LastLife = Scenario.getLifeBar().get(lastIndex);

```

into this :

```
Life LastLife =  (Life) SpaceWorld.getLifeBar().get(lastIndex);

```

and it works just fine.

Check the Reference here
> 0 votes

---
Tags: java, exceptions
---


# Question
Title: BitmapFont - where is getBounds method in new 1.6 libGDX
I download newest libgdx version 1.6 and i cant solve problem with center my BitmapFont text. Earlier in version 1.54 i used getBounds() method to find out width of text.

Share your solutions, thanks

# Answer
There was a post explaining the changes, but is not easy to find. The link was on the 1.5.6 release changelog: http://www.badlogicgames.com/wordpress/?p=3666

And the link about changes in fonts was: http://www.badlogicgames.com/wordpress/?p=3658

```
private static GlyphLayout glyphLayout = new GlyphLayout();
private BitmapFont fontA = new BitmapFont(), fontB = new BitmapFont();

// Set text and font each time you want to calculate bounds.
glyphLayout.setText(fontA, "my string");
fontA.draw(batch, glyphLayout, x + glyphLayout.width / 3, y + glyphLayout.height / 3);
y += glyphLayout.height;

glyphLayout.setText(fontB, "different font");
fontB.draw(batch, glyphLayout, x + glyphLayout.width / 3, y + glyphLayout.height / 3);

```
> 15 votes

---
Tags: java, libgdx
---


# Question
Title: Unity and the problem with calling functions from other scripts
I'm not sure how everyone handles this, but I'm running into lots of instances where I want to call a nonstatic script from another script which forces me to add the nonstatic script to the gameobject that also handles the other script. Such as, I would have two classes in different scripts:

```
public class Example1:MonoBehaviour{
public void someMethod(){
}
}

    public class Example2:MonoBehaviour{
public void anotherMethod(){
}
}

```

if I wanted to call anotherMethod from someMethod, I would need to do this:

```
   public class Example1:MonoBehaviour{
    private Example2 exampleTwo;

void Awake(){
exampleTwo = gameObject.AddComponent<Example2>();
}
        public void someMethod(){
exampleTwo.anotherMethod();
        }
        }

```

Is this really how everyone is working? It just seems extremely long and complicated, making me attach a whole bunch of scripts to one gameobject at runtime, and then I run into a whole bunch of issues with multiple copies of each script (such as with mousedown functions or input functions).

# Answer
> 3 votes
How exactly this is best handled depends on the exact use case. The two main use cases are: 1. You want to access a shared background object that persists throughout the game. 2. You want to access a specific object within the scene.

For situation 1, you could use one of the code patterns like Service Locator or singleton (justin's suggestion is basically a Unity flavored singleton). Alternatively you could use FindObjectOfType() to reference an existing object in the scene.

For situation 2, you can simply drag the object onto a variable in the Inspector. In other words, create a serialized variable at the top of the script (eg. public Example2 otherScript) and then that variable will appear in the Inspector so that you can drag in an object in the scene. Now you can call any public methods of that object.

(incidentally, as zee points out the AddComponent command does exactly what it says, it *adds* a new component, not give you access to an existing component. If you don't want a new component added, then use a different command like GetComponent)

# Answer
> 3 votes
Let me first question you on a few things.

> exampleTwo = gameObject.AddComponent();

Do you really need to ADD a script to your object during runtime? Why? I mean I can understand adding a collider to an object that you didn't want to collide at some point, adding lots of things are explainable. But why Add a script? Why not just keep it attached to the object, and then it's your choice if you are going to use it or not.

> I would have two classes in different scripts

The first question you should ask yourself is : "Can I get rid of one of them"? I once ran into a case where I had 3 scripts that would switch between themselves in a loop. I just sat down and thought, why do I need three? You will probably be able to merge all the methods you have in Example1 with Example2. I hope you consider it.

Now for your issue :

> It just seems extremely long and complicated, making me attach a whole bunch of scripts to one gameobject at runtime, and then I run into a whole bunch of issues with multiple copies of each script (such as with mousedown functions or input functions).

That is exactly what I asked you. Why are you attaching scripts at runtime? If you want an object to have a script attached to him all the time, just Select him in the Hierarchy, Add Component \> Scripts \> Choose your desired script from the list. If that object does not appear from the start of the scene, and is instanciated from a prefab, just add the script(s) to the prefab.

Ultimately, if you were to remove the "AddComponent" method from your script, and wanted to address another script, it would be something like this :

```
public void someMethod(){
this.getComponent<Example2>().anotherMethod();
        }

```

Piece of cake? Addresing scripts that exist as component of the same object couldn't be easier `this.getComponent<className>().methodName()`.

Other than that, if you have a variable/method that is relatively "unique" in your script, consider making that variable/method static, not the whole class. So instead of `this.getComponent<className>().methodName()`, you would simply use `className.methodName()`, or `className.variableName`. Cheers.

# Answer
> 0 votes
```
 public class Example2:MonoBehaviour{
 public static Example2 Instance;
 void Awake()
 {
     Instance = this;
 }
  //Now you can access the public methods or variable of Example2 from any class by
  Example2.Instance.YourMethodOrVariable;
 }
 //---------------------------------------------------------------------------------
 //But if you have a Boolean in your Example1 and don't want to make a whole Instance of the class you can
 public static bool example1ClassBool = false;
 //then from any other class you can use
 Example1.example1ClassBool = true;
 //---------------------------------------------------------------------------------

```

---
Tags: unity
---


# Question
Title: unity -- object references, why do I always get errors?
For context:

I randomly generate a few points on the map, and each point is a gameobject with a script containing an OnMouseDown method. Here's the relevant pieces of code(I've omitted the irrelevant parts to make it easier to read).

```
    public class MouseClick : MonoBehaviour {
    public static string clickedWaypoint;
    void Awake(){
        nWM = gameObject.AddComponent<NavigateWorldMap>();

    }
    public void OnMouseDown(){
        clickedWaypoint = gameObject.name;

        Player.updatePlayerPosition();

    }
    }

```

I also have a Player game object in my scene with the player script attached:

```
public class Player : MonoBehaviour {
    private Transform playerTransform;
    private GameObject waypointObj;

    void Start(){
        chooseStartingLocation();
    }
    private void chooseStartingLocation(){
        int number = Random.Range(0,WorldMapPoints.waypointNumber);
        transform.position = GameObject.Find ("waypoint"+number).GetComponent<Transform>().position;

    }

    public static void updatePlayerPosition(){
        waypointObj = GameObject.Find (MouseClick.clickedWaypoint);

    }
}

```

I get the following error:

```
Assets/Scripts/Player.cs(19,17): error CS0120: An object reference is required to access non-static member `Player.waypointObj'

```

Which is really confusing to me since I can't see anything wrong with what I wrote and this is the first time I encountered this error. Anyone know what's up?

# Answer
Your error here is that you're addressing a non-static variable, with a static method.

I recommend you take a time-out of Unity, and get to know better non-static vs static variables, and non-static vs static methods. I will recapitulate in a bunch of words and explain it to you roughly though.

So the non-static variable here is `waypointObj`. As you can see in the error message, "An object reference is required to access non-static member Player.waypointObj". The **static** method `updatePlayerPosition()` is trying to call a variable that is not specific to the **class** but is a variable related to every **instance** of the class.

The fix here would be to whether make your method non-static, or to make the variable waypointObj static. Choose any of these according to your needs.
> 1 votes

---
Tags: unity
---


# Question
Title: Going from WPF to Unity3D, how to implement the MVVM-pattern?
I've been working with MVVM in WPF for a long time and I'm now trying out Unity3D for a GUI-driven application.

Can I work with view models and bind them to properties in GUI-components? I guess the attached script-instance would be the "data context"? But how do I for instance bind (two-way) a text-property in my script to the text-property of a GUIText?

If Unity3D doesnt support this out of the box, could I implement a "bindable GUIText" myself somehow?

I know there are a few GUI frameworks for Unity3D out there allready and some of them seem to "support" MVVM as well. But I havent been able to find out many details about this. For instance the "data binding" support in NGUI/NData seem to be only between view-components and not between view and viewmodel, which is what MVVM is all about.

**UPDATE**

Apparently, the guy behind Durandal and Caliburn.Micro is working on a binding-framework for Unity3D which looks very promising. I guess this answers my question basically.

# Answer
> 2 votes
Unity - not unlike some other game engines - provides as the backbone of its architecture a scene-graph that unifies all aspects of the MVC / MVVM triad. Trying to work around such fundaments of the platform will only cost you more in time than you think you might gain by adapting it to the architectural paradigm you mention... rest assured.

Re your question on GUI: This depends very much on which Unity GUI system you are using:

* IMGUI requires you to make GUI calls on every update -- thus there is no "retained mode" data binding.
* Retained mode GUI for v4 should retain the values you put into them, but that isn't the same as data-binding. You'd need to explicitly update the values.
* Unity 5 (due around July 2014) will provide access to the new GUI system. Being NGUI based, you'll have access to data-binding, as you can see that NGUI has for some time supported data binding.

# Answer
> 0 votes
I wanted proper MVVM support in Unity so I created a new framework. It's built upon the unity 4.6 UI system so no extra UI framework needed. It allows you to create views using XML, it supports theming, data binding, animations, dynamic/responsive content etc. It's similar to WPF/Silverlight (XAML) and other MVVM/MVC/MVP frameworks such as Caliburn, AngularJS etc. It's available here: www.markux.com.

# Answer
> 0 votes
I recently just released, finally, an old project of mine that does just this. It's only for the legacy GUI, I'm not up to speed on the best options for the new UI.

Basically it creates a "retained mode" by building an object hierarchy of controls just once, then making the appropriate GUILayout calls each time OnGUI is called. It does data binding and a bunch of other stuff. Overhead is minimal, only function calls. No reflection.

Kind of late in the game but it's an option if anyone needs it.

https://github.com/mattolenik/AffinityUI

---
Tags: unity, gui, wpf, ngui
---


# Question
Title: OpenGL ES respecting alpha for background but not for objects
I have a problem with the alpha of my game, maybe it is solved in another post but as I am new in OpenGl and Game developemnt I dont understand most of the vocabulary and cant find a solution.

The problem is I have enemies with alpha and coins with alpha that works great, but when an enemy pass through the coin it take seem the background instead of the coin(same with shoots)

there is a image explaining it

There is the code to draw enemys and coins

```
public void drawEnemy(GL10 gl)
{
    gl.glFrontFace(GL10.GL_CCW); // Front face in counter-clockwise
                                    // orientation
    gl.glEnable(GL10.GL_CULL_FACE); // Enable cull face
    gl.glCullFace(GL10.GL_BACK); // Cull the back face (don't display)

    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
    gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); // Enable
                                                            // texture-coords-array
                                                            // (NEW)
    gl.glTexCoordPointer(3, GL10.GL_FLOAT, 0, texBuffer); // Define
                                                            // texture-coords
                                                            // buffer (NEW)

    gl.glEnable(GL10.GL_BLEND);
    gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);

    // front
    switch (type)
    {
        case 0:
            gl.glBindTexture(GL10.GL_TEXTURE_2D, TextureLoader.textureIDs[0]);
            break;
        case 1:
            gl.glBindTexture(GL10.GL_TEXTURE_2D, TextureLoader.naveEnemigaIDs[0]);
            break;
        case 2:
            gl.glBindTexture(GL10.GL_TEXTURE_2D, TextureLoader.naveEnemigaIDs2[0]);
            break;
    }

    gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);

    gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); // Disable
                                                            // texture-coords-array
                                                            // (NEW)
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDisable(GL10.GL_CULL_FACE);
    gl.glDisable(GL10.GL_BLEND);
}

public void drawCoin(GL10 gl)
{
    gl.glFrontFace(GL10.GL_CCW); // Front face in counter-clockwise
                                    // orientation
    gl.glEnable(GL10.GL_CULL_FACE); // Enable cull face
    gl.glCullFace(GL10.GL_BACK); // Cull the back face (don't display)

    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
    gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); // Enable
                                                            // texture-coords-array
                                                            // (NEW)
    gl.glTexCoordPointer(3, GL10.GL_FLOAT, 0, texBuffer); // Define
                                                            // texture-coords
                                                            // buffer (NEW)

    gl.glEnable(GL10.GL_BLEND);
    gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);

    // front
    gl.glBindTexture(GL10.GL_TEXTURE_2D, TextureLoader.CointextureIDs[0]);
    gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);

    gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); // Disable
                                                            // texture-coords-array
                                                            // (NEW)
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDisable(GL10.GL_CULL_FACE);
    gl.glDisable(GL10.GL_BLEND);
}

```

# Answer
The issue was the drawing order. If I draw the money and then the ship it respect the alpha.
> 1 votes

---
Tags: android, opengl-es, alpha
---


# Question
Title: How to sample a texture with specified LOD in SM 2.0?
That is my question, in SM 3.0 there is the HLSL intrasic function tex2Dlod to pick a color on a texture2d at specified coords and specified level-of-detail.

But after long search on the web, I don't find equivalent in SM 2.0 (ps\_4\_0\_level\_9\_3)...

# Answer
> 0 votes
Shader Model 2.0 has no such function, but "tex2Dgrad" can be used to the same effect if your shader has access to the dimensions of the texture.

(Note that tex2Dgrad availability is subject to the caps bit D3DD3DPSHADERCAPS2\_0\_GRADIENTINSTRUCTIONS, so this isn't a sure thing)

Instead of:

> color = tex2Dlod(map, uv, lod);

Do:

> float scale = exp2(lod);
>
> color = tex2Dgrad(map, uv, float2(scale/texture\_width, 0.0), float2(0.0, scale/texture\_height));

# Answer
> 1 votes
Look at the pixel shader instructions in Shader Model 2. I found "texldb" :

*Biased texture load instruction. This instruction uses the fourth element (.a or .w) to bias the texture-sampling level-of-detail just before sampling*

***Syntax***

*texldb dst, src0, src1*

https://msdn.microsoft.com/en-us/library/windows/desktop/bb206217(v=vs.85).aspx

# Answer
> 0 votes
Thank you a lot, the solution with tex2Dgrad work perfectly ! I don't have tested the solution with texldb, because there use registers and I want to avoid that.

---
Tags: shaders, hlsl, level-of-detail, mipmaps
---


title: How do I make my camera follow my cube?

text:
# Question
Title: How do I make my camera follow my cube?
I've recently started to learn some C# scripting in Unity. I've been able to make my PlayerCube move around using Vector3 Transform.translations, but I want my camera to follow my cube while moving around, and it's not working since Unity can't find PlayerCube. How do I make make it so it understands that there's a PlayerCube?

```
using UnityEngine;
using System.Collections;

public class CameraScript : MonoBehaviour {
    Player = GameObject.Find("PlayerCube");

    // Use this for initialization
    void Start ()
    {
    //  GameObject.Find(PlayerCube);
    }

    // Update is called once per frame
    void Update ()
    {
        Transform.LookAt (PlayerCube);
    }
}

```

# Answer
> 1 votes
You can use this script. Attach it to your camera, and place your cube in the Target spot in the inspector.

```
using UnityEngine;
using System.Collections;

public class TargetFollower : MonoBehaviour
{

    [Tooltip("Target to be followed")]
    public Transform Target;
    [Tooltip("Mimic the Target's changes in x coordinate")]
    public bool FollowTargetX = true;
    [Tooltip("Mimic the Target's changes in y coordinate")]
    public bool FollowTargetY = true;
    [Tooltip("Mimic the Target's changes in z coordinate")]
    public bool FollowTargetZ = true;

    // Update is called once per frame
    void FixedUpdate()
    {
        if (Target)
        {
            Vector3 targetMovement = GetTargetMovement();
            UpdatePosition(targetMovement);
        }
    }

    private Vector3 oldTargetPosition;
    private Vector3 GetTargetMovement()
    {
        if (oldTargetPosition == Vector3.zero)
        {
            oldTargetPosition = Target.transform.position;
        }
        Vector3 newTargetPosition = Target.transform.position;
        Vector3 targetMovement = newTargetPosition - oldTargetPosition;
        oldTargetPosition = new Vector3(newTargetPosition.x, newTargetPosition.y, newTargetPosition.z);
        return targetMovement;
    }

    private void UpdatePosition(Vector3 targetMovement)
    {
        float xPosition = transform.position.x;
        float yPosition = transform.position.y;
        float zPosition = transform.position.z;
        if (FollowTargetX)
        {
            xPosition += targetMovement.x;
        }
        if (FollowTargetY)
        {
            yPosition += targetMovement.y;
        }
        if (FollowTargetZ)
        {
            zPosition += targetMovement.z;
        }
        Vector3 updatedPosition = new Vector3(xPosition, yPosition, zPosition);
        transform.position = updatedPosition;
    }
}

```

# Answer
> 1 votes
the fastest way is to make the camera child of the cube (in the editor), then in the Update() of the camera script use LookAt :

```
void Update() {
    transform.LookAt(transform.parent);
}

```

# Answer
> 0 votes
By looking at your script and if it's the exact same in Unity you have a problem with the variable `Player` (no type and wrong name in Update ()). And you need to pass a **Transform** and not a **GameObject** in tranform.LookAt ().

```
using UnityEngine;
using System.Collections;

public class CameraScript : MonoBehaviour {
    GameObject Player = GameObject.Find("PlayerCube");

    void Update ()
    {
        transform.LookAt (Player.tranform);
    }
}

```

I don't recommand making the camera a child of the cube as suggest @dnk-drone.vs.drones.

If you only want your camera to look at your object then the `transform.LookAt ()` is what you need. If you want to move the camera with the object you need to write it in your script.

You can also use a public reference for your object and drag it by using the Unity inspector.

Also, you can watch in the Unity/Standard Assets, a CameraFollow script exist already.

---
Tags: unity, monodevelop
---


# Question
Title: GameObject's scale gets 0 after being parented in editor
1) Before

2) After being parented.

I found a pattern. When adding the child, if the parent's scale.z = 0 the child scale.xyz becomes 0 on parenting. If the parent's scale.z != 0 it works. Another experiment that I tried was, after successfully adding the child(without getting scaled down to 0) and then to make the parent's scale.z = 0, the children's scales don't get affected at all.

Why?

# Answer
> 2 votes
When you change an object's parent in Unity, the editor automatically adjusts the object's local position/rotation/scale values so that the global appearance stays the same (or as close as possible)

So for instance, if I take an object with scale (1, 1, 1), and add it to a parent with scale (2, 2, 2), Unity will adjust the child's scale to (0.5, 0.5, 0.5) so that the net result of its transform hierarchy is the same (1, 1, 1) it started with.

Unfortunately, there are a few cases where this breaks down, and Unity can't maintain the object's global appearance. One such case is if any of the parent's scale axes are zero. Trying to compensate for a zero scale results in a division by zero, so there's no right answer.

It looks like in this case, Unity sets the scale of the object to zero as a fallback.

The best way to avoid this complication is to not use non-uniform scaling on parent objects. Uniformly scaled transforms are easy to nest & re-parent without loss or distortion.

# Answer
> 1 votes
In order to get around this programmatically you can do

`transform.SetParent(newParent, false);`

What this does allows you to keep the local values the same instead of leaving the global values the same, idk if this will give you your intended affect since it will move the object but it is an option.

---
Tags: unity
---


# Question
Title: In Unity3D, how can I improve image clarity?
The same images that appear clearly in Adobe Flash appear blurry in Unity.

My game uses quads, cubes and sprites. I've tried the game on Android, iPhone, Mac and PC, but the image appears poor-quality on all of them.

A sample screenshot:

What can I do about this?

# Answer
You will get all needed informations in the official documentation: see Manual: 2D Textures.

Basically you can control the "quality" of textures by tweaking the compression format and filtering mode.
> 0 votes

# Answer
If you need good image quality you can use Format: Truecolor or ARGB 32 with an high Max Size and avoid compression:

You can try playing with Filter Mode and Aniso Level too in the advanced settings:
> 1 votes

# Answer
If you have mitmaps enabled on your resources, you may be inadvertently using a lower quality image. You can try disabling mitmaps on each resource to see if your image quality increases.

Furthermore in Edit\>Project Settings\>Quality you can set quality flags of your application.

You may also want to make sure that your resources are a large enough size, and that you're not blowing up a 16x16 image onto a large texture for example.
> 0 votes

---
Tags: unity, sprites, rendering
---


# Question
Title: DirectX is the camera a point or a plane?
I've built an application in SlimDX using an orbit camera. Currently I treat the position of the camera as a singular point in space. I've noticed my projections from 3D space to 2d space are off by a small amount. The further something is from the center of the view, the more the projection to 2D space is off.

Should I be thinking of the camera position as a point in space, or as a plane? Treating the camera as a plane would be conceptually similar to saying the lens of the camera has the same height & width as the view it observes.

# Answer
There are 2 main types of projections used in video games and 3d applications:

1. Perspective
2. Orthogonal

## Perspective

This type of projection is the one that is the most commonly used to represent a 3d world simulation; it acts a little like a normal camera with lenses. All the elements of the scene are projected *toward* a **single point**, but *drawn* on a **plane**. In the case of computer 3d perspective projection, the plane is at the near clipping plane. On the camera, it is on the film or the photo-sensors (or whatever you call that device). The difference between the real world camera lenses and the 3d world projection is that the lenses distort the image circularly because of the shape of the lens, while the 3d version distort it linearly, because it's a straight matrix computation (the same matrix is used for all the vertices in the scene).

## Orthogonal

This type of projection takes the vertices and brings them directly on the projection **plane**, there is no try in giving any effect at all. This kind of projection is mainly used for 2d interface, 2d games (made in 3d, like a side-scroller) and you can see it used a lot in CAD graphics tools as it does not distort sizes with depth.

**So to answer your question**, you most likely will treat your camera as a **point in space** that **projects on a plane**. Unfortunately, the distortion you see is "normal" (as in "expected") and there is very little you can do about it. What you see depends on the paramters you give it (field of view, aspect ration, near and far clipping planes; treat it as a pyramid with the top chopped off).

Depending on your application, you can try to use an orthographic camera but you will not get the same effect; you may also try to attenuate the effect by changing the field of view and/or the aspect ratio, but again, that might not help you.

A last suggestion I could give would be to attenuate it by doing a render to texture of your scene, apply that texture on a grid (mesh) model, modify the points of the vertices of the mesh to attenuate the distortion (you display that textured mesh instead of your scene); this would give a better or worse result, depending on your application.
> 2 votes

---
Tags: directx, camera, slimdx
---


# Question
Title: Why does my sprite player move faster when I move the mouse?
I'm trying to develop a simple game made with Pygame (Python library).

I have a `sprite` object which's the `player` and I move it using arrow keys. If I don't move the mouse, the sprite moves normally, but when I move the mouse, the sprite moves faster (like x2 or x3). The `player` object is inside the `charsGroup` var.

I've run the game in W7 and in Ubuntu. Same thing happens in both OS.

I have more entities which move like NPCs and bullets but they don't get affected, just the player. Given this, I think that the problem maybe has a direct connection with the player moving system (arrow keys).

Here is the `update()` method of the `player` object:

```
def update(self):

    for event in pygame.event.get():
        key = pygame.key.get_pressed()
        mouseX, mouseY = pygame.mouse.get_pos()
        if event.type == pygame.MOUSEBUTTONDOWN:
            self.bulletsGroup.add(Bullet(pygame.image.load("bullet.png"),
                                          self.rect.x + (self.image.get_width()/2),
                                           self.rect.y + (self.image.get_height()/2),
                                            mouseX, mouseY, 50, 50))

        if key[pygame.K_RIGHT]:
            if not self.checkCollision():
                self.rect.x += 10
            else:
                self.rect.x -= 10
        if key[pygame.K_LEFT]:
            if not self.checkCollision():
                self.rect.x -= 10
            else:
                self.rect.x += 10
        if key[pygame.K_UP]:
            if not self.checkCollision():
                self.rect.y -= 10
            else:
                self.rect.y += 10
        if key[pygame.K_DOWN]:
            if not self.checkCollision():
                self.rect.y += 10
            else:
                self.rect.y -= 10

```

And here is the while loop:

```
while True:

    if PLAYER.healthBase <= 0:
        GAMEOVER = True

    if not GAMEOVER:
        mapTilesGroup.draw(SCREEN)
        charsGroup.update()
        charsGroup.draw(SCREEN)
        npcsGroup.update()
        npcsGroup.draw(SCREEN)
        drawBullets()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

    if GAMEOVER:
        myfont = pygame.font.SysFont("monospace", 30)
        label = myfont.render("GAME OVER!", 1, (255, 255, 0))
        SCREEN.blit(label, (400, 300))

    freq.tick(0)

    pygame.display.flip()

```

I don't know what more you can need to help me, but anything you need (more info or code) just ask for it!

# Answer
**tl;dr** don't mix your *event loop* with your *game loop*.

When you move your mouse, the game receives a load of `pygame.MOUSEMOTION` events. You don't actually use these events to update your mouse position though, you are getting the current state of the mouse using `pygame.mouse.get_pos()`. That's inefficient, but it's not the problem.

The problem is you are updating the player position *inside the event loop*!

This is what's supposed to happen:

```
game loop:
    event loop # get key presses, mouse moves etc.)
    if key pressed in the event loop:
        move the player

```

This is what your code does:

```
game loop:
    event loop:
        if key pressed:
            move the player

```

When you move your mouse, the event loop will execute many times per frame. But when you check which keys are pressed with `pygame.key.get_pressed()`, they stay pressed until you let go, some time later. So as your event loop is churning through the mouse move events, it will re-apply the player moves repeatedly.

The solution is simple: move the player outside the event loop.
> 43 votes

# Answer
Here are some more thoughts to complement the existing answer.

*Gaffer On Games* has a great article on game loops that has been referenced everywhere.

Your game loop should have different independent stages: Input, Update, Render.

You could for example read inputs 30 times per second (or in real-time for better responsiveness), do 30 updates per second and render 60 frames per second, or whatever values work well for your game.
> 4 votes

---
Tags: game-loop, python, pygame
---


# Question
Title: Bouncing projectile off of sprite, the sides work but top and bottom do not
I'm having a problem bouncing a projectile off a sprite, we've been asked to move the projectile using the equations of motions which makes things a little more difficult but as far as I can see what I have should work.

What I'm trying to do is change the angle of the collided projectile depending on which direction it is coming from.

Here is a video that is hopefully not too laggy for you to see what is happening:

Link

When the projectile collides with the left or right hand side of the sprite everything works as expected, it just switches X direction.

When it hit's the top or bottom of the sprite however it doesn't change, it just sort of rolls along the top and the shoots off.

Here is the movement code:

```
float nX = get_x() + cos(nGetAngle() * 3.14 / 180) * getU() * getT();
float nY = get_y() - sin(nGetAngle() * 3.14 / 180) * getU() * getT() + 0.5 * 9.8 * getT() * getT();
set_world_position(nX, nY);

```

Where U is initial velocity, T is time and nGetAngle() is the angle in degrees (which is set to radians whenever the angle is set).

Here is my collision for the top of the player:

//if the projectile is colliding in any way with the player sprite

```
if (projectiles[currProj]->get_y() < player->get_y()) // top of player
{
    float vx = cos(projectiles[currProj]->nGetAngle());
    float vy = sin(projectiles[currProj]->nGetAngle());

    float newAngle = atan2(-vy, vx) * 180 / 3.14;

    projectiles[currProj]->nSetAngle(newAngle);
    projectiles[currProj]->set_world_position_y(player->get_y() - projectiles[currProj]->get_height() - 1);
}

```

and here is my collision for the left of the player:

```
else if (projectiles[currProj]->get_x() < player->get_x()) // left of player
{
    projectiles[currProj]->set_world_position_x(player->get_x() - projectiles[currProj]->get_width());

    float vx = cos(projectiles[currProj]->nGetAngle());
    float vy = sin(projectiles[currProj]->nGetAngle());

    float newAngle = atan2(vy, -vx) * 180 / 3.14;

    projectiles[currProj]->nSetAngle(newAngle);
}

```

The left side collision works, the top does not and I have no idea why.

If necessary I can post the entire project somewhere.

# Answer
Let me put this simply. (Or I will try to)

First of all, you should read up on Vectors, find out what these are:

Vector Magnitude; Vector X,Y coordinates; Normalised Vector;

After this, you should read up a bit on physics, especially Newtons three laws; kinetics; momentum; and collisions.

After a week or so you should start to understand these things.

You will need to assign a velocity vector to the "ball"(upon shooting it), on every frame you will add the Gravity vector to this "ball". Then you will set up a collision detection function, that will return the collision normal, and the collision point.

Using this data, you will remove both objects from penetration. Then you will need to calculate the relative velocity of both objects = vA - vB = vAB. you will then use the dotProduct to project the Relative Velocity Vector onto the collision Normal. This will Give you the Impulse scalar. You will Scale this by -(elasticity (value between 0-1) + 1). You will then Scale the collision normal vector by the scaled Impulse * 2 (because you just want the ball to move).

After doing all this. You will have learned a lot about physics, expanded your knowledge of many usefull things, (that will be very usefull to you in game programming and many other programming fields).

best of luck!!
> 1 votes

---
Tags: sprites, physics, sdl
---


# Question
Title: Strategies to Defeat Memory Editors for Cheating - Desktop Games
I'm assuming we're talking about desktop games -- something the player downloads and runs on their local computer. Many are the memory editors that allow you to detect and freeze values, like your player's health.

How do you prevent **cheating via memory-modifiation?** What strategies are effective to combat this kind of cheating?

For reference, I know that players can: \- Search for something by value or range \- Search for something that changed value \- Set memory values \- Freeze memory values

I'm looking for some good ones. Two I use that are mediocre are:

* Displaying values as a percentage instead of the number (eg. 46/50 = 92% health)
* A low-level class that holds values in an array and moves them with each change. (For example, instead of an int, I have a class that's an array of ints, and whenever the value changes, I use a different, randomly-chosen array item to hold the value)

The game is offline, free and single-player.

**Edit:** for posterity, I solved this (in C#) and posted my solution here, on my blog.

# Answer
> 21 votes
Another possibility (for integer values) is to have a second member-variable which holds a bitwise complement of an existing variable.

So imagine you got `health`, you would also have `healthComplement`. Your implementation could look like this:

```
// setter sets value and complement
void setHealth(int value){
    health = value;
    healthComplement = ~value;
}

// getter checks if value was changed outside of the setter
int getHealth(){
    if(value != ~healthComplement){
        // launch some cheat-counter-measure, like crashing the game?
        exit;
    }
    return health;
}

```

Somebody who wants to cheat would have to set health and healthComplement correctly, otherwise the game would crash.

**I think it's kinda pointless to try to prevent stuff like this. People have successfully created hacks/cheats for much more complex stuff and it just needlessly obfuscates your code or makes your game perform worse.**

# Answer
> 12 votes
Here's one scheme I came up with when someone was asking for it on some board long ago. Using percentages or doubled variables doesn't really work, as you can search for "any" values and freeze them.

Instead, make a monster of a data type.

Basically, store your important values as a structure with:

* 32 pointers to bits
* For quick reading, have the struct include the current value as a plain int too

For manipulation, collect the current value from the separately-allocated bits (which can be true/false ints), change the value, and then store them back.

Here's the nasty bit: every time you manipulate the value, free and allocate the bits again. Allocation should happen **in random order**, so the data jumps around in memory and can't be easily frozen.

Additional safeguards would be to store checksums of the values (as well as the "plain" int) and compare these during the manipulation calls too. If mismatch is found, do something subtle, like remove a random key needed to unlock doors to progress in the game.

**Edit:** For further memory movement, make sure you allocate the new "bits" before freeing the old ones.

**Edit:** For multiplayer games, it's also possible to serialize the data structure, compress it, and send it over the network. Not the most efficient use of the network, but definitely harder to figure out through packet sniffing.

# Answer
> 9 votes
How about you store the health complemented with a random value generated each time you store it. This would at least defeat the simple mechanism of searching for increasing/decreasing values in memory to find the health.

```
class Player
{
  int m_Health;
  int m_RandomHealth;
  Random m_Rnd = new Random();

  public int Health {
    get
    {
      return m_Health ^ m_RandomHealth;
    }

    set
    {
      m_RandomHealth = m_Rnd.Next();
      m_Health = value ^ m_RandomHealth;
    }
  }
}

```

In addition, you might want to reset the value each frame, even if the health doesn't change. This will prevent people from searching for changed addresses when their health changes and that stay the same when their health stays the same.

Bonus: Create a new object each time it changes so the memory addresess change, and set the health to change the random number, xored value, and address in memory every time you *read* it:

```
class Player
{
  int [] m_HealthArray; // [0] is random int, [1] is xored health
  Random m_Rnd = new Random();

  public Player() {
    this.Health = 100;
  }

  public int Health {
    get
    {
      int health = m_HealthArray[0] ^ m_HealthArray[1];
      Health = health; // reset to move in memory and change xor value
      return health;
    }

    set
    {
      m_HealthArray = new int[2];
      m_HealthArray[0] = m_Rnd.Next();
      m_HealthArray[1] = m_HealthArray[0] ^ value;
    }
  }
}

```

# Answer
> 8 votes
Although I made the first comment questioning the point of degrading the experience of a portion of your audience for no apparent gain, I still find it an interesting question from a technical point of view.

I just had this idea: What cheaters do is find values that change and freeze them. The search would then happen only between deaths or events that changed the player's health. Moreover, the cheater could be refining the search by filtering out what changed when he was "not dying".

What if the "health" counter is changing the whole time? Make it a pointer and reallocate it every frame or every N frames if the performance hit is too big. Or XOR it with a random value that changes every frame (XORing again against the same value for decrypting before encrypting with a new random value).

If you have other in-game data also changing the whole time (including x and y positions of the player character, or the time counter), that might make it harder to find out which of all the changing data is the health. And freezing the whole game state is a no-go for the cheater.

For further mislead, you can actually store the health in a plain write-only variable meant as a honey pot.

**Edit**:

Still, the cheater might try to find which of the variables that is changing the whole time is the one to freeze through trial and error. A possible solution would be to couple the variables together.

An example:

Instead of storing health (h) and position (x), you store them in two variables a and b, from which you can retrieve the values later:

```
a = x+h; b = x-h
x = (a+b)/2; h = (a-b)/2

```

This way, if the cheater freezes only one of them and then moves the character, the position is affected and, depending on which one was frozen, h goes negative (instant death). You can switch between the above formulas and:

```
a = x-h; b = x+h
x = (a+b)/2; h = (b-a)/2

```

In consecutive frames, and you guarantee that in at most 2 frames after either one of the variables have been frozen health will turn 0 the moment x changes. Remember that you are storing only a and b. Combine this with the continuous XOR as mentioned above. The result is a collection of variables that are changing every frame to seemingly random values, and freezing any single one or a subset of them only produces undesired side effects in the game, instant death being one of them.

# Answer
> 7 votes
One possible option I think might work (I'm not too familiar with these cheating tools): don't hide it. Perform your operations and expect certain results. After the operation (possibly next frame), check to ensure that the results are as you expect them to be. If you subtract health and then verify it, only to find health never changed, you can be pretty sure (provided you don't have some obscure bug) that it was locked.

If you detect cheating, you are now free to change the rules of the game as you see fit for maximum griefing, if that is your intent. If your intent is to ignore the cheating and have the game continue to work, reallocate the health elsewhere in memory and change your pointers so that the new value gets used and the old is ignored. Repeat ad infinitum.

# Answer
> 6 votes
Any attempts at mere obfuscation are bound to fail in theory, but in practice you just need to make it hard enough to break that the challenge becomes less fun than succeeding at the game. I don’t know what your game is, so I won’t risk suggesting data obfuscation methods, even less as I believe they’re pointless.

That said, and you will probably not be fond of it, I believe you are looking for *memory curtaining*, which is a Trusted Computing concept.

# Answer
> 3 votes
One very effective technique used by some roguelikes (DoomRL, Brogue) is to *mask the actual variables.* What this means is that instead of showing health as "2/10," show it as "20%."

Remember, most memory editors work well with specific value searching/filtering. If you don't know the specific value, you can still track it down (eg. search for changed/decreased values after the player health drops), albeit it takes much longer to do it that way.

I also suggest an anti-cheat backlash. For example, if you have a game where the player takes non-positive damage and their health didn't drop, you can easily and accurately check this and know that the player cheats. Do something interesting, like spawning some uber enemies around him :)

# Answer
> 2 votes
Write a ring 0 driver that hooks SSDT and logs / blocks when ReadProcessMemory / WriteProcessMemory is called on your application. It'd be better to just log so you can slowly change their game behavior over time rather than just crash.

# Answer
> 2 votes
Why would you prevent players from cheating themselves (which cheating in a single player game amounts to)? In a multiplayer environment, it's the server's task to detect unnatural changes and counter them (typically by either ignoring the input or blocking the culprit out from the server completely), but in a single player environment there's nothing happening except the cheater is doing himself a disservice.

IOW, unless you're creating a multiplayer game it's a waste of money, and if you are you're thinking of hardening the wrong place.

# Answer
> 2 votes
Research the known cheating tools - and frequently check whether any of the most common ones are detected running (check process names?)

If any are detected, let the player cheat (if offline, it's harmless), but make sure no scores/acheivements will be posted to any online leaderboard/acheivement system - just make it silently fail?

Won't stop more determined hackers, but will reduce the chance of more casual cheats messing up your leaderboards.

(Might annoy coders that have dev tools open and minimized for legit purposes and are taking a gaming break, though...)

# Answer
> 1 votes
I think the simplest solution to this is to implement a cheat option. Disable scoring while in cheat option.

Another good idea, that I have no idea how you would implement. Is to shut off the game when there is a frozen memory variable or something like that :)

Good luck (Y)

---
Tags: anti-cheat
---


# Question
Title: GameObject is only rendered when it has a negative z scale
I have an orthographic camera that looks like this:

I create 2d polygonal meshes that have uniform z values in their vertices. I use Camera.ViewportToWorldPoint() to map these viewpoint vertices to world vertices.

The initial z valueI use for each polygon vertex is 1.0f. When I view my generated polygons, they each have a scale of (1,1,1) and are not being rendered. However, when I set the z value of the scale to any value less than zero, the mesh is rendered.

Could this be an issue with my camera's properties?

# Answer
> 1 votes
Apparently Unity only render one face of the quad with the default shader (you can test it by moving your camera around). By setting another shader (in your case "Sprite/Default" should do the stuff), it will render both faces.

At least it solved the problem for me.

The reason it work with negative z is that a negative scale will flip the quad (thus exposing the other face to your camera).

---
Tags: unity, rendering, camera, projection
---


# Question
Title: Tilesets - how to make the pink color appear transparent
recently I searched for some free to use Tilesets on the internet. And wherever I found a sheet of sprites there is this pink color in the background. i know that all the spots having that color should be transparent later on but how do I do that? And has it any other special use or effect on the tile data? An example of those sheets can be found here: http://opengameart.org/content/rpg-indoor-tileset-expansion-1

# Answer
You could use the transparent png instead. These sprites with a pink color were used a lot in old games, usually using images with a palette (indexed colors). Commonly the pink color is Red = 255, Blue = 255, Green = 0, and it is defined as the first color in the palette (index 0), meaning it should be transparent pixels. Defining the color as pink helped to handle designs when the painting tools was not so cool like now (pink is easy to spot in most images). Using indexed colors could help to reduce a lot the size of images, and it is very common to store a set of images sharing a common palette (like in this tileset).
> 1 votes

# Answer
In doubt, when you can not obtain a version of the tileset where the "pink" areas are indeed transparent, you can simply replace all pink pixels of the image with transparent ones, with a method like `replaceColor` in this example:

```
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class ColorReplaceExample
{
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                createAndShowGUI();
            }
        });
    }

    private static void replaceColor(
        BufferedImage image, Color oldColor, Color newColor)
    {
        for (int y=0; y<image.getHeight(); y++)
        {
            for (int x=0; x<image.getWidth(); x++)
            {
                int color = image.getRGB(x, y);
                if (color == oldColor.getRGB())
                {
                    image.setRGB(x, y, newColor.getRGB());
                }
            }
        }
    }

    private static void createAndShowGUI()
    {
        JFrame f = new JFrame();

        BufferedImage image0 = null;
        BufferedImage image1 = null;
        try
        {
            image0 = ImageIO.read(new File("tileset.png"));
            image1 = ImageIO.read(new File("tileset.png"));
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        replaceColor(image1, new Color(255,0,255), new Color(0,0,0,0));

        f.getContentPane().setLayout(new GridLayout(1,2));
        f.getContentPane().add(new JLabel(new ImageIcon(image0)));
        f.getContentPane().add(new JLabel(new ImageIcon(image1)));
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }
}

```
> 1 votes

---
Tags: java, spritesheet, tiles
---


title: Torus World Collision Dection

text:
# Question
Title: Torus World Collision Dection
I am looking for a collision detection solution for use when 2d screen wrapping. Specifically, when the image is split between the right and left side I can only detect a collision for a limited area.

For example, the program detects the collision when the rectangle intersects the circle in the first image. However, it doesn't in the second image. I am using the Rectangle.Instersects method to check for the collision in both cases.

I used the screen-wrapping solution at the following link: How to create a 2D region where sprites are automatically wrapped?

However, since I am not using the physics engine, I am not using the related solution at: How to create a very specific kind of joint in Farseer?

I am aware of the following question: https://stackoverflow.com/questions/8679304/wrapping-drawn-image-in-xna-4-0, and incorporated part of the code to reset the draw rectangle's position when wrapping for both sprites:

```
 // reset draw rectangle for wrapping
        if (drawRectangle.X < -sprite.Width)
        {
            drawRectangle.X += parentWindowWidth;
        }
        if (drawRectangle.X > parentWindowWidth)
        {
            drawRectangle.X -= parentWindowWidth;
        }
        if (drawRectangle.Y < -sprite.Height)
        {
            drawRectangle.Y += parentWindowHeight;
        }
        if (drawRectangle.Y > parentWindowHeight)
        {
            drawRectangle.Y -= parentWindowHeight;
        }

```

This post also says that I have to check for the collision in the two separate positions, but I am having trouble doing so.

Any suggestions?

# Answer
I had to solve this issue a long time ago, and all I did was do:

* One normal collision check.
* One where I shifted everything up one "world-height" (aka screen height)
* Shift down
* Shift left one "world-width" (screen width)
* Shift right
* Up and Right
* Up and Left
* Down and Right
* Down and Left

eg:

```
if(x + width  > test.x && x < test.x + test.width &&
   y + height > test.y && y < test.y + test.height)
{
    Collide!
}
else if(x + width  > test.x + worldWidth && x < test.x + test.width + worldWidth &&
        y + height > test.y && y < test.y + test.height)
{
    Collide!
.... 7 more times

```

Seems cumbersome and inefficient, and it probably is, but it's the easiest & most straight-forward way to solve this issue.

Below, I've drawn your playable area in **white**, and the possible collision zones in other colours in the diagram below:

In this example, I have left the circle in place (x and y in example code), and compared it against your squiggle of colours in all 9 possible configurations listed above. As a visual demonstration, I've drawn all 9 possibilities.

This should get you pointed in the right direction.

Other torus-world tips I can provide are:

* You're going to need to detect when an object crosses these boundaries and draw the same thing up to 4 times if it's straddling a corner.
* Shortest paths (eg, Homing missiles) will need to compare all 9 routes to the target.
> 3 votes

---
Tags: xna, c#, collision-detection
---


# Question
Title: Scaling of a bone is working while rotation is not Unity3d
I'm using Unity3d and I'm trying to rotate the left leg bone of an avatar but it is not working although scaling is working well.

This is the code used for scaling and is working perfect:

```
 r.localScale += new Vector3( 0.1f , 0.1f , 0.1f);

```

and these are my attempts to is the code of rotation but not working:

```
 r.eulerAngles = new Vector3(10, 10, 10);
 r.rotation = transform.rotation * r.rotation;

```

where r is the transform of the left leg.

EDIT:

This is my file.

So this doesn't work when I'm using the `Update` function, like nothing happens to the avatar. If I used `LateUpdate` function, I can see the rotation made but then flickers back to the old position, I wonder how to apply the rotation to all the remaining frames as well.

If anyone could please advise

# Answer
Your code doesn't seem to have any "rotation" for me. Plus you're addressing r.eulerAngles, which is why your rotation is failing. Quote from Transform.eulerAngles :

> Only use this variable to read and set the angles to absolute values. Don't increment them, as it will fail when the angle exceeds 360 degrees.

And for the next part, what are you expecting this to do? What's `transform`?

```
 r.rotation = transform.rotation * r.rotation;

```

Ayways for rotation, try using :

```
r.Rotate(new Vector3(10,10,10));

```

By the way, by addressing `r.rotation`, you will be addressing the quaternion. Operations on quaternions aren't the same a operations on "Vector3"s.
> 1 votes

---
Tags: unity, unityscript
---


title: Validating User Actions on the Server

text:
# Question
Title: Validating User Actions on the Server
I am currently working on a networked first person shooter. I have created a server implementation that can synchronize player data. But while implementing a damage system, I realized that I almost simply sent a packet with

```
PLAYER DAMAGE [target id] [amount]

```

But that would likely be open for any player to save a list of IDs and inject that packet to damage every ID. Unfortunately the server is unable to know what the environment is like -- meaning it cannot check if there is something between the two players or likewise.

How would I keep this from being possible?

# Answer
I don't understand why you use server client model, if your server has 0 authority and lacks capability to enforce rules. Your server have to know the map. How else could it stop player from walking through walls. You say "client side is unmodifiable", I say you are misinformed. There is no such thing as "unmodifiable client". You are trusting too much on client and without map/world awareness, the server cannot do anything.

Heres example of client server communication:

**Client**: *"I am clicking my mouse 1 now"*

***Server****:"Ok, based on my memory, you stand at x y and aim towards x2 y2, you click mouse 1 and your selected weapon is desert eagle with 2 bullets in clip, lets shoot and check if you hit someone"*

***Server****-again: "based on calculations, player1 hit player2, so lets update everyone to let them know this happened."*

See the difference? If you wanna have authoritative server, you have to give more information for it. This is the way, the modern server client games work. Client is just a remote input device with display. Server is the one who does all the decisions. Your client should not be able to send damage packets or kill packets or anything at all. Only packets, that tell the server what the client did after last update.
> 3 votes

---
Tags: networking, multiplayer, client-server, anti-cheat
---


# Question
Title: Changing scene while joining room and RPC buffer problem
I have a button on my main menu that creates and has the player join a random room. After the client joins this room, I change the scene to the game (main) scene in the `OnJoinedRoom` method. This works well, until I use the RPC call with buffers.

There are 5 spawn points in the game scene, and every time a player joins the room, they occupy a spawn point, so no-one else can spawn at that point. So, I have list of spawn points in my code, and every time a player joins, it randomly picks a point from that list and "removes" it from the list. It does this via RPC call, so if a player joins the game late, it removes that point, too.

There is a problem with that RPC's buffer because of the "scene change". After `OnJoinedRoom`, the RPC buffers are called only when the player joins the room, and before the scene change. Because the scene hasn't changed yet, it has trouble finding the buffered `photonview`, and it throw outs an error. It doesn't update the list.

Can I delay the buffer calls, is there a better way to change my scene while joining a room?

# Answer
A more reliable and efficient method of syncing new players is delegating this task to another player. Since Photon's servers aren't authoritative, this is the next best option to catch someone up.

One method is to send an RPC to the master client telling it to catch you up on the game state. The master client then sends you a stream of data giving you information about everything you need. This gives you full control over the replication on new player.

Alternatively, you could buffer received buffered RPCs and process them once your scene is loaded. This is probably easier since you won't have to have the master client gather everyone's information but keep in mind that every single buffered RPC will get sent to the new player. This means if you send a buffered RPC every time a door opens/closes, the new player will get all those RPCs even if all but 1 are outdated and useless.
> 0 votes

---
Tags: unity, networking
---


title: Packet size vs packet frequency

text:
# Question
Title: Packet size vs packet frequency
I am making a multiplayer game in Java that uses a client-server model, where all important decisions are made by the server and communicated to all clients over UDP. Currently the clients and the server both send packets at 30fps. The clients just send a single packet each time, but for the server the situation is a little more complicated.

The server needs to update the client on the positions of all Entities in the game, of which there could be many (100+) at any given time. Currently each of these updates is being sent in a separate packet.

It seems to me that combining some of these updates into a single packet could be beneficial, as it would reduce the overhead of creating and sending all these packets. But combining too many updates would create a packet that is "too large" to be sent efficiently across the network.

Where does the balance lie between packet size and the number of packets being sent, in order to achieve the fastest and most reliably delivery?

# Answer
> 5 votes
According to the answers on this page, about 512 is a safe amount for ipv4 because nearly all consumer's hardware will be able to support that size. For ipv6, 1500B is the maximum safe packet size. Subtract 40 + 8, the ipv6 and UDP header sizes, and you get 1454B maximum data inside that packet. If you send something over the limit, it's most likely going to be cropped out. With some clever compression methods, you should break the limit very rarely so a simple check then to send out an additional packet should work fine.

If you have 100+ entities, 30 syncs per second will simply not be viable. If you're just syncing positions and rotations, which together is i.e. 24B, the bandwidth demand per second will be 24 * 100 * 30 = 72,000. Assuming that spatial and delta compressions are used, this number can dwindle down to i.e. 32,000. Then there's the packet headers which will be negligible compared to the data within the packets: (40 + 8) * 30 = 1440. Now, this is much, much better than syncing entities with individual packets (216,000B/s) but 33,440B/s is still a hefty amount, especially since we're only considering positions and rotations (not bullets, health, etc.). If every one of those entities was a player needed to be synced, this tasks the server to send out 3MB/s of data for a single room. To put things into perspective, an hour long game hosted on Amazon EC2 would cost about $1.50. If you make a profit of $10 off a player, you would start losing money from that player after he has played 660 hours.

**Conclusion:**

A lower sync rate is definitely called for and spacial culling must be used extensively in order to make the data size manageable. You haven't specified if you're using ipv4 or ipv6 but you should probably use ipv6 so you can fit more data into a packet.

**Sidenotes:**

I would recommend using a lockstep model for anywhere of 32+ entities. Actually, I think almost all multiplayer games would be best off using the lockstep model because of the unbeatable bandwidth efficiency and hack prevention.

If you don't want to deal with indeterminism or want players to be able to join mid-game, look at PlanetSide 2. They use a semi-authoritative server that syncs thousands of players with 5 syncs per second, clever extrapolation, and spatial culling. Granted, the game is far from perfect and very laggy but it gets the job done. What I mean by semi-authoritative is that the server is only authoritative about what is most important and practical (positions, deaths, abilities). Being authoritative about every single projectile would lead to many weird bullet behaviors when shooting because of the lag.

---
Tags: networking, client-server, udp
---


# Question
Title: In the game loop, apply dt before the loop starts, or after it finishes?
Say I have a Game class with an update loop that receives a time increment `dt` by parameter. I was wondering if it's better or customary to apply this dt before the loop starts or after the loop finishes.

```
class Game
{
    void Update(float dt);
    float m_time;
}

```

`dt` is the delta time from last update loop.

`m_time` is the total accumulated time since the game started running.

Option 1:

```
void Game::Update(float dt)
{
    m_time += dt;
    /*
    do stuff
    */
}

```
* Pros: I think it's more clear.
* Cons: No update loop is processed at `m_time = 0`. The very first update loop already has `m_time = dt`.

Option 2:

```
void Game::Update(float dt)
{
    /*
    do stuff
    */
    m_time += dt;
}

```
* Pros: The update loop starts at `m_time = 0`.
* Cons: I find it a bit weird that the time is updated after all the processing has finished.

Any advise on which option is better or preferred over the other?

# Answer
> 1 votes
dt, which I'm assuming is the time between frames, should be added to m\_time at the beginning of the frame so that m\_time will be the time since the start of the game when you use it later on in the frame, assuming that's what m\_time is.

---
Tags: game-loop
---


# Question
Title: Endless Running Game - Changing Lane Function in JAVA
I am developing a kind of vertical endless running game, where the character has 4 possible lanes to be in. I am using libGDX and want the character to change lanes by adding a horizontal velocity to a Vector2. The position will be upgraded by velocity increments and not by simply changing the position to the next lane. So far I have a working function, but as I increment the horizontal velocity, along the run, it loses accuracy. Let's assume each lane is 50px width.

I am also using a acceleration vector to slow down as the character gets closer to the next lane.

The 2 functions below are about what happens when the screen is touched right or left. The position verification is a boundary condition to avoid the character going off the screen.

```
public void onClickRight(){
    if(!(position.x>=50*2.75)&&isAlive){
        velocity.x=350+extraSlideSpeed;
        acceleration.x=-500;
    }

}

public void onClickLeft(){
    if(!(position.x<=50*0.75)&&isAlive){
        velocity.x=-350-extraSlideSpeed;
        acceleration.x=500;
    }
}

```

The function below is called about 60 times per second, as delta is a very small number and represents time.

```
public void updateRunning(float delta){

    velocity.add(acceleration.cpy().scl(delta));
    position.add(velocity.cpy().scl(delta));
    displacement.add(velocity.cpy().scl(delta));

    if(displacement.x>=50||displacement.x<=-50){
        velocity.x = 0;
        acceleration.x = 0;
        displacement.x = 0;
    }
}

```

I am looking for smarter options as I am not pleased with my own. Help would be appreciated!

# Answer
> 3 votes
You should do a bounds check as you mentioned then reduce the velocity so you don't get shaky behavior. You kind of got it but I'm not sure what displacement does.

```
//This code goes after velocity is set
if (position.x > 50)
{
    position.x = 50;
    //If we're heading towards the bounds, stop
    if (velocity.x > 0) velocity.x = 0;
}
else if (position.x < -50)
{
    position.x = -50;
    if (velocity.x < 0) velocity.x = 0;
}

```

Velocity can be handled however you like but the above code should ensure that the runner stays between -50 and 50 inclusive and doesn't shake when it hits a bound.

---
Tags: java, libgdx, vector, game-loop, optimization
---


title: Moving texture OpenGL ES 2.0

text:
# Question
Title: Moving texture OpenGL ES 2.0
I am trying to implement a sprite of 8 columns and 8 rows in OpenGL ES 2.0
I made appear the first imagen but I cant figure out how to translate the Texture matrix in OpenGL ES 2.0 , the equivalent of the code in OpenGL 1.0 that I am looking is

```
        gl.glMatrixMode(GL10.GL_TEXTURE);
        gl.glLoadIdentity();
        gl.glPushMatrix();
        gl.glTranslatef(0.0f, 0.2f, 0f);
        gl.glPopMatrix();

```

This are the matrix that I am using atm

```
/**
 * Store the model matrix. This matrix is used to move models from object space (where each model can be thought
 * of being located at the center of the universe) to world space.
 */
private float[] mModelMatrix = new float[16];

/**
 * Store the view matrix. This can be thought of as our camera. This matrix transforms world space to eye space;
 * it positions things relative to our eye.
 */
private float[] mViewMatrix = new float[16];

/** Store the projection matrix. This is used to project the scene onto a 2D viewport. */
private float[] mProjectionMatrix = new float[16];

/** Allocate storage for the final combined matrix. This will be passed into the shader program. */
private float[] mMVPMatrix = new float[16];

/**
 * Stores a copy of the model matrix specifically for the light position.
 */
private float[] mLightModelMatrix = new float[16];

```

# Answer
> 0 votes
Answer by OFE in StackOverFlow:

You will need to perform transformations to the texture co-ordinates yourself, you could do this in one of four places:

-Apply the transformation to your raw model data.

-Apply the transformation in the CPU (not recommended unless you have good reason as this is what vertex shaders are for).

-Apply the transformation in the vertex shader (recommended).

-Apply the transformation in the fragment shader.

If you are going to apply a translation to the texture coordinates the most flexible way will be to use your maths library to create a translation matrix and pass the new matrix to your vertex shader as a uniform (the same way you pass the mMVPMatrix and mLightModelMatrix). You can then multiply the translation matrix by the texture coordinate in the vertex shader and output the result as a varying vector.

Vertex Shader:

```
 texture_coordinate_varying = texture_matrix_uniform * texture_coordinate_attribute;

```

Fragment Shader:

```
 gl_FragColor = texture2D(texture_sampler, texture_coordinate_varying);

```

Please note: Your GLES 1.0 code does not actually perform a translation as you surrounded it with a push and pop.

---
Tags: android, textures, opengl-es2
---


# Question
Title: Animator, gameObject position not being kept
I have idle & popout animations. Idle- simple scaling up and down 2d object and popout- get the gameobject's position to the right and leave it there. I'm using animator for this purpose. I have a trigger Popout, which when triggered the animator goes from playing the Idle animation to the popout animation. Then another transition from the popout anim back to the idle anim. The problem is that when it gets back to the idle anim, the position gets back to the first one(i.e. as if the popout anim hasn't been played). My goal is, after playing the popout, the gameObject to stay at the last position from the popOut anim and to continue to be scaled up and down(the idle anim). My goal is, the gameObject to keep its last position set from the popout anim(which is to the right of its initial one) and to continue playing the idle anim from there instead of going back to its initial position.

**Why does the animator reverses the gameobejct's position to its initial one, after the popout anim has been played?**

In this video you can see the problem and what exaclty I'm doing.

# Answer
> 2 votes
I seen your video and it seems to me that your problem might be in Exit condition of the second animation. You need to have your logic set up like this :

http://gfycat.com/ElasticPastBlackcrappie

In your code you need to set the same toggle state for both your animations. And you need to set the condition for both of them, to work if the toggle is on.

Now after that, you need to realize that, you don't have **two** states in your animations, you have **three**.

Idle1 \>\>\> TransitionAnimation1 \>\>\> Idle2

So you will need not just two animation controllers, but three. Once you press toggle, it will run the transition animation, and then after that animation is over, it will switch to the Idle2 state. You won't need any conditions for the transition state, so you will keep everything you have, except you'll add the second state between them.

And I'm not done yet. Your transition state **changes** between the animations. So you will need **another** animation controller to go back to the other one. Your controllers should look something like this :

I hope you understand how animations work now. The best extra tip I can give you is to not use animators for basic translations. You see you will need to have 3 extra Animation states now. It's very unefficient. You can just script a boolean that will translate it to Y position when space is pressed, and translate it back to X position when space is pressed again. With only one idle animation that remains the same. Cheers.

---
Tags: unity, animation
---


# Question
Title: Load a simple text file through asset manager in libgdx
It's easy to load a simple text file from the `internal`:

```
Gdx.files.internal("data/colors.txt");

```

But I currently use an `AssetManager` to load assets that are defined in an array of `AssetDescriptor<?>`s while a loading screen (with a progress indicator) is shown. So I'd like to use something like this in my array of descriptors:

```
...
new AssetDescriptor<_type_>(Gdx.files.internal("data/colors.txt"), _type_.class),
...

```

I'd like to load the file through an asset manager, so the overall progress can be displayed as the `data/colors.txt` file can get very large and therefore take longer to load (I use an tool to automatically generate a very long list of color definitions: `RRR,GGG,BBB,AAA`, each in the range of `0-255`).

Is there a good way of doing this?

# Answer
I searched the wiki for an answer and found that there is no `Loader` for text files (see list here).

So I followed the instructions on the same page to write my own loader (the instructions can be found here). This is what I came up with:

---

The `Text` class is basically a wrapper around a simple `String`:

```
package mygame.assets;

import com.badlogic.gdx.files.FileHandle;

public class Text {

    private String string;

    public Text() {

        this.string = new String("".getBytes());

    }

    public Text(byte[] data) {

        this.string = new String(data);

    }

    public Text(String string) {

        this.string = new String(string.getBytes());

    }

    public Text(FileHandle file) {

        this.string = new String(file.readBytes());

    }

    public Text(Text text) {

        this.string = new String(text.getString().getBytes());

    }

    public void setString(String string) {

        this.string = string;

    }

    public String getString() {

        return this.string;

    }

    public void clear() {

        this.string = new String("".getBytes());

    }

}

```

The `TextLoader` class is the corresponding loader class for an asset of type `Text`:

```
package mygame.assets.loaders;

import com.badlogic.gdx.assets.AssetDescriptor;
import com.badlogic.gdx.assets.AssetLoaderParameters;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.assets.loaders.AsynchronousAssetLoader;
import com.badlogic.gdx.assets.loaders.FileHandleResolver;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.Array;

import mygame.assets.Text;

public class TextLoader extends AsynchronousAssetLoader<Text, TextLoader.TextParameter> {

    public TextLoader(FileHandleResolver resolver) {

        super(resolver);

    }

    Text text;

    @Override
    public void loadAsync(AssetManager manager, String fileName, FileHandle file, TextParameter parameter) {

        this.text = null;
        this.text = new Text(file);

    }

    @Override
    public Text loadSync(AssetManager manager, String fileName, FileHandle file, TextParameter parameter) {

        Text text = this.text;
        this.text = null;

        return text;

    }

    @SuppressWarnings("rawtypes")
    @Override
    public Array<AssetDescriptor> getDependencies(String fileName, FileHandle file, TextParameter parameter) {

        return null;

    }

    public static class TextParameter extends AssetLoaderParameters<Text> {

    }

}

```

Then, to register the `Text` asset and its `TextLoader`, in the `create()` method of the main class:

```
@Override
public void create() {

    // ...

    // Assuming that the main class contains the global AssetManager

    assetManager.setLoader(
            Text.class,
            new TextLoader(
                    new InternalFileHandleResolver()
            )
    );

    // ...

}

```

To use it:

```
assetLoader.load( new AssetDescriptor< Text >( "data/colors.txt", Text.class, new TextLoader.TextParameter() );
String string = assetLoader.get( "data/colors.txt", Text.class ).getString();
// Process the string

```

---
> 3 votes

# Answer
As you automatically generate these color definitions, maybe you could generate it instead of loading from a file. If the problem loading is the size of the file, you could consider using compression. But as you wanna try with assets loader, I'll add some links that could be useful.

To manage these color definition assets you could write your own loader.

Also you could consider a custom json serialization.
> 0 votes

---
Tags: java, libgdx
---


# Question
Title: Implement dynamic 2 player splitscreen based on player positions
Having a local 2 player game, when the distance between the player is big enough, we have a splitscreen whose shape is defined by the angle between the two players. When they get close enough to each other it should fall back to single screen and when they get farther, the screen zooms out before becoming a splitscreen again.

Pretty much the way it's demonstrated in this video: https://www.youtube.com/watch?v=XzIzHKwVDH4

How would that be implemented? What would be a decent GameObject-Hierarchy for this?

# Answer
> 1 votes
In the description for that video (click "show more") you'll find he also posted a tutorial on how he did it.

The tutorial starts here.

He also has it posted on the asset store here.

---
Tags: unity, camera
---


title: XNA - Offscreen Vertices Optimization

text:
# Question
Title: XNA - Offscreen Vertices Optimization
Okay, I have a set of vertices that is around 10,000,000 (it's a long story, but it seems that it is needed), however only a few thousand of those will be onscreen at a time. It's currently setup as one vertex buffer (and it's one shape anyway) so the normal view frustum culling solution would not seem to be applicable here.

Is there any way of making it only drawing those few thousand verticies needed onscreen at one time?

Thank you!

# Answer
> 2 votes
One way would be organizing the model's triangles (not vertices) into a spatial hierarchy system like an octree. Then test the octree against the view frustum.

The XNA sample library has the 'ship game sample' that does this for collision testing of player's bounding box to the walls of the map(which are organized into the octree). But it wouldn't be much harder to test it against a view frustum as a bounding box.

---
Tags: xna-4.0
---


# Question
Title: Unity Vector3.MoveTowards over the span of a minute with Time.deltaTime
I'm trying to figure out how to use `Time.deltaTime` to let me move an object over the course of a minute.

From my understanding, `Vector3.MoveTowards(transform.localPosition, finish, Time.deltaTime)` will result in `transform` moving to `finish` over the span of one second. The same function but with `Time.deltaTime * 2` would result in the object completing the movement in the span of 30 seconds.

Therefore, I thought that `Vector3.MoveTowards(transform.localPosition, finish, Time.deltaTime / 60)` would cause the movement to happen over the course of 60 seconds. However, the move is extremely slow, and it looks like it would take several minutes to reach its destination.

I'm clearly using a wrong value somewhere, but what is it?

# Answer
> 1 votes
You're better off using Lerp.

```
float ElapsedTime;
float FinishTime;
Vector3 StartPosition
Vector3 Target;

void Start ()
{
    Vector3 StartPosition = Vector3.zero;
    Target = Vector3.one * 50;
    ElapsedTime = 0;
    FinishTime = 60f;
}

void Update ()
{
    ElapsedTime += Time.deltaTime;
    transform.position = Vector3.Lerp (StartPosition, Target, ElapsedTime / FinishTime);
}

```

This interpolates transform.position from the StartPosition to Target in FinishTime, which is a minute.

If you really want to use MoveTowards, you need to calculate the speed at which you need to move at to reach Target in 1 minute.

```
float Speed = Vector3.Distance (Target, StartPosition) / 60f;

void Update ()
{
    transform.position = Vector3.MoveTowards (transform.position, Target, Speed * Time.deltaTime);
}

```

By the way, in case it's unclear: Time.deltaTime is the time between frames in seconds.

# Answer
> 2 votes
Your understanding of Vector3.MoveTowards() is close, but not quite right.

```
public static Vector3 MoveTowards(Vector3 current, Vector3 target, float maxDistanceDelta);

```

Each time you call this method it returns a point along the vector from current to target that is at most maxDistanceDelta away from current. So if current is (0.0, 0.0, 0.0) and target is (1.0, 0.0, 0.0) and maxDistanceDelta is 0.1 then MoveTowards() will return (0.1, 0.0, 0.0).

In general, under the hood it's doing something like this:

```
current + (target - current).normalized * maxDistanceDelta

```

The exception is that if the distance between current and target is less than maxDistanceDelta then MoveTowards will just return target. That is, it won't overshoot.

If you want to control the speed of the movement then you just need to set maxDistanceDelta equal to the speed you want and multiply it by the Time.deltaTime, like so

```
Vector3.MoveTowards(current, target, speed * Time.deltaTime)

```

So if your speed is set to 10.0 you mean that you want the point to move 10 units per second. Since Time.deltaTime tells you how much time passed in the last frame multiplying it by the speed tells you the maximum distance the point should have moved in the last frame. Make sense? Multiplying or dividing by other numbers in maxDeltaTime just ends up effectively changing the speed. That's why Time.deltaTime / 60.0f made things so much slower. Your implicit speed was 1 and then you divided that by 60.0f...

Finally, if you want to traverse a set distance in a given period of time then you need to figure out the total distance (outside of Update) and divide that by the total time you want to take to get a speed. Then use that speed, scaled by deltaTime, in your call to MoveTowards() inside of Update().

See the Vector3.MoveTowards() documentation for more info and an example.

---
Tags: unity, movement
---


# Question
Title: Vector2.Distance on different resolutions
```
firstTouchPos = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);

endTouchPos = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);

                        //the height of the background(previously scaled to fit the screen) / 10
minSlidedDistance = (int)(SpriteRend.bounds.size.y / 10);

if (Vector2.Distance(firstTouchPos, endTouchPos) > minSlidedDistance)
{
  //do smth
}

```

This way I check if the player has slided into any direction with a slided distance longer than minSlidedDistance. It works perfectly for different size devices.

**Is unity going to make the calculations itself if I simply write minSlidedDistance = 100? I.e. is it still going to work same way on all devices?**

P.S. this is not the full code, there are many other IF checks, like the ones for assigning the value to firstTouchPos & endTouchPos

# Answer
Yes, unity does make the calculations itself.

Test case: Game Window -\> select different resolutions and run the following code:

```
private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            firstTouchPos = Input.mousePosition;
        }
        else if (Input.GetMouseButtonUp(0))
        {
            endTouchPos = Input.mousePosition;
            Debug.Log(Vector2.Distance(firstTouchPos, endTouchPos));
        }
    }

```
> 1 votes

---
Tags: unity, resolution
---


title: Actor not taking touch libGDX

text:
# Question
Title: Actor not taking touch libGDX
I am trying to handle the touch of one of the `Actor`s in the stage. The following is the code I have written:

```
public class MyGame extends ApplicationAdapter
{
    private GameStage gameStage; //Game stage is custom stage class.
    @Override
    public void create ()
    {
        gameStage = new GameStage();
        Gdx.input.setInputProcessor(gameStage); //Set the input processor
    }

    @Override
    public void dispose()
    {
        super.dispose();
        gameStage.dispose();
    }

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

        gameStage.act(Gdx.graphics.getDeltaTime());
        gameStage.draw();
    }
}

```

Now in the `GameStage` class:

```
public class GameStage extends Stage implements ContactListener
{
    MyActor myActor; //Custom actor object.
    public GameStage()
    {
        super(new ScalingViewport(Scaling.fill, Constants.APP_WIDTH, Constants.APP_HEIGHT, new OrthographicCamera(Constants.APP_WIDTH, Constants.APP_HEIGHT)));
        setUpWorld(); //Code to setup the world. added background and other actors. none of them are touchable.
        addActor();
    }

    private void addActor()
    {
        myActor = new MyActor(100, 100, 100, 100, 1000, 0);
        myActor.setTouchable(Touchable.enabled);
        myActor.addListener(new InputListener()
        {
            @Override
            public boolean touchDown(InputEvent event, float x, float y,
                                     int pointer, int button)
            {
                actorTouched(); //This method is not getting triggered becaused the call never comes in this function.
                return true;
            }
        });
        addActor(myActor);
    }
}

```

The custom actor class initializes the actor with a sprite image.

```
public class MyActor extends Actor
{
    public MyActor(int startX, int startY, int startWidth, int startHeight, int endX, int speed)
    {
        TextureAtlas textureAtlas = new TextureAtlas(Gdx.files.internal(Constants.ATLAS_PATH));
        TextureRegion[] runningFrames = new TextureRegion[Constants.MOVING_REGION_NAMES.length];

        for (int i = 0; i < Constants.MOVING_REGION_NAMES.length; i++)
        {

            String path = Constants.MOVING_REGION_NAMES[i];
            runningFrames[i] = textureAtlas.findRegion(path);
            if (horizontalMovingDirection == MovementDirection.Right)
            {
                runningFrames[i].flip(true, false);
            }
        }
    }
//code to draw and animate in a straight line by overriding the draw and act methods.
}

```

Am I doing something wrong here? Why am I not getting the touch in the actor?

# Answer
I figured out the solution. The problem was that `Listeners` would work only after we set a bound to our `Actor`. I hadn't set any bounds, so it was not taking the touches. Now I set the bounds in the `draw()` method(so that it will get updated each time the actor moves) and it is working like a charm.

```
@Override
public void draw(Batch batch, float parentAlpha)
{
    super.draw(batch, parentAlpha);
    setBounds(currentAnimationBounds.x, currentAnimationBounds.y, currentAnimationBounds.width, currentAnimationBounds.height);
    //Rest of the code
}

```
> 4 votes

---
Tags: android, libgdx, input, touch
---


# Question
Title: Do mods for games like Skyrim look good on a resume?
As a lot of people know, Bethesda just came out with their Creation Kit for developing mods to Skyrim.

I've been developing for a while, I have a couple of games released including one that's doing well in the App Store. My goal is to get a job at a studio like Bethesda, Bioware, or Valve. Right now my work shows I can do some of the harder parts of a game engine, but I have nothing directly in the RPG field which is where I want to be.

Would building a mod for Skyrim help my resume enough to justify the time it takes to do it, or would my time be better spent making another non-RPG game from scratch? This mod would be a full side game completely separate from the game's world. My usual thought of mods is they are for fun and don't really help the resume as much as more raw projects, but with how open the creation kit is, it seems you can really go a long way in development.

Before I get any *duh* or *subject to opinion* answers, this question is about my lack of knowledge on the perception of notable mods to games. My assumption is there is a general consensus to if mods can be impressive and help a resume which already has some (decent) content for the level of job it's after. Also, I have no intention of starting an RPG from scratch if anyone is crazy enough to offer that as a solution, this is for my resume only.

Lets assume the mod I would make would be impressive for a mod. If that was up for debate, the answer to this might come out a bit gray.

# Answer
> 15 votes
Bethesda specifically asks for experience with their development tools when applying to a position with them. So, if you want a job at Bethesda, successfully completing a mod project is a great step to take to put your foot in the door.

If you don't want to work for Bethesda, a successful mod project still goes a long way to help you. Just think of how popular Skyrim is, if your mod works out that's considerably more eyes on it than many games before it (especially with how Bethesda is promoting modding). If it's awesome, you'll get not only a lot of fans for your own personal work, but even possibly studios looking to bring you in. (To feed off your popularity or just for your talent)

# Answer
> 5 votes
According to this interview http://www.youtube.com/watch?v=h5ebFjlLptE , doing a mod for Skyrim will help if you want to be hired at Bethesda. For Valve or Bioware, I don't know, although it probably won't hurt.

Also, it depends on the kind of development you do. If you are a core engine programmer, I doubt a mod will show your abilities.

# Answer
> 1 votes
If you can make a proper mod with a full fleshed out idea, it certainty would help. And, it shows some experience in the rpg genre. However, i would continue to work on your own games.

# Answer
> 0 votes
If you can write game engines, Bethesda's modding kits should be cake. That's where I started learning to program and it ended up opening up a whole new way of thinking and world to me. I progressed into Unity, started learning C#, took up Visual Studio and did a bunch of standard object oriented programming, moved into C++ for a brief while, then back to C# and now I'm learning WPF...

Bethesda likes experience in their creation kit/GECK - it's extremely easy to use and script and pretty fun if you like these games - if you want to apply at Bethesda, I would definitely recommend modding - otherwise I'm not sure it would be particularly beneficial anywhere else though having it in your portfolio would help most with showing your view of story flow, level design, and content creativity more than helping bolstering your credit as a quality programmer and/or graphic designer.

Unfortunately, we live in a market that isn't very "quality writing and storytelling" driven otherwise New Vegas would be considered the Magnum Opus of games designed in Bethesda's engine, so I'm not sure most studios would be looking at that first and foremost. Skyrim had some moments I almost cringed from how bad the writing was... Some of it was ok..

# Answer
> 0 votes
As a guy that's been modding many games for the past... 14-18 years, I'll just chip in.

* only a FEW modders ever got paid for their work or somehow got money out of it. IceFrog may or may not be one of them, and I really doubt he got any money out of Valve for DotA2 (if I could actually remember my mail/password for ICQ, i would've asked him now.)
* CounterStrike devs may have got paid, but I doubt that too. UT2k14 in UnrealEngine4 certainly do *not* get paid to make Epic a new game, they just get some developer help from time to time.
* The man that made the skyrim expansion mod, Falskaar did *not* get hired, even though one of the reasons he did everything he featured in the mod *was* to get hired. Thats why he did the voiceacting.
* A few more examples of people that contributed greatly but never got anything out of it: for Warcraft3:TFT Vexorian made a pretty hefty spell system used by all (not all, a big portion of them) maps that feature custom spells that don't behave like original ones. Actually i'll just stop here.

A big thing to note here is - "a mod is *not* protected and copyrighted intellectual property, and anyone is free to remake your mod with different people", which is why I doubt both the DotA author and CS authors got paid for their work.

One of the best ways to actually monetize on your modding work, is to hack the game at some point, and/or ask for donations to keep the servers running after the original multiplayer servers get shutdown.

Just writing this post overflooded me with alot of bad and some really bad memories :/

---
Tags: modding
---