title: Box2d jetski on water

text:
# Question
Title: Box2d jetski on water
At the moment I am trying to code a 2d game in java, where a jetski is riding on water. If you press on the screen the jetski should dive down and jump back up on release. How do I have to do this in Box2d? My idea was to put a rectangular body as the water and an other one as the jetski. Since I am new to box2d I don't really know how I should bring this into code. I hope one of you can help.

# Answer
I spent a good while looking how to implement Box2D in Android studio, so for anyone else in the same boat, or just looking to implement Box2D - here goes.

For implementing Box2D into your java code/framework, Box2D is tuned to work with numbers between 0.1 and 10 (it works in meters), quoting from the Box2D manual:

http://box2d.org/manual.pdf

> Box2D is tuned for MKS units. Keep the size of moving objects roughly between 0.1 and 10 meters. You'll need to use some scaling system when you render your environment and actors. The Box2D testbed does this by using an OpenGL viewport transform. DO NOT USE PIXELS.

I have no experience in libgdx, but I believe Box2D coordinate conversions and implementations can be general/universal (I have managed to implement Box2D in C++ and Java using the same ideas).

In the implementations that I do, there will usually be a standard base gameobject/sprite class, and in this class you could have the conversion variables and functions to convert from your local framework coordinates, to Box2D coordinates:

I am assuming you have the Box2D world all set up!

```
public class GameObject extends Sprite
{
    protected static float box2DFrameworkScale = 100.0f;    // How much you want to scale down from FRAMEWORK coordinates to BOX2D coordinates.
    protected static float box2DFrameworkOffsetX = 0.0f;    // How much of an offset there will be to map your Jetski sprite, to the body created in Box2D.
    protected static float box2DFrameworkOffsetY = 0.0f;    // Same as above for the y coordinate.
    protected static float box2DSizeOffset = 0.75f;         // How much does the size of the Box2D body need to be scaled down from the framework width and height in order for collisions to "look"/"be" correct; this value tends to work for me.

    //
    // Your GameObject class functions...
    //

    // Here are the functions to convert from your framework coordinates, to Box2D coordinates and vice versa.
    // You will need access to screen width and height if possible!

    // GETTERS.
    // Getting FRAMEWORK COORDINATES.
    // Convert Box2D coordinates into local framework coordinates.
    public float getFrameworkXPosition(float box2DX)   { return ((box2DX * box2DFrameworkScale) + box2DFrameworkOffsetX); }                   // Getting your local framework x coordinate FROM Box2D x coordinate.
    public float getFrameworkYPosition(float box2DY)   { return (screenHeight - (box2DY * box2DFrameworkScale + box2DFrameworkOffsetY)); }    // Getting your local framework y coordinate FROM Box2D y coordinate.
    public float getFrameworkSize(float dimension)     { return (dimension * box2DFrameworkScale); }                                          // Getting your local framework width/height FROM Box2D width/height.

    // Getting BOX2D COORDINATES.
    // Convert local framework coordinates into Box2D coordinates.
    public float getBox2DXPosition(float frameworkX)   { return ((frameworkX - box2DFrameworkOffsetX) / box2DFrameworkScale); }                 // Getting the Box2D x coordinate FROM your framework x coordinate.
    public float getBox2DYPosition(float frameworkY)   { return ((frameworkY - screenHeight + box2DFrameworkOffsetY) / -box2DFrameworkScale); } // Getting the Box2D y coordinate FROM your framework y coordinate.
    public float getBox2DSize(float dimension)         { return (dimension / box2DFrameworkScale); }                                            // Getting the Box2D width/height FROM your framework width/height.
}

```

With these conversions you can then go and implement a Dynamic Body class, I used an outdated version of Box2D for my android project, but it should provide you with the basic understanding of implementing the conversion functions above!

Your Jetski will most likely be a dynamic body of sorts, you can find out how to create on in the manual I linked to you above, here is a basic implementation (angles aren't considered, feel free to look into that, bodyDef.angle and fixedRotation etc. that kind of thing - if it is a later version):

```
public class DynamicBody extends GameObject
{
    // Creating the dynamic body.
    public void init(World world, Vector2 positions, Vector2 dimensions)
    {
        // Initialising the game object here.
        init(positions, dimensions, angle);

        // Setting up the body definition.
        BodyDef bodyDef = new BodyDef();
        bodyDef.position.set(new Vec2(getBox2DXPosition(getSpriteLeft()), getBox2DYPosition(getSpriteTop())));    // Use conversion functions to place local framework coordinates into Box2D coordinates.
        body = new Body(bodyDef, world);
        body = world.createBody(bodyDef);
        body.setXForm(new Vec2(getBox2DXPosition(getSpriteLeft()), getBox2DYPosition(getSpriteTop())), 0.0f);

        // Here is where we create the actual box/rectangle in Box2D.
        PolygonDef box = new PolygonDef();
        box.setAsBox(getBox2DSize(dimensions.getX()) * box2DSizeOffset, getBox2DSize(dimensions.getY()) * box2DSizeOffset);    // This function MIGHT be different in newer versions of the Box2D library. Convert from your framework width and height into the Box2D width and height.
        box.density = 1.0f;    // Change these around to get your desired effect on the dynamic body properties and physics.
        box.friction = 0.5f;
        box.restitution = 0.65f;

        body.createShape(box);
        body.setMassFromShapes();

        // Setting the "connection" of data between sprites and the body.
        body.setUserData(this);
    }

    // You will want the body and sprite to be at the same place at the same time.
    // Call this every frame to keep the two aligned!
    public void update()
    {
        // New coordinates for the sprite x and y position given by the Box2D body position.
        float newX = body.getPosition().x;
        float newY = body.getPosition().y;

        // Convert the new coordinates into your local framework coordinates to correctly place your sprite on the screen in line with your Box2D body.
        setPosition(getFrameworkXPosition(newX), getFrameworkYPosition(newY));
    }
}

```

For the water you may want to create a static body class, similar to the dynamic body class above, hope this has helped you in some way! If not, sorry for the misunderstanding/unhelpful answer.

As for making the jetski go up/down, you can apply impulses to bodies in Box2D:

```
// Change body.getWorldCenter() for the front end of the jetski body.
// Two vector 2's, the impulse force AND the point where the impulse will be applied.
// This will apply an impulse of X/Y to the centre of the body.
body.applyImpulse(new Vec2(impulseX, impulseY), body.getWorldCenter());

```
> 2 votes

---
Tags: java, android, physics, libgdx, box2d
---


# Question
Title: MonoGame - Left/Right Sided Collision Not Working
I'm working on a platformer as part of my course, the problem I have come across is Left/Right sided collision is not working very well. I already have bottom & top collision working. Here is an example of the problem in action:

As you can see pretty much all the time I'm slowing down, I know this issue but haven't found a work around code solution yet. The main problem I'm having as you can see is my player being able to slide almost into the middle of the block if he's coming down and moves into the block.

The slow down problem is due to my left/right collision code, I just haven't found a viable solution yet for sided collision.

**Collision Code:**

```
        foreach (SkyTile block in PlatformBlocks)
        {

            IntersectRectangle = block.GetRect();
            GetRect().Intersects(ref IntersectRectangle, out IntersectResult);
            if (GetRect().Intersects(block.GetRect()))
            {
                if (IntersectResult && (IntersectRectangle.Bottom > GetRect().Bottom))
                {
                    isPlatformColliding = true;
                }

                if (IntersectResult && (IntersectRectangle.Top < GetRect().Top))
                {
                    isPlatformBottomColliding = true;
                }

                if (IntersectResult && (IntersectRectangle.Left > GetRect().Left))
                {
                    isPlatformLeftColliding = true;
                }

                if (IntersectResult && (IntersectRectangle.Right < GetRect().Right))
                {
                    isPlatformRightColliding = true;
                }
                break;
            }
        }

        if (isPlatformColliding)
        {
            velocity.Y = 0;
        }

        if (isPlatformBottomColliding && !isPlatformColliding)
        {
            velocity.Y = 20;
        }

        if (isPlatformLeftColliding)
        {
            velocity.X = 0;
        }

        if (isPlatformRightColliding)
        {
            velocity.X = -0;
        }

```

# Answer
Could you post your update loop? I don't immediately see something wrong with the code you posted which causes this behavior so it is possible the problem is somewhere else in your code.

Usually you would do something like this when programming a simple physics engine in your game: 1. Update positions of the objects based on their velocity 2. Check for collision and resolve these

If I understand your code correctly you do not resolve collisions but rather update the velocity to prevent the player from moving through a rectangle. There are a couple of problems with this approach:

1. The player will still be colliding with the rectangle which you can argue is an undesired state.
2. If you update the position of the player *before* checking for collisions the player will move through the object (I suspect this could be the problem you are experiencing).
> 2 votes

---
Tags: xna, collision-detection, monogame
---


title: Varying framerate (FPS)

text:
# Question
Title: Varying framerate (FPS)
In my game-loop, I am using fixed time step for physics and interpolation for rendering as suggested on Gaffer on Games | Fix Your Timestep!

However, when the framerate is varying between 30-60fps during the game, the game looks jumpy. For example, balls suddenly look accelerated when the frame rate increases from 35 to 45 suddenly.

Is there a way to make the game look smooth while framerate is varying?

Here is my game loop:

```
protected void update(float deltaTime) {
    //do some pre stuff

    deltaTimeAccumulator +=deltaTime; //deltaTimeAccumulator is a class-member holding the accumulated frame time
    while(deltaTimeAccumulator>FIXED_TIME_STEP) {
        world.step(FIXED_TIME_STEP, 6, 2);  //perform physics simulation
        deltaTimeAccumulator-=FIXED_TIME_STEP;
    }
    // world.step(deltaTime, 6, 2);

    destroyBodiesScheduledForRemoval();
    render(deltaTimeAccumulator /FIXED_TIME_STEP); //interpolate according to the remaining time
}

```

Here is the part related to the interpolation (related inner works of render() method) : this.prevPosition = this.position; //get previously simulated position

```
    this.position = body.getPosition(); //get currently simulated position

    //interpolate
    Vector2 renderedPosition = new Vector2();
    if (prevPosition != null) {//&& !isFloatApproximatelyEquals(this.prevPosition.x, this.position.x) && !isFloatApproximatelyEquals(this.prevPosition.y, this.position.y)) {
        renderedPosition.x = this.position.x * interpolationAlpha + this.prevPosition.x * (1 - interpolationAlpha);
        renderedPosition.y = this.position.y * interpolationAlpha + this.prevPosition.y * (1 - interpolationAlpha);
    } else {
        renderedPosition = position;
    }

    //Draw the object at renderedPosition

```

# Answer
> 6 votes
## Temporal Aliasing

As Andon M. Coleman is stating out in the comments what you describe is called **temporal aliasing**.

Temporal aliasing is due to a too low sampling rate of the scene compared to the the transformation speed of one or more objects within the same scene. In other words if an Object of the scene is more often updated (transformation speed to high) compared to the to the number of frames per second (sampling rate to low) *temporal aliasing artefacts* are appearing and the Object/s seem/s to jump around.

---

To avoid **temporal aliasing** you have to increase the sampling rate aka your FPS without increasing the transformation speed( your number of update calls ).

One way of doing this, see this example here: Vittoria Romeo's Tutorials

```
            while(running)
            {
                auto timePoint1(chrono::high_resolution_clock::now());

                window.clear(Color::Black);

                inputPhase();
                updatePhase();
                drawPhase();

                auto timePoint2(chrono::high_resolution_clock::now());
                auto elapsedTime(timePoint2 - timePoint1);
                FrameTime ft{chrono::duration_cast<
                    chrono::duration<float, milli>>(elapsedTime).count()};

                lastFt = ft;

                auto ftSeconds(ft / 1000.f);
                auto fps(1.f / ftSeconds);
            }

```

The key is now to take a close look into the updatePhase:

```
void updatePhase()
        {

        // If `currentSlice` is greater or equal than `ftSlice`,
        // we update our game logic and decrease `currentSlice` by
        // `ftSlice` until `currentSlice` becomes less than `ftSlice`.
        // Basically, if `currentSlice` is three times as big as `ftSlice`,
        // we update our game logic three times.

            currentSlice += lastFt;
            for(; currentSlice >= ftSlice; currentSlice -= ftSlice)
            {
                //logic
                someupdatefunction(FixedtimeStep)
            }
        }

```

What we do is to divide our time in different slices:

```
 |............|............|............|..........
 |            |            |            |
 \-> slice    \-> slice    \-> slice    \-> slice

```

And, every frame, we will call `update(mFT)` "n" times, where "n" is the number of slices we passed through with our last frametime. Example:

```
       v-----+frametime---+--v
 |............|............|............|..........
 |            |            |            |
 \-> slice    \-> slice    \-> slice    \-> slice

```

In the above example, in the time it took to process a single frame, we went over two different slices. We will then call `update(mFT)` twice in the same frame.

No matter how big or how small or last `frametime` was, we will always call `update(mFT)` in fixed intervals (our slices). If the game goes extremely fast, we will completely skip the updating phase during certain frames. If the game goes extremely slow, we will probably need to update multiple times during a single frame. This method allows fine control over our movement precision, and guarantees the same behavior with any FPS.

This explanation is from Vittorio Romeo. You will find a complete tutorial how to implement this there via source code or Video. Vittoria Romeo's Tutorial

---
Tags: game-loop
---


# Question
Title: Why does the Texture placement of my CCSprite slightly shift when changing it's location?
So I've been seeing this issue for a while now. When using a delta method to change the location of a CCSprite, the placement of texture of my sprite slightly moves into the direction where I'm headed, while the physicsbody stays the same. This is really noticeable, since I'm using CCActionFollow to center this sprite in the view at all times. The code is displayed below. Is this normal behaviour, or am I perhaps overlooking something really obvious? Thanks!

```
- (void) move:(CCTime)delta toPosition:(CGPoint)point
{
OverworldScene * parentScene = (OverworldScene *)self.parent.parent.parent; //Go over physics node
OverworldLayer * parentLayer = (OverworldLayer *)self.parent.parent; //Go over physics node

//meewind of tegenwind?
float angleWind = parentScene.compass.rotation;
float angleShip = self.rotation;
float difference;
float windFactor;

if (angleWind > angleShip)
{difference = angleWind - angleShip;}
else{difference = angleShip - angleWind;}

if (difference > 180)
{difference = 360 - difference;}

//Incorporate wind power...
if (difference > 90)
{   //Tegenwind
    windFactor = 1-((((90- (180 - difference))/90))*(parentLayer.windPower/12));
}
else
{   //Meewind
    windFactor = 1+((((90-difference)/90))*(parentLayer.windPower/12));
}

if (windFactor < 0.4){windFactor = 0.4;}

//point is the current position of the user's sprite
//a, b and c are the right triangle sides lengths formed by the caser sprite and the user's sprite positions
float a = ABS(self.position.y - point.y);
float b = ABS(self.position.x - point.x);
float c = sqrt(pow(a, 2) + pow(b, 2));

//angle of the hypotenuse
float beta_rad = asin(b/c);

//velocity in pixels per second (used to be 60)
c = 60 * self.velocityFactor * windFactor;    //Now accounts for windfactor!
parentScene.speedLabel.string = [NSString stringWithFormat:@"Speed %.1f knots", self.velocityFactor * (60*windFactor)/8];

//x-axis velocity component
float x = c * sin(beta_rad);
//y-axis velocity component
float y = c * cos(beta_rad);

//adjustments based on position of the this (chaser) sprite and the user's sprite, if chaser is on the right or below the user's sprite it is needed to reverse the velocity vector component x and y
if (self.position.x > point.x) x *= -1;
if (self.position.y > point.y) y *= -1;

//final velocity vector
CGPoint velocityVector = CGPointMake(x, y);
CGPoint newPosition = ccpAdd(self.position, ccpMult(velocityVector, delta));

//NSLog(@"Updating position: %@", NSStringFromCGPoint(newPosition));

//Only update in case new position is in bounds
if (newPosition.x < 0 || newPosition.x > parentLayer.contentSize.width)
{
    newPosition = CGPointMake(self.position.x, newPosition.y);
}

if (newPosition.y < 0 || newPosition.y > parentLayer.contentSize.height)
{
    newPosition = CGPointMake(newPosition.x, self.position.y);
}

self.position = newPosition;

}

```

# Answer
So I figured that setting the location of a node without forces has this effect on the camera. Simply use forces or set the velocity of your node.
> 0 votes

---
Tags: cocos2d-iphone, ccsprite
---


title: accelerometer not working unity

text:
# Question
Title: accelerometer not working unity
why is the cube moving when I use a controller, but not with the accelerometer?

```
void Update () {
    text.text = "X: " + Input.acceleration.x + "; Z: " + Input.acceleration.z;
    //transform.position = new Vector3(10* Input.acceleration.y, 0, 10* Input.acceleration.z);

    transform.Translate(Input.acceleration.x, 0, Input.acceleration.z);

    //transform.position = new Vector3(10* Input.GetAxis("Horizontal"), 0, 10* Input.GetAxis("Vertical"));

    transform.Translate(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
}

```

(I'm on a Xperia Z3 compact by the way)

# Answer
> 1 votes
I guess you might need to apply some speed so that it works on the phone. Might be the Input.acceleration.x value is not high enough on phone, but works on the controller. Also it is advisable to use Time.deltaTime to keep the speed constant on all device, else it will change as per the device processing power.

```
 public float speed = 10.0f;
 void Update ()
 {
        transform.Translate(Input.acceleration.x*speed*Time.deltaTime, 0, Input.acceleration.z*speed*Time.deltaTime);

 }

```

---
Tags: unity, android
---


title: I cant Attach C# Script to my Player?

text:
# Question
Title: I cant Attach C# Script to my Player?
Every time I try to attach my C# Script to my Player, it gives me this error message:

> "Can't add script component 'Player' because the script class cannot be found. Make sure that there are no compile errors and that the file name and class name match."

Here is my script, just for good measures

```
using UnityEngine;

using System.Collections;

public class Player : MonoBehaviour
{
    public float speed = 50f;
    public float jumpPower = 150f;
    public bool grounded;
    private Rigidbody2D rb2d;
    // Use this for initialization
    void Start ()
    {
        rb2d = gameObject.GetComponent<Rigidbody2D>();
    }

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

    }

    void FixedUpdate()
    {
        float h = Input.GetAxis ("Horizontal");
        rb2d.AddForce ((Vector2.right) * speed * h);
    }
}

```

I have no Idea how to fix that...

Anyway, I am using Unity Engine 5

EDIT: I HAVE FOUND THE ERROR. (I forgot to save the script XD)

# Answer
> 3 votes
The message basically says it all. Either the name of your class which in this case is "Player" is not exactly the same as the c# script file name. Check if the c# script is called "Player.cs". If not rename it to that. (Case sensitive!) If that wasn't the case or it didn't solve the problem you should check if you have any compiler errors and fix those first.

---
Tags: unity
---


# Question
Title: What sprite Resolution did 16-Bit Games use?
I am making a new 16-Bit Styled game and I was wondering what the most common sprite resolution is for 16-Bit Systems.

# Answer
The sprite design of that era was heavily influenced by the technical capabilities of that time.

Both the Sega Genesis and the SNES had specialized hardware for drawing sprites. But in both cases that hardware only allowed sprites with width and height which were multiples of 8. Both systems also had a limit on the number of sprites it could draw every frame and also a limit per scanline. But video memory was very limited, so it was important to not use more 8x8 blocks than necessary.

So spritesets of that era usually had grid sizes which were multiples of 8.

When designing an animated character, it was important to not already fill the whole available size in the base frame. When you add more animation phases, you will usually need additional space, and it would be quite wasteful to use a larger spritesize for some frames just for a few pixels. Sonic the Hedgehog, for example, used a 32x48 sprite size, but the base frame is only 29x39. Still there are animation phases which reach the whole width of 32 or height of 48.

Another limitation of that time was the available color palettes. The Genesis had 512 colors, but only allowed up to 16 different colors per sprite and only 4 such 16 color palettes on the screen at the same time. The SNES was more flexible in this regard: it had a 32,768 color palette (RGB555) with up to 256 simultaneously on one screen.
> 8 votes

---
Tags: sprites
---


# Question
Title: How do engines that can be scripted with a different language than the engine code work?
There are some engines that can be scripted with different languages than that of which the engine, itself, is written with. How does that work?

# Answer
> 6 votes
There are many ways to implementing scripting in game engines, or applications in general.

Most conventional scripting languages are just like any other library. Just as libpng interprets a particular data format and provides APIs to read the results of processing that format, a scripting language library like Lua read in a particular format (Lua source code) and provides API for reading the results of interpreting that data. In general, compilers and interpreters are just like any other algorithm: they process input data and produce output data.

Scripting language libraries provide a means of binding functions from the host language into the script language and provide a means of calling a script function from the native code. There are myriad ways for this binding to work. Some scripting languages use a "foreign function interface" (FFI) that can allow the script language to directly call native functions by mapping integers and strings and such between the script language's representation and the native representations. Other language provide specialized abstractions, meaning that only particular native functions can be called from the scripts, requiring that wrapping binder functions be written. Other script languages (or helper libraries) can auto-generate those binder functions.

Examples:

**FFI**

LuaJIT has an FFI library that allows you to write this:

```
ffi.cdef[[int printf(const char *fmt, ...);]]
ffi.C.printf("Hello %s!", "world")

```

That allows the Lua script code to call any exported C function it wants.

**Explicit Binding**

With regular Lua, only C functions of the exact interface `int(Lua_State* state)` can be bound to the interpreter. In order to retrieve arguments, the programmer must use special functions provided by Lua. Likewise, to return values, the programmer must call particular functions. To bind a non-variadic `printf` function, the programmer would have to write something like:

int printf(Lua\_State\* state) { puts(lua\_tostring(state, -1)); return 0; }

If there is a function such as `int LoadLevel(char const* name)` in the engine, the programmer would then have to write a wrapper `int script_LoadLevel(Lua_state*)` function that reads the Lua parameters and transfer them to the native C function.

**Automatic Wrappers**

In these APIs - which can be wrappers or helpers for libraries not intended for them - the user specifies the functions that should be exported to script in the native language and then a special tool or support code generates the binding functions. Languages like C don't make this innately possible, but you can build binding helpers in C++ or D or the like easily enough.

Tools like SWIG can read in C code and then generate binding code.

Since many game engines already have complex reflection systems to deal with I/O serialization, networking, level editors, or so on, they will reuse these reflection systems to generate script bindings with a library like Lua. A user might write a class like this:

```
class Player {
public:
  int GetHitPoints() const;
  void SetHitPoints(int hp);
};

```

and then bind this with reflection like so:

```
BEGIN_REFLECT(Player)
  PROPERTY("hp", GetHitPoints, SetHitPoints);
END_REFLECT(Player)

```

and then the scripting system might have some code like this:

```
void Reflect(ReflectedType& type)
{
  auto scriptType = CreateScriptType(type.GetName());
  for (auto& property : type.GetProperties())
    AddGetterSetter(
        scriptType,
        property.GetName(),
        property.GetGetter(),
        property.GetSetter()
    );
}

```

**Summary**

Game engines pick a scripting language and some library that implements that language. This in turn determines how the scripts are bound to the language.

Then the game engine decides what it wants to expose to the language and uses the appropriate method to bind the engine's functionality to the language.

There's many different types of scripting languages, some languages have multiple libraries that are bound in different ways, and engines can decide to expose different functionality in different ways (just like some game engines must be purely procedural/imperative and some might be object-oriented and some are functional and so on, likewise two different engines using Lua can decide to expose functionality in a procedural style or an OO style or whatever the way).

---
Tags: scripting
---


title: Libgdx coordinate system

text:
# Question
Title: Libgdx coordinate system
I just started with libgdx and I'm still figuring out how the coordinate system work.The code below would draw the image at \[0,0\] without the Orthographic camera

What I can't understand is why the code doesn't draw the image when I uncomment the camera and viewport. I thought the camera is at point \[0,0\] by default. But I'm not sure why I can't see the image.

\[Edit\] Reading the question I posted this morning, I guess what I want to ask is how camera and viewport affect the coorindates that is passed to the SpriteBatch.

**Working code**

```
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.badlogic.gdx.utils.viewport.Viewport;

public class SpriteBatchSample extends GdxSample {
    private static final Color BACKGROUND_COLOR = new Color(0.39f, 0.58f, 0.92f, 1.0f);
    private static final float WORLD_TO_SCREEN = 1f;
    private static final float SCENE_WIDTH = 100f;
    private static final float SCENE_HEIGHT = 100f;

    private OrthographicCamera camera;
    private Viewport viewport;
    private SpriteBatch batch;
    private Texture cavemanTexture;
    private Texture sbTexture;
    private Color oldColor;

    @Override
    public void create() {
        camera = new OrthographicCamera();
        viewport = new FitViewport(SCENE_WIDTH, SCENE_HEIGHT, camera);
        //Gdx.app.log("SpriteBatch",    camera.position.toString());
        batch = new SpriteBatch();
        oldColor = new Color();
        camera.position.set(100/2f, 100/2f,0);
        cavemanTexture = new Texture(Gdx.files.internal("data/sb.png"));
        cavemanTexture.setFilter(TextureFilter.Nearest, TextureFilter.Nearest);
    }

    @Override
    public void dispose() {
        batch.dispose();
        cavemanTexture.dispose();
        sbTexture.dispose();
    }

    @Override
    public void render() {
        Gdx.gl.glClearColor(BACKGROUND_COLOR.r,
                BACKGROUND_COLOR.g,
                BACKGROUND_COLOR.b,
                BACKGROUND_COLOR.a);

        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        //batch.setProjectionMatrix(camera.combined);

        batch.begin();

        int width = cavemanTexture.getWidth();
        int height = cavemanTexture.getHeight();
        float originX = width * 0.5f;
        float originY = height * 0.5f;
        Gdx.app.log("SpriteBatchSample", "width " + width + "\n"
            + "height: " + height + "\n"
            + "originX" + originX + "\n"
        );

        // Draw
        batch.draw(cavemanTexture,
                0, 0,                       // x, y
                originX, originY,                           // originX, originY
                cavemanTexture.getWidth(), cavemanTexture.getHeight(),// width, height
                WORLD_TO_SCREEN, WORLD_TO_SCREEN,           // scaleX, scaleY
                0.0f,                                       // rotation
                0, 0,                                       // srcX, srcY
                cavemanTexture.getWidth(),cavemanTexture.getHeight(),   // srcWidth, srcHeight
                false, false);                              // flipX, flipY

        batch.end();
    }

    @Override
    public void resize(int width, int height) {
        //viewport.update(width, height, false);
    }
}

```

***Not Working***

```
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.badlogic.gdx.utils.viewport.Viewport;

public class SpriteBatchSample extends GdxSample {
    private static final Color BACKGROUND_COLOR = new Color(0.39f, 0.58f, 0.92f, 1.0f);
    private static final float WORLD_TO_SCREEN = 1f;
    private static final float SCENE_WIDTH = 100f;
    private static final float SCENE_HEIGHT = 100f;

    private OrthographicCamera camera;
    private Viewport viewport;
    private SpriteBatch batch;
    private Texture cavemanTexture;
    private Texture sbTexture;
    private Color oldColor;

    @Override
    public void create() {
        camera = new OrthographicCamera();
        viewport = new FitViewport(SCENE_WIDTH, SCENE_HEIGHT, camera);
        //Gdx.app.log("SpriteBatch",    camera.position.toString());
        batch = new SpriteBatch();
        oldColor = new Color();
        camera.position.set(100/2f, 100/2f,0);
        cavemanTexture = new Texture(Gdx.files.internal("data/sb.png"));
        cavemanTexture.setFilter(TextureFilter.Nearest, TextureFilter.Nearest);
    }

    @Override
    public void dispose() {
        batch.dispose();
        cavemanTexture.dispose();
        sbTexture.dispose();
    }

    @Override
    public void render() {
        Gdx.gl.glClearColor(BACKGROUND_COLOR.r,
                BACKGROUND_COLOR.g,
                BACKGROUND_COLOR.b,
                BACKGROUND_COLOR.a);

        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        batch.setProjectionMatrix(camera.combined);

        batch.begin();

        int width = cavemanTexture.getWidth();
        int height = cavemanTexture.getHeight();
        float originX = width * 0.5f;
        float originY = height * 0.5f;
        Gdx.app.log("SpriteBatchSample", "width " + width + "\n"
            + "height: " + height + "\n"
            + "originX" + originX + "\n"
        );

        // Draw
        batch.draw(cavemanTexture,
                0, 0,                       // x, y
                originX, originY,                           // originX, originY
                cavemanTexture.getWidth(), cavemanTexture.getHeight(),// width, height
                WORLD_TO_SCREEN, WORLD_TO_SCREEN,           // scaleX, scaleY
                0.0f,                                       // rotation
                0, 0,                                       // srcX, srcY
                cavemanTexture.getWidth(),cavemanTexture.getHeight(),   // srcWidth, srcHeight
                false, false);                              // flipX, flipY

        batch.end();
    }

    @Override
    public void resize(int width, int height) {
        viewport.update(width, height, false);
    }
}

```

# Answer
> 0 votes
Because by default Camera sees your game screen from top, having it's 0,0 fixed at top left corner.

On the other hand, things you draw in render method, have 0,0 fixed at bottom left corner.

To combine your game screen's coordinate with camera's coordinate, you use,

```
batch.setProjectionMatrix(camera.combined);

```

Read this article, written by libGDX creators (Mario), you would understand, how Camera actually project your images.

http://www.badlogicgames.com/wordpress/?p=1550

# Answer
> 0 votes
Adding an answer to my question above. what happened was I was thinking in exact pixel coordinates. When I should have thought of world units when using viewports

yes thecamera is centered at (0, 0) by default but the world width and height was only 100. There is a transparent space at the bottom left of my image. That is why even though it is also at (0,0) , I still can't see the image.

This video tutorial helped me a lot https://www.youtube.com/watch?v=Ml-XXQaN0hc As well as this forum link http://www.badlogicgames.com/forum/viewtopic.php?t=19640&p=82259

---
Tags: java, libgdx
---


# Question
Title: Marketing a browser game with a specific audience
My issue is that I have extensively developed an online browser game, but mainly the marketing and independent developer guides tailor to action packed executable games. My game also tailors to a specific audience that is not typically on the indie gaming promotional websites. Namely those interested in Politics, Economy, Law, and/or Sociology.

(My first issue) I wanted to know if there are any suggestions, ideas, or references to any resources that may bring marketing value to my gaming community pre and post-launch? I have began development on my beta campaign already to include some crowd funding websites (mostly for promotion), a press kit, advertisements, and the like. However I would greatly appreciate more resources for the development and launch, namely for the target audience.

(My second issue) Many of the marketing strategies for games depend on a video, game photos, etc. While I can take photos of the screen, there are not too many things I can do for a video except add some stock footage and dress it up by explaining game mechanics and showing some photos of the game. Would that contribute to the game or is it just a waste of time? (Feel free to suggest any ideas for this as well if you are willing).

Thank you for your assistance!

# Answer
You have a very specific audience? That's great, because it means that your advertisement is easy to target.

* Go to where your target demographic is. Find out what communication channels they use, and pitch your game there. But tread lightly: Communities are allergic to people who are obviously only there to promote a product, so make sure your participation is constructive and in accordance with the written and unwritten rules of the community. A good method is to not ask them to buy, but rather ask them for feedback how well your game captures their area of interest and advice how to make it better. Your first goal should not be to get people to want your product, but just to talk about your product. When people talk about it, those who want it will appear on their own.
* Contact any news media commonly consumed by your target demographic, even when not game-specific. When your game is very unique and relevant for the demographic, its existence alone might make it newsworthy, even for media which usually does not report about games. Contacting smaller blogs and websites likely has a better chance of success, but you have nothing to lose by also writing to the big names.
* When you are willing to invest some money into advertisement, most web advertisement services allow you to pick the interests of the people you want to see your ads.
> 2 votes

---
Tags: graphics, browser-based-games, game-industry, marketing, trailer
---


# Question
Title: Unity a ball bounce inside a sphere sometime will penetrate and drop outside
i'have made a ball within a sphere (which imported from blender, with mesh collider), see the pic

after the scene started, the ball bounce inside around 5 seconds, and then the ball will penetrate (see the arrow) the sphere and drop out of sphere, anyone knows the reasons?

# Answer
> 1 votes
The physics engine is doing its updates every so often, tick-wise. that means if the ball is too fast it passes through the object it should collide with. I dont know how far you can modify the physics engine, but saving the last calculated position in addition to the actual position and then checking if an object is in beetween those positions should fix it.

---
Tags: unity
---


# Question
Title: Monogame/XNA Making animations play once per click
I'm currently making a #gbjam entry and everything has been going smoothly up to this point.

My issue being that I've implemented a shooting mechanic and along with it an animation to play as a shot is fired, however I'm struggling to make it so that the animation plays properly each click of the mouse. I only ever see sporadic flickers with no real pattern to them. I'm using an animation class and for anything else it's been working fine.

Here's my animation's Draw() method:

```
public void Draw(SpriteBatch sB, GameTime gT, Vector2 pos)
    {
        time += (float)gT.ElapsedGameTime.TotalSeconds;

        while (time > frameTime)
        {
            frameIndex++;
            time = 0f;
        }

        if (frameIndex >= totalFrames)
        {
            frameIndex = 0;
        }

        Rectangle source = new Rectangle(frameIndex * frameWidth, 0, frameWidth, frameHeight);

        sB.Draw(spriteSheet, pos, source, Color.White, 0.0f, origin, 1.0f, SpriteEffects.None, 0.0f);
    }

```

For reference the animation spritesheet is 20 frames long, each 128px by 128px.

Here is the Update() and Draw() calls that are use in handling shooting and the shooting animation:

```
        #region Shooting
        if (mS.LeftButton == ButtonState.Pressed && mSP.LeftButton == ButtonState.Released)
        {
            if (bCount > 0)
            {
                shooting = true;
                bCount--;
                Debug.WriteLine("Bang!" + " Rounds Left: " + bCount);
            }
            else
            {
                shooting = false;
                Debug.WriteLine("OUT OF AMMO");
            }
        }
        else
        {
            shooting = false;
        }

        if (mS.RightButton == ButtonState.Pressed && bCount == 0)
        {
            shooting = false;
            bCount = 6;
            Debug.WriteLine("RELOAD");
        }
        #endregion
        mSP = mS; //mSP being the previous mouse state and mS being the current
    }

    public void Draw(SpriteBatch sB, GameTime gT, Camera cam)
    {
        if (shooting)
        {
           revolverShoot.Draw(sB, gT, fpsPos);
        }
        else
        {
            revolverIdle.Draw(sB, gT, fpsPos);
        }
    }

```

If anyone could offer any ideas as to 'force' the game to complete the animation first before continuing I would be really greatful.

# Answer
> 1 votes
> If anyone could offer any ideas as to 'force' the game to complete the animation first before continuing I would be really greatful.

It looks like you haven't implemented any way to tell if the animation is complete.

You are using a `shooting` flag that appears to be a bit confused about it's purpose. The `shooting` flag gets set when the user clicks the left button and unset:

* *between* clicks
* when the player runs out of ammo
* when the player reloads

This logic seems very odd. I think the first thing you need to do is define the purpose of the `shooting` flag. To me, it should mean this:

**The `shooting` flag is `true` when the animation is playing and `false` when the animation is stopped.**

With that logic in mind, I think you need to refactor the code to meet those requirements.

In other words, the `shooting` flag should be set when the player clicks the left button and unset when `frameIndex >= totalFrames`. You'll probably also want to block player input while the animation is playing, or perhaps queue the next action while waiting for the animation to complete. This stuff can take some tweaking to feel nice.

Since this is going to require a re-think about the design of the code I'm not going to provide a full code sample. Hopefully this will be enough to get you going again though.

Good luck with the #gbjam

---
Tags: xna, c#, animation, monogame, spritesheet
---


# Question
Title: Stencil buffer VS conditional discard in fragment shader
I have a continuous height-mapped mesh to represent landscape. I also have 1 to let's say 10 wells on this landscape represented by additional models. What I want to achieve is to create an illusion of an actual hole in landscape at the place where the well sits.

I see the solution in two ways:

1. Draw holes to stencil buffer an then use it in fragment shader to discard landscape fragments.
2. Send an array of uniforms (vec2) and then conditionally discard fragments if they are near those hole-points.

The question is **what way should I prefer if I'm good with rectangular holes and want to get best performance?**

# Answer
Modern hardware performs early stencil testing using the same sort of tile-based approach as early depth. It can reject large groups of fragments before they make it to the fragment shader stage. That means shader units will not waste time calculating data they are just going to throw out anyway.

You add an extra 8-bits of memory per-pixel (pretty much a non-issue on modern hardware) but you can skip the fragment shader stage completely for any fragment that fails the stencil test. The best solution is one that can broadly reject a lot of work. The more complicated your fragment shader, the more you will benefit from using stencil rejection.

> Draw holes to stencil buffer an then use it in fragment shader to discard landscape fragment

However, this is where you shot yourself in the foot technically speaking. You need *really* modern hardware to sample the stencil buffer from a fragment shader. It has long been a fixed-function test, and for best performance you should keep it that way.

Use the fixed-function test early rather than implementing your own programmable test as part of the shader itself. This is the only way to reap the benefits discussed above. discarding in the fragment shader will produce a lot of needless work and should be avoided whenever a fixed-function test would suffice.
> 3 votes

---
Tags: opengl, glsl, fragment-shader, stencil
---


# Question
Title: What is the difference between “dynamic generation” and “procedural generation”?
When I think of a dynamically generated game, I think of things like Diablo with randomly generated levels. When I think of a procedurally generated game, I think of things like Flappy Bird and other infinite runners.

But both of these just randomize a level. Is it that procedurally generated games are constantly being generated and dynamically generated games are all generated up front? Or are these terms interchangeable?

What is the difference between a *dynamically generated game* and a *procedurally generated game*?

# Answer
> 21 votes
"Procedural" means that some algorithm made the content. This is opposed to content being created manually by a human.

"Dynamic" means that the content changes over time. This is opposed to "static" content that does not change after being created, or only changes in predefined ways e.g. key-framed character animation.

You can also have in-game player-created content. That's a game feature that allows players to alter the levels or game during game play rather than using external tools to mod the game. For the sake of the next few paragraphs, I'm assuming that we're not talking about player-created content.

You can use code to generate something that never changes; such content is static and not dynamic, despite being procedural. **All dynamic content is procedural, but not all procedural content is dynamic.**

You can mix manual, procedural, static, and dynamic content in all kinds of ways, too. For instance, an artist might create a building model manually, use a tool to procedurally generate various texture maps for the model, and then setup data for physics or gameplay systems to dynamically destroy the building and spawn static debris during play.

**Note**: these definitions are *not formal*. You could argue semantics about these words forever. You are likely to run into people with different definitions of these words and neither of us would necessarily be wrong. Even technology jargon is far more fluid than us programmer types tend to prefer. :)

# Answer
> 4 votes
"Dynamic" means

> "(of a process or system) characterized by constant change, activity, or progress."

(says google.)

To distinguish those two terms, I'd go with "dynamic generation" meaning "created just in time, on the fly, while you play"...

And "procedural generation" meaning algorithmically generated, either up front or on-the-fly.

# Answer
> 1 votes
Here's a quick little overview.

> * Dynamic Generation
>
> The word 'dynamic' means changing. The word 'generation' means creation of things therefore 'dynamic generation' is changing generation. Therefore 'dynamic generation' refers to content that is constantly changing.
>
> * Procedural Generation
>
> The word 'procedural' refers to content created by a computer algorithm and not a human. As we established 'generation' means creation so therefore 'procedural generation' refers to content which are generated via a computer algorithm.

---
Tags: procedural-generation, random, terminology
---


title: How to implement angled surface?

text:
# Question
Title: How to implement angled surface?
I'm trying to implement 2D platformer game inspired by N game.
But the problem is I have no idea how to implement something like this:

and

I have two ideas of how this could be implemented, but I don't know if they are somewhere near truth:

1. Pick two nearby pixels of the surface, draw a line between them and then rotate player so his height was perpendicular to that line.
2. Check if the bottom-left pixel is touching surface and bottom right is not, rotate player so bottom-right pixel would touch the surface too.

# Answer
i did something similar a while back, it's not that hard, one very easy and understandable way is :
1- rotate everything! means every line every object, so everything is simply flat!
2- calculate velocity, gravity, friction and ... anything you like ! just the way you always do in a flat and without rotation world
3- rotate everything back the way it was !
there is also using physic libraries which is a bit complicated since you need to study the samples and learn how to use the library !
if this is your first attempt on making a game with motions and ... i suggest you take a look at :
1 - http://www.amazon.com/Foundation-Actionscript-3-0-Animation-Making/dp/1590597915
2- http://www.amazon.com/AdvancED-ActionScript-Animation-Friends-Learning/dp/1430216085/ref=pd\_sim\_14\_2?ie=UTF8&refRID=1Y0G31E4VKEY4FZ43HPM
i found a source code that i wrote a long time ago
it uses the 3 step i mentioned above

```
package
{
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.MouseEvent;
    import flash.geom.Rectangle;

    public class AngleBounce extends Sprite
    {
        private var ball: Ball;
        private var line: Sprite;
        private var gravity: Number = .3;
        private var bounce: Number = -.6;

        public function AngleBounce()
        {
            init();
        }

        private function init():void
        {
            ball = new Ball();
            addChild(ball);
            ball.x = 100;
            ball.y = 100;
            line = new Sprite();
            addChild(line);
            line.graphics.lineStyle(1);
            line.graphics.lineTo(300, 0);
            line.x = 50;
            line.y = 200;
            line.rotation = 30;

            addEventListener(Event.ENTER_FRAME, onEnterFrame);
            addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
            addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
        }

        private function onMouseDown(event:Event):void
        {
            ball.startDrag();
            removeEventListener(Event.ENTER_FRAME, onEnterFrame);
        }

        private function onMouseUp(event:Event):void
        {
            ball.stopDrag();
            ball.vx = 0;
            ball.vy = 0;
            addEventListener(Event.ENTER_FRAME, onEnterFrame);
        }

        private function onEnterFrame(event:Event):void
        {
            line.rotation = (stage.stageWidth/ 2 - mouseX) * .1;
            ball.vy += gravity;
            ball.x += ball.vx;
            ball.y += ball.vy;

            if (ball.x < 0 + ball.width / 2 || ball.x > stage.stageWidth - ball.width / 2)
            {
                ball.vx *= -1;
            }

            if (ball.y < 0 + ball.height / 2 || ball.y > stage.stageHeight - ball.height / 2)
            {
                ball.vy *= -1;
            }

            var bounds:Rectangle = line.getBounds(this);
            if(ball.x > bounds.left && ball.x < bounds.right)
                {
                var angle: Number = line.rotation * Math.PI / 180;
                var sin: Number = Math.sin(angle);
                var cos: Number = Math.cos(angle);

                var x1: Number = ball.x - line.x;
                var y1: Number = ball.y - line.y;
                var vy1: Number = cos * ball.vy - sin * ball.vx;
                var y2: Number = cos * y1 - sin * x1;

                if (y2 > -ball.height / 2 && y2 < vy1)
                {
                    y2 = -ball.height / 2;

                    var x2: Number = cos * x1 + sin * y1;
                    var vx1: Number = cos * ball.vx + sin * ball.vy;

                    vy1 *= bounce;

                    x1 = cos * x2 - sin * y2;
                    y1 = cos * y2 + sin * x2;
                    ball.vx = cos * vx1 - sin * vy1;
                    ball.vy = cos * vy1 + sin * vx1;
                    ball.x = line.x + x1;
                    ball.y = line.y + y1;
                }
            }
        }

    }

}

```
> 1 votes

---
Tags: 2d, collision-detection, physics, rotation
---


# Question
Title: How To Program a fully controllable spring (Damped) motion
i'm working on a project that needs realistic 2D Animation, none linear motion you might say, i have tried many things such as Hermite Curve and a few other motions and in the end Spring Motion.
because my spring is based on a simple distance, velocity, friction base i can not control the time that spring finishes and the number of times it pases through it's target, after some study i found out that i need to program damping motion and i found an article
http://www.ncsu.edu/per/Articles/MarchewkaAbbott&Beichner.pdf
which uses Total energy to solve the problem, but even after reading it many times i couldn't program it !
which is the reason i'm here , please i really need help
**my goals** : programming a fully controllable damping motion that is
**1-** has a progress based on an interval between 0 and 1 (meaning whatever the motion is, you can play it like a movie, you give the percent and it returns the position)
**2-** you can determine the number of times that object passes through the target before it settles down **here is the final function that i have in mind :**

```
 /*Returns the position object must be at the specified percent */
 springAtPercent(startPosition, targetPosition, cycleNum /*the Number Of Times That Object Passes Through The Target*/, percent /*between 0.0 and 1.0*/);

```

i think the function makes it prettly clear what i need, i have searched a lot and found lots of result ! but none of them is good enough or has enough maneuver capability to achieve complicated animations that is why i need something like this.
in the end here is an image i made for a question in StackExchange physics section which resulted in the article i mentioned, hope it helps to further clarify my question.
*(i'm programming in pure C++, i also use ogre, in the end programming language doesn't matter that much, so if you don't know c++ feel free to use any language you like)*
Thanks.

**Edit 1:**
i have tried to implant MickLH answer
but i have a few problem!
i can not get the friction right ! i know what Newton's Method is and how it works but how many times do i need to calculate the new friction ?
and when you say friction\[0\] = 0 do you mean the x(n+1) = x + f(x) / f'(x) with n = 0 , should have an x = 0 ? because i tried that and the result of friction is very small! (as you can see the code)
i think the stiffness formula is right ! because i tried with test variable(which is 7.164850514373732 from your code) and with that constant i can get a right stiffness, which means the only problem i have is with the friction ! can you explain what should happen so that i get a right friction ? (note i can not use any math library because i'm using an company engine), thx

the lines i have written for friction and stiffness :

```
// as you can see the very first friction is calculated using friction = 0 which means e ^ 0 = 1
ATVector2 friction = csc(Ogre::Math::PI * cycleNum) * (((2 * Ogre::Math::PI * cycleNum * Ogre::Math::Cos(Ogre::Math::PI * cycleNum)) / decayTime) - ((2 * Ogre::Math::PI * cycleNum * 1 * pull) / (decayTime * stopped)));
    ATVector2 aftePow =  ATVector2(pow(e, -(decayTime * friction.x) / 2), pow(e, -(decayTime * friction.y) / 2));
    ATVector2 frictionplus1Part1 = Ogre::Math::PI * cycleNum * (2 * Ogre::Math::Cos(Ogre::Math::PI *  cycleNum) * aftePow * stopped - decayTime * friction * pull - 2 * pull);
    ATVector2 frictionplus1Part2 = decayTime * (Ogre::Math::Sin(Ogre::Math::PI * cycleNum) * aftePow * stopped - (Ogre::Math::PI * cycleNum * pull));
    ATVector2 frictionplus1 = frictionplus1Part1 / frictionplus1Part2;
    ATVector2 test = ATVector2(1.842068074395237, 1.842068074395237);
    ATVector2 stiffness = ((decayTime * decayTime) * (test * test) + 4 * (Ogre::Math::PI * Ogre::Math::PI) * (cycleNum * cycleNum))
    / (4 * decayTime * decayTime);

```

there is also csc which is 1 / sin(pi \*4) which is divide on 0 , which if we fix, can be a large number about 672, is this okay as well ?
here is another test which even after 100 time calculating friction i can only get 1.#INF0000 which is invalid!
here is the test :

```
//here, the initial value for friction is set to zero
mFriction = ATVector2::ZERO;
ATVector2 aftePow = ATVector2::ZERO;
/*
    decayTime = 5;
    cycleNum = 4;
    stopped = 0.01;
    pull = ATVector(1, 1);
*/

for (int i = 0; i < 100; i++)
{

    // here i calculate e^ ... to make things simpler
    aftePow =  ATVector2(pow(e, -(decayTime * mFriction.x) / 2), pow(e, -(decayTime * mFriction.y) / 2));
    mFriction = csc(Ogre::Math::PI * cycleNum) * (((2 * Ogre::Math::PI * cycleNum * Ogre::Math::Cos(Ogre::Math::PI * cycleNum)) / decayTime) - ((2 * Ogre::Math::PI * cycleNum * aftePow * pull) / (decayTime * stopped)));
}

//after the loop mFriction = ATVector(1.#INF0000, 1.#INF0000)

```

**Edit 2 :**
**for now the friction is not going to be an issue! because i found an even bigger problem!**
in **MickLH** answer, the **friction is calculated on the onUpdate()** and it **uses the previous friction** and that makes it useless inside a game with delta time on each update, why?
for example **when decayTime is 5** it means if the animation is played for example 10 time in every second, it will play a smooth and good spring! but if **some kind of lag occurs** that means the friction was not updated correctly! and the animation will be played on **decayTime + lagTime** !
it also take away control of the element for example :
you can not play an specific part of the animation, for example in a 5 sec animation you only need the last 2 second ! using **MickLH** answer you can only do that if you write some kind of loop and do the calculation 10 * 3 = 30 time ! so the friction is on the right amount !
in the end **The Answer does not meet** my need for getting the position on a specific percent ! , which is also something i mentioned at the beginning of my question
so once again if possible, anyone, please i need a function that can return a position based on Percent, based on DeltaTime, based on the time that passes, something accurate , i say this once again, it must become something like
this :

```
springAtPercent(startPosition, targetPosition, cycleNum /*the Number Of Times That Object Passes Through The Target*/, percent /*between 0.0 and 1.0*/);

```

MickLH is it possible to write your answer based on DeltaTime, percent ?
Thx

# Answer
> 6 votes
I'm using Hooke's Law here as the definition of a spring. (\\$F = -k * X\\$)

Given the derivatives of position and velocity, are velocity and force respectively, we can construct a differential equation for the stretching of the spring.

$$ \frac{d^2}{dt^2}y(t)=-\textit{Stiffness }y(t) - \mathit{Friction} \bigg{(}\frac{d}{dt}y(t)\bigg{)}$$

Which is just a damped harmonic oscillator, and since we already know that only the under-damped case need analysis, we can obtain a nice solution:

$$ \small{ y(t) = e^{-\frac{\textit{Friction }t}{2}}\bigg{(}\\%k\_1 \text{ sin}\big(\frac{t\sqrt{4\textit{ Stiffness} - Friction^2}}{2}\big) + \\%k\_2 \text{ cos} \big( \frac{t\sqrt{4 \textit{ Stiffness} - \textit{Friction}^2}}{2} \big) \bigg)} $$

We can eliminate the unknowns by knowing initial position \\$ y(0) = pull \\$ and velocity \\$ \frac{d}{dt}y(0)=0 \\$

$$ \small{ y(t) = \frac { pull \sqrt{4\\:\textit{Stiffness} - \textit{Friction}^2}} { \scriptsize{ \sqrt{4\\:\text{Stiffness} - \textit{Friction}^2}\\:e^\frac{Friction\\:t}{2} \text{cos}\big(\frac{\sqrt{4\\:\text{Stiffness} - \text{Friction}^2} t}{2}\big) - Friction\\;e^\frac{Friction\\;t}{2} \text{sin} \big( \frac{\sqrt{4\\:\text{Stiffness} - \text{Friction}^2} t}{2} \big) }}}$$

Ugly. But we have a closed form solution in time :)

Before we can solve for the parameters you're interested in, we have to address one small ambiguity: The damped harmonic oscillator never stops, only decays. I will use a threshold where we consider motion "stopped", and solve for the peak which attains this amplitude.

Now, from the solution above, I have obtained that the set of peaks are generated by:

$$t=\frac{2\pi\mathbb{Z}}{\sqrt{4\text{ Stiffness} - \text{Friction}^2}}$$

Which conveniently brings the n-th peak into the relationship.

Since you've specified both the decay time, and the number of crossings, we can derive a relationship between the two constants we are trying to compute:

$$\text{Stiffness}=\frac{\text{DecayTime}^2\text{Friction}^2+4\pi^2\text{CycleNum}^2}{4\text{ DecayTime}^2}$$

And now by substituting the time of the peak into the amplitude function, we can express the magnitude of the peak after a target number of equilibrium crossings:

Setting this equal to our "Stopped" threshold, we can then solve for the desired Friction coefficient:

I have obtained an implicit solution, and although it looks like it could maybe be solved by the W function in closed form, we would then need to implement the W function in C++, so I have not investigated that. Instead, I have taken the approach of reformulating the problem as root-finding, and numerically approximating the soluiton using Newton's Method. This strategy has yielded the following fixed point iteration:

I have **not** analysed the convergence properties of this formula with respect to the initial guess. With that said, seeding with `Friction[0] = 0` appears to place the attractor into the correct basin.

As a quick test, I've plugged in these values:

```
CycleNum = 4
DecayTime = 5
Stopped = 0.01
Pull = 1

```

And received the results:

```
Stiffness = 7.164850514373732
Friction = 1.842068074395237

```

Which I have then plugged into the most basic Euler integrator, with a step size of 1/10, and it produced this graph:

Which appears to be right on target, crossing 4 times to achieve a peak value of 0.01, after 5 seconds of simulated time.

---

EDIT

Here's my prototype code, I let maxima do newton's method:

```
params:[DecayTime = 5.0, Stopped = 0.01, Pull = 1.0, CycleNum = 4.0]$

load("mnewton")$
Friction = csc(%pi*CycleNum)*(2*%pi*CycleNum*cos(%pi*CycleNum)/DecayTime
                              -2*%pi*CycleNum*%e^-(DecayTime*Friction/2)*Pull
                               /(DecayTime*Stopped))$
subst(params, %)$
mnewton(%, Friction, 0);

```

> \[\[Friction=1.842068074395236\]\]

I also continued with maxima while completing stiffness:

```
subst(flatten([%,params]), Stiffness = (DecayTime^2*Friction^2+4*%pi^2*CycleNum^2)/(4*DecayTime^2)), numer;

```

> Stiffness=7.164850514373732

So I plugged these constants into a quick little C++ program:

```
#include <stdio.h>

class SpringAndMassEuler {
public:
    float Stiffness, Friction;
    float MassOffset, MassVelocity;

    SpringAndMassEuler() {
        Stiffness = 7.164850514373732;
        Friction = 1.842068074395237;
        MassOffset = 1;
        MassVelocity = 0;
    }

    float Update(float dt) {
        MassVelocity -= dt * (Stiffness * MassOffset + Friction * MassVelocity);
        MassOffset += dt * MassVelocity;
        return MassOffset;
    }
};

int main() {
    float t = 0;

    SpringAndMassEuler sim;
    printf("[%f, %f],\n", t, sim.MassOffset);

    // Choosing this timestep to play it safe with lame Euler
    float dt = 0.1;

    int c = 50;
    while (c--) {
        sim.Update(dt);
        t+=dt;
        printf("[%f, %f],\n", t, sim.MassOffset);
    }
}

```

Which produced the data pairs that I copy pasted back into maxima:

```
plot2d([discrete, [ ..... ]]);

```

---
Tags: 2d, physics, mathematics, animation
---


# Question
Title: Is there a way to prevent users from adjusting their gamma correction to 'cheat' their way out of a 'dark' area?
In almost every game I've come across that includes a dark situation designed to change the way a user interacts with the environment, there are always some players who turn up their monitor's gamma correction in order to negate the desired effect.

**Is there a way to prevent users from adjusting their gamma correction to 'cheat' their way out of a challenge? (the darkness)**

I'd imagine if you could reliably retrieve the current gamma correction of the user's monitor, you could use that to more or less prevent the advantage it would otherwise grant without causing the normal users any inconvenience.

# Answer
If you **absolutely need to** control whether the player can see something or not, possibly for multiplayer anti-cheat or if it's key to your game mechanics, then **completely obscure them**. This way no amount of gamma correction will make them visible.

Not the best example, but in Closure, areas not being lit are in complete darkness:

> ... if you could reliably retrieve the current gamma correction of the user's monitor ...

Please don't go down this path; there are many reasons - other than cheating - for correcting gamma; maybe the player has poor eyesight, or a bad monitor, or is playing during the day. **Please respect your users!** Don't let a few cheaters/pirates/what-have-you ruin the experience for everyone else.
> 66 votes

# Answer
What I'd suggest is adding a small amount of white noise to the rendered output. In bright scenes this won't be visible, in dark scenes with ordinary gamma setting it's similar to what cameras or the human eye actually do in reality. But for someone who cranks up the gamma, this noise would be a strong nuisance. Not only won't dark objects become properly visible, the boost of the low-range noise will then also distract from bright objects; so it should sufficiently discourage people from doing that.

(Of course, very clever guys might still come up with sophisticated de-noising techniques, but those are at least not available in ordinary monitors)
> 11 votes

# Answer
There are a couple of Windows API functions that might do the trick: SetMonitorBrightness and SetDeviceGammaRamp. However, this will be hardware-dependent; probably not all monitors support setting the brightness programmatically, and different monitors may produce different results, etc.

Moreover, it doesn't sound like a very good idea. Locking the gamma/brightness to some fixed value will surely annoy your players, and very probably render the game unplayable for some, because it happens to come out too dark (or too bright) on their setup.

Ultimately, if it's a singleplayer game and the player wants to make the game easier for themselves, that's their right. Why should you stop them? If it's a multiplayer game, then other strategies are needed, such as only sending the player information about events close enough for them to see or within their flashlight beam, or something of that nature.
> 10 votes

# Answer
Given the random brightness/contrast/gamma of the user's screens, not the mention the room lighting where the user sits, there's no reliable way to make something that will be "just visible enough" or "just invisible enough". If you want something to be invisible, make it black. If you want to make something ambiguously perceptable, you have to accept that some players will have a better opportunity to see it.
> 0 votes

# Answer
If its single player it doesn't really matter.

In multiplayer what about just having a collision box showing what they can view. If they are in a dark area tell the client to not draw other players/stage objects/etc at all until they are in field view collision box.
> 0 votes

---
Tags: rendering, anti-cheat
---


# Question
Title: Problem passing variables in fragment shader
I'm trying to pass a point light from an array to a CalcLight function in a fragment shader. It works when I hard code in the value, but not when I use a loop. Here's the code:

```
#define TOTAL_LIGHTS 2
struct PLight
{
    vec4 pos;

    vec4 diff;
    vec4 spec;
    vec4 amb;

    float con;
    float lin;
    float quad;
};

layout(std140) uniform Light
{
    PLight pLights[TOTAL_LIGHTS];
}light;

vec3 CalcPoint(in PLight p)
{
    ...
}

```

When I pass in the light from main using hard coded values it works fine.

```
void main()
{
    ...
    pointLight += CalcPoint(light.pLights[0]);
    pointLight += CalcPoint(light.pLights[1]);
    ...
}

```

But, when trying to use a loop, the first light works fine but not the second.

```
for(int i = 0; i < TOTAL_LIGHTS; i++)
    pointLight += CalcPoint(light.pLights[i]);

```

Any thoughts as to why the loop isn't working?

# Answer
> 2 votes
### That structure is not aligned correctly, which may be the source of your problem.

To form an array using `std140` out of `PLight`, you need to pad it with an extra `float` at the end. Otherwise, `PLight pLights[TOTAL_LIGHTS]` is misaligned and you will fetch the wrong memory from `pLights [1]` -- everything will be off by 1 scalar component on the second light in this array of structures.

### Consider this instead:

```
struct PLight
{
    vec4 pos;

    vec4 diff;
    vec4 spec;
    vec4 amb;

    float con;
    float lin;
    float quad;
    float padding;
};

```

The entire array size needs to be padded out to a multiple of the base-alignment for `std140`. Your base-alignment in this case is `vec4` (4N). So that means to satisfy this alignment you need to add a `float` to the end. GLSL will do this for you automatically, and this `float padding` element is something you need to take care of when you declare this structure in code outside of the shader.

# Answer
> 0 votes
Non-constant indexing into uniform array can be tricky and depends on GLSL version. I think that what you are doing should be within spec (even for GLES 2.0), but it still might be problem. See for example what GLES 2.0 GLSL 1.0 spec says about indexing uniform array in fragmen shader:

Apendix A section 5

> In the vertex shader, support for all forms of array indexing is mandated. In the fragment shader, support for indexing is only mandated for constant-index-expressions.

and

> constant-index-expressions are a superset of constant-expressions. Constant-index-expressions **can** include loop indices as defined in Appendix A section 4.

On desktop it should be better, but still could cause problem, as you have to have specified const. array size (which you did).

I know this is not much helpful in solving problem, but may give some clue to what might be going on.

---
Tags: opengl, glsl
---


# Question
Title: Calculating the illumination level of an object
In my (UE4) scene I have an object and several (point) light sources. The object can move around, getting closer and away from all those light sources. Now I need to calculate for each light source how much it affects the object at its current position (i.e. distance from the light).

Every light source has three important values:

* **Intensity**: How bright the light shines (integer vlaue 0..10000)
* **Attenuation**: Radius around light, how far it visibly influences the scene
* **Falloff exponent**: Radial falloff around light (inverse squared by default, or can be an integer between 2 and 8)

Now, depending on how far the object is from a light source, it is more or less affected by the light. If the object is outside the attenuation radius, it is not affected at all by the light. I am not so much interested in the light intensity, but more in the distance between the object and a light.

For each light I am interested in a value between 0 and 1. So the easy way would be to simply calc: `1 - distance / attenuation`. But I would like to take the falloff exponent into account. Any ideas how to accomplish that?

# Answer
> 0 votes
Take a look at a few of these and see if they match what you're looking for. I let attenuation = 10 for the purpose of demonstrating, but you should play around with all the numbers involved. WolframAlpha is very good at visualizing this sort of thing.

Keep in mind, negative exponents probably are not what you're looking for. Inverse squares, or negative exponents of any magnitude, will produce asymptotic functions.

---
Tags: algorithm, lighting, unreal-4
---


title: I cannot move a gameObject in my scene

text:
# Question
Title: I cannot move a gameObject in my scene
I am trying to move a cube to the right in my scene with this piece of code, but it does not work. What is the problem?

```
using UnityEngine;
using System.Collections;

public class Jump : MonoBehaviour {

Vector3 endPos;

void Update()
{
 if(Input.GetButtonDown("right") && gameObject.transform.position == endPos)
 {
     endPos = new Vector3(transform.position.x + 1, transform.position.y, transform.position.z);
 }
 }
 }

```

# Answer
There are multiple ways to move your object in the game world. You can set the transform manually (method 1), translate the object from it's local coordinates (method 2), or add a force onto your object's rigidbody (method 3).

```
using UnityEngine;
using System.Collections;

public class Jump : MonoBehaviour {

    private Rigidbody rb;
    private float thrust;

    void Start() {

        rb = GetComponent<Rigidbody>();
        rb.mass = 10;
        thrust = 5000;

    }

    void Update () {

        if(Input.GetKeyDown(KeyCode.Space)) {

            //You can use any of these

            //method 1
            transform.position += Vector3.up;

            //method 2
            transform.Translate(Vector3.up);

            //method 3
            rb.AddForce(Vector3.up * thrust);

        }

    }
}

```

Use only one of the options to make your object "jump".
> 1 votes

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


# Question
Title: Unity Grid Layout causing multiple draw calls
We are developing a game in Unity 4.6.6 for both Android and iOS.

Currently I am building the game UI with the new Unity UI system. In particular I am building a button list to create kind of inventory slots using the Grid Layout.

I have noticed that my draw call count is increasing considerably despite having my UI in an atlas (using Sprite packer) and using the same font all over the UI. After some tests I noticed that one draw call is generated per each UI Text and UI image present in the scene composing each button when using a Grid Layout Group, when the Grid Layout is not used the draw calls are reduced noticeably.

7 elements without Grid Layout, results in 2 draw calls: (Screenshots taken in play mode)

7 elements WITH Grid Layout, resulting in 14 draw calls: (Screenshots taken in play mode)

I have no idea if it is possible to reduce the number of draw calls when using the Grid Layouts.

# Answer
Without code to reference the only thing I can assume is that the grid is adding another object to each button. Each button is one call, so 7, and the only reasonable assumption is that the layout is adding an additional call to each, now totaling 14.

From what it looks like, you're forcing height and width bounds and spacing is either assigned or being split between them all. 2 passes on each button versus whatever you where using in the first screenshot.
> -1 votes

---
Tags: unity, gui, optimization
---


# Question
Title: Pygame - implementing a scrolling camera
I am currently making a 2d game in Pygame and have run into a roadblock trying to make a scrolling camera (follows the character). I have seen some other answers to similar questions, but they have helped very little. Also, I am purposely doing this without the use of Pygame's `Sprite` class, so that makes things a little more complex. How should I approach this?

```
display_width = 800
display_height = 640
size = (display_width, display_height)
half_width = int(display_width / 2)
half_height = int(display_height / 2)

black = (0,0,0)
white = (255,255,255)

clock = pygame.time.Clock()
pygame.display.set_caption("My game")
screen = pygame.display.set_mode(size)

background = Surface((32,32))
background.convert()
background.fill(Color('#783131'))

x = 0
y = 0

platformlst = []
players = []

level = [
    "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP",
    "P                                          P",
    "P                                          P",
    "P                                          P",
    "P                    PPPPPPPPPPP           P",
    "P                                          P",
    "P                                          P",
    "P                                          P",
    "P    PPPPPPPP                              P",
    "P                                          P",
    "P                          PPPPPPP         P",
    "P                 PPPPPP                   P",
    "P                                          P",
    "P         PPPPPPP                          P",
    "P                                          P",
    "P                     PPPPPP               P",
    "P                                          P",
    "P   PPPPPPPPPPP                            P",
    "P                                          P",
    "P                 PPPPPPPPPPP              P",
    "P                                          P",
    "P                                          P",
    "P                                          P",
    "P                                          P",
    "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP",]

total_level_width = len(level[0])*32
total_level_height = len(level)*32
map_size = (total_level_width, total_level_height)
virtualwindow = pygame.Surface.get_rect(screen)

class Camera:
    def __init__(self, players):
        self.left_viewbox = display_width/2 - display_width/8
        self.right_viewbox = display_width/2 + display_width/10

    def follow(self, shift_x):
        virtualwindow.x += shift_x
        print virtualwindow.x
        for i in players:
            i.rect.x += shift_x

    def viewbox(self):
        if player.x <= self.left_viewbox:
            view_difference = self.left_viewbox - player.x
            player.x = self.left_viewbox
            self.follow(view_difference)

        if player.x >= self.right_viewbox:
            view_difference = self.right_viewbox - player.x
            player.x = self.right_viewbox
            self.follow(view_difference)

```

Basically, the `player` objects are added to a list, which is called out in the `follow()` function, which is called by the `viewbox()` function. Then the `follow()` function should be adding the `view_difference` as `shift_x` to the `virtualwindow.x`. Shouldn't this therefore scroll the map along its `x` axis relative with the characters movement?

Here is the full code: https://github.com/tear727/Netse/blob/master/game.py

# Answer
Code:

```
import pygame
pygame.init()
#
###
class Player:
    def __init__(self):
        self.image = pygame.Surface((16,16)) # Create Player Image
        self.image.fill(colors["RED"]) # Fill Player Red
        self.rect = pygame.Rect((50,50),(16,16)) # Create Player Rect
    def move(self,camera_pos):
        pos_x,pos_y = camera_pos # Split camara_pos
        #
        key = pygame.key.get_pressed() # Get Keyboard Input
        if key[pygame.K_w]: # Check Key
            self.rect.y -= 8 # Move Player Rect Coord
            pos_y += 8 # Move Camara Coord Against Player Rect
        if key[pygame.K_a]:
            self.rect.x -= 8
            pos_x += 8
        if key[pygame.K_s]:
            self.rect.y += 8
            pos_y -= 8
        if key[pygame.K_d]:
            self.rect.x += 8
            pos_x -= 8
        #
        if self.rect.x < 0: # Simple Sides Collision
            self.rect.x = 0 # Reset Player Rect Coord
            pos_x = camera_pos[0] #Reset Camera Pos Coord
        elif self.rect.x > 984:
            self.rect.x = 984
            pos_x = camera_pos[0]
        if self.rect.y < 0:
            self.rect.y = 0
            pos_y = camera_pos[1]
        elif self.rect.y > 984:
            self.rect.y = 984
            pos_y = camera_pos[1]
        #
        return (pos_x,pos_y) # Return New Camera Pos
    def render(self,display):
        display.blit(self.image,(self.rect.x,self.rect.y))
###
#
#
###
def Main(display,clock):
    world = pygame.Surface((1000,1000)) # Create Map Surface
    world.fill(colors["BLACK"]) # Fill Map Surface Black
    for x in range(10):
        pygame.draw.rect(world,colors["BLUE"],((x*100,x*100),(20,20))) # Put Blue Rectagles On Map Surface
    #
    player = Player() # Initialize Player Class
    camera_pos = (192,192) # Create Camara Starting Position
    #
    while True:
        clock.tick(60)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                return
        #
        camera_pos = player.move(camera_pos) # Run Player Move Function And Return New Camera Pos
        #
        display.fill(colors["WHITE"]) # Fill The Background White To Avoid Smearing
        world.fill(colors["BLACK"]) # Refresh The World So The Player Doesn't Smear
        for x in range(10):
            pygame.draw.rect(world,colors["BLUE"],((x*100,x*100),(20,20)))
        player.render(world) # Render The Player
        display.blit(world,camera_pos) # Render Map To The Display
        #
        pygame.display.flip()
###
#
if __name__ in "__main__":
    display = pygame.display.set_mode((500,500))
    pygame.display.set_caption("Scrolling Camera")
    clock = pygame.time.Clock()
    #
    global colors # Difign Colors
    colors = {
    "WHITE":(255,255,255),
    "RED"  :(255,0,0),
    "GREEN":(0,255,0),
    "BLUE" :(0,0,255),
    "BLACK":(0,0,0)
    }
    Main(display,clock) # Run Main Loop

```

I remember when I had this same issue. The above code is an example I wrote up quick showing how handled the issue. Feel free to take it and reverse engineer it to your hearts content. :)

The way I figured it out is that since the actual window is itself a surface, if all the games world assets, the player, scenery, goals, etc., were placed on a player made surface instead of the display surface. This surface can then be moved against the player movement to create the allusion that the player remains in the same place.

This is shown in my example code here within the players move function:

```
        pos_x,pos_y = camera_pos # Split camara_pos
        #
        key = pygame.key.get_pressed() # Get Keyboard Input
        if key[pygame.K_w]: # Check Key
            self.rect.y -= 8 # Move Player Rect Coord
            pos_y += 8 # Move Camara Coord Against Player Rect
        if key[pygame.K_a]:
            self.rect.x -= 8
            pos_x += 8
        if key[pygame.K_s]:
            self.rect.y += 8
            pos_y -= 8
        if key[pygame.K_d]:
            self.rect.x += 8
            pos_x -= 8

```

By moving the blitting coods of the camera the an opposite direction and at the same velocity of the player, it cancels out the momentum of the player object, and creates the illusion that the player is standing still while the game world moves around him/her/it. (I actually figured this all out in Physics class during a lecture on momentum)

Make sure to blit the player to the world surface and not the display surface as shown in the code:

```
        display.fill(colors["WHITE"]) # Fill The Background White To Avoid Smearing
        world.fill(colors["BLACK"]) # Refresh The World So The Player Doesn't Smear
        for x in range(10):
            pygame.draw.rect(world,colors["BLUE"],((x*100,x*100),(20,20)))
        player.render(world) # Render The Player
        display.blit(world,camera_pos) # Render Map To The Display

```

As if you mistakenly blit the player to the display instead of the world, they won't work off of each other and the player will instead have the illusion of moving twice as fast as the world. If you want, you can switch out:

```
        player.render(world) # Render The Player

```

with:

```
        player.render(display) # Render The Player

```

And see what I mean by that.

I hope all this helps, and best of luck with your future coding projects. :)
> 0 votes

# Answer
Take a look at this post. Basically you can keep the camera position around, and decide where to draw things based on that. I couldn't quite make sense of your game but here are some brief changes I made:

```
...
total_level_width = len(level[0])*32
total_level_height = len(level)*32
map_size = pygame.Rect(0, 0, total_level_width, total_level_height)
cameraPosition = [0, 0]
#################Objects################

class Camera:
    def __init__(self, players):
        self.left_viewbox = display_width/2 - display_width/8
        self.right_viewbox = display_width/2 + display_width/10

    def follow(self, shift_x):
        cameraPosition[0] += shift_x
        print cameraPosition
        for i in players:
            i.rect.x += shift_x

...

```

Whenever you draw an object then you can call blit like this:

```
screen.blit(self.img, (self.x - cameraPosition[0], self.y - cameraPosition[1], self.w, self.h))

```
> 0 votes

---
Tags: python, pygame, scrolling
---


# Question
Title: How to pass a big (60+) amount of variables to an HLSL pixel shader?
I am in trouble at trying to pass a big amount of variables needed for my pixel shader computations.

After trying and failing to link my struct to a cbuffer (data alignement mismatch) I tried passing my variables first to the vertex shader (with an `D3D11_INPUT_ELEMENT_DESC` / `CreateInputLayout`) with the intent to link them to the pixel shader through semantics but I hit the 32 shader inputs limit.

I am really stuck (and quite a noob at DX). What is a common / standard way to do this ? Can I only rely on a cbuffer ? Is creating a `D3D11_INPUT_ELEMENT_DESC` / `CreateInputLayout` even possible for the pixel shader ?

Example struct I want to pass to my pixel shader :

```
struct SceneParamsInterface {
    bool DEAOEnabled;
    XMFLOAT4 DEAOColor;
    double DEAOPow;
    bool lightEnabled;
    XMFLOAT4 lightColor;
    XMFLOAT3 lightDirection;
    bool lightMultiply;
    double lightMultiplyFactor;
    bool ambiantLightEnabled;
    XMFLOAT4 ambiantLightColor;
    bool HSEnabled;
    int HSSpread;
    bool fogEnabled;
    XMFLOAT4 fogColor;
    double fogDistanceMax;
    bool glowEnabled;
    XMFLOAT4 glowColor;
    double glowRadius;
    XMFLOAT4 skyColor;
    bool skyBoxEnabled;
    //uniform sampler2D skyBoxTexture;
    int skyBoxScheme0; // top
    int skyBoxScheme1; // left
    int skyBoxScheme2; // front
    int skyBoxScheme3; // right
    int skyBoxScheme4; // back
    int skyBoxScheme5; // bottom
    int skyBoxRotate;
    double skyBoxRotateSpeed;
    XMFLOAT3 skyBoxRotateAround;
    bool orbitTrapsEnabled;
    int orbitTrapsId;
    XMFLOAT4 objectColor;
};

```

Thanks!

# Answer
Use several constant buffers and group variables together based on how often they change.

If your variables are fairly static ( or just huge ) you may be better off converting values into a texture and extracting them in the shader.
> 7 votes

---
Tags: c++, directx11, hlsl, fragment-shader
---


title: Player in Spaceship

text:
# Question
Title: Player in Spaceship
I want to realize space game on Unity3d engine. There are some huge spaceships in the void. So, I want players flying in space in weightlessness, but when they go inside any spaceship, they will be under the influence of local gravity field of spaceship (if it is in `On` state).
I going to do it using `addForce()` function applied to `rigidbodies` of players towards spaceship floor. But with this approach Players will be only magnify to a floor, but not to stay on they feet automatically.
**How can I put they on they feet the best way?**
Or, maybe, anybody knows the completely different approach to solve this custom gravity fields issue?
PS: It will be a multiplayer game with many ships with different orientation in space with a lot of players in them. Each ship has it's own gravity field.

# Answer
> 3 votes
Each rigid body has an attribute indicating if it's affected by gravity or not. You can just mark that attribute as true, whenever player enters the spaceship, and later turn it false, when he exits. But that'll limit you with a big limitation. The gravity itself in unity is something global, meaning all entities are affected by same gravity force (if any). This means, even if two spaceships have different rotation, players in both of them, will be affected by same gravity, and they are both pulled towards same direction.

This might not be that much of a problem on it's own, but it depends on your design. For example you might limit all the spaceships so that they all have same rotation (they all share same up vector). In that case you can easily use the built-in gravity function, and get away with it.

But in case you don't want that to happen, and want to leave different ships to have different ups, You should consider applying the gravity yourself. Just note that Gravity is an acceleration, not a force. Meaning when applying you should use "ForceMode.Acceleration". That acceleration could simply be the exact opposite of up direction of current spaceship. I'm talking about "-transform.up" of spaceship. You can also use same Up vector, to rotate player so that gravity actually feels right, aka. player feet are pointing towards gravity.

# Answer
> 0 votes
Under the rigidbody tab in the hierarchy freeze rotation X and Z. This will keep them from falling over. Then you should be able to apply gravity on the Y axis without a problem.

---
Tags: physics, scripting, unity, rigidbody
---


title: Objects stick together on Collision

text:
# Question
Title: Objects stick together on Collision
I have a ball which has CircleCollider2D attached to it. It is also rigidbody. When it lands on a platform, it jumps . The platform is static, with Edge Collider attached. It also has a platform effector attached with "Use One Way" selected.

Most of the times it works fine, but some times, the ball lands on the platform and instead of bouncing, just sits on the platform.

When ball lands on the platform, following code is executed:

```
 rb.AddForce(upForce, ForceMode2D.Impulse);

```

upForce is Vector2(4,10);

image shown below:

Why is this happening?

# Answer
As requested by SanSolo - Comment converted to answer.

If you are calling the AddForce method from **OnCollisionEnter2D** then it will only get called on the initial contact of both colliders. If for some reason, your collision fails to get recognised, your AddForce method will fail.

An easy way to fix this is to simply place your AddForce method inside of the **OnCollisionStay2D** method. This will ensure that your AddForce method gets called every time your colliders are in contact regardless of any unrecognised initial collisions.
> 0 votes

# Answer
Gravity in unity is a default of roughly 9. Are you simulating gravity, are you using the correct scale and have you tried adding more force?
> 1 votes

# Answer
Try using `AddForce()` in the function `OnCollisionStay2D()` so that it is called every time there is a collision.
> 0 votes

---
Tags: unity
---


# Question
Title: THREE.JS: why is the rotation only applied on the last axis used?
my function:

```
    function rotateAroundWorldAxis2(object, radians1, radians2) {

        object.rotWorldMatrix.makeRotationX(radians1).makeRotationZ(radians2);
       // object.rotWorldMatrix;

        // old code for Three.JS pre r54:
        //  rotWorldMatrix.multiply(object.matrix);
        // new code for Three.JS r55+:
        object.rotWorldMatrix.multiply(object.matrix);                // pre-multiply

        object.matrix.copy( object.rotWorldMatrix );

        // old code for Three.js pre r49:
        // object.rotation.getRotationFromMatrix(object.matrix, object.scale);
        // old code for Three.js pre r59:
        // object.rotation.setEulerFromRotationMatrix(object.matrix);
        // code for r59+:
        object.rotation.setFromRotationMatrix(object.matrix);

    }

```

my object was initialized like this: object.rotWorldMatrix = new THREE.Matrix4();

# Answer
> 1 votes
Calling "makeRotationX/Y/Z" will fill up the matrix cells with values for rotation around the wanted axis, thus overriding any previous value in the matrix.

According to example here, you should instead build one separate matrix per rotation axis then at the end multiply those matrices in a single final one.

So in your case it would look like :

```
var mX = new THREE.Matrix4();
mX.makeRotationX(radians1);

var mZ = new THREE.Matrix4();
mZ.makeRotationZ(radians2);

var m = new THREE.Matrix4();
m.multiplyMatrices( mX, mZ );

object.rotWorldMatrix.copy(m);

object.rotWorldMatrix.multiply(object.matrix);

//...

```

Note that depending on the order you use to multiply matrices you may get different result, this is called the "gimbal lock" problem but this is another vast subject, I will not discuss it here...

---
Tags: rotation, matrix, three.js
---


# Question
Title: Make a plane to display material from both sides
I know there is a setting in Cry Engine, which allows you to be able to read materials of the plane from both sides, so I am wondering if there is such a setting in **Unity5**.

Thanks in advance

# Answer
> 3 votes
You need to edit your shader source file in order to add "Cull Off" inside, more info here

If you are not writing your own shaders (and so use default provided Unity shaders) then you can look at proposed solutions here

---
Tags: normals, unity, materials
---


# Question
Title: Rendering Performance: num Draw Calls == num Texture Bindings
I'm making a game with Libgdx 1.6.4 and experience some lag issues on iPhone 4 and then discovered:

```
// in the constructor
GLProfiler.enable();

...

// in the render method
Gdx.app.debug("draw calls: " + GLProfiler.drawCalls);
Gdx.app.debug("texture bindings: " + GLProfiler.textureBindings);
GLProfiler.reset();

```

What the log shows is that the number of draw calls is **always equal** to the number of texture bindings. Do you know if this is ok?

It seems strange because I have all images as **TextureRegion** in only one **TextureAtlas** with size 1024x512. Isn't it supposed to be that I will have for example 50 draw calls and only 1-2 texture binding instead of 50 draw calls and 50 texture bindings. Can this be the source of the lag?

Another clue may be, that I use a SpriteBatch and Scene2d Stage at the same time, but they both use the same TextureAtlas. The Scene2d Skin is loading the TextureAtlas and SpriteBatch draws TextureRegions from the skins' regions.

Thank you for any help.

--- Update ---

The main SpriteBatch (it's only one) is making **9 totalRenderCalls**. The value of **maxSpritesInBatch is 26**. These values seem normal from what I read in the Docs and the FPS during rendering with the SpriteBatch is **60 FPS**. Which is ok, no problem there.

The problem with the lag is when I use a Scene2D **Stage** to display a Dialog above the GameScreen. The Stage has it's own batch which I don't manipulate directly. When the Dialog is displayed the frame rate drops to **49-50** and the Animations in the Dialog are crappy. I guess the problem has something to do with Texture Binding of the main SpriteBatch and the Stage's SpriteBatch.

# Answer
> 1 votes
As described here (last chapter), please check the value of the field renderCalls in your SpriteBatch (you have only one unique SpriteBatch instance right ?), this should tell you the real number of draw calls that the batch has made.

If you have more renderCalls than what you would expect then maxSpritesInBatch value is too low or your sprites have properties which make them not batchable (they would use different textures, or different shaders, or their shaders would need different uniforms values depending on which sprite is drawn).

---
Tags: opengl, libgdx, textures, performance, spritebatch
---


title: GUI.DrawTexture problem in Unity

text:
# Question
Title: GUI.DrawTexture problem in Unity
I'm having a problem with **GUI.DrawTexture()** and I'm looking an alternative function to draw 2D Texture Images. The problem I have is that my textures draw above all other objects and when my camera moves, the images move with the camera, keeping their relative position inline with the cameras position.

```
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using UnityEngine;

public class AnimatedGifDrawer : MonoBehaviour
{
public string loadingGifPath;
public float speed = 1;
public Vector2 drawPosition;

List<Texture2D> gifFrames = new List<Texture2D>();
void Awake()
{
    var gifImage = Image.FromFile(loadingGifPath);
    var dimension = new FrameDimension(gifImage.FrameDimensionsList[0]);
    int frameCount = gifImage.GetFrameCount(dimension);
    for (int i = 0; i < frameCount; i++)
    {
        gifImage.SelectActiveFrame(dimension, i);
        var frame = new Bitmap(gifImage.Width, gifImage.Height);
        System.Drawing.Graphics.FromImage(frame).DrawImage(gifImage, Point.Empty);
        var frameTexture = new Texture2D(frame.Width, frame.Height);
        for (int x = 0; x < frame.Width; x++)
            for (int y = 0; y < frame.Height; y++)
        {
            System.Drawing.Color sourceColor = frame.GetPixel(x, y);
            frameTexture.SetPixel(frame.Width - 1 - x, y, new Color32(sourceColor.R, sourceColor.G, sourceColor.B, sourceColor.A)); // for some reason, x is flipped
        }
        frameTexture.Apply();
        //frameTexture.LoadImage.
        gifFrames.Add(frameTexture);
    }
}

void OnGUI()
{
    GUI.DrawTexture(new Rect(drawPosition.x, drawPosition.y, gifFrames[0].width, -gifFrames[0].height), gifFrames[(int)(Time.frameCount * speed) % gifFrames.Count]);
}

```

}

The code above is designed to draw animated GIFs using System.Drawing.dll in Unity

# Answer
You need to use camera faced billboards in order to solve this issue. Which means that you need :

* To use a 3D quad to display those textures (which you construct by code)
* To give this 3D quad a 3D position, and a 3D size
* To orient this 3D quad towards camera at each frame, either by code or in its vertex shader

Example to construct a billboard here And to orient toward camera here (may be a bit outdated) General doc on 3D billboards here
> 1 votes

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