# Question
Title: Can I legally use retro video game music in a quiz game?
I am considering making a video game music quiz game, where you guess the game that the music is taken from. For example from NES and SNES games.

In that regard I was wondering if anyone know of any legal issues this might have. Could I for example limit the music playback to 'X' seconds without any legal repercussions?

Seeing that these are really old games, who actually owns the licenses to the music now? For example for games made by developers that no longer exist?

Also, if I would provide screenshots from the games in question, would that be a legal issue as well?

**UPDATE**

My thoughts was not to copy gameplay elements from the games, but to create a game consisting of a quiz on music from other games. So the games wont be similar to the games that the music is from at all.

Examples of this type of game:

If using the music from other games is a violation, are these games violating the copyright?

# Answer
> 4 votes
I am not a lawyer, so do not take this as legal advise. When you want to undertake this project, consult a lawyer who knows about your local copyright laws.

But according to my layman's knowledge of copyright, that would most definitely be a copyright violation. When the piece of media is long enough to recognize it, it is long enough to sue about it.

The company no longer existing does not make it safe either. When a company is liquidated, the intellectual property rights are usually sold to other companies which can then sue on their behalf. Such deals are not always made public, so finding out the actual copyright holder can be difficult in many cases.

You might be able to use a fair use defense in courts in some jurisdictions, but such lawsuits are civil, and in civil lawsuits you need to pay the lawyer to defend yourself upfront. So it's not just about being right, it's about being right and having the money to afford proving it. Ask your lawyer about how much capital you should keep on hand to cover future lawsuits.

**Regarding your update:** Yes, these games are very likely copyright violations. The copyright holders might not have sued them (yet) because they either haven't noticed that these games exist, can not identify the author (for examle when it's published under a pseudonym) or consider it not worth pursuing because the author doesn't seem to have the money which would make it worth a lawsuit (their lawyers also want money upfront, and when the defendant can't pay them, then the coyright holder won't get that money back). Copyright holders can decide which violations they want to pursue. So just because someone else does it doesn't mean you should do it too.

---
Tags: legal, copyright, music
---


# Question
Title: How to change the way LibGDX scales images?
I'm using FillViewport and OrthographicCamera. LibGDX is scaling my images rather badly - jagged edges, visible pixels. How can I change the scaling method?

by the way, I'm pretty sure the issue isn't my images. I've scaled them using imaging software and they look a lot better than when LibGDX scales them.

# Answer
> 1 votes
The issue is probably because of Texture Filters. And it's not LibGdx problem either, but OpenGL's.

You can set filters for Libgdx textures using `setFilter()` method. For eg., try setting the filter to:

`yourTexture.setFilter(TextureFilter.MipMapLinearNearest,TextureFilter.Nearest);`

Here's the detailed explanation written by Mario himself.

---
Tags: java, libgdx
---


# Question
Title: Unity question: When attaching my custom camera script camera shakes when player starts to move fast
Here is my player code.

```
Rigidbody rb;

Vector3 currMovement;
public float jumpSpeed = 10;
public float moveSpeed = 10;
public float rotSpeed = 180;

float distToGround;

public float smoothTimePos = 0.25f;
float currPos;
float targetPos;
float posVel;

public float smoothTimeRot = 0.25f;
float currRot;
float targetRot;
float rotVel;

void Start()
{
    rb = GetComponent<Rigidbody>();
    distToGround = GetComponent<Collider>().bounds.extents.y;
}

bool isGrounded() { return Physics.Raycast(transform.position, Vector3.down, distToGround + 0.1f); }

void Update()
{
    targetRot = Input.GetAxisRaw("Horizontal") * rotSpeed * Time.smoothDeltaTime;
    targetPos = Input.GetAxisRaw("Vertical") * moveSpeed;
}

void FixedUpdate()
{
    Move();
}

void Move()
{
    if (isGrounded())
    {
        if (Input.GetButtonDown("Jump"))
            rb.velocity += Vector3.up * jumpSpeed;
    }

    // Rotation smoothing.
    if (targetRot > 360)
        targetRot -= 360;
    if (targetRot < 0)
        targetRot += 360;
    currRot = Mathf.SmoothDampAngle(currRot, targetRot, ref rotVel, smoothTimeRot);

    transform.eulerAngles += new Vector3(0, currRot, 0);

    // Movement smoothing.
    currPos = Mathf.SmoothDamp(currPos, targetPos, ref posVel, smoothTimePos);
    currMovement = new Vector3(0, 0, currPos);
    currMovement = transform.rotation * currMovement;

    rb.position += currMovement * Time.smoothDeltaTime;
}

```

I have a Rigidbody attached to my player. I think the problem is with my camera script. Here is my camera script.

```
public Rigidbody player;
Quaternion targetLook;
Vector3 targetMove, targetMoveRaycast, targetMoveUse;
public float smoothLook = 8, smoothMove = 0.25f;
public float distFromPlayer = 5, heightFromPlayer = 3;
Vector3 moveVel;

void LateUpdate()
{
    CameraMove();
}

void CameraMove()
{
    targetMove = player.position + (player.rotation * new Vector3(0, heightFromPlayer, -distFromPlayer));

    RaycastHit hit;
    if (Physics.Raycast(player.position, targetMove - player.position, out hit, Vector3.Distance(player.position, transform.position)))
    {
        targetMoveRaycast = hit.point;
        targetMoveUse = targetMoveRaycast;
    }
    else
    {
        targetMoveUse = targetMove;
    }

    transform.position = Vector3.SmoothDamp(transform.position, targetMoveUse, ref moveVel, smoothMove);

    targetLook = Quaternion.LookRotation(player.position - transform.position);
    transform.rotation = Quaternion.Slerp(transform.rotation, targetLook, smoothLook * Time.smoothDeltaTime);
}

```

The player is not an parent of my camera. When I parent the player to my camera the shake stops. But I want a custom smooth camera movement with my custom scirpt, so I can't make the player a parent of the camera.

# Answer
Try this:

1. Add a kinematic Rigidbody to the camera
2. Cache the rigidbody
3. Use rigidbody.position and rigidbody.rotation instead of transform.position and transform.rotation
4. Call CameraMove() from FixedUpdate() instead of LateUpdate()
5. Play around with interpolation on the camera and the player if necessary

```
public Rigidbody player;

Quaternion targetLook;
Vector3 targetMove, targetMoveRaycast, targetMoveUse;
public float smoothLook = 8, smoothMove = 0.25f;
public float distFromPlayer = 5, heightFromPlayer = 3;
Vector3 moveVel;

private Rigidbody m_Rigidbody; // added

/// added
void Awake() {
    m_Rigidbody = GetComponent<Rigidbody>();
    m_Rigidbody.isKinematic = true;
}

void FixedUpdate() { //Edited
    CameraMove();
}

void CameraMove() {
    targetMove = player.position + (player.rotation * new Vector3(0, heightFromPlayer, -distFromPlayer));

    RaycastHit hit;
    if (Physics.Raycast(player.position, targetMove - player.position, out hit, Vector3.Distance(player.position, m_Rigidbody.position))) {//Edited
        targetMoveRaycast = hit.point;
        targetMoveUse = targetMoveRaycast;
    }
    else {
        targetMoveUse = targetMove;
    }

    m_Rigidbody.position = Vector3.SmoothDamp(m_Rigidbody.position, targetMoveUse, ref moveVel, smoothMove); //Edited

    targetLook = Quaternion.LookRotation(player.position - m_Rigidbody.position); //Edited
    m_Rigidbody.rotation = Quaternion.Slerp(m_Rigidbody.rotation, targetLook, smoothLook * Time.smoothDeltaTime); //Edited
}

```
> 2 votes

---
Tags: unity, c#, camera, movement
---


title: How to use the SDL viewport properly?

text:
# Question
Title: How to use the SDL viewport properly?
I'm very confused about the SDL2 viewport, I did some googling to find out how to implement it but people keep mentioning things like "world coordinates" which I don't have in my game.

**Question** : Do I even need world coordinates for the SDL2 viewport to work? If yes, how do I implement it?

---

I've currently got a problem where if my viewport goes too much to the right or down, the entire window will become green, kinda like if it stopped rendering all my sprites.

Here's a GIF to show you what I mean :

As you can see, whenever I go too much to the right or down the entire screen goes green.

I thought this maybe was beause of me not using world coordinates, but I have no idea I'm just guessing stuff at this point...

---

My current codes for moving the viewport, drawing it, and such looks like this :

**Creating the viewport / camera :**

```
Camera::Camera(Uint16 x, Uint16 y, Uint16 w, Uint16 h)
{

    // Sets up the viewport positions and sizes
    viewport.x = x;
    viewport.y = y;
    viewport.w = w;
    viewport.h = h;

    // Sets the viewport so that SDL uses it
    SDL_RenderSetViewport(Window::GetRenderer(), &viewport);

}

```

**Drawing the viewport :** (gets called every frame)

```
void Camera::DrawCameraViewport()
{
    SDL_RenderSetViewport(Window::GetRenderer(), &viewport);
}

```

**I set the cameras position during runtime like this :**

```
void Camera::SetCameraPosition(int _x, int _y)
{
    viewport.x = _x;
    viewport.y = _y;
}

```

**And here's how I set the cameras position using the above function :**

*Note : Sorry, the line became giantic...*

```
camera->SetCameraPosition(
    -SpriteManager::GetPlayerSprite()->GetPosition().x
    + Window::GetWindowMiddlePoint().x
    - SpriteManager::GetPlayerSprite()->GetMiddlePoint().x

    , -SpriteManager::GetPlayerSprite()->GetPosition().y
    + Window::GetWindowMiddlePoint().y
    - SpriteManager::GetPlayerSprite()->GetMiddlePoint().y);

```

---

**Question** : Am I implementing the viewport correctly?

# Answer
> 11 votes
My guess is you're trying to implement a camera, and should *not* be using SDL Viewports. The viewports are for UI elements like menus, minimaps, etc. It's a way of dividing up the *screen* into multiple areas.

To implement a camera, you will want to think about coordinate systems. The **world coordinates** are the positions in the world, without thinking about the camera. If a tree is at 300,200 then it stays at 300,200 even if you move the camera around. The **screen coordinates** are where that tree is drawn on the screen. As you move around, the tree might be drawn in different places on screen.

If you try to use screen coordinates everywhere, things get really confusing. Every time you move the camera, you now need to go update everything. If you use world coordinates, you don't "move" the tree around. Instead, you draw it in a different place. The tree doesn't move. The camera moves.

Here's the basic formula:

```
screen + camera = world

```

You know the world coordinates of the tree, and the camera location, and you want to figure out the screen coordinates, so you rewrite the formula this way:

```
screen = world - camera

```

With the tree example, the tree is at x=300,y=200, and let's say the camera is at x=50,y=70, then you want to know *where to draw the tree*:

```
screen.x = tree.x - camera.x
screen.y = tree.y - camera.y
#
screen.x = 300 - 50 = 250
screen.y = 200 - 70 = 130
# draw tree at 250,130

```

When you move your camera, you redraw everything on the screen by calculating the new screen coordinates. If you moved the camera to x=100,y=20, you'd redraw the tree:

```
screen.x = tree.x - camera.x
screen.y = tree.y - camera.y
#
screen.x = 300 - 100 = 200
screen.y = 200 - 20 = 180
# draw tree at 200,180

```

Notice that `tree.x`,`tree.y` didn't change here. It's only the camera that changed. (You can later optimize this by not drawing the things that won't be on the screen, but first get the basics working before trying to optimize.)

(A bonus with the formula is that it works backwards too. If you got a mouse click and want to know where in the world you clicked, you use `screen + camera = world`. You know the screen location of the mouse click, and you know the camera location, so you add them together to figure out what you clicked on.)

One day I will finish my tutorial on this topic…

# Answer
> -1 votes
try using `SDL_RenderSetClipRect()` instead of `SDL_RenderSetViewport` . Had the same problem and changed into `SDL_RenderSetClipRect()`. Cheers!

---
Tags: maps, coordinates, sdl2, viewport
---


# Question
Title: Parenting a child object to parent in Unity
I am making an 3d Tennis game in Unity 5.0. I have made 3d model of the Tennis player in Makehuman and have successfully imported it to Blender and Unity.

I want to add an tennis racket in the hand on my Makehuman model. So what should the strategy be?

Should I add the tennis racket to the Makehuman character in Blender as the child of the Makehuman model and then animating it or is there a simple way to do that in Unity in the game.

# Answer
Make the racket as child of a finger or hand bone that will translate/move as you want.

Animate the humanoid without racket but keep the moves of hand as if there is a racket in hand.

Go to the skeletal rig under your model prefab object. Drag and drop the racket under your chosen bone. We put rifle with forearm.
> 2 votes

---
Tags: unity, blender, makehuman
---


# Question
Title: What is the most efficient way to render water?
1. Would I create the water surface mesh in C++, and control the movement/animation in the CPU, and afterward apply any shaders (reflect/refraction/caustics/etc..).
2. Or should I only create the mesh in C++ and afterward control movement in the vertex shader?

It seems with the second approach, it would be more difficult to simulate more complex water models.

What is the most common approach in modern video games?

# Answer
> 1 votes
Depends on which level of detail you wanna achieve. Height Maps could be a solution, try to avoid as much work on the CPU as possible in every case.

You can combine also some techniques as tesselation. There are plenty sites on the web for inspiration, you know where to search :)

# Answer
> 0 votes
Simplest possible way is obviously the following:

1. create mesh with enough vertices that describes water surface
2. configure your shader to move the vertices in a circle

---
Tags: opengl, c++, shaders, graphics, water
---


title: QT SFML Integration Trouble

text:
# Question
Title: QT SFML Integration Trouble
I have been having trouble linking sfml to qt creator I have downloaded the pre-compiled libraries and headers for MINGW on the sfml website here : http://www.sfml-dev.org/download/sfml/2.3.2/

This is my .pro file

```
QT       += core gui opengl

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = SFML_MapEditor
TEMPLATE = app

SOURCES += main.cpp\
        MainWindow.cpp

HEADERS  += MainWindow.h

FORMS    += MainWindow.ui

INCLUDEPATH += "C:\VsIncludes\SFML\SFML-2.3.2\include"
DEPENDPATH += "C:\VsIncludes\SFML\SFML-2.3.2\include"

LIBS += -LC:\VsIncludes\SFML\SFML_QT\SFMLLIBS\

CONFIG(debug, release|debug): LIBS += -lsfml-window-d -lsfml-audio-d -lsfml-graphics-d -lsfml-main-d -lsfml-system-d -lsfml-network-d
CONFIG(release, release|debug): LIBS += -lsfml-window -lsfml-audio -lsfml-graphics -lsfml-main -lsfml-system -lsfml-network

```

Here is the project files where the binaries are read

Now my problem lies in the loadFromFile() function. When I do run the program with the loadFromFile() function it will immediately give me this error:

C:\Users\Alex\Documents\QT\_Projects\SFML\_MapEditor\main.cpp:14: error: undefined reference to \`\_imp\___ZN2sf7Texture12loadFromFileERKNSt7\__cxx1112basic\_stringIcSt11char\_traitsIcESaIcEEERKNS\_4RectIiEE'

However when I run the program without loadFromFile() it will run without a hitch

My main.cpp file

```
#include "MainWindow.h"
#include <iostream>
#include <QApplication>
#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>
#include <QDebug>

void SFML_Test()
{
    sf::RenderWindow window(sf::VideoMode(800, 600), "HELLO SFML");

    sf::Texture tex;

    if (!tex.loadFromFile("Default_Texture.png"))
    {
        return;
    }

    sf::Sprite sprite(tex);

    while (window.isOpen())
    {
        sf::Event e;

        while (window.pollEvent(e))
        {
            if (e.type == sf::Event::Closed)
            {
                window.close();
            }
        }

        window.clear();
        window.draw(sprite);
        window.display();
    }
}

int main(int argc, char *argv[])
{
    /*
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
    */

    SFML_Test();

    return 0;
}

```

# Answer
> 1 votes
Turns out that I was using sfml 2.3.2 which I guess isn't fully compatible with qt creator so I tried sfml 2.0 and it suddenly worked.

Here is a link to a video describing how to link SFML to Qt Creator: https://www.youtube.com/watch?v=VWvD4mUpyfU

---
Tags: c++, 2d, sfml, qt
---


# Question
Title: Joint based destructible physics (like Armadillo Run)
I've implemented a destructible terrain system like Worms before (where weapons create holes in the terrain), but for the game I'm designing I want something more like Armadillo Run: https://www.youtube.com/watch?v=4JoPlcyxxb4 where everything is made from individual parts connected by physics joints.

I've figured out how to make a chain of planks using Unity's joints that can fall, swing off each other, bend if unsupported, and break at the joints. But I can't think of how to make planks break instead of the joints. There's an example of what I want at 2:25 in the video, where the plank on the right breaks (not the joints, but the actual plank itself). Obviously I'd just have to destroy the plank object, but how do I decide when to do that?

I'm using the Unity engine (2D physics), but I'd be perfectly happy to implement something myself if someone can direct me to some research on the subject or anything else to help me get started.

# Answer
> 1 votes
If you apply too much force to a plank, then the connecting joint is going to break.

So that should be your indicator that the plank needs to be destroyed. At first, I'd just destroy the plank when the joint of the plank breaks. I think that's pretty much what's happening in the video you linked to.

You could further refine the process by doing something like this:

Keep a list of all your joints and store their current reaction force (`GetReactionForce`) with each update.

Whenever a joint breaks, you'll usually have two game-objects involved (the one with the joint and the one that's connected to the joint). Find all the joints attached to each GameObject and average the force applied to all joints. Then destroy the GameObject that has the highest average force on its joints.

---
Tags: unity, box2d, joints
---


# Question
Title: Game Maker - Create Instance When Health Is 0
I have five objects: `obj_Boss`, `obj_bossHealth`, `obj_GameOver`, `obj_BtnOK`, and `obj_rec2`.

This is what I want. When `obj_Boss` has no more health, `obj_GameOver` and `obj_BtnOK` will appear.

**This is my first method:**

In `obj_bossHealth`, I have these events:

> Create Event: set var `global.bossHealth to 100`
>
> Draw Event: draw\_healthbar

In `obj_Boss`, I have these events:

> Collision with `obj_rec2`: set var `global.bossHealth relative to -1.5`; destroy the instance (other)
>
> No More Health: create instance of `obj_GameOver`; create instance of `obj_BtnOK`

**This is my second method:**

In `obj_bossHealth`, I have these events:

> Create Event: set var `global.bossHealth to 100`
>
> Draw Event: draw\_healthbar
>
> Step Event: if `global.bossHealth is equal to 0` then create instance of `obj_GameOver` and create instance of `obj_BtnOK`

In `obj_Boss`, I have these events:

> Collision with `obj_rec2`: set var `global.bossHealth relative to -1.5`; destroy the instance (other)

**The result of both methods:**

`obj_GameOver` and `obj_BtnOK` won't appear. How can I fix this? Please explain your answer. Thanks.

I add some images: method1 method2

# Answer
> 1 votes
The reason your `obj_GameOver` and `obj_BtnOK` won't appear is because you are checking the wrong variable. The *No More Health Event* is triggered by checking for the value of variable `health`. From the YoYo Documentation:

> **No More Health**
>
> GameMaker: Studio has a built-in health system, which, like Lives above, is basically a global scope variable that is created for you at the start of a game. There are actions to set and change the health variable as well as to draw a health-bar, with code available to change them too should you prefer to use GML. This event is triggered whenever the health becomes less than or equal to 0. It is typically used to reduce the number of lives or to restart the game or room.

Since in the first method you are working with the variable `global.bossHealth`, which was defined by *you*, instead of `health`, a *built-in* variable modeled around the GM:S framework functionalities, there's absolutely no chance your *No More Health Event*s will be triggered. If you set `global.bossHealth` to 0 or less, `health` will still be 100 or somewhat else.

Being the `health` variable in unique wherever you read/write it from, that's why I encourage your second method.

### It's just a math matter

The reason your buttons won't appear is just a mathematical issue: if your `bossHealth` starts from 100 and you subtract 1.5 per hit, we'll get to the point where the `obj_Boss` has been hit 66 times. Then, the health amount the Boss lost is:

> 66 \[hits\] * 1.5 \[damage per hit\] = 99 \[damage\]

At this point, its health will be:

> 100 \[health\] - 99 \[damage\] = 1 \[health\]

And here comes the trouble: if the Boss is hit again, his health will be:

> 1 - 1.5 = -0.5

But since you are checking for `global.bosHealth` to be equal to 0, this condition will never evaluate to true.

### The solution

This is *VERY* simple: just edit your condition for `global.bossHealth` value: don't just check if it is equal to zero, but **less than or equal to**.

In the *Step Event* of object `obj_bossHealth`, your code would look as follows:

```
// Step event - Check health
if (global.bossHealth <= 0)
{
    instance_create(x1,y1,obj_GameOver);
    instance_create(x2,y2,obj_BtnOK);
}

```

Here, `x1`, `y1`, `x2`, and `y2` are meant to be set to the right values for your objects.

# Answer
> 1 votes
I haven't worked in GameMaker Studio before but just from looking at your screenshot it appears that when obj\_rec2 collides with obj\_Boss it is literally setting bossHealth to -1.5, so that after the collision it bossHealth = -1.5. Therefore bossHealth is never reaching 0 to create instances of obj\_BtnOK and obj\_GameOver

---
Tags: game-maker, instancing
---


# Question
Title: How do I let the an object know where in a matrix it is?
**Game Engine:** Gamemaker Studio

**Situation:** I want 6 rows of 6 objects, each housed in a cell of a 6x6 matrix. However, this presents the problem of the matrix knowing what's in the cell, but the object in the cell doesn't know where in the matrix it is.

Reason why this is a problem is because I want to have events in the housed object's events that check adjacency to other objects in the matrix.

**Question:** How do I let the an object know where in a matrix it is?

Do I just need to have 2 variables in the object, which is set to the object's position in the matrix, or is there an easier way to do this? Or a better way, I guess.

Or perhaps the question is, is there a better way than the way I am doing?

**How I'm using it Right Now:**

`//check if the last link in the chain is adjacent to the target link`

```
     //includes diagonals
     if(obj_Handle_Links.Last_Link.Matrix_Location_y = (Matrix_Location_y-1)
     || obj_Handle_Links.Last_Link.Matrix_Location_y = (Matrix_Location_y+1)
     || obj_Handle_Links.Last_Link.Matrix_Location_x = (Matrix_Location_x-1)
     || obj_Handle_Links.Last_Link.Matrix_Location_x = (Matrix_Location_x+1))
    {
        obj_Handle_Links.Match_Length +=1; //because we're increasing the length
        image_index = 1; //this should highlight
        //add to link - implement later
        obj_Handle_Links.Last_Link = id; //makes it so this is what's seen as last link
    }

```

# Answer
> 1 votes
**Original**

Your original solution is perfectly fine, you can simply tell your game objects where in the matrix they are using variables...

**However...**

If there is a method being called that your game objects update from you could also pass their position in the matrix through to this method using parameters.

---
Tags: game-maker
---


# Question
Title: Why do my sprites stutter when I move them too quickly?
**The Problem**
I have some sprites animating across my screen (some spaceships). I alter their X coordinates (like -5, for animation) in my game loop.

I want the animation to happen faster, however when I alter their coordinates too much (like position-=5 each time), the animation becomes jumpy and stutters.

For example, decrementing objects xPosition by 1 = slow moving smooth animation
But, decrementing objects xPosition by 5 = faster, but choppy/stuttering animation

**What I've tried**
The only way I can think is to make my game FPS like 100 with a lower position incrementing speed, which is extremely wasteful.

My game loop is below.
(I know this isn't a great game loop, but its one of the few I understand. I also can't see how it would be a problem for this example)

```
private final int FPS = 60;
private final long TICKS = 1000/FPS; //16.67ms per update max

public void run() {
    long startTime = System.currentTimeMillis();

    while(gameRunning){

        cycleEnemies();
        repaint();

        startTime += TICKS;

        sleepTime = startTime - System.currentTimeMillis();

        //So timeout isnt negative
        if(sleepTime > 0){
            try{
                Thread.sleep(sleepTime);
            }catch(InterruptedException e){
                System.out.println("Interrupted: " + e.getMessage());
            }
        }else{
            //We're running behind!
        }
    }

}

```

And this is my cycle method:

```
    private void cycleEnemies(){
        for(Enemy e : enemyShips){
            e.setXPosition(e.getXPosition() - 5);
        }
    }

```

This is my drawing code:

```
private void drawEnemy(Graphics g){
    //Loop through enemyShips array, drawing all
    for(Enemy e: enemyShips){
        g.drawImage(e.getTexture().getImage(), e.getXPosition(), e.getYPosition(), null);
    }
}

```

# Answer
**The problem is in your game loop**

1. You are limiting your rendering fps to your game world fps. You should update your world on a fixed timestep and either leave the render timestep to vsync or limit to something like 60..
2. You're using non floating point variable types where you should be using floating point math. This adds imprecision and can cause stutering.

Your main game loop is the most important part of your game and your implementation is less than perfect here...

A possible alternative may help you here.

```
public boolean gameRunning;
public int fps, frames;
public float delta;
public int wantedFPS = 60;

public void loop(){
    gameRunning = true;

    long lastTime = System.currentTimeMillis();
    long lastFPS = lastTime;

    float fixedTimestep = 0;

    while(gameRunning){
        frames++;
        delta = (System.currentTimeMillis() - lastTime ) / 1000f;

        if(System.currentTimeMillis() - lastFPS > 1000){
            fps = frames;
            frames = 0;
            lastFPS = System.currentTimeMillis();
        }

        //Optional loop to ensure game doesn't malfunction due to the inprecise nature of floats
        if(delta < 0.01f){
            try{
                Thread.sleep(1);
            }catch(Exception e){
                e.printStackTrace();
            }
        }

        fixedTimestep += delta;
        if(fixedTimestep >= wantedFPS/1000f){
            //perform fixed update (physics etc)
        }

        //update other game logic
        //render game
    }
}

```

*This function is untested but has the general idea of how to make a good game loop*

The optional part is there in case your system proccesses the entire game loop too quickly and `float delta` ends up as 0.
> 3 votes

---
Tags: java
---


# Question
Title: Is an array in Gamemaker infinitely expandable?
Arrays in Gamemaker Studio seems to not need to have its size be declared, and infact it doesn't seem to be possible to declare a finite array.

Instead, it seems it just keeps indexing for each declaration....at least as far as I can tell. Obviously, this is limited by memory, I would presume.

**Question:** So, can I have a loop that says something like `array[i] = 0`, while increasing i for each loop through?

# Answer
It seems that after 32767 the engine will have undefined behavior. This is stated at the return length array function. Game Maker reference

However, if you ever go higher than 1000 in a array you're using it wrong.

Another important note is that when you assign a index that doesn't exist before, it will allocate memory up to that index, so it would be best if you assign first the highest value you need and then count down to zero.
> 2 votes

# Answer
Yes they are not finite and you can not set a size. So if you wan't to have an finite array you'll have to set a size in another variable
> 1 votes

---
Tags: game-maker
---


title: How to create 2D cameras in swing?

text:
# Question
Title: How to create 2D cameras in swing?
What is the best way to create a camera for a 2D platformer using swing, and I want to create a camera that moves instead of moving the background. This is because I'm going to have objects rotated by a transformer and need the camera to stay on the object whilst also allowing zooming and rotation. Any help would be appreciated.

# Answer
Swing / Java2D doesn't have a concept of a camera, but what you can do is store the transform of the camera, and apply that first before any other transforms.

Also note that you are almost certainly going to run into unpleasant performance problems if you're not using an OpenGL-based rendering system. (I speak from years of painful experience.) I would heavily recommend using eg libGDX or maybe Slick2D.
> 1 votes

---
Tags: java, 2d, camera, platformer, swing
---


# Question
Title: Multiple traversal of a component-based hierarchy
Let's say a game use a component-based hierarchy to store all of its entities. So it can have objects, characters, lights organized in some kind of tree.

When rendering the game, it needs to first render objects, then lights. So it needs to first traverse the hierarchy and render all the objects it finds, then traverse a second time to render all the lights it finds. What is a better way to do this? If the hierarchy has thousands of entities, it could be slow to traverse twice the tree.

I thought about having two lists, one containing objects to render, the second one being lights. Each time the user adds an entity to the hierarchy, it adds it to the corresponding list. This way, the game only have to traverse the object list then the light list, without traversing useless entities.

What is the best option?

# Answer
You shouldn't have a *hierarchy*. One reason component-based approaches are popular right now is because it's easy use them to separate the association of a component with an entity (the "hierarchy") with the actual concrete storage of the components such that the storage can be contiguous and cache-friendly for processing.

Ideally, you'd have a renderable component and a processor/system that holds all those components. Because that system knows that the rendering must be done in two phases, it can keep the components in two otherwise-contiguous arrays. Then it can simply blast through the first array, and then the second array, issuing the appropriate calls to the real, underlying renderer to first draw the objects and then lights, or whatever else you need.

In an entity system, what hierarchy exists is usually only one level deep: entities have components, but components don't have other components. In any case, you don't want to be traversing components for processing by looking at each entity and then looking at each of its children (components) in that hierarchy. As you said, it's not very efficient.

Divorce the conceptual association of your entities and their child component references from the physical storage of their components and you solve the problem.
> 1 votes

---
Tags: entity-system, optimization
---


# Question
Title: How to Check and Destroy "linked" gems quickly efficiently
**Engine:** Gamemaker Studio

**(simplified) Situation:** I have a 6x6 board (at this moment) stored in a 2D matrix, a mechanism for linking adjacent squares, similar to Puzzlecraft, and a button that confirms the link - adding the resources, and destroying the instances of the squares, then moving existing squares and generating new ones.

**Question:** Is there a way to instantly go through the linked squares, and not just check for any instances marked as `linked = true`.

Efficiency is in all likelihood not a true concern, especially on this tiny scale, but I'd like to know for the sake of self-improvement more than anything.

**Idea for Solving it:** I've thought of a way that may be fairly lightweight and quick, I don't know if it is though:

Once a square is added to the link, put the square's position in the matrix in a separate array (one which has 36 slots, in case the entire board is linked). Then once the button to confirm is pressed, it goes up from the bottom of the array, until it reaches a `null` or `-1` value - destroying and setting the value of this array at the appropriate position to `null` or `-1`.

**Question on the idea:** Would this work? How would I store the square's position in the matrix in this array? Would I need to make the array 2D so that it can hold both the x and y position of the square \[ie. 0 to 5\]?

# Answer
> 1 votes
Your own suggestion sounds exactly what I would do. Note that you are not limited to store just ints or strings in an array. Make an array of objects: Basically you create a game cell object that holds information you would need like position, type and so on.

This cell object is then added to the 1D array:

```
 linkedcells[i]  =  instance_create(x,y,obj_cell)
 linkedcells[i].type  =  1

```

# Answer
> 0 votes
Stacks would actually, in all likelihood, be easier (and faster, so I've heard) than an array. Also, it's got really useful tools like `clear` which is great when you just want to negate the entire link.

Well, it would be if simply clearing the internal link was all you needed to mark everything as "not linked". You'd probably still want to go 1 by 1 and by using the `pop` function for stacks, so you can do all the appropriate stuff...but it's still more convenient than having to track and compare to say the `Link_Length`, and then count up to / down from that number.

---
Tags: optimization, game-maker
---


# Question
Title: Detect collision with static collider only
Is this possible to detect collision with static colliders only I check it is not working. I dont want to use rigidbody or character controller with my box collider.

# Answer
> 1 votes
Static colliders shouldn't collide with one another, and they should not be used on objects that will move (such as a player). You may want to give more information about what it is that you are doing, but for most purposes, two static colliders will never hit. If one object is moving, it should have a rigidbody if physics are applied. Otherwise it should use a non-static collider.

Edit: thanks @philipp

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


title: who programs attack speed in a game

text:
# Question
Title: who programs attack speed in a game
Is it the game designer that programs attack speed and attack values for the player in a game, or does the artificial intelligence programmer program attack speed and attack values for the player in a game.

# Answer
The concept of attacks and varying speeds would be implemented by a gameplay or engine programmer typically. The designer would be the one deciding if those concepts should exist and also on the particular values of each attack.
> 1 votes

---
Tags: game-design
---


title: Game crashes when sound is finished

text:
# Question
Title: Game crashes when sound is finished
I'm trying to code a simple audio playback test game (which will be used in my actual project), and everything works fine, except for the fact that after the audio has finished playing, the game will crash with a 'stopped working' dialog.

Here's the code that's used to load and play the audio. Regardless of whether it's in LoadContent or not, the crash still happens.

```
List<SoundEffect> soundEffects;
FileStream soundStream = new FileStream("test.wav", FileMode.Open);
soundEffects.Add(SoundEffect.FromStream(soundStream));
soundStream.Dispose();
SoundEffectInstance soundeffectinstance = soundEffects[0].CreateInstance();
soundeffectinstance.Volume = 0.35F;
soundeffectinstance.Play();

```

The audio file is a 2 seconds long beep. The game works fine, and the graphics draw fine too. I should also mention that the SoundEffectInstance's State property doesn't seem to work properly as well.

I'm using **Visual Studio 2010** with .NET 4.0, and **MonoGame framework 3.4.0.459** (MonoGame.Framework.WindowsDX, from NuGet), because that's the only thing I can use without Visual Studio telling me to upgrade to .NET 4.5.

I am unable to debug, as when I debug, the 'stopped working' dialog appears again (for some reason I cannot debug any projects directly through the Debug option in VS), and the debugger hook gets confused.

Is this an upstream issue, or is there just something wrong with the way I load the audio file? (P.S. I'm not using the Content Pipeline due to the nature of my project)

# Answer
> 0 votes
Fixed after updating MonoGame to 3.5 and .NET to 4.5. Apparently it was a MonoGame 3.4 issue that was causing the problem. It's a pity though, because that means I can't support Windows XP users anymore.

---
Tags: c#, xna, directx, monogame, visual-studio
---


# Question
Title: Unity 2d square position not lining up with its size
I want to have one square that rests at the Unity 2d coordinates (5,5). Using `transform.localScale` I make the square be 3 units by 3 units large. So I thought that if I made another square that is the exact same except it is at the coordinate (8,5), the second square would be directly to the right of the first one, touching it. But instead, the square spawns a bit more to the right than it should, implying that the size x,y units are smaller than the position x,y units. Any way I can solve this problem, and have both touching? Thank you.

Code for placing the squares (tileHeight = 3 and tileWidth = 3):

```
GrassTile.transform.localScale = new Vector3(tileWidth, tileHeight, 0f);
Instantiate (GrassTile, new Vector3 (0f, 15f, 0f), Quaternion.identity);
Instantiate (GrassTile, new Vector3 (3f, 15f, 0f), Quaternion.identity);

```

Screenshot of what it looks like, as well as what the prefab looks like:

Screen shot of the grassTile stats:

# Answer
Your image is 64x64 and your Pixels To Units setting is 100.

That means at native size your Sprite is 64/100 = 0.64 units wide.

To make this 3 units wide, you'd need to set your local scale to 3/0.64 = 4.6875

Or, you can change your Pixels to Units setting to 64, then your sprite will come in at exactly 1x1 unit, and a local scale of 3 will make it 3 units wide, as you originally expected.
> 1 votes

---
Tags: unity, c#, 2d, coordinates
---


# Question
Title: Permanent Adjacency Problem [Gamemaker Studio]
**Situation:** I started work on a pet project recently. It's a bit like Puzzlecraft, or Bejewled, but slightly different. You click one gem, as we'll call it, and if it's the first in the link, then it's added to the link.

That works well enough. However, the problem comes in that after that, in order to link, it must be adjacent to the last link... and somehow, something goes wonky. The first time you click something not adjacent, it doesn't get put on the link...or it at least doesn't highlight. It also doesn't run across any of my `show_message` popups - aside from "second else".

Yet, somehow, it seems to act as though that one you clicked on was the `Last_Link`, after that point...permanently...which shouldn't even be possible...

So, if you click adjacent to the one that got to "second else", it will still consider that "adjacent", even if it's across the entire board from the last one that actually highlighted.

And this permanent allocation of `Last_Link` can happen for every gem on the board. At the same time. (Note: It does deallocate once you restart the program.)

This DOESN'T make sense!

I have no step events (yet). This is also the only left click event in the game at the moment. Every other event is a create or game start event, mostly for initialization purposes. So I have no idea what is doing this. Can someone tell me?

**Left Click Event for the Gems**

```

if (obj_Handle_Links.Match_Length = 0) //if this would be the first in the link
{
    show_message("first to link");
    obj_Handle_Links.Match_Length +=1; //because we're increasing the length
    image_index = 1; //this should highlight
    //add to link, later
    show_message( Matrix_Location_y );
    obj_Handle_Links.Last_Link = id; //makes it so this is what's seen as last link
    show_message(obj_Handle_Links.Last_Link.Matrix_Location_y);
}
else
{
    // show_message("first else");
    //check if the target is the same type as the last Link's type
    if(obj_Handle_Links.Last_Link.Type = Type &&
        //check if the last link in the chain is adjacent to the target link
        //includes diagonals
         (obj_Handle_Links.Last_Link.Matrix_Location_y = (Matrix_Location_y-1)
         || obj_Handle_Links.Last_Link.Matrix_Location_y = (Matrix_Location_y+1)
         || obj_Handle_Links.Last_Link.Matrix_Location_x = (Matrix_Location_x-1)
         || obj_Handle_Links.Last_Link.Matrix_Location_x = (Matrix_Location_x+1)) )
        {

            show_message( Matrix_Location_y );
            //show_message("third if");
            obj_Handle_Links.Match_Length +=1; //because we're increasing the length
            image_index = 1; //this should highlight
            //add to link, later
            obj_Handle_Links.Last_Link = id; //makes it so this is what's seen as last link
           show_message(obj_Handle_Links.Last_Link.Matrix_Location_y);
         }
    else{

        show_message("second else");
        //play sound that link failed
    }
}

```

# Answer
> 0 votes
I found the reason why it wasn't working as expected - it's because it's checking if it's within the entire row above and below, as well as the entire column to the left and right.

It was sheer coincidence (due to the small size of the map), that it seemed to be adjacent to a clicked object that was previously clicked on that wasn't assigned to a link.

---
Tags: game-maker, debugging, bug
---


title: Game Maker - Turn On/Off Sound

text:
# Question
Title: Game Maker - Turn On/Off Sound
**What I have**

I have two rooms: `rm_home` and `rm_options`. I have a sound: `snd_Bgm`. And, I have three objects: `obj_bgm`, `obj_BtnOnClicked`, and `obj_BtnOffClicked`.

**What I want is very simple**

Player can turn on/off the `snd_Bgm`.

**What I have done**

In `obj_bgm`, I have these events:

> Create Event: set var `global.sound to 1`
>
> Room Start: stop sound `snd_Bgm`; if `global.sound == 1` then play sound `snd_Bgm`

In `obj_BtnOnClicked`, I have these events:

> Left-Pressed Event: play sound `snd_Bgm`; set var `global.sound to 1`

In `obj_BtnOffClicked`, I have these events:

> Left-Pressed Event: stop sound `snd_Bgm`; set var `global.sound to 0`

I put `obj_BtnOnClicked`, and `obj_BtnOffClicked` in `rm_options`, which can be accessed from `rm_home`. Then, I put `obj_bgm` in `rm_home`.

**This is the problem**

When game start, it will show `rm_home` and plays the `snd_bgm`. I go to `rm_options`, then click the `obj_BtnOffClicked` to turn off the sound, so the sound is off. But, when I go back to `rm_home`, the sound is on again.

**What I think**

I shouldn't put `Create Event: set var global.sound to 1` in `obj_bgm`, because when `rm_home` start, it takes the value of var `global.sound` from *Create Event*. But, if I put *Create Event* in `obj_BtnOnClicked` or `obj_BtnOffClicked`, it shows a *Get Error*.

What should I do? Please explain your answer. Thanks.

# Answer
> 1 votes
I do believe that each time you enter a room, you create a new instance of obj\_bgm, unless it is a persistent object. So, you are constantly setting global.sound to be 1 when you enter the room.

If it is not a persistent object, change it to be one, and it should fix the problem. (This should be as simple as checking the box that says "persistent" to the right of the the events window.)

---
Tags: game-maker, sound
---


# Question
Title: How to find starting velocity for a body thrown by an angle when known distance it must pass?
From course of mechanic, we know, that to find distance, passed by a body thrown by an angle, we need to use that formula:

Sy(t) = V0 * sin(angle) * t - (g*t*t) / 2;
Sx(t) = V0 * cos(angle) * t;

My question is, how do we find the right starting velocity, if we know the distance body must pass (Sx and Sy) and angle (let's say, it's 45 degrees)?

I tried to derive formula, but it seems to be wrong:

V0 = ( Sy(t) + (g * t * t) / 2 ) / sin(angle\_in\_rads);

# Answer
Your starting velocity is a vector, not a scalar (to be pedantic, `V0` is actually the *speed*, i.e. the magnitude of the velocity).

If `v0x= v0*cos(a)` and `v0y= v0*sin(a)`, then your analytical solution for the positions is correct: `sx(t) = v0*cos(a)*t` and `sy(t) = v0*sin(a)*t - g*t^2/2`.

Your question is ambiguous, but assuming you want to find the launch speed and angle that allows you to reach a maximum height (`sy_max`) and a maximum range (`sx_max`), then this is how to approach it:

* the maximum height is attained when the instantaneous velocity attains a null vertical component. Since `vy = v0*sin(a) - g*t` then `t_sy_max = v0*sin(a)/g`. Since you know `sy_max = sy(t_sy_max)`, you have found one equation.
* the maximum range is attained when `sy` becomes zero (and `t > 0`, naturally). So you start with the equation `0 = v0*sin(a)*t_max - g*t_max^2/2` from where you find tour `t_max = 2*v0*sin(a)/g`. Due to the symmetry of the parabola, you can confirm that `t_max = 2*t_sy_max`. You end up with the second equation, mainly `sx_max = sx(t_max)`.
* Both equations that you have written for the known `(sx_max, sy_max)` input pair are assembled into system of equations that is nonlinear (trigonometric in this case). You should be able to work out the values of `v0` and `a` from it.
> 3 votes

---
Tags: physics
---


# Question
Title: UNITY : I want to make my UI text fade in after 5 seconds
I know this question has been asked and asked but none of the topics i visited gave me an answer. I'm making a game programmed in c# where you control a boat and i want my UI to appear smoothly by fading in after X seconds. May someone help me?

# Answer
> 7 votes
Here is a rather simple extension class that you can use.

```
public static class GraphicExtensions
{
   /// <summary>
   /// Fade methods forUI elements;
   /// </summary>
   /// <param name="g"></param>
   public static void FadeIn(this Graphic g)
   {
    g.GetComponent<CanvasRenderer>().SetAlpha(0f);
    g.CrossFadeAlpha(1f, .15f, false);//second param is the time
   }
   public static void FadeOut(this Graphic g)
   {
    g.GetComponent<CanvasRenderer>().SetAlpha(1f);
    g.CrossFadeAlpha(0f, .15f, false);
   }
}

```

To use it do something like this :

```
public class FadeTest : MonoBehaviour
{
  void Start()
  {
    gameObject.GetComponent<Graphic>().FadeIn();
  }
}

```

Make sure that you include the namespace where you have put the static extension class and that you have attached this script to a UI element.

# Answer
> 4 votes
Another approach, non-programmatically:

1. Add animator component to your Text element. Create an animator asset for it, or:
2. Select your text and Ctrl+6. In the opened window, click 'Create animation', that will add Animator component and Animator controller asset.
3. Click add property and select Text-\>Color.
4. Click on Color.a
5. Click on Curve editor tab.
6. You see two keys. Select leftmost key and right-click it, select edit keys. In the appeared box type Time '0' and Value '0'.
7. Select rightmost key, right-click. edit keys, type Time '1' and value '1'.
8. Set a condition for a transition from Idle state to FadeIn state in animation controller if you need it. also, you should add IdleState and make default transition to that state before you jump into FadeIn state.

# Answer
> 2 votes
You can use a coroutine to change the alpha. You'd attach a `CanvasGroup` component to the UI's container object. Then adjust the alpha like so:

```
public class Fade : MonoBehaviour {

public float changeTimeSeconds = 5;
public float startAlpha = 0;
public float endAlpha = 1;

float changeRate = 0;
float timeSoFar = 0;
bool fading = false;
CanvasGroup canvasGroup;

void Start()
{
    canvasGroup = this.GetComponent<CanvasGroup>();
    if(canvasGroup == null)
    {
        Debug.Log("Must have canvas group attached!");
        this.enabled = false;
    }
}

public void FadeIn()
{
    startAlpha = 0;
    endAlpha = 1;
    timeSoFar = 0;
    fading = true;
    StartCoroutine(FadeCoroutine());
}

public void FadeOut()
{
    startAlpha = 1;
    endAlpha = 0;
    timeSoFar = 0;
    fading = true;
    StartCoroutine(FadeCoroutine());
}

IEnumerator FadeCoroutine()
{
    changeRate = (endAlpha - startAlpha) / changeTimeSeconds;
    SetAlpha(startAlpha);
    while (fading)
    {
        timeSoFar += Time.deltaTime;

        if (timeSoFar > changeTimeSeconds)
        {
            fading = false;
            SetAlpha(endAlpha);
            yield break;
        } else
        {
            SetAlpha(canvasGroup.alpha + (changeRate * Time.deltaTime));
        }

        yield return null;
    }
}

public void SetAlpha(float alpha)
{
    canvasGroup.alpha = Mathf.Clamp(alpha, 0, 1);
}

```

}

---
Tags: unity, c#, gui, text
---


title: snap an object to another object?

text:
# Question
Title: snap an object to another object?
so I have some walls which are cubes stretched along a direction.and I have some windows and doors that are suppose to snap to a wall and don't let go until the desired location is out of the snapping range.and in the meantime I want the Objects to move along the wall but never detach from it.

if I wasn't clear enough let me know.

# Answer
> 1 votes
I have dabbled in some dragging and snapping behavior before. This script allows you to drag a cube, changes its color when its near the object to snap to and then snaps it to the right axis when you release the mouse. Sadly it has no code for dragging the object while its snapped to the wall but it might be a good starting point. Here is the code :

```
using UnityEngine;
using System.Collections;

public class Snap : MonoBehaviour {

  public  string partnerTag;
  public  float closeVPDist = 0.05f;
  public float farVPDist = 1;
  public  float moveSpeed = 40.0f;
  public  float rotateSpeed = 90.0f;

  private Vector3 screenPoint;
  private Vector3 offset;
  private bool isSnaped;
    Color color = new Color(1, 0, 0);

    float dist = Mathf.Infinity;
    Color normalColor;
    GameObject partnerGO;
    // Use this for initialization
    void Start () {
        normalColor = GetComponent<Renderer>().material.color;
        partnerGO = GameObject.FindGameObjectWithTag(partnerTag);
    }
    void OnMouseDown()
    {
        screenPoint = Camera.main.WorldToScreenPoint(transform.position);
        offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
        Cursor.visible = false;
    }
    void OnMouseDrag()
    {
        //transform.SetParent(null);
        Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
        Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
        transform.position = curPosition;
        Vector3 partnerPos = Camera.main.WorldToViewportPoint(partnerGO.transform.position);
        Vector3 myPos = Camera.main.WorldToViewportPoint(transform.position);
        dist = Vector2.Distance(partnerPos, myPos);
        GetComponent<Renderer>().material.color = (dist < closeVPDist) ? color : normalColor;
    }
    void OnMouseUp()
    {
        Cursor.visible = true;
        if (dist < closeVPDist)
        {
            transform.SetParent(partnerGO.transform);
            StartCoroutine(InstallPart());
            isSnaped = true;
        }
        if( dist > farVPDist)
        {
          //  transform.SetParent(null);
        }
    }
IEnumerator InstallPart()
    {
        while (transform.localPosition != Vector3.right || transform.localRotation != Quaternion.identity)
        {
            transform.localPosition = Vector3.MoveTowards(transform.localPosition, Vector3.right, Time.deltaTime * moveSpeed);
            transform.localRotation = Quaternion.RotateTowards(transform.localRotation, Quaternion.identity, Time.deltaTime * rotateSpeed);
            yield return new WaitForEndOfFrame();
        }
    }
}

```

# Answer
> -1 votes
As far as I know Unity has only has snapping to grid by holding down `Ctrl` (`Cmd` on mac).

Unity has a tutorial for it here

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


title: How to calculate delta time with SDL?

text:
# Question
Title: How to calculate delta time with SDL?
I have heard that you can calculate delta time with two functions called SDL\_GetPerformanceCounter and SDL\_GetPerformanceFrequency. I'm not sure how they work completely, but I heard it is a bit similar to using SDL\_GetTicks()

```
    Uint64 NOW, LAST;
    double deltaTime = 0;

    while (somebool)
    {
       LAST = SDL_GetPerformanceCounter();
       NOW = SDL_GetPerformanceCounter();
       LAST = NOW;

       deltaTime = (NOW - LAST) / (double)SDL_GetPerformanceFrequency();

       /**Rendering**/
    }

```

I have this code but whenever I print out deltaTime or try to use it it always equals some really random and insane numbers. Is this correct?

# Answer
> 21 votes
When reading the code-example provided by SDL on the SDL\_GetPerformanceFrequency I could easily find out how you could calculate a deltatime using these functions.

It should basically come down to this for you:

```
Uint64 NOW = SDL_GetPerformanceCounter();
Uint64 LAST = 0;
double deltaTime = 0;

while (somebool)
{
   LAST = NOW;
   NOW = SDL_GetPerformanceCounter();

   deltaTime = (double)((NOW - LAST)*1000 / (double)SDL_GetPerformanceFrequency() );

   /**Rendering**/
}

```

**Note: the first frame will always have a deltatime of 0 or something very close to it**

This should fill the value deltaTime in milliseconds, this can easily be converted to seconds by multiplying the final result with 0.001.

Reference: https://wiki.libsdl.org/SDL\_GetPerformanceFrequency

# Answer
> 5 votes
They way I've gone about calculating the delta time has been via `SDL_GetTicks()`:

```
struct Clock
{
    uint32_t last_tick_time = 0;
    uint32_t delta = 0;

    void tick()
    {
        uint32_t tick_time = SDL_GetTicks();
        delta = tick_time - last_tick_time;
        last_tick_time = tick_time;
    }
};

```

Then I simply tick a `Clock` instance in the main loop.

---
Tags: c++, algorithm, sdl
---


title: How to stack sprites?

text:
# Question
Title: How to stack sprites?
I am currently working on a 2D game in Unity, I am using Animation Controllers / Animators for the different slots of armor on the character. The scripts set the Animation to the player object and that seems to work out alright for the most part.

However when I walk long distances without stopping it seems like the armor tends to drift away from the player object and I haven't been able to find out why.

```
// This will update the player and then update all his inventory to match his position.
public void UpdateMovement()
{
    if (IsActive == true)
    {
        float input_x = Input.GetAxisRaw("Horizontal");
        float input_y = Input.GetAxisRaw("Vertical");
        bool playerMoved = false;

        Vector2 movement = new Vector2(input_x, input_y);
        float delta = Time.deltaTime;

        if (movement != Vector2.zero)
        {
            _animator.SetBool("IsWalking", true);
            _animator.SetFloat("x", input_x);
            _animator.SetFloat("y", input_y);
            playerMoved = true;
        }
        else
        {
            _animator.SetBool("IsWalking", false);
            playerMoved = false;
        }

        PlayerController.transform.position += new Vector3(input_x, input_y, 0).normalized * delta;
        Inventory.UpdateMovement(input_x, input_y, delta, playerMoved, PlayerController.transform.position);
    }

   // This code is for each slot to update it's position.
   public void UpdateMovement(float x, float y, float time, bool isWalking, Vector3 pos)
    {
        _animator.SetBool("IsWalking", isWalking);

        if (isWalking == true)
        {

            _animator.SetFloat("x", x);
            _animator.SetFloat("y", y);
        }

        _animator.transform.position += new Vector3(x, y, 0).normalized * time;

        // _animator.transform.position = pos;
    }

```

So my question is, what is the best approach for layering armor sprite animations on a player in Unity 5?

# Answer
> 1 votes
Depending on how many potential pieces of armour a player can get throughout your game, it may be best to have a parent Game Object that contains both the player sprite and all of the armour they could ever have. Rather than moving the player sprite itself, you would then move the parent object (effectively this can be done with your player controller), and the armour will move with it.

All you need to do then is enable only the visible armour pieces. For exampole, your hierarchy could look like this:

```
- Player_Controller
   - Player_Sprite
   - Armour_Holder
       - Helmet_1
       - Helmet_2
       - Chest_plate_1
       - Chest_plate_2
       - Boots_1
       - Boots_2

```

For animation, you can either keep track of the enabled objects and their animators, or you can use a single animation controller with multiple layers and change the layer weight depending on what is being worn. If you don't want a seperate state machine for each layer, you can sync them

---
Tags: unity, unityscript
---


# Question
Title: Can I include social networks' name and logo in game credits without incurring in legal issues?
I'm planning to release an alpha version of a video game I'm working on as a personal project. I'm also creating a "Credits" section, that is meant for me to give credit to used sources, and to other peoples whose work I've used, edited, or got inspired from (with their permission, of course); and obviously, my own name.

I'd also like to include links to social network pages, such as my Twitter profile, a YouTube channel, and eventually a GitHub page. As an indie developer, I want people who play my game to have the chance to contact me, tell me their impressions about my game(s), and stay updated on my progress as development goes on. It's another way to receive feedback and reach even more people.

I wonder if mentioning the names "Twitter", "YouTube", "GitHub", and any other, and including their original logo or an edited version, is somehow possible and/or allowed - perhaps including some sort of clause - and what are the limits I'm subject to when dealing with trademarked names and logos under copyright.

# Answer
> 3 votes
Usually you are permitted to do this, provided you comply with the guidelines set forth by the owner of the relevant trademark or copyright. But you'll generally need to look up the specifics for each logo or name you want to use. While there are commonalities in how most companies will permit you to use their logos ("don't change it, just use it to link to us, et cetera"), there may be specific concerns a company has with how their marks are presented.

Fortunately this isn't too hard to find, usually. Most companies will have a section on their website concerning how you are permitted to use their trademarks and related works. The relevant terms to search for are usually something like "brand assets," "brand use," "press kit," and so on.

For example:

# Answer
> 0 votes
I'm a not a lawyer and this should not be considered legal advice. If you just google for example 'youtube logo copyright' you get a good deal of information on the subject. As far as I know if you use the logos for a so called 'social line up' you need no special permission, but if for example a character in your game goes to Facebook in the game itself then you need to fill some permission forms to get the approved brand assets.

---
Tags: legal, copyright, trademark
---


# Question
Title: Handling input through callbacks or through game loop?
I've tried to figure out how to handle player input properly, but without luck so far.

As far as I have figured out, I can either:

> Call the respective methods directly through the callback fired when an input event is detected.

Or

> Save the input in an array and detect it through my main loop.

I would like some thoughts on this in terms of if there is any restrictions/benefits using one over the other.

# Answer
If you handle input directly from the OS's event callback (or similar platform events), you generally only have access to the data the OS gave you for that event. That data usually only pertains to the immediate input action (pressing *this* key or moving the mouse on *that* axis, and maybe some information about what modifiers were down). This can make it difficult to properly translate to handling your game's input if your game has more complicated inter-relationships with other input state.

If you instead do you input handling in your main update loop body via cached input state, you have access to all of that information. You may also more easily have access to information that lets you determine if a key is "still down" in a useful way (OS input events may be biased by key repeat delay).

Frankly, I think you should support both. Certain types of input lend themselves to being more easily handling with the first option, others with the second. Possibly even within the same game.

You can implement the second option in terms of the first; listen to input events from the OS or platform and in response, cache that somewhere for your main update loop to handle later. You can also implement a method of letting you game register callback hooks that you fire in response to those platform events, after you have cached the appropriate state.

That way, your game code can handle the input in whichever way makes the most sense for it.
> 4 votes

# Answer
Whether you handle input through callbacks or in the game loop have their advantages and disadvantages:

* **Using callbacks:** this method make sure to detect any key the user press ,or any other form of input. Being an asynchronous event, any callback is fired at any time, granting real-time input detection. *CONS:* user input may affect your simulation at any possible moment, and this may lead to inconsistency between your game logic and what actually happens. It is absolutely acceptable for network packets to arrive at any moment, but their computation must not break the internal game logic.
* **Using game loop:** Being the detection of input synchronized with the game loop, the input will be detected at a given moment, like just before computing physics and rendering. *CONS*: the user expects its input to be performed almost instantly, if your game loop cycles at a quite low frequency, a player may press a key right after input detection was performed, and at the next iteration such input could even be lost, forcing the player to press that key again. And maybe, getting upset.

Then, you can implement a hybrid system to detect input: you use callbacks to detect input in real-time, and save the current input scheme in the game, in order to be performed at the right time when the game loop iterates user input again.

Still, any method becomes seamless if your engine works at a high enough sync rate. Important is, not letting the input being computed at **any** moment, in order not to break game logic. A player pressing the Jump key expects his character to jump while standing on a floor, but not being in mid-air right over the edge of a platform.
> 2 votes

---
Tags: javascript, architecture, input
---


# Question
Title: Use an instance or a class for game resources (wood,iron,gold)
So I'm making a game where you can send ships to locations to sell or buy resources like wood, iron, gold, etc.

Now I was wondering how the resources should be created in de game. I came up with 2 options

1. Create a class for each resource:

```
public class ResourceBase {
    private int value;
    // other base properties
}

public class Gold : ResourceBase {
     public Gold {
         this.value = 40 // or whatever
     }
}

```
2. Create instances of a Resource class

```
public class Resource {
    string name;
    int value;

    public Resource(string name, int value) {
        this.name = name;
        this.value = value;
     }
 }

// later on...

Resource gold = new Resource("Gold",40);

```

With the second option it's possible to fill the game resources from a resources.json file, I kinda like that structure.

New ideas / design patterns / structures are always welcome!

**EDIT:** It's a little bit like Assassins Creed Black Flag's companion app. See the resource bar on the image below

**EDIT 2:** I've done some more research on the "load items/resources from JSON file" and found this blog: Power of JSON in Game Development - Items. It shows the best of option 1 and option 2. You're still able to add functionality to each resource :)

# Answer
> 50 votes
Go with the second approach, simply due to the fact that you can introduce new resource types or items at any time without having to rewrite or update code (data driven development).

---

**Edit:**

To elaborate a bit more on why this is in general good practice, even if you're 100% sure some value won't ever change.

Let's take the console game example mentioned in the comments, because this provides a very good reason on why you shouldn't hard-code anything, unless you really have (or want) to, e.g. encryption keys, your own name, etc.

When releasing a game on consoles, these usually have to go through a review process, where the console manufacturer's own QA will test the game, play through it, look for issues, etc. This is mandatory and costs money, a lot of money. I think I've once read that a release might cost 30,000-50,000$ just for the certification alone.

Now imagine you're pushing your game for release, paying the 30,000$ and wait. And suddenly you notice that some of your game values are literally broken. Let's say you can buy iron bars for 50 gold and sell them for 55 gold.

What do you do? If you've hard-coded that stuff, you'll have to create a new update/release version, which will have to go through review once again, so worst case you'll pay once again for the re-certification! I bet Ubisoft won't mind, but for your own little indie games developer pocket… ouch!

But imagine the game would just occasionally check for updated game definitions (e.g. in the form of a JSON file). Your game could download and use the latest version at any time without requiring a new update. You could fix that imbalance/exploit/bug at any time without requiring re-certification or any other money paid. Just some minor design decision, you didn't think was worth it, just saved you a 5 digit sum of money! Isn't that awesome? :)

*Just don't get me wrong. This also applies to other types of software and platforms. Downloading updated data files is in general a lot more easy and doable for the standard user, no matter whether it's a game or some kind of application/tool. Imagine a game installed under Program Files in Windows. Your updater needs administrator rights to modify anything and you can't modify running programs. With DDD your program just downloads the data and uses it. The player might not even notice there's been an update.*

# Answer
> 30 votes
A rule of thumb is that you use different classes when objects require different code and instances of the same class when the objects only require different values.

When the resources have different game mechanics which are unique to them, it might make sense to represent them with classes. For example, when you have Plutonium which has a half-life time and Rabbits which procreate according to the fibonacci sequence, then it might make sense to have a base-class `Resource` with a method `Update` implemented as a no-op and two derived classes `HalfLifeResource` and `SelfGrowingResource` which override that method to decrease/increase the value (and maybe also include logic to govern what happens when you store both next to each other).

But when your resources are really just dumb numbers, then it makes no sense to implement them with anything more fancy than a simple variable.

# Answer
> 14 votes
I would like to add there are two extra options:
**Interface:** you can consider it if the resource class would be just a "storage" for 5 integers and each other entity would have different logic regarding resources (e.g. player spend/loot, city produces resource). In that case you might not want a class at all - you merely wanted to expose that some entity has a variable others can interact with:

```
interface IHasResources {
  int Gold { get; set; }
  int Wood { get; set; }
  int Cloth { get; set; }
  // ....
}

class Player : IHasResources { }
class City: IHasResources { }

```

in addition, this has the upside you can loot a city with exactly the same code as you would loot enemy fleet, promoting code reuse.
Downside is, implementing such interface can prove tedious if many classes implements it, so you might end up using interfaces but not for original problem, solving it with option 1 or 2:

```
interface IHasResources {
   IEnumerable<Resource> Resources { get; }
}

```

**Instances (with enum):** in some cases, it would be desirable to use enum instead of string when defining resource type:

```
enum Resource {
   Gold, Wood, Cloth, //...
}

class ResourceStorage {
   public Resource ResourceType { get; set; }
   public int Value { get; set; }
}

```

this will provide a bit of "safety", because your IDE will give you list of all valid resources when assigning it after writing the dot `ResourceType = Resource.`, in addition there are more "tricks" with enums you *might* need, like explicit Type or composition/**flags** which I can imagine to be useful when crafting:

```
[Flags]
enum Metal {
 Copper = 0x01/*01*/, Tin = 0x02/*10*/, Bronze = 0x03/*11*/
}
Metal alloy = Metal.Copper; //lets forget Value(s) for sake of simplicity
alloy |= Metal.Tin; //now add a bit of tin
Console.WriteLine(alloy); //will print "Bronze"

```

As for what is best - there is no silver bullet, but personally I would lean towards any form of instances, they might not be as fancy as interface but they are simple, doesn't clutter inheritance tree and are widely understood.

# Answer
> 2 votes
You should use option 1, which has 3 advantages:

1. It's easier to instantiate a resource - instead of having to pass the type of the resource as a parameter, you would just do, for example, `new Gold(50)`
2. If you need to give special behaviour to a resource, you can by changing it's class.
3. It's easier to check if a resource is a certain type - `resource instanceof Gold`

# Answer
> 1 votes
If your resources have no business logic of their own, or special case scenarios with how they interact with the environment, other resources (besides trade which you've covered) or the player then option two makes adding new ones very easy.

If you need to consider situations like what would happen if you mix two resources for crafting, if the resources can have vastly different properties (a bucket of water is very different than a lump of coal) or other complex economic interactions, then approach 1 is far more flexible for the engine, but not the data.

---
Tags: c#, game-design, data-structure, strategy, json
---


# Question
Title: In Unity, Change which mouse button is used to scroll in ScrollRect
I've created a new ScrollView in Unity. How do I change which mouse button is used to scroll in ScrollRect (through script or in the editor).

By default it's the left mouse button. I'd like to be able to change this to another mouse button.

I'd also like to be able to use a keyboard key and disable it altogether (via script without also disabling the scrollbars), but mainly I at least want to change it from the left mouse button.

# Answer
> 2 votes
Grab the UI source from bitbucket. Default input should be changed by changing those left mouse button input.

Or you may override those methods.

---
Tags: unity, mouse, ui-design, scrolling
---


title: Unity AddForce causing twitch

text:
# Question
Title: Unity AddForce causing twitch
Since this wasn't clear enough, I've removed even more code. It kind of defeats the purpose I was aiming for, but I guess getting any answer relevant to the problem is better than none.

What I want: A cube to leave the ground with N velocity in the negative x direction, then gravity pulls it back down.

THE SETUP:

```
void Start () {
    rb = GetComponent<Rigidbody>();
}

void Update() {

    //Jump
    if (Input.GetKeyDown("space"))
    {
        jump = true;
    }
}

```

TEST 1 (I really thought this should work as it was the solution I saw in so many google results)

```
void FixedUpdate()
{
    if (jump)
    {
        rb.AddForce(new Vector3(0, 0, -5000f));
        jump = false;
    }
}

```

TEST 2 (Added ForceMode.VelocityChange)

```
void FixedUpdate()
{
    if (jump)
    {
        rb.AddForce(new Vector3(0, 0, -5000f), ForceMode.VelocityChange);
        jump = false;
    }
}

```

TEST 3 (Tried other ForceModes)

```
void FixedUpdate()
{
    if (jump)
    {
        rb.AddForce(new Vector3(0, 0, -5000f), ForceMode./*INSERT OTHER ForceModes*/);
        jump = false;
    }
}

```

TEST 4 ( I know, changing velocity directly is a bad thing, but seeing as what I want is the cube to move upwards at a certain speed, it made sense to try it )

```
void FixedUpdate()
{
    if (jump)
    {
        var vel = rb.velocity;
        vel.z += -5000f;
        rb.velocity = vel;
        jump = false;
    }
}

```

It's been a long day, I'm sure I left some other attempts out.

Can someone explain to me why the cube is teleporting from Z=0 to Z= -2 (or some other value depending on the magnitude of the force)?

I can understand if it was something having to do with impact force not having enough time to change the velocity, but then why did the position change so drastically? And why didn't changing the velocity work, even though I know that is a bad way to go about it?

# Answer
Your problem comes from changing the velocity of the rigid body in a update. In my Spencerian this does not work at all. You have two solutions. Dont move your character with physics engine or use AddForce to move him. I changed your Fixedupdate to this and it works fine for me :

```
    void FixedUpdate()
    {
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

        Vector3 movement = new Vector3(moveHorizontal,0, moveVertical);
        _rigidBody.AddForce (movement * speed);

        if (jump)
        {
            _rigidBody.AddForce(new Vector3(0, 500, 0));
            jump = false;
        }
}

```

Note I did not add ground checks and I use `_rigidBody = GetComponent<Rigidbody>();` in the Start() method. Its a good tip not to use GetComponent in Update methods.
> 1 votes

# Answer
Whenever you are using rigidbody to control movement you are handing over control to the physics engine. Unless you really know what you are doing, you should ***not*** set velocity (or position for that matter) explicitly if you are using the physics engine. It will result in unpredictable behaviour.

If you want to jump then ou should add force with ForceMode.Impulse as per documentation: Rigidbody.AddForce

Let the gravity control when the body should start moving down. If you want classic platformer behaviour like the Super Mario games you grew up with, remember that Mario's world has a higher gravity constant than 9.82 m/s as described in this very scientific analysis

The code posted by @Uri Popov should work, but, as stated I would use ForceMode.Impulse to be able to set a jump impulse that is defined in SI-units. If you want the user to be able to control the jump height by holding the jump button for different lengths of time then you want to use a force, i.e. ForceMode.Force for a variable length of time, say 0-0.5 seconds.

## EDIT:

Ok you want the cube to get a certain velocity when jumping and then want gravity to affect it and make it go down?

Here's example code that makes that happen:

```
    void FixedUpdate()
    {
        float jumpVelocity = 5;//Meters per second
        if (jump && isGrounded())
        {
            _rigidBody.AddForce(new Vector3(0, jumpVelocity, 0), ForceMode.VelocityChange);
            jump = false;
        }
    }

```

Note that in this case I use the notation of y-axis being height, if you really really want to continue using z-axis then just apply the velocity change to that axis instead.

I think your problem is not in code per se, you need to read up on classical newtonian mechanics a bit before making a physics based game.

## EDIT 2:

As you updated your answer again, I'll add another edit. Remember that the physics engine is using SI base units. This means that if you add a velocity change of 5000 that means you add 5000 m/s or 18000 km/h.

I *think* this may cause issues with the physics engine as the drag at those speeds will be enormous, and even if IRL drag would sooner or later reduce the speed to more sane values, in the discrete model in the engine with floating point errors and such *maybe* it could result in the body coming to a complete stop one frame later.

Try once more to do the same while first checking that all values are more "normal", i.e. gravity ~10 N/kg, drag \< 1 and velocity changes 1-10 m/s. Also check that gravity is pointing the right direction (normal setting is negative y), and that the physics update step is about 0.02 s.
> 0 votes

# Answer
After several more hours working on it, I've narrowed it down to a bug/peculiarity in the Unity engine.

I deleted everything and started fresh, on doing so, the original code worked fine. During my attempts to replicate what I originally had, I found that adjusting the drag to something \> 1 while either turning on/off the "Use Gravity" tickmark or changing the gravity from 0 to 9.81 or reverse between two runs caused the problem with no way to undo it.

As best I can tell, what happened was the cube moved at an incredible speed, seeming to teleport, but then was restricted to its maximum velocity in the second frame, then had its velocity reduced due to the gravity, making it stand still then fall. The slowness was also caused by the drag, which I managed to overcome by writing my own function to simulate the acceleration due to gravity, though this stopped working properly when I re-did the entire project, causing the cube to drop at incredible speeds as it no longer needed to overcome the 'invisible air resistance'.

Even after reducing drag back down to 0 this problem persists, meaning that although the surface to surface friction was returned to 0, the air drag was not.

This was done using Unity 5.3.5f1 (64-bit)
> 0 votes

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


# Question
Title: How do I optimize checking adjacency within a matrix (including diagonals)? [Gamemaker Studio]
**How I was checking adjacency before:**

```

if (obj_Handle_Links.Last_Link.Matrix_Location_y = (Matrix_Location_y-1)
         || obj_Handle_Links.Last_Link.Matrix_Location_y = (Matrix_Location_y+1)
         || obj_Handle_Links.Last_Link.Matrix_Location_x = (Matrix_Location_x-1)
         || obj_Handle_Links.Last_Link.Matrix_Location_x = (Matrix_Location_x+1))
{
        //do stuff
}

```

**The Problem with that:**

This only checks if the object's matrix location is within an adjacent row or column, not simply if it's directly adjacent to the object. Thus, it doesn't need to actually be adjacent to the `last_link`. That's a problem.

**The Long solution:**

I could individually check for each and every individual square adjacent to the object clicked on. However, this is rather inefficient (taking a minimum of 2 checks, and up to 8, if I don't include diagonals), at least if I use `matrix location x/y`. And if I include diagonals, that doubles the number of checks again, and makes the if statement really long.

**The Question:**

How do I efficiently and with as little code as possible, and make is as easily understandable as possible? Comments are obvious inclusions for that last bit, but aside from that.

**Graphical Example of how the map looks**

format: x,y

```

0,0  1,0  2,0  3,0
0,1  1,1  2,1  3,1
0,2  1,2  2,2  3,2
0,3  1,3  2,3  3,3

```

***Below is the requested, relevant code***

**obj\_Handle\_Links create event**

```

Match_Length = 0;

Link_Stack = ds_stack_create();

```

**obj\_Board\_Generator create event**

```

//hardcoded height and width. could change later
Large_Width = 6
Large_Height = 6

var i = Large_Width-1
var j = Large_Height-1

repeat(Large_Width)
   {
    repeat(Large_Height)
        {
        //initialize the board by generating the objects
        //later, need to randomize.
        BoardGems[i, j]  = instance_create((i-1)*36, (j-1)*36, obj_Parent)
        BoardGems[i, j].Matrix_Location_x = i
        BoardGems[i, j].Matrix_Location_y = j
        j -= 1;
        }
    j = Large_Height-1;
    i -= 1;
   }

```

**obj\_Parent Create event**

```

image_speed = 0
Linked = false
Type = "Parent"

//Matrix_Location_y = 0
//Matrix_Location_x = 0

```

**obj\_Parent left click event**

```

if (obj_Handle_Links.Match_Length = 0) //if this would be the first in the link
{
    show_message("first to link");
    obj_Handle_Links.Match_Length +=1; //because we're increasing the length
    image_index = 1; //this should highlight
    Linked = true;
    ds_stack_push(obj_Handle_Links.Link_Stack, id) //adds the instance to the stack
    obj_Handle_Links.Last_Link = id; //makes it so this is what's seen as last link
}
else
{
   // show_message("first else");
    //check if the target is the same type as the last Link's type
    if(obj_Handle_Links.Last_Link.Type = Type &&
        //check if it's already been linked
        (Linked = false) &&
        //check if the last link in the chain is adjacent to the target link
        //includes diagonals
         ((obj_Handle_Links.Last_Link.Matrix_Location_y = (Matrix_Location_y-1) && obj_Handle_Links.Last_Link.Matrix_Location_x = (Matrix_Location_x)) //checks up
         || (obj_Handle_Links.Last_Link.Matrix_Location_y = (Matrix_Location_y-1) && obj_Handle_Links.Last_Link.Matrix_Location_x = (Matrix_Location_x-1)) //checks up, left
         || (obj_Handle_Links.Last_Link.Matrix_Location_y = (Matrix_Location_y-1) && obj_Handle_Links.Last_Link.Matrix_Location_x = (Matrix_Location_x+1)) //checks up, right
         || (obj_Handle_Links.Last_Link.Matrix_Location_y = (Matrix_Location_y+1) && obj_Handle_Links.Last_Link.Matrix_Location_x = (Matrix_Location_x)) //checks down
         || (obj_Handle_Links.Last_Link.Matrix_Location_y = (Matrix_Location_y+1) && obj_Handle_Links.Last_Link.Matrix_Location_x = (Matrix_Location_x-1)) //checks down, left
         || (obj_Handle_Links.Last_Link.Matrix_Location_y = (Matrix_Location_y+1) && obj_Handle_Links.Last_Link.Matrix_Location_x = (Matrix_Location_x+1)) //checks down, right
         || (obj_Handle_Links.Last_Link.Matrix_Location_x = (Matrix_Location_x-1) && obj_Handle_Links.Last_Link.Matrix_Location_y = (Matrix_Location_y)) //checks left
         || (obj_Handle_Links.Last_Link.Matrix_Location_x = (Matrix_Location_x+1) && obj_Handle_Links.Last_Link.Matrix_Location_y = (Matrix_Location_y)) //checks right
         ) //parenthesis to enclose the adjacency check
         ) //parenthesis closes conditional statement
        {
            show_message("did link");
            obj_Handle_Links.Match_Length +=1; //because we're increasing the length
            image_index = 1; //this should highlight
            Linked = true;
            ds_stack_push(obj_Handle_Links.Link_Stack, id) //adds the instance to the stack
            obj_Handle_Links.Last_Link = id; //makes it so this is what's seen as last link
         }
    else{

        show_message("didn't link");
        //play sound that link failed
    }
}

```

# Answer
You can construct an efficient test of whether a point lies within an axis-aligned rectangle with well-understood algorithms. Try this answer.
> 1 votes

# Answer
You can find many articles and repos online related to this topic. User *dgkanatsios* on GitHub created his MatchThreeGame and included an article on his site in which he explains how to make such a game in Unity step by step. As well, did *rembound* with his Match-3-Game-HTML5 which was developed in JavaScript and run in a browser.

Although you're working with GM:Studio, you can still read their guide and extrapolate the algorithms they use to accomplish the various tasks to make their respective games work. The earlier article also shows a DFA state chart representing the main operations performed by the game loop routine while the game is running.

Anyway, we can't help you as much as we could, until you show us some more code or fully explain how your current algorithm works, what's the data structure you're using to deal with the game status, and so on.
> 0 votes

---
Tags: optimization, game-maker
---


# Question
Title: Data structure to store breakable parts of a mesh
I have a wall mesh that is divided into destructible pieces. As it gets destroyed, the wall can collapse into separate objects with physics that can be destroyed as well. (Cut the wall in half horizontally and the top wall becomes a separate object with its own physics).

I already have the adjacency info to know neighbors, but how should I store the pieces so that I can detect when to split them into separate objects? What kind of tree would suit this and know when the branch was severed and what pieces to make a new object out of?

A test would be to smash a circle out of the wall, and the middle of the circle would fall out and contain only those remaining connected pieces as a new object.

Any examples out there?

Thanks!

# Answer
I have implemented https://sourceforge.net/projects/satsumagraph/?source=navbar and it worked great. Very simple to use.

Added undirected adjacency to a custom graph then used a sub-graph to call a strongly connected query that returns a list of strongly connected nodes.
> -2 votes

---
Tags: architecture, data-structure
---


title: Unity, Steam and updaters!

text:
# Question
Title: Unity, Steam and updaters!
I am probably asking a question answered here already; but I have yet to find the answer! Can anyone here help me with how updates work for your games? I know that through visual basic you can create batches to make shorter updates and everything like that but overall I am completely confused:/

How to get your game from Unity to Steam and how can you update the version and files efficiently?

# Answer
> 4 votes
If you publish your game through Steam you don't have to provide your own update mechanism – I'd even strongly suggest not doing so. While this gives some control away from you (i.e. you have to wait for Valve to push updates), it let's you forget about all the update handling and your players also won't hit problems in case they verify Steam's cache integrity (which might cause Steam to revert the game to a previous state, which will then have to be patched once again).

Basically you just create your game with no update mechanics in place. If you publish a new version, eversyone's installation will be updated without you having to worry about it.

If you want to prevent players from using outdated versions, just include some version/protocol check when one connects online.

As for publishing on Steam, check out Steam Greenlight, if you don't have any publisher handling this for you.

It basically works like any workshop showcase. Once your game has attracted enough attention, Valve should contact you with further details and how to proceed (signing contracts and stuff).

---
Tags: unity, steam, deployment
---


# Question
Title: How to fix an alarm event not triggering? [Gamemaker studio]
**Object\_1's alarm 1 event**

```

show_message("alarm triggered");
if (Destroy = true){
    instance_destroy();
}

```

**Object\_trigger's alarm start**

```

 while (!ds_stack_empty(obj_Handle_Links.Link_Stack))
      {
        temporary = ds_stack_pop(obj_Handle_Links.Link_Stack);
        temporary.Destroy = true;
        temporary.image_index = 0;
      }
        alarm[1] = 3;

```

**Comments:**

I've tried changing the alarm (and alarm event). I've tried having the `alarm[1]=3` in and out of the while loop. I've tried changing the values assigned to alarm.

No matter what I do, the alarm event just doesn't trigger. It doesn't hit the `show_message`. I just don't know what is going on.

# Answer
> 3 votes
The alarm needs to be on the same object. When invoking `alarm` it's reading the local alarms, you would need to do `Object_1.alarm[index]` to be able to change that.

---
Tags: game-maker, debugging, bug
---


# Question
Title: How do I Sync data from client to server?
I'm trying to Sync data from the client to the server using the new Unity Networking, and I'm failing for some reason.

I've set up a prefab with a `NetworkIdentity` component with the attribute `Local Player Authority` set.

I (manually) spawn that on the server, and it is correctly propagated to the clients.

I have a couple of vars on this class, which the client sets and the server should read:

```
public class PlayerController : NetworkBehaviour
{
    [SyncVar] public bool engineOn;
    [SyncVar] public Quaternion lookAt;

```

The client correctly sets them, however the server never receives them, they always stay at the default value.

What might be happening?

# Answer
`[SyncVar]` only sends messages from the server to the client. You need `[Command]`.
> 4 votes

# Answer
Not sure if this has been figured out or but here goes. I dropped the \[SyncVar\] portion except for health and shields on players and used the following code to get by break lights to sync across network.

```
void LateUpdate () {

    if (isLocalPlayer) {
        if (Input.GetButton ("Fire1")) {
            breakLightsOnOff = true;
        } else {
            breakLightsOnOff = false;
        }
        CmdBLC (breakLightsOnOff);
    }
}

[Command]
void CmdBLC(bool OnOff) {
    RpcBreakLightControl (OnOff);
}

[ClientRpc]
void RpcBreakLightControl(bool OnOff) {
    breakLights.SetActive (OnOff);
}

```
> 1 votes

# Answer
The problem is that Server will never receive these updates unless there is a LocalClient on the machine running the server. Refer unity docs for the word **Host** i.e. Sever and a Client
> -1 votes

---
Tags: unity, networking, unity-networking
---


# Question
Title: Multithreading/Optimisation for Random Generation in Gamemaker
I have a `FurGeneration()` script in my game; when run, it randomly generates individual `oFur` objects in specified areas in the game's single Room. Each has a random depth and one of three sprites, and the script produces the impression of dense, layered fur. I've attached a screenshot.

At the moment, the script is working well, as I am using it on relatively small areas. However, my next challenge is to apply this across the single, 20,000 x 20,000 room of my game to produce a consistent field of fur.

My first attempt at this was to create a background sprite, a simple 1000x1000 grey square with its `image_alpha` set to 0. These would be generated in rows across the entire space of the room, and then *each one* would have the `FurGeneration()` script run on it to generate individual squares of fur flush with each other. I've applied this to one 'row' of my games' Room, and the game really slows down; it doesn't crash, but evidently there are just t0o many calculations going on at once.

My question is: is there a way to multi-thread in Gamemaker? Or does it already multi-thread, meaning that this plan is a foolish one? It would be interesting to hear your thoughts.

# Answer
> 2 votes
Yes, GM:S already does multi-threading programming on its own. Being a development framework, it would be a pain in the neck if it didn't so.

Instead of creating several objects with different `sprite_index`es to create a seamless field of fur, you may want to draw them on a *Surface* first, and then draw it into your room.

**What are** **Surfaces****?**
Surfaces are a special type of canvas on which you can draw whatever you want, at any moment, with any object, and in any way, and when you're done you can draw such surface in your room (or GUI as well) and see the results.

There are many possible applications of Surfaces, such as fake lighting effects, particles, several blending modes at once, and so on.

So, instead of generating `oFur` objects randomly, since they are to be drawn on the screen, you can create a Surface and draw random fur sprites on it at random position (using the same position algorithm to create your `oFur`s); when you're done, simply draw the Surface.

There ARE performance advantages. Assuming your early `oFur`s weren't supposed to be moving, you can draw on your Surface once only in a particular *Event*, and then draw your Surface into the room in the *Draw Event*. This is better than having *n* `oFur` instances, which must draw their `sprite_index` at their *x* and *y* position, each step. You draw the single sprites on the Surface *once only*, and finally draw the Surface at position *(0, 0)* so that it is able to fit your room.

# Answer
> 2 votes
In Game Maker, every object has a lot of built-in variables. Creating an object for every piece of fur may be a waste of resources.

You could create a single object, that would store the basic variables for every piece of fur (sprite\_index, position, etc.) and then in it's draw event draw them all at once.

EDIT : as you want to interact with the fur bits, this method may be unsatisfactory. My advice, if you still want to use objects for every fur bit, would be to put as few code as possible in the fur object. For example, create a cursor object, with a slightly wide hitbox, and check for the coordinates of the fur bits inside this box. This way, the calculations will be faster.

---
Tags: optimization, game-maker
---


title: Playing Audio in Unity 5.x

text:
# Question
Title: Playing Audio in Unity 5.x
I've started using Unity recently and have ran into some snags with the built audio features. I am trying to have multiple sounds play from the Player Game Object. I'm not sure what the best way to do this.

I have looked into solutions that involve changing the audio clip in the audio source. The problem I ran into with this method was that using the function "PlayOneShot" allows the sounds to stack. So if I try using this method for the walking noise it creates a new instance of that sound that layers on top of each other each frame the player walks. I figure I need to make just a player noise track that starts and stops depending on when the player is walking.

I've also considered trying to use multiple audio sources on the game object.

I'm really not sure what the best approach is for this and I'm having a hard to finding resources in this subject area.

# Answer
You need audio source component to use audio clip.

From getting that component you can access to PlayOneShot() function.

The best way to sync play the walking sound is to call an event from animation. Whenever the walking animation is making the legs touching ground call a public function from there which has PlayOneShot() in it.
> 1 votes

---
Tags: unity, audio
---