title: Error running an Action in Cocos2d-x

text:
# Question
Title: Error running an Action in Cocos2d-x
In my game I have a "rocket" type and I want to run a sequence of actions on it. At first it must run an explosion animation and then remove itself from the game. For this I used the following code, but it does not work and results in a runtime error.

Rocket class:

```
void Rocket::movingRocket(float dt)
{
    // ...
    if(rocketIsCollideWithEnemy()) // run only one time
    {
        this->stopAllActions();
        CCAnimation *animation = CCAnimation::create();

        for (int i = 0; i < EXPLOSION_FRAME_NUMBER; i++)
        {
            CCString *str = CCString::createWithFormat("/explosion-%d.png", i);
            animation->addSpriteFrameWithFileName(str->getCString());
        }

        animation->setDelayPerUnit(0.06f);
        CCAnimate *animate = CCAnimate::create(animation);
        CCCallFuncN* remove_rocket = CCCallFuncN::create(this, callfuncN_selector(Rocket::removeRocket));

        this->runAction(CCSequence::create(animate,remove_rocket, NULL));
        this->unschedule(schedule_selector(Rocket::movingRocket));
    }
}

```

And for removing a rocket I use:

```
void Rocket::removeRocket(CCObject *pSender)
{
    ((CCNode*)pSender)->removeFromParentAndCleanup(true);
}

```

And when I run the above, an error occurs in the following code, part Cocos2d, at line 4:

```
void CCAnimate::update(float t)
{
    // ...
    if( splitTime <= t )
    {
        CCAnimationFrame* frame = (CCAnimationFrame*)frames->objectAtIndex(i);
        frameToDisplay = frame->getSpriteFrame();
        ((CCSprite*)m_pTarget)->setDisplayFrame(frameToDisplay);

        CCDictionary* dict = frame->getUserInfo();
        if( dict )
        {
            //TODO: [[NSNotificationCenter defaultCenter] postNotificationName:CCAnimationFrameDisplayedNotification object:target_ userInfo:dict];
        }
        m_nNextFrame = i+1;
    }
    // ...
}

```

What could be causing my problem?

# Answer
My answer won't be a clean solution but for a side note, and if you really need it to be fixed before attempting trying to find a clean working solution, I use the approach below.

I have a lot of action-chain used in my game. I found the exact same problem as you mention about that code section you posted.

I have spent so much time checking that whether every new action stops the previous one or unused ones. This is to minimize the chance of error in the case that actions might lost in the midst of nowhere. But I got no good result. So I applied the below code fix to `CCActionInterval.cpp` (I still use version 2.0.3)

```
if(m_pTarget == NULL)
{
     // make the animation finish
     t = 1.0f;

     return;
}

CCAnimationFrame* frame = (CCAnimationFrame*)frames->objectAtIndex(i);
frameToDisplay = frame->getSpriteFrame();
((CCSprite*)m_pTarget)->setDisplayFrame(frameToDisplay);

```

It might not be the best solution, but it works for me.
> 0 votes

---
Tags: animation, cocos2d-iphone, cocos2d, objective-c, cocos2d-x
---


# Question
Title: How do i calculate the velocity of a sprite after it leaves circular motion?
I'm trying to make a game where the character can swing on a rope.

I want to know how the velocity of player is calculated when it stops circular motion. Any help would be appreciated.

# Answer
> 1 votes
This picture exemplifies it well. In the given example the rope pulls the robot with the blue vector (a force in the direction of the rope). Once you let go of the rope, of there wass no gravity the robot would move with equal speed in a straight line tangential to the point he stopped the circular motion. If there's gravity, the only acceleration on the robot is the green vector pointing down.

In realistic accelerated movement, it's often better to control only the acceleration of the robot, and determine velocity as a by-product of acceleration, using kinematic equations.

# Answer
> 4 votes
Circular motion already has velocity; what makes it circular is the continued application of a rotating acceleration of constant magnitude. So to let the object leave the circle at the proper velocity, just stop applying the acceleration.

---
Tags: physics
---


# Question
Title: Raycast doesn't point on the right direction
The raycast line im rendering is acting weird, it doesn't point where I want it to.

I want it to point from the yellow object to the selected one but it draws it at another position.

Here is my script:

```
    #pragma strict

var player : Transform;
var turret : Transform;

var bullet : Transform;
var barrelEnd : Transform;

var shootRate = 0.3;

var canShoot : boolean = true;

var soundEffect : AudioClip;

function Update()
{
    shoot();
}

function shoot()
{
    turret.LookAt(player);
    var hit : RaycastHit;
    var fwd = turret.forward;
    if(Physics.Raycast(turret.position, player.position,hit, Mathf.Infinity))
    {
        if(hit.collider.transform.gameObject.tag == "Player")
        {
            if(canShoot == true)
            {
                var bulletInstance : Transform;
                bulletInstance = Instantiate(bullet, barrelEnd.position, transform.rotation);
                bulletInstance.LookAt(player.position);
                audio.PlayOneShot(soundEffect);
                w();
            }
        }
    }

    Debug.DrawRay(player.position, transform.position);
}

function w()
{
    canShoot=false;
    yield WaitForSeconds(shootRate);
    canShoot=true;
}

```

Thank you! I hope someone can help

# Answer
> 1 votes
You're using the `RayCast` and `DrawRay` methods incorrectly. Both call for a direction for their second parameter, and you're passing in a position.

In the case of the `RayCast` you probably want your direction to be the `fwd` variable you create using `turret.forward`.

---
Tags: unity, raycasting, unityscript
---


# Question
Title: Approaches for a clickable map of nations (such as a Risk game) with Spritekit
I would like to create a political map where each country is clickable by tapping but I'm not sure the best way to determine which nation was selected. Imagine Risk where each country can be individually clicked to bring up additional information.

My current approach is to make a sprite for each nation where every image is the size of the screen The images are mostly transparent except for the country, that way when all of the images are displayed the countries are in the correct place relative to one another. To determine if a click occurs on an individual country I look to see if the tapped location is a non transparent pixel and check that the sprite's name is one of the countries. Additionally the nation needs to glow or something when tapped as an indicator, however my current solution is yet another sprite that is displayed.

This seems like a terrible approach and I was wondering what other solutions might achieve the same results. I'm pretty new to SpriteKit so I'm not entirely sure.

The other idea I had was creating a single texture where each country is a different shade of gray, then when I get the tap location I do a lookup on the color at that location and get the corresponding country. However, I'm not sure how to create a hilight or glowing country effect with that method.

# Answer
> 3 votes
(A) If you need the countries to be sprites I would try this:

1. Make the sprite for each country just big enough to contain them
2. Make a UIBezierPath for each country and save that as a property of the country
3. Use `containsPoint` in the touchesBegan of each country to check if touch is inside

(B) If you don't *have to* use SpriteKit (for this particular part) then I would:

1. Draw the entire map with vector graphics using drawRects (or CAShapeLayers)
2. Use the same bezier paths for drawing and for touch detection

(C) You could actually use vector graphics in SpriteKit using the same approach as in (B) with the SKShapeNode, although it is quite buggy. In this case it might work well though.

In either case, I would use the wonderful app PaintCode to make the country shapes! There are also free alternatives that let you convert SVG drawings to objective c (or Swift) bezier paths.

# Answer
> 1 votes
An other approach would be to use an UIButton for each country and detect if the player touch the non transparent part of the png.

For that you need an UIBUTTON that respond to touches only in areas where the image that is assigned to the button for UIControlStateNormal is non-transparent.

There is a custom UIBUTTON class : OBShapedButton https://github.com/ole/OBShapedButton that implement this.

# Answer
> 0 votes
Make each country a different spritenode and in your TouchesEnded event check each country to see if there was a touch inside of it.

```
 If(yourCountrySKspritenode contains:location)
    {
     //change yourCountrySKspritenode image to another duplicate but brighter image
     //execute whatever else should happen
    }

```

---
Tags: ios, maps, spritekit
---


# Question
Title: Ease action to simulate a clank in a moving or rotating device near end of the trajectory
You know those mechanisms that moved or rotated, and then just a few millimeters near the end of the trajectory they oppose a bit of resistance and then clank to the final position.

I want to simulate that clank with an ease function that can be combined with the standard ease actions. The link is for reference to some examples of ease transition functions, but I just need the pseudocode like this:

```
float clankActionTime(float t) {
    if (t > 0.9)
        return (0.5*sin(10.0*t*2.0*M_PI)+2.0*10.0*t)/20.0;
    return t;
}

```

That is what I have so far, which gives this graph for t between 0 and 1.

But I want something more like this:

Where A and B are parameters passed to the ease function to indicate where to star the clank and how deep is the valley near the end of the curve, respectively.

# Answer
```
clankTime(t, A, B) {
    float cT = 1.0-A;
    float t1 = cT+0.5*(1.0-B)*(1.0-cT);
    float t2 = cT+0.5*(1.0+B)*(1.0-cT);

    if (t > t1) {
        float m = (1.0-t2)/(1.0-t1);
        return m*(t-t1)+t2;
    }
    else if (t > cT) {
        float m = (t2-cT)/(t1-cT);
        return m*(t-cT)+cT;
    }
    return t;
}

```

Where **A** is the duration of the clank from where the movement starts slowing down until the end of the ease transition, and **B** is how deep is the valley measured on a line perpendicular to `y=x` that intersects the line at `0.5*A`.
> 1 votes

---
Tags: animation
---


# Question
Title: Is it possible to look up a texel from a texture in GLES2 GLSL framgent shader without using sampler?
Is there some way I can **directly access texture memory** from **fragment shader** in `GLES2` `GLSL`? I don't need the sampler to be involved since I am just using it as a **look-up table**.

# Answer
texelFetch is used for lockups without performing mip-mappnig, filtering..etc. and even with this you still need to pass a sampler.

Otherwise your out of luck, as far as I am aware, making such operation available restricts driver writers from doing certain optimization, for instance they need to keep textures in a certain layout in memory.
> 0 votes

---
Tags: textures, glsl, opengl-es2, fragment-shader
---


# Question
Title: Get object length and width divided by two?
I have googled and found a script for the following task; Make the camera move to touched position. However, this script will jump to x and y positions on an object, while i would like for it to move to the middle of the object, and then only be able to jump to others.

```
using UnityEngine;
using System.Collections;

public class TapToMove : MonoBehaviour
{
    // flag to check if the user has tapped / clicked.
    // Set to true on click. Reset to false on reaching destination
    private bool flagTouchCoords = false;
    // destination point
    private Vector3 cameraDestination;
    // alter this to change the speed of the movement of player / gameobject
    public float duration = 100.0f;
    // vertical position of the gameobject
    private float yAxis;

    void Start()
    {
        // save the y axis value of gameobject
        yAxis = gameObject.transform.position.z;
    }

    // Update is called once per frame
    void Update()
    {
        // check if the screen is touched / clicked
        if ((Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
        || (Input.GetMouseButtonDown(0)))
        {
            // declare a variable of RaycastHit struct
            RaycastHit hit;
            // Create a Ray on the tapped / clicked position
            Ray ray;
            // for unity editor
            #if UNITY_EDITOR
            ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            // for touch device
            #elif (UNITY_ANDROID || UNITY_IPHONE || UNITY_WP8)
            ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
            #endif

            // Check if the ray hits any collider
            if (Physics.Raycast(ray, out hit))
            {
                // set a flag to indicate to move the gameobject
                flagTouchCoords = true;
                // save the click / tap position
                cameraDestination = hit.point;
                // as we do not want to change the y axis value based on touch position, reset it to original y axis value
                cameraDestination.z = yAxis;
                Debug.Log(cameraDestination);
            }
        }

        // check if the flag for movement is true and the current gameobject position is not same as the clicked / tapped position
        if (flagTouchCoords
        && !Mathf.Approximately(gameObject.transform.position.magnitude, cameraDestination.magnitude))
        {
            // && !(V3Equal(transform.position, endPoint))){
            // move the gameobject to the desired position
            gameObject.transform.position =
                Vector3.Lerp(gameObject.transform.position,
                             cameraDestination,
                             1 / (duration * (Vector3.Distance(gameObject.transform.position, cameraDestination))));
        }
    }
}

```

So this is how the game looks. The script moves correctly, but will jump at different positions when it hits the collider on the lily pads. I could reduce the collider, but I feel like there should be an easy way to get length and width of a collider, and reduce it by /2 to make the camera move directly in the middle.

Anyone care to help? Thanks in advance. :)

# Answer
> 2 votes
if you want to obtain the object owner of the collider instead of the hit point (that can be anywhere over the collider) simply use this code instead of hit.point:

```
cameraDestination = hit.collider.gameObject.transform.position;

```

The camera will center on the gameobject that owns the collider. If the position of the object is also the "visual" center you are done.

Hope this is your wanted behaviour.

---
Tags: unity, gameobject
---


title: Trouble Using Component Base Pattern

text:
# Question
Title: Trouble Using Component Base Pattern
I am trying to use a component based pattern on my new project. The last projects I did the old fashioned way. Base class and derive from that until your brain hurts. This time I wanted to do it on a new way with a component approach.

Component Base Summary: The idea is that you build components and compose your objects out of different components e.g. the Player class holds *GraphicComponent*, *PhysicComponent*, *InputComponent*, *CameraComponent*, *ScriptComponent* and so on, but an decoration object like a plant only has *GraphicComponent* and maybe *PhysicComponent*.

I like this approach. I tried to implement it but I have a little understanding issue.

As far as I understand it, each component has the logic for itself in it, and barely know of other components. But this is the part I don't understand: Let's say we have a **RenderComponent** which holds the logic for rendering. But each concrete object like a player, a plant an UI-element and so on has to be rendered on a completly different way. The player hast special effects and different animations, the plant is only a sprite and the ui element is a combination of both. Do I put the logic for every different rendering in the **RenderComponent** all at once e.g. `RenderPlayer()`, `RenderPlant()`, `RenderUIElement()` which does not make sense to me or do I make an Interface out of the RenderComponent and create a specific RenderComponent for each concrete objects like `PlayerRenderComponent : IRenderComponenent` ?

**Update**

After reading the Answer from Nick, I did a quick UML-likish diagram to clearify if I got the idea/structure right. The diagram is just an example with a pseudo UML-like diagram an some pseudo example constelations. The Idea is, that the concrete composition objects holds and treats their component as a data structure. They set it, alter it, and read from it to do it's logics. They also can compare Components of other concrete objects for convience and provice their components to higher systems (like managers)

**Update 2** After some discussion and a bit of confusion due opposites arguments, I started to google with new keywords I got from the comments and found an article which helped me understand how the system is glued together.

# Answer
While components *may* have logic in them, the sort of logic you're talking about (loosely termed *batch* logic) doesn't exist at the entity level -- instead it exists in the game loop.

This makes sense when you look at a theoretical (but typical) deferred 3D renderer. This renderer may have to run through all objects of similar `type` (a data member of your entity class/struct); say we're doing a rendering pass for all entities of `type == TRANSPARENT`. Here, we have certain graphics API functions that must be called **just once** before and/or after all `TRANSPARENT` elements are processed, to allow for correct blending. This is common in game engines... you may have heard the term *batching*. The particles are treated as a batch. They don't *act*, they are *acted upon*.

Why? Well, as you've realised, if you were to have such logic contained in each entity, you would not be able to make your API calls just once for the batch of transparent particles; instead those calls would be made per particle, which may be impossible due to performance or other limitations (typically the purpose of batching is to tackle similar processing in the same place (in the code, and linearly in memory in order to improve cache performance, and as batching is such a common pattern in games development, CBEs are typically designed to support this). This is because no entity can know what other entities are doing (to enable this would be architectural folly), so none know whether the necessary rendering calls have or haven't been called yet. So we move this logic "up-and-out".

To conclude: Cycle through all elements of similar "type" together -- this may require a pre-sort or you may already maintain these in different lists -- and process them using one master block of code that is not embedded in entities or components, but instead exists directly or indirectly (through helpers) in your game loop. This will allow you to treat all similar components in the same way, in phases relating to their different properties in terms of physics / rendering / AI etc.

P.S. It is a good idea to start thinking of your entities as data / state rather than functionality, IMO. See Mick West's Evolve Your Hierarchy for more details.
> 2 votes

---
Tags: component-based
---


# Question
Title: Backface culling without light leaking through
I want to be able to see through walls, so to do this I used planes for the walls, and enabled backface culling. However with shadow mapping I have a lot of light leaking through:

I read that using a thick wall solves this, so I did just that. This solved the leaking light:

but now I cannot see through the walls (camera is within the room in the above screen), all the backfaces are inward.

How could I prevent light leaking, as well as enable seeing through the walls?

# Answer
When rendering to the screen you can simply not include the geometry to make the walls thick.
> 1 votes

---
Tags: opengl, lighting, webgl, shadow-mapping, deferred-rendering
---


# Question
Title: Space Invaders: Getting the aliens to move as one
I'm having issues getting my invaders to move together. Currently they hit the edge of the screen and then go crazy.

Here is the code for the Alien:

```
#include "Alien.h"
#include <iostream>
#include <stdlib.h>
#include <time.h>
Alien::Alien()
{
}

void Alien::Init(ISprite * a,  float hp, float vp, int sValue)
{
    srand(time(NULL));
    alien = a;
    horizontalPos = hp;
    verticalPos = vp;
    rev = false;
    bombInterval = float(rand() % 10 + 1);
    lastDropped = 0;
    scoreValue = sValue;
    alive = true;
}

bool Alien::testCollision(Rocket R)
{
    if(R.getX() >= horizontalPos &&
       R.getX() <= (horizontalPos + 32) &&
       R.getY() >= verticalPos &&
       R.getY() <= (verticalPos + 32)) {
           return true;
}

    return false;
}

void Alien::Update(float move, DResourceManager& drm)
{

    if(rev){
            horizontalPos -= (move);
    }
    else{
        horizontalPos += (move);
    }

    if(horizontalPos >= (640-32))
    {
        drm.alert();
    }
    if(horizontalPos < 32)
    {
            drm.alert();
    }
        // Check to see if we are colliding with any rockets.
        if(drm.getRocketCount() > 0)
        {
            for(std::vector<Rocket>::iterator roit = drm.getRockets().begin(); roit != drm.getRockets().end(); ++roit) {
            if(roit->alive){
                if(testCollision(*roit))
                {
                    setDead();
                    roit->setDead();
                    drm.getRockets().erase(roit);
                    return;
                }
            }
        }

    }
}

int Alien::getScore()
{
    return scoreValue;
}

void Alien::reverse()
{
    rev = !rev;
}

bool Alien::isAlive()
{
    if(alive){
        return true;
    }

    return false;
}

void Alien::setDead()
{
    alive = false;
}
float Alien::getX()
{
    return horizontalPos;
}

float Alien::getY()
{
    return verticalPos;
}

void Alien::setPosX(float x)
{
     horizontalPos += x;
}

void Alien::setPosY(float y)
{
     verticalPos += y;
}

void Alien::draw()
{

        alien->draw(int(horizontalPos),  int(verticalPos));
}

void Alien::destroy()
{
    alien->destroy();
}

Alien::~Alien(void)
{
}

```

And the update and draw functions of my DResourceManager class.

```
void DResourceManager::update(float time)
{
    player->update(time, this);
    int direction = 1;
    float max = 0;
    float min = 0;
    for(std::vector<Alien>::iterator it = aliens.begin(); it != aliens.end(); ++it)
    {
        if(it ->isAlive()){
            it->Update(time, *this);
        }
    }
    if (rev)
    {
        for(std::vector<Alien>::iterator it = aliens.begin(); it != aliens.end(); ++it)
        {
            it->setPosY(5);
            it->reverse();
            rev = false;
        }
    }

    // Update rockets if we have any.
    if(rocketCount > 0){
        for(std::vector<Rocket>::iterator roit = rockets.begin(); roit != rockets.end();     ++roit) {
            if(roit == rockets.end()){
                return;
            }
                if(roit->alive){
                    roit->update(time);
                }
            }
    }

}

/* Draw all objects to the screen */
void DResourceManager::draw()
{
    player->draw();

    for(std::vector<Alien>::iterator it = aliens.begin(); it != aliens.end(); ++it) {
        if(it->isAlive())
            it->draw();
    }

    for(std::vector<Rocket>::iterator it = rockets.begin(); it != rockets.end(); ++it) {
        if(it->alive)
            it->draw();
    }
}

```

Your help with getting these aliens to move as one would be much appreciated.

# Answer
I didn't read your code, but I would recommend having a position for "the group" and then have each alien have its own "offset" position from that group position. Then when you draw them you add the two together, and to move the group you move the one group position.
> 1 votes

---
Tags: c++, movement
---


# Question
Title: How to make an object in box2d have constant velocity even after collision?
I have iOS game where I have a bouncing character. Everything is being handled by box2d. The problem is when the character hits a wall of another character it's velocity changes, but I don't want this. I need the velocity to stay constant even after collisions.

I was thinking the only way to do this was to keep setting the velocity after each collision unless there's another way to do this that I'm not aware of?

# Answer
If you want to maintain the velocity of a body (and have it ignore collisions), just set the body type using the `b2body::setType` function:

```
mybody.setType(b2_kinematicBody);

```

Alternatively, the `b2BodyType` can be assigned to the `b2BodyDef` before the body is created using the `b2BodyDef::type` public attribute:

```
mybodydef.type = b2_kinematicBody;

```

All kinematic bodies will move with constant velocity, completely ignoring collisions.
> 0 votes

---
Tags: box2d, ios
---


title: Movement nudge instead of constant

text:
# Question
Title: Movement nudge instead of constant
I am making a small game where the player is constantly moving upwards, and I am having slight problems with the movement to the sides. The script located under works quite perfectly in itself, but my problem is that I want the balloon-player to nudge in a direction, rather than go at a constant speed. Kinda like a small punch to the side of the balloon.

How could I easily implement this? GetMouseButton or GetMouseButtonDown? Thanks in advance. :)

```
    void Update () {

    transform.Translate(Vector3.up * Time.deltaTime, Space.World);

    if(Input.GetMouseButton(0))
        transform.Translate(Vector3.left * Time.deltaTime, Space.World);

    if(Input.GetMouseButton(1))
        transform.Translate(Vector3.right * Time.deltaTime, Space.World);

}

```

# Answer
This looks like it would be something the physics system could fairly easily handle. I'd add a `Rigidbody2D` and then you can manipulate the balloon via the `AddForce` function. Note that in order to make the balloon "rise" you can get rid of your translate and instead set `GravityScale` to something like `-0.5` and it will "fall" but up.

So I'd do something like this:

```
void Update ()
{
    if(Input.GetMouseButtonDown(0))
    {
        rigidbody2D.AddForce(-Vector2.right);
    }
    else if(Input.GetMouseButtonDown(1))
    {
        rigidbody2D.AddForce(Vector2.right);
    }
}

```
> 1 votes

# Answer
What you need is a Velocity/Inertia system. Create an additional vector to represent the amount of "energy" in a given direction for the object - I call mine "Velocity". Every update, apply a percentage of the velocity to the position and subtract it from the velocity. Every time you hit a button to move, add to the velocity rather than directly moving the object.

It's a bit convoluted to set up but it works quite nicely and is the way its always done afaik.
> 0 votes

---
Tags: unity
---


# Question
Title: Percentage of object inside a moving rect
The idea is that I want to get a percentage of the position of Rect2 in relation to Rect1. In the picture, it would be about 75/80%. Rect2 never leaves Rect1. I move Rect1 around all the time, so it should work regardless of Rect1's position.

I had something like this, but it didn't work as intended: ((Rect2.X + Rect1.X) / (Rect1.Width + Rect1.X)) * 100

Rect1.X would work as an offset so the calculation would "ignore" the moving around of Rect1. Or that was the idea...

# Answer
> 1 votes
If you want 100% to mean, "Right edge of Rect2 touches right edge of Rect1", then we just want the ratio of where the Rect1's left edge is within that reduced range of Rect2.

```
(Rect2.left - Rect1.left) / (Rect1.width - Rect2.width) * 100.0

```

Should do it. (I used "left" instead of "x" to remove some possible ambiguity.) You could do it from the right, like

```
100.0 - (Rect1.right - Rect2.right) / (Rect1.width - Rect2.width) * 100.0

```

Where right = left + width.

---
Tags: mathematics
---


title: C++ Ray Traversing in 3D Voxel game

text:
# Question
Title: C++ Ray Traversing in 3D Voxel game
I'm currently working on a Voxel game in 3D and need a tad bit of help to figure out what Voxel the player is looking at. This is the data I currently have:

```
GRRLIB_Camera3dSettings(Player.x, Player.y, Player.z + 4, 0,0,1, Player.x + Camera.lookx,Player.y + Camera.looky,Player.z + Camera.lookz);

```

And the two 3d arrays that contains the player cords and block cords:

```
struct Player{
  int X;
  int Y;
  int Z;
}
int World[X_MAX][Y_MAX][Z_MAX];
//The cords are ALWAYS positive. ( and the array data: 0 Means air, anything higher is solid), The player

```

(GRRLIB camera is described here: http://grrlib.santo.fr/doc/group\___all\_func.html#ga7300940a38526ab5aa9be0f4abe4a32a)

So what I basically need to understand is how I would implement ray tracing using this data. The whole project can be found here: https://github.com/filfat/WiiCraft

***For clarification* I am asking for a simple way in C or C++ to create a Ray tracing algorithm that would be used in a Minecraft like game for selecting the block the player is looking at, all data that is needed is above. So in short I need help to understand the math in a Ray Tracing algorithm and need a simple example so I could implement it myself.**

Thanks! :)

# Answer
I assume your world is represented as a grid, the algorithm you need to do line grid intersection is called Digital differential analyzer algorithm. The code too much to write quickly, you can find a full explanation here.

This algorithm/technique is used to solve different problems that need interpolating a variable over an interval. It's similar to Bresenham line drawing algorithm but extended into 3D Grid.
> 4 votes

---
Tags: c++, c, raytracing
---


# Question
Title: How do "procedural" and "random" generation differ?
To my understanding, everything that isn't directly created by a human is called "procedural". Procedural generation systems have different complexities and may consist of various algorithmic processes, some of which may be "random".

Some games explicitly refer to their systems as "random", while others call them "procedural", as if indicating a distinct difference.

Is there such a distinct difference? Where do you draw the line?

---

For example, here are contrasting examples of RPG loot generation:

**Type A**: Loot generation is ultimately left to chance, but it's based on a large intial factor of deterministic, specifically encoded knowledge.

Boss characters drop loot, which type is determined by the boss' characteristics (e.g. species, character class, elemental affinity, …) and additionally influenced by the player's play-style, to create more enjoyable gameplay: For example, more likely drop a fire-damage sword to a player who prefers fire-based melee attacks, along with gold.

**Type B**: Loot generation is almost completely random, based on minimal explicit knowledge.

Bosses have a randomised loot table (e.g. 1 legendary, 2 epics, 5 blues). If the roll is right to drop a legendary, random attributes are generated for that legendary, which may be high in value. Stuff like character attributes, player behaviour and such don't matter.

---

Both designs qualify as procedural by the initial definition, since their output is automatic, but Type A is significantly more sophisticated in crafting player experience.

Must an algorithm seem as if a person had designed its output by hand, to qualify as "procedural" rather than "random"?

# Answer
As it has been previously remarked in the comments, and as you seem to think as well, random generation is a just another possible form of procedural generation.

Procedural content generation implies that content is being generated by an algorithm rather than manually crafted by a human being. That said, the frontier is very blurry. On one hand, we have what we could call full-blown procedural generation, such as in Minecraft, Terraria, Starbound or No man's sky. On the other hand we have fully-designed games such as, perhaps, Mario and other old school titles. However, there is a lot of ground in the middle, from simple design-time tools for laying out textures, passing through the offline creation of, for instance, trees, landscape and even multitudes, to the online generation of maps in Civilization, or items and monsters in most RPG titles.

Each and every of these examples could use a mix of random and deterministic techniques. Like @Philipp suggested in the comments, generation can be completely deterministic and used just for the sake of compression, like the classic Elite game. In the other corner, it can be (almost) completely random, like many puzzle games (as long as they are solvable, so I guess completely random is mostly out of question). Most of the solutions sit somewhere in the middle, using a set of deterministic rules that can be randomly applied in different orders, or with various inputs, much like your own examples.

There is also a growing field named search-based procedural content generation that approaches content generation as an optimization or search process, and often employs a random generator coupled with some heuristic optimizer (like GAs, or other evolutionary algorithms) and a fitness function that determines the "goodness" of the content. This has the advantage that we don't need to know how to generate good content, we just need to know how to generate lots of content, and how to grade a content's quality (which could be as hard as actually generating it, but it is often easier).

So, to round up my answer, I think that random generation can be mostly seen as a (many times simple) form of procedural generation, and also as component of many procedural generation algorithms, but there is also a lot of procedural generation that is mainly non-random.

Much more info can be found of the PCG wiki.
> 8 votes

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


# Question
Title: web based networked game physics efficiency
I am writing a web based game, using websockets. its pretty simple, two players shooting at each other with bullets that have acceleration from a starting point at an angle.

The client side (frontend in web dev terms) uses phaser.io with p2js for physics.

However after reading this post, i believe that it's smarter to do some of the physics for the players on the server side. Such as collision detections, and update the player positions at regular intervals to keep the two players at sync.

Now i have two questions

* if i use the Box2d javascript port on nodejs on the server side to simulate server side physics, than is it just as efficient as using the native c++ one? seeing as from what i have read so far it seems the js ports aren't that well maintained, and they are js ported - on the other hand the js codes might be easier to deal with than the c++ ones.
* using p2js on the client side and using box2d on the server. The server being authoritative, and sends regular updates (once every second) as to the actual positions of the players. will the physics simulation be in sync (atleast to the user)? Theoretically i don't see any reason for it to not, given that both user has the exact same latency (this is assumed for sake of simplicity).

# Answer
* Obviously, c++ is faster than JavaScript but that is not an actual question. You could simply run some tests and check.
* The second part of the question isn't clear at all. The physics simulation will be in sync if you run the simulation on the server side and use the results from the server to "guide" the clients. You can only extrapolate (or whatever you want to call it on the client) but you need to actually use the server as the "common grounds" that decide what actually happened at every point in time.

The clients can't see each other, definitely not in real time! You can't coordinate between them unless there is a very sophisticated algorithm or in your case a "ruling entity" dictating what actually happened at any point in time where the server is that mediator in your case and the clients "just" tell the server what each player is up to (handling input and control).

So yes, the clients will be in sync because the server tells them to be (in the same state); and no it's impossible to have the "exact same" latency unless you control the environment (your own network w/o using the Internet).
> 1 votes

---
Tags: box2d, phaser
---


# Question
Title: Do you need Visual C 2013 to compile Unreal 4?
Do you need a specific version of Visual C to compile Unreal 4? If so, why? I read in a lot of places:

> Please make sure you are running Visual Studio 2013 Professional or Visual Studio Express 2013 for Windows Desktop installed before proceeding. If you are using Mac, make sure to have Xcode installed.

Why would you need that version? What is wrong with version 2010?

# Answer
The reasons could include solution/project file versions (older versions could just not open it at all), but most probably main reason is C++ compiler version which is tigthly coupled with version of VS (AFAIK you can't update VC++ compiler, but continue to use older version of VS IDE). Latest versions of VC++ compilers are significantly improved in terms of `C++11` standard support which is, most probably, used by UE4.
> 2 votes

---
Tags: unreal-4
---


title: Throwing a bomb LibGDX Box2D

text:
# Question
Title: Throwing a bomb LibGDX Box2D
I am trying to create game where somenone throw a bomb. I am wondering how I can have an bomb react in a way that is represented by the following picture :

Is there are any tools in Box2D that can help me achieve this?

# Answer
Give the ball some restitution (box2d property) having a rigid circle body attached, and later, simply apply some force to it ;) It will work as shown (of course, u should be having some bounding box)

Could give you currect code if u needed :)

# code:

```
Body ball;

BodyDef _b = new BodyDef();
_b.position.set(new Vector2(0, 0));   //your wish
_b.type = BodyType.DynamicBody;

CircleShape ball_shape = new CircleShape();
ball_shape.setRadius(0.5f);

FixtureDef ball_physic_property = new FixtureDef();
ball_physic_property.density = 0.1f;       //your wish
ball_physic_property.restitution = 0.8f;   //your wish
ball_physic_property.friction = 0.5f;      //your wish
ball_physic_property.shape = ball_shape;

ball = world.createBody(_b);
ball.createFixture(ball_physic_property);
ball_shape.dispose();

```

## I believe you got some basics in libgdx box2d :) this should sort you out :)

For the bomb thing, you could make a sprite follow the rigidbody's position ;)
> 1 votes

---
Tags: libgdx, box2d, physics
---


# Question
Title: How do I throw a ball on particular angle?
I want to create a game like "Angry Bird". I want to throw a ball from a destination to a target on a parabolic curve. I have the angle-selection part implemented but now I need to throw a ball from this angle.

```
if (action == MotionEvent.ACTION_MOVE) {
        emX = (int) event.getX();
        emY = (int) event.getY();
        if (emX < h / 2 && emY < w / 2) {

            if (spX != emX || spY != emY) {
                olX = spX;
                olY = spY;
                spX = (int) event.getX();
                spY = (int) event.getY();
                int kx = spX - olX;
                int ky = spY - olY;

                if (Math.abs(kx) > Math.abs(ky)) {
                    if (kx < 0 && angle > 0) {
                        angle -= 1;
                    } else if (angle < 90) {
                        angle += 1;
                        int temp = angle;
                        temp++;
                        System.out.println("Temp is= " + temp);
                    }
                } else {
                    if (ky < 0 && angle > 0) {
                        angle -= 1;
                    } else if (angle < 90) {
                        angle += 1;
                    }

                }

            }

        }
    }

```

How can I throw on object using the angle selected from the above method?

# Answer
> 0 votes
By throwing, i think you want some force added. Do this: Let the angle u want to throw be 60degree. And the force to be applied be 2Newton So, by using trignometric identities, u could do this:

Vector2 force = new Vector2(2 * sin(60), 2 * cos(60));

Apply the force to ur body. (Most libraries take vector as force). (Also, u might want to convert it into your library)

Hope it helps :)

---
Tags: android
---


# Question
Title: How can I create the illusion of a 3D object moving around in a static background?
I'm designing a Resident Evil clone using OpenGL. I'm curious how the older *Resident Evil* games used a static pre-rendered background with 3D models roaming around:

<sub>(source: spong.com)</sub>

Here, if the main player (Claire) moved a few steps back, she will overlap with the pay phone booth. But if she keeps moving alongside the phone booths, she'll still be overlapping them until she is adjacent to the second phone booth.

Conceptually, how is this done and how can I replicate it? I'm not interested in the implementation technicalities on any particular platform. Just the concepts.

# Answer
> 1 votes
The simple solution is to not pre-render the background at all. Draw everything live, in 3D, with a fixed camera angle. Modern GPUs can achieve live results that look better than what we often had to pre-render for back in the day (especially with good art).

That said, if you want to reproduce the technique for "authenticity," efficiency, or simply to achieve something even better than what you could do live, it's fairly straightforward in concept: pre-render the scene and save both the color *and* the depth information.

This will allow you to know the depth of every pixel in the scene, which you can reconstruct into a world-space position of every pixel in the scene (also as a pre-computation step, since the camera angle is fixed). This means you can know when the character is in front of or behind that pixel (render characters and dynamic objects live, in 3D, with the same camera transform used to render the scene). You can use this information to slice the scene into 2D layers which can be drawn back-to-front.

You'll also want to bake out the collision information for props in the 3D scene, such as (in your example), the payphones. Otherwise the player will phase through them, either instantly (in the case of a layer-based rendering) or "smoothly" (if you only work with the pixel depths). Both cases will look very unusual in practice and you'll want to prevent them.

As Krom says, you'll probably also want a simple navigation mesh to define where the player can and cannot walk; this can *also* be exported from the pre-computed scene baking pipeline. There is, in fact, quite a lot of optimization you can do do with this approach in terms of pre-computing data (the downside, of course, being that iteration on the specific details of the room may require re-exporting through the entire pipeline, which may be costly).

---
Tags: 2d, 3d, graphic-effects
---


title: Device and user progression conflicts

text:
# Question
Title: Device and user progression conflicts
Im designing a game with both digital currency and player progression, but have hit a confusing snag, where I possibly can't be the first to come to a decent solution.

To keep it simple, it's a mobile game, where the player is identified by his Device ID in the beginning. He is encuraged to connect with facebook, and if he does so, will be identified by his Facebook User ID (FBID) instead. For security reasons (and because its core to the game) you can only play online, and progression and resources are maintained by the server.

So far, the flow is simple:

* If the server has no FBID on the user, an account is created based on his DeviceID, and he plays on that.
* If the user connects to facebook, the account is updated with the new FBID, and all resources are carried over.
* If the player deletes the app, and redownloads it, we still identify him based on device id, and he gets his old account back.

But here are the area that I'm concerned:

If the same player has a second device, he would like to play from instead/also.

It's a fair scenario that if the player requires an tablet next to his phone, and he wants to play with the same account.

So my play so far, is to wipe the "temporary account" from the server, find the account with the matching FBID, and add this new device to an array of devices on the original account.

I have session based control, so they can't be playing on the same time. The old device will simply be logged out if the same user appears on the new one.

But I have a feeling this is not the best way of doing things. What if the "temporary" game is played by someone else, and that person will technicly get his account wiped and device "taken over" by the logged in user ? Im especially concerned about family-type scenarios, where devices are shared.

Does anyone have any good suggestions on structure on this ? Maybe I'm completely in the woods with my method here, and doing it all wrong.

My priorities are :

* Duplication of ingame resources must not occur
* A player should never be "punished" by starting over, if he signs in using facebook.
* A player should be able to maintain and restore his progress in the game, even if he logs out.

# Answer
> 0 votes
I would have a table with three important fields: PlayerId, FacebookId, EmailAddress

If they don't want to connect with Facebook, you use email address as your unique identifier for a player. If they eventually "migrate" to Facebook, you shove the FBID in that record.

Devices are in a separate table with two important columns: PlayerId, DeviceId.

This way, it doesn't matter how many devices they have; you can always get back to a unique PlayerId.

---
Tags: mmo, client-server, facebook
---


# Question
Title: C# XNA - How to animate using Texture Atlas/ Sprite Sheet
I have a problem which I need to resolve. I am making a Space Invaders game in C# XNA. I've been following this tutorial for the Invaders. But I also have my own code for animating the Invader spritesheet. And eventually here's what I'm drawing:

```
void Draw(SpriteBatch spriteBatch){
  for (int r = 0; r < m_InvaderRows; r++)
  {
    for (int c = 0; c < m_InvaderCollumns; c++)
    {
      spriteBatch.Draw(m_BotInvaderTex, m_BotInvaderPos, m_BotInvaderHitBox, Color.White, 0f, Vector2.Zero, 1.0f, SpriteEffects.None, 0);

      // ???

      spriteBatch.Draw(m_BotInvaderTex, m_BotInvadersRect[r, c], Color.White);
    }
  }
}

```

So the first `Draw()` call draws only 1 animated sprite. The second draws 50 non-animated sprites. `m_BotInvadersRect[r, c]` is a rectangle I used as a multi-dimensional array. So I'm looking for a way to combine both `Draw` calls and have 50 animated sprites drawn on my screen. If you need to see my variables or `Update(GameTime gameTime)` just comment and I'll edit the question.

How can I animate the Bot Invaders using a texture atlas?

My code:

```
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;

namespace SpaceInvaders
{
class botInvader
{

    public botInvader()
    {

    }

    public static Texture2D g_BotInvaderTex;
    Rectangle m_BotInvaderHitBox;
    public static Vector2 g_BotInvaderPos = new Vector2(0, 24);
    Vector2 m_BotInvaderOrigin;

    int m_BotInvaderCurrentFrame = 1;
    int m_BotInvaderFrameWidth = 52;
    int m_BotInvaderFrameHeight = 88;

    float m_Timer = 0f;
    float m_Interval = 100;

    Rectangle[,] m_BotInvadersRect;
    int m_InvaderRows = 5;
    int m_InvaderCollumns = 10;
    String m_BotInvadersDirection = "RIGHT";

    public void Initialize()
    {

    }

    public void LoadContent(ContentManager Content)
    {
        g_BotInvaderTex = Content.Load<Texture2D>(".\\gameGraphics\\gameSprites\\botInvaders\\normalInvaders\\spritesheet"); // invaderShip1
        m_BotInvadersRect = new Rectangle[m_InvaderRows, m_InvaderCollumns];
        for (int r = 0; r < m_InvaderRows; r++)
        {
            for (int c = 0; c < m_InvaderCollumns; c++)
            {
                m_BotInvadersRect[r, c].Width = g_BotInvaderTex.Width;
                m_BotInvadersRect[r, c].Height = g_BotInvaderTex.Height;
                m_BotInvadersRect[r, c].X = 70 * c;
                m_BotInvadersRect[r, c].Y = 70 * r;
            }
        }
    }

    public void Update(GameTime gameTime)
    {
        m_BotInvaderHitBox = new Rectangle(m_BotInvaderCurrentFrame * m_BotInvaderFrameWidth, 0, m_BotInvaderFrameWidth, m_BotInvaderFrameHeight);
        m_BotInvaderOrigin = new Vector2(m_BotInvaderHitBox.X / 2, m_BotInvaderHitBox.Y / 2);

        m_Timer += (float)gameTime.ElapsedGameTime.Milliseconds;

        if (m_Timer > m_Interval)
        {
            m_BotInvaderCurrentFrame++;
            m_Timer = 0f;
        }

        if (m_BotInvaderCurrentFrame == 2)
        {
            m_BotInvaderCurrentFrame = 0;
        }

        m_BotInvaderHitBox = new Rectangle(m_BotInvaderCurrentFrame * m_BotInvaderFrameWidth, 0, m_BotInvaderFrameWidth, m_BotInvaderFrameHeight);
        m_BotInvaderOrigin = new Vector2(m_BotInvaderHitBox.Width / 2, m_BotInvaderHitBox.Height / 2);

        int m_RightSide = 800;
        int m_LeftSide = 0;

        for (int r = 0; r < m_InvaderRows; r++)
        {
            for (int c = 0; c < m_InvaderCollumns; c++)
            {
                if (m_BotInvadersDirection.Equals ("RIGHT"))
                {
                    m_BotInvadersRect[r, c].X = m_BotInvadersRect[r, c].X + 1;
                }

                if (m_BotInvadersDirection.Equals("LEFT"))
                {
                    m_BotInvadersRect[r, c].X = m_BotInvadersRect[r, c].X - 1;
                }
            }
        }

        String m_BotInvadersChangeDirection = "N";

        for (int r = 0; r < m_InvaderRows; r++)
        {
            for (int c = 0; c < m_InvaderCollumns; c++)
            {
                if (m_BotInvadersRect[r, c].X + m_BotInvadersRect[r, c].Width > m_RightSide)
                {
                    m_BotInvadersDirection = "LEFT";
                    m_BotInvadersChangeDirection = "Y";
                }

                if (m_BotInvadersRect[r, c].X < m_LeftSide)
                {
                    m_BotInvadersDirection = "RIGHT";
                    m_BotInvadersChangeDirection = "Y";
                }
            }

            if (m_BotInvadersChangeDirection.Equals("Y"))
            {
                    for (int c = 0; c < m_InvaderCollumns; c++)
                    {
                        m_BotInvadersRect[r, c].Y = m_BotInvadersRect[r, c].Y + 3;
                    }
            }
        }
    }

    public void Draw(SpriteBatch spriteBatch)
    {
        for (int r = 0; r < m_InvaderRows; r++)
        {
            for (int c = 0; c < m_InvaderCollumns; c++)
            {
                spriteBatch.Draw(g_BotInvaderTex, g_BotInvaderPos, m_BotInvaderHitBox, Color.White, 0f, Vector2.Zero, 1.0f, SpriteEffects.None, 0);
                spriteBatch.Draw(g_BotInvaderTex, m_BotInvadersRect[r, c], Color.White);
            }
        }
    }
}

```

}

# Answer
> 3 votes
You need a Source Rectangle and Destination Rectangle.

The Source Rectangle will pull a rectangle defined by you out of the sprite sheet, then draw it at the specified position.

**PsuedoCode**

```
        int width = txtHero.Width / Columns;
        int height = txtHero.Height / Rows;
        int row = (int)((float)currentFrame / (float)Columns);
        int column = currentFrame % Columns;
        Rectangle sourceRectangle = new Rectangle(width * column,height*row,width,height);
        spriteBatch.Draw(txtHero, DrawLocation, sourceRectangle, Color.White);

```

However you choose to iterate through your sprites in the sprite sheet is entirely up to you.

A great reference when I first learned XNA can be found here

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


# Question
Title: Touch sides of tablet, moves that direction
I am making a game where the player flies a balloon through a cavelike structure.

I am having trouble making him fly correctly when I try it out on my android tablet, seeing as it requires different input to move.

How can I make the player move towards the touched side? By creating a ray? through touched objects? :)

# Answer
> 1 votes
Following along with the other suggestions, you can use the screen width to determine the left or right side of the screen. I might also suggest using a dead spot around the balloon. Precision touching can be difficult. if you split the screen on a single column of pixels, touches near this divide might get registered on the wrong side of the line that the player wants.

This bit of pseudo code assumes that the balloon stays in the center of the screen and the background moves.

```
var leftBounds  : float = screenWidth/2 - balloonWidth/2;
var rightBounds  : float = screenWidth/2 + balloonWidth/2;
if (Input.touchCount > 0) {
    var touchPositionX : float = Input.getTouch(0).position.x;
    if (touchPositionX <= leftBounds) {
         rigidbody2d.AddForce(-vector2.right*5);
    }
    if (touchPositionX >= rightBounds) {
        rigidbody2d.AddForce(vector2.right*5);
    }
}

```

If the balloon does not stay in the center of the screen, then the `leftBounds` and `rightBounds` will have to be calculated off of the balloons current position.

# Answer
> 0 votes
Using two different inputs (one finger and two fingers) for a same action (add a force) can be disturbing.

I would suggest you to only use one finger and orient the force accordingly to the touch position on screen.

As you seem to use Unity, you can easily get the touch position thanks to Input.mousePosition. Combined with Screen.width you will know if player has touched left or right side of the screen.

I don't know much about the actual gameplay of your game but with such technique it's easy to determine the actual force applied accordingly to the finger position... you could says something like "the closest of the border your tap is the biggest the applied force is"

I hope it helps.

---
Tags: unity, android, touch
---


title: HLSL compiled code

text:
# Question
Title: HLSL compiled code
I've been using RenderDoc for debugging my shaders, and one thing that struck me as odd is that sometimes, after stepping through the debugger, I notice some vector attributes are interchanged, for example sometimes a float3 variables register has `.z` interchanged with `.y`, and I'm positive there is nothing wrong in the shader code part.

Is this some magic optimizations from the compiler? It certainly makes debugging ALOT more frustrating, never being quite sure if it truly is the `viewPosition.z` or actually the `viewPosition.y` for example... Is there any good ways around this?

# Answer
> 2 votes
The compiler won't always put the ".xyz" of a hlsl variable into ".xyz" of a register, if that's what you're referring to - sometimes it will move between .xyz, .xyw, .yzw, or even between components in separate registers, depending on if it's some intermediate calculation value or not and how much register pressure there is. As far as I'm aware there's no way to change this, it's just how the internal register allocation handles things. If this swizzling is happening and getting you some wrong output though, that means a bug in RenderDoc :).

You can make it a little easier to read if you disable optimisations and enable the debug flag /Zi or D3DCOMPILE\_DEBUG when compiling your shader. That way whenever you have a function that returns a value, it will always compile in a 'mov' instruction that contains the return value, to make it easier to trace what's happening from then on. I think it also makes a 'mov' for each function parameter, but don't quote me on that. In either case, the compiler doesn't try nearly as hard to minimise the number of registers used.

What's all the more infuriating is that modern GPUs have moved away from the SIMD vector style instructions and it all compiles down to scalar operations under the hood, but we're stuck with this old-style fxc!

---
Tags: directx11, hlsl
---


# Question
Title: Achieving 1 pixel outline around sprites which changes colour depending on the background?
Here's an example of what I mean:

In this gif, when the character is on the dark background, his outline is almost black, whilst it retains more colour if the background he's on is the sky one. How can I achieve this in Unity? I don't think it's individual sprites

# Answer
> 6 votes
Your gif is from Path to the Sky (TIGSource), and definitely uses a pixel shader to achieve that particular outline.

For a guide to using custom shaders in Unity, have a glance at their shader reference page. There are a few tutorials and samples that should get you started.

However, I agree with @DMGregory, you can create a similar looking effect with a LOT less effort by using a dark but transparent border around the sprites.

# Answer
> 3 votes
I think there is a simple/dump way of achieving this (which I have not tried yet on code).

Assets:

* You have one background image
* You have an image with the same size as the background but painted in the colours you want the border to be painted in (referred to as "border-color" image)
* You have your regular sprites
* You have a 1-bit (or 8-bit) outline sprite for each sprite

What you do is render the game in 3 layers:

* Background at the back with 100% alpha
* The "border-color" image with 0% alpha aligned to the background
* Your sprites with their alpha on top

You also need a "hidden" layer, one that will not be rendered directly on the scene. This layer will contain the "outline" sprites (which should be aligned with the regular sprites). This layer will be in turn used as the mask of the "border-color" layer.

---

I got the following working on Pixelmator (something like Photoshop) real quick with sprites I found on the Internet:

The border-color image is simply the background with inverted colours.

---
Tags: unity
---


# Question
Title: How to write a unity script to observe the position of a game object (during scene creation)
I want to write a simple Unity script to be notified when a game object is moved, during the creation of the scene.

More precisly, I want to write a Unity script that can recognize when the user click on the blue, or red, or green axis of the selected game object, and then when the user release the click.

If this is not possible, I want to write a script that can recognize when the selected game object position changes.

Are there existing c# listeners that can be used from within Unity to achieve this?

# Answer
> 0 votes
The update function can be activated during edit time. Here you could detect if the object has moved.

Firstly, you need to tell unity that you want the update function during edit time; \[ExectureInEditMode\] attribute. For more information see here.

This will cause the update routine to be called every time something in the scene changed. You will then need to store a "last position" variable in your object and check if the current position is different. If it is, the object moved.

```
[ExecuteInEditMode]
public class ExampleClass : MonoBehaviour {
    public Transform target;
    private Vector3 lastPosition;
    void Update() {
        if (lastPosition != transform.position)
        {
            // object moved
        }
        lastPosition = transform.position;
    }
}

```

This will also execute at runtime, so you might want to set a flag to indicate if it's runtime or not. This can be done by setting the flag in the Start() routine.

There is already a flag to indicate this. You can check Application.isPlaying or Application.isEditor.

---
Tags: unityscript
---


# Question
Title: How can I change the value of a matrix uniform in an OpenGL vertex shader?
I'm new at OpenGL. I have a uniform transform matrix in a vertex shader file. I want to modify the matrix by individually assigning each values in the matrix. How can I do that in C++?

I learned that we have to get location variable by using `glGetUniformLocation` but I am not sure how to access and modify index *n* with it with `glUniform`.

# Answer
First you get the uniform's location:

```
GLint location = glGetUniformLocation(programId, "uniform name");

```

Once you have the location you can send the entire value of the matrix via `glUniformMatrix4fv`:

```
const GLFloat matrix[] = { ...16 values of the matrix here... };
glUniformMatrix4fv(location, 1, GL_FALSE, matrix);

```

Thus, to change a single element, change it in the CPU-side representation of the matrix (for example, set `matrix[4] = 1.0f`) and re-send the entire matrix uniform, leaving the rest of the elements unchanged.

If, for some reason, you no longer have a CPU-side copy of the matrix value, you can use `glGetUniformfv` to query the current value of a uniform based on its location. Note that you should generally keep a CPU-side copy of the matrix around because modifying it and sending it via `glUniformMatrix4fv` alone is going to be faster than first querying it via `glGetUniformfv`, modifying the queried data, and resending it.

(You cannot directly query and modify a single element of a matrix via OpenGL, you can only query and send the 16 elements all at once; you can modify a single element of the 16-element array on the CPU however.)
> 1 votes

# Answer
using glUniformMatrix4fv:

```
float[16] matrix = {/*16 individual values*/};

glUniformMatrix4fv(location, 1, GL_FALSE, matrix );

```

this will overwrite all 16 values, if you want to keep the old ones you can keep them yourself or query them with `glGetUniform`
> 0 votes

---
Tags: opengl, c++
---


title: Libgdx - gesture dection

text:
# Question
Title: Libgdx - gesture dection
I have made a card game, and have two methods that sort the players hand.

```
sortHandBySuit();
sortHandByValue();

```

I would like one method to be called when the user slides their finger from left to right across the screen, and the other from right to left.

```
public class InputHandler implements InputProcessor{
  .............
  public boolean touchDragged(int screenX, int screenY, int pointer) {
    world.getHand().sortHandBySuit();
    return false;
  }
  .............
}

```

How can I use touchDragged to call my methods?

# Answer
Not sure if this is the best way for detecting gestures, but this is how I would do it:

On touchDown() I would set two member variables to store where the touch began.

```
int xStart;
int yStart;

int xDrag;
int yDrag;

boolean gestureStarted = false;

public boolean touchDown(int screenX, int screenY, int pointer) {
  xStart = screenX;
  yStart = screenY;
  return true;
}

```

Then, in touchDragged(), I would find the last point that the touch is dragged to.

```
public boolean touchDragged(int screenX, int screenY, int pointer) {
  gestureStarted = true;
  xDrag = screenX;
  yDrag = screenY;
  return true;

```

}

Finally, the gesture will end when they lift their finger from the screen and this is when we compare our values and make our sorting calls.

```
public boolean touchUp(int screenX, int screenY, int pointer) {
//check that the user hasn't dragged up or down and that we are making a gesture
  if(yDrag<yStart+50 && yDrag>yStart-50 && gestureStarted){
//check if user has dragged left
    if(xDrag<xStart-50){
      sortHandBySuit();
//check if user has dragged right
    }else if(xDrag>xStart+50){
      sortHandByValue();
    }
  }
  gestureStarted = false;
  return true;
}

```

If you wanted them to be able to swipe back and forth to rapidly change the sorting without lifting their finger, you can do all the value checks and method calls in touchDragged(). This would also make the `gestureStarted` variable unnecessary. However, without a timer of some sorts, this makes a slow awkward gesture still potentially trigger the sorting and might not be the kind of control you like. You would have to also implement a timer to make sure that the gesture happens within a short period of time (1 second).

```
public boolean touchDragged(int screenX, int screenY, int pointer) {
//check that the user hasn't dragged up or down and that we are making a gesture
  if(yDrag<yStart+50 && yDrag>yStart-50){
//check if user has dragged left
    if(xDrag<xStart-50){
      sortHandBySuit();
      xStart = screenX;
      yStart = screenY;
//check if user has dragged right
    }else if(xDrag>xStart+50){
      sortHandByValue();
      xStart = screenX;
      yStart = screenY;
    }
  }
  return true;
}

```
> 2 votes

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


title: Sprite collision with color?

text:
# Question
Title: Sprite collision with color?
Is this possible?

To elaborate, I am making a PacMan offshoot. Essentially it is a "zoomed in" version of the game, but the board is randomly generated. I have 11 .png files each to be used as a background for different hallway shapes. You have your straightaways, corners T junctions and cross intersection. They are very simple, each has a black background and the walls are blue. What I am looking for is a way to stop the player from walking on the blue parts of each image. Is that possible?

My current set-up is that I have a `Piece` class that holds the image, `Entry points` as bools (up down left right) for when I randomly select the image to be used so that a path can be created, size, etc. I then have a `Board` class that holds a list of Pieces (size 11 (One for each image))) and then 2D an array "board" (currently 9x9) that randomly but intelligently generates the map. When it comes to player pathing, I was manually going to add to the `Piece` class code that adds invisible rectangles over the blue walls and then have the `Player` class, or some other class, check for collision. This would take a ton of extra code because each image is different so each would need to be manually done.

I was just thinking there must be an easier way to do this, and the whole color idea occurred to me. If i could just check if it intersects the blue and then change its position back that would be much easier.

I am at work currently, but if there is any code you would need to see, or any other helpful information let me know and I will add it as soon as I get home!

TL;DR Is there a way to check collision via color, or add rectangle automatically over a specific color.

# Answer
I wouldn't even try to use pixel perfect collisions for this. Given the fact that you've got a limited and fixed amount of possible tiles as well as pretty simple rules ("allow player to leave the tile in some direction or not"), I'd just work with a bitmask/property for your tiles.

For example, you could create an enum with the possible directions:

```
enum TileFlags
{
    BorderTop    = 0x01,
    BorderBottom = 0x02,
    BorderLeft   = 0x04,
    BorderRight  = 0x08,
    Solid        = 0x0f
};

```

Every tile would then store its own bitmask defining the directions that are enclosed/sealed-off:

```
struct TileData
{
    uint spriteOffset; // used for drawing
    uint flags;        // define the tile's behavior
}

```

For example, to define a tile that has a border on the top and right borders, you could set its `flags` like this:

```
tiles[someIndex].flags = BorderTop | BorderRight;

```

When determining, whether the player is able to leave that tile to the right (or get close to the right border; depends on your implementation):

```
bool may_move = (tiles[someIndex].flags & BorderRight) == 0;

```

This will also allow you to add even more tile flags later on, for example you could create ice fields, acceleration pads, mud slowing you down, teleports, etc. Just add a new enum member and then use it when doing your checks.
> 1 votes

# Answer
An option would be to process the images once, when they are loaded. Grab the pixel data, and process it to determine the smallest Rectangle that encompasses all the pixels of a specific color.

This isn't a pixel perfect collision, but it will help with processing your images, and getting collision boxes for you.

You can further optimize this by storing the bounds in a data file, instead of running it every time you execute the binary. But if you just do it during your game load phase, it should be relatively fast, considering you have a relatively small number of images to process.

```
//Get smallest rectangle from Texture, cased on color
Rectangle GetSmallestRectangleFromTexture(Texture2D Texture, Color color)
{
    //Create our index of sprite frames
    Color[,] Colors = TextureTo2DArray(Texture);

    //determine the minimum bounds
    int x1 = 9999999, y1 = 9999999;
    int x2 = -999999, y2 = -999999;

    for (int a = 0; a < Texture.Width; a++)
    {
        for (int b = 0; b < Texture.Height; b++)
        {
            //If we find a color match, update bounds if needed
            if (Colors[a, b] == color)
            {
                if (x1 > a) x1 = a;
                if (x2 < a) x2 = a;

                if (y1 > b) y1 = b;
                if (y2 < b) y2 = b;
            }
        }
    }

    //We now have our smallest possible rectangle for this texture
    return new Rectangle(x1, y1, x2 - x1 + 1, y2 - y1 + 1);
}

//convert texture to 2d array
Color[,] TextureTo2DArray(Texture2D texture)
{
    //Texture.GetData returns a 1D array
    Color[] colors1D = new Color[texture.Width * texture.Height];
    texture.GetData(colors1D);

    //convert the 1D array to 2D for easier processing
    Color[,] colors2D = new Color[texture.Width, texture.Height];
    for (int x = 0; x < texture.Width; x++)
        for (int y = 0; y < texture.Height; y++)
            colors2D[x, y] = colors1D[x + y * texture.Width];

    return colors2D;
}

```

This is not exactly what you are asking, but I think this could help you.

Edit: Write up a blog post about this: http://www.jgallant.com/auto-calculating-bounding-box-from-texture-in-monogame-xna/
> 0 votes

---
Tags: xna, c#, collision-detection, color, bounding-boxes
---


title: CopySubresourceRegion results in no-op

text:
# Question
Title: CopySubresourceRegion results in no-op
I'm having some trouble copying a subregion from a source texture (2D) to a destination texture.

Both textures are mipmapped 2D textures, with dimensions (at mip 0) of 512 x 32.

Rather than tell you about each parameter, it's easier to show you, according to the Visual Studio debugger, at the call site:

So, question 1: **Is there anything wrong here that would cause CopySubresourceRegion to fail**? There is nothing in the Debug window (the debug layer is enabled). The destination texture is a Staging resource with the CPU Read access flag.

If that seems okay to you, here's the rest of the question:

I'm making this call as part of a unit test, and attempting to read the data right out of the destination texture immediately after. If I replace the CopySubresourceRegion call with a CopyResource instead, the answer is wrong, but there is definitely data copied across. **However, after making the call to CopySubresourceRegion and then using a Map/Read/Unmap chain, the data that comes back is all zeroes**. The texel type is R32G32B32A32\_FLOAT (or whatever it is).

I realise that the call is made asynchronously, so I added the following code between the copy and the read:

```
for (UINT i = 0U; i < numDeferredContexts; ++i) {
    CHECK_CALL(deferredContextPtrArr[i]->FinishCommandList(FALSE, &outCommandList));
    immediateContextPtr->ExecuteCommandList(outCommandList, FALSE);
}

```

And still, all zeroes. So I went one further, and changed it to the following (desperate) code:

```
for (UINT i = 0U; i < numDeferredContexts; ++i) {
    deferredContextPtrArr[i]->Flush();
    CHECK_CALL(deferredContextPtrArr[i]->FinishCommandList(FALSE, &outCommandList));
    immediateContextPtr->ExecuteCommandList(outCommandList, FALSE);
}
immediateContextPtr->Flush();
Sleep(10000);

```

But still nothing. Finally, I turned off the multithreaded rendering so it all executes on the immediate context, but even then, still zeroes.

So I'm totally stuck, and any ideas are appreciated: How can I make CopySubresourceRegion actually copy the data?

# Answer
False alarm, my apologies. I was passing the number of texels to the initial data struct's row-stride field, rather than the number of bytes.

By pure unlucky coincedence, the other unit tests I had on this area were using single-element 8-bit texel formats, which meant I was getting really lucky (as the texel count and the byte count were the same).

Thanks for your time anyway.
> 2 votes

---
Tags: c++, directx, directx11
---


# Question
Title: How do I choose an optimal texture size for a mobile Unity game?
I am developing a 2D game with Unity2D for Android, iOS, WebPlayer and maybe for desktop computers. I think the working resolution of my game is 1280\*800.

How do I choose the optimal size of textures? May the textures be high resolution, for example 1920\*1080? I read somewhere that it could be bad for devices with a small resolution.

# Answer
> 1 votes
There are essentially two things to consider when thinking about the drawback of a larger texture size; performance and build size.

Large textures are more complex to render so have higher requirements of the hardware.

Large textures also make the build size much larger which may be an issue when considering the mobile market - mobile devices have less storage and, in the case of smart phones, the users are likely to want to download the application on a mobile broadband connection - 3g/4g etc - where build size often makes a difference in a person's decision to download an application.

These two factors need to be balanced with what you consider a minimum graphical quality on each platform.

The first thing to note in unity is that it's possible to have platform specific import settings in which you can dictate the maximum resolution for textures on a given platform. This is controlled in the texture importer window. The settings can also be toggled by scripts.

This page on reducing the build size discusses adjusting texture quality. Essentially it discusses the fact that textures tend to be the largest part of the build, so if the build is too big you should change the texture import settings to set a maximum size.

If performance is the only issue, the easiest way to adjust for that is to change the quality settings. It has a texture quality option in which you can tell the system to use full, half, quarter or eighth resolution. So for different platforms you could just set this value to something else. I don't think this affects the build size however.

# Answer
> 1 votes
Basically you have to balance \- reduced number of draw calls \- small memory footprint at runtime \- small application package size (as already said)

I suggest to organize textures/sprites that are printed in the same scene in "Sprites Atlases" and keep the max resolution of atlases around 1024x1024 or 2048x2048. This, combined with some good scripting as NGUI, will reduce drastically your draw calls. Also try to organize the sprites based on the "layer" or "depth" they are printed at: for example put in a atlas all GUI sprites and in another all your "character sprites" (especially if you use 2D sprites animations".

At the other end if you have big images/texture you want to use as background, it's generally better to use them as isolated textures and get rid of them when you load another level.

When importing 2D sprites use advanced mode and disable MIP MAPPING, as you don't need it (they will be always at the same distance from the camera) and try both Point and Bilinear filter mode and see what gives you the best result.

If you want the best quality in a wide range of resolution (pixel perfect or near pixel perfect from 320x200 to 1920x1080) you may have to produce multiple versions of the same sprite atlases and decide which one to load at start time (when loading the game the first time).

---
Tags: unity, android, textures
---


title: How to randomize the ball direction?

text:
# Question
Title: How to randomize the ball direction?
I've started trying a few things with Sprite Kit for Game Development. I was creating a brick breaking game. So I've run into a issue on how to randomize the initial starting direction of the ball.

I set the following properties for my ball which launches from the paddle.

```
ball.physicsBody.friction = 0;
ball.physicsBody.linearDamping = 0;
ball.physicsBody.restitution = 1 ; //energy lost on impact or bounciness

```

To start at different direction during the gameplay, I've randomized the selection of the 4 vectors because I'm using the `applyImpulse` method to direct the ball in a particular direction and I need to make sure the ball does not go slow if the vector values are low.

```
int initialDirection = arc4random()%10;
CGVector myVector;

if(initialDirection < 2)
{
    myVector = CGVectorMake(4, 7);
}
else if(initialDirection >3 && initialDirection <= 6)
{
    myVector = CGVectorMake(-7, -5);
}
else if(initialDirection >6 && initialDirection <= 8)
{
     myVector = CGVectorMake(-5, -8);
}
else
{
     myVector = CGVectorMake(8, 5);
}
//apply the vector
[ball.physicsBody applyImpulse:myVector];

```

Is there any way I can randomize the direction and still maintain a speed for my ball ?

# Answer
You could instead get a random angle (within some range) and then use that for the initial direction of the ball. Something like:

```
// min angle: 10, max angle: 170
int min_angle = 10;
int max_angle = 170;
int degrees = arc4random_uniform(max_angle - min_angle) + min_angle;
float radians = degrees * M_PI/180.0f;
myVector = CGVectorMake(cos(radians), sin(radians));

```

This will be a unit direction vector though, so, you would want to multiply this by whatever amount of force you want in this direction.
> 2 votes

---
Tags: spritekit
---


# Question
Title: How can I get the instantaneous volume level of a sound at a particular playback point?
How can I go about getting the current volume output of an audio file in libGDX? By that I mean of the actual file at its current play position.

Essentially I want to write my own version of a plugin I was using in Unity for basic lip syncing. Depending how loud the audio is, a different mouth shape sprite will be shown.

So for example if there was a sound with a sentance "what is *that*?" you would expect the "that" to be a different shape than the "what is," as it's louder. Is there a way to do this, to get the volume at a certain point?

# Answer
> 1 votes
If you have read access to the audio wave, there are a few ways to do it. I will cover an accurate, and a fast method. If you do not have read access to the audio wave, you need to get access to the audio wave.

I'm not familiar with libGDX, but I highly doubt it has built-in functionality for this. It's not functionality that is typically needed, or asked of, in any software. Including software like Audacity. That said, here are my solutions:

**Accurate Method**

---

What you want are the green lines there. The length of that green line (the difference between the top of the wave, and the bottom), is going to correlate to a percentage of the max volume. The percentage could be calculated by `float percentage = greenLineLength / MaxLength;` If it ranged from -1 to 1, `MaxLength = 2`. If it ranges from 0 to 255, `MaxLength = 255`

The green lines going to be a little tricky though. First your going to need to identify those peaks. say you're analyzing the wave at point `i`. If you were to take the difference between `i` and `i+1` (`getSample(i) - getSample(i+1)`), you would end up with a value representing the direction that the wave is headed at point `i`. If the value is positive, then it is going up. If it is negative, then it is going down.

If that were put into sudo code:

```
float GetDifference(int i)
{
    return GetSample(i) - GetSample(i+1);
}

```

A peak is when it changes from going up to going down, or when it's going down and then up. Since we already know how to find out if it's going up or down. We just need to compare the value with the previous value. In sudo code:

```
bool IsPeak(int i)
{
    float a, b;
    a = GetDifference(i); // direction of the current sample
    b = GetDifference(i-1); // direction of the previous sample

    if ( ((a > 0) and (b < 0)) // if it's going up then down.
      or ((a < 0) and (b > 0)) ) // if it's going down then up.
    {
        return true; // it's a peak!
    }

    // otherwise
    return false;
}

```

From there, we just need to find peak 1, store that value, then find peak 2, and difference the two.

```
float FindVolumeFromSample(int i)
{
    int  Peak1, Peak2; // our two peaks
    bool FoundPeak;   // = true; if we have found the peak. Otherwise, false;

    // find our first peak
    FoundPeak = false;
    Peak1 = i;         // start out at the point we're searching from
    while (not FoundPeak)
    {
        if (IsPeak(Peak1)) // check to see if this is a peak
        {
            FoundPeak = true; // found the peak
        }
        else // this is not a peak
        {
            Peak1 = Peak1 + 1; // move to the next sample
        }
    }

    // loop to our second peak
    FoundPeak = false;
    Peak2 = Peak1 + 1; // Start off just after the previous peak
    while (not FoundPeak)
    {
        if (IsPeak(Peak2)) // check to see if this is a peak
        {
            FoundPeak = true; // found the peak
        }
        else // this is not a peak
        {
            Peak2 = Peak2 + 1; // move to the next sample
        }
    }

    return (GetSample(Peak1) - GetSample(Peak2)) / Maxlength;
}

```

**Fast Method**

---

Since looping through all that data can be a little too cpu intensive, there is also a simpler method: Loop through a small section of audio, find the highest point, and the lowest point, and find the difference between those. The difference between them being proportional to the percentage of the max volume as stated in the first paragraph, above.

So lets say you can access the samples through `GetSample(i)`, your given a start point, and an end point. You want to find the volume between start and end. You loop through all values from start to end, and keep the two most extreme values. In sudo code:

```
float FindVolumeBetweenSamples(int start, int end)
{
    float max, min; // the maximum, and minimum, points.

    // the current sample i, is initially equal to start
    // continue the loop while i has not reached or passed end, and,
    // increment until then.
    for (int i = start; i < end; i++)
    {
        float sample = GetSample(i);

        if (sample > max) // the new one is bigger
        {
            max = sample;
        }
        else if (sample < min) // the new one is smaller
        {
            min = sample
        }
    }

    return (max - min) / MaxLength;
}

```

As your start and end point get closer and closer, it will become more and more accurate, to a point. This method fails when you start trying to measure volume between peaks. You'll just have to hope that doesn't happen.

---
Tags: libgdx, sound
---


title: How can I optimize the size of my .apk?

text:
# Question
Title: How can I optimize the size of my .apk?
I noticed that the Flappy Bird `.apk` is only around 900 KB. I'd like to know how I can achieve a similar optimization in `.apk` file size for my own games, which use Unity. A small single-scene game developed with Unity will have an `.apk` size of nearly 10 MB, in comparison.

# Answer
It's possible to use an Android "APK Expansion File" so that additional content is downloaded at runtime the first time you launch it.

Next, if you have very few graphics that always repeat (if I remember well Flappy Bird has very few graphics assets) they can be compressed in the `.apk` and expanded in-memory during execution. Graphics and art assets are the files that have more impact on final `.apk` sizes than most other assets.

Unity loads a lot of stuff, but if you program the game directly in OpenGL you are able to cut your code and libraries to the essential and achieve very small packages.

I remember the time when adventure games (like Maniac Mansion) were all in one floppy disk.
> 2 votes

# Answer
Unity is a very powerful and very complex game engine. Most games only use a small fraction of its features. But no matter how much of it is actually used, a game which uses the Unity engine must include the whole engine which is a hefty 10MB chunk of additional filesize.

For a very simplistic game like Flappy Bird, using such a huge engine is usually overkill. They can usually be made using just the native Android API which allows to create much more compact applications.
> 1 votes

---
Tags: unity, android
---


# Question
Title: HLSL: An array of textures and sampler states
The shader must switch between multiple textures depending on the Alpha value of the original texture for each pixel. Now this would word fine if I didn't have to worry about SamplerStates. I have created my array of textures and can select a texture based on the Alpha value of the pixel. But how do I create an Array of SamplerStates and link it to my array of textures? I attempted to treat the SamplerState as a function by adding the (int i) but that didn't work. Also I can't use Texture.Sample since this is shader model 2.0.

```
//shader model 2.0 (DX9)
texture subTextures[255];
SamplerState MeshTextureSampler(int i)
{
    Texture = (subTextures[i]);
};

float4 SampleCompoundTexture(float2 texCoord, float4 diffuse)
{
    float4 SelectedColor = SAMPLE_TEXTURE(Texture, texCoord);
    int i = SelectedColor.a;
    texture SelectedTx = subTextures[i];
    return tex2D(MeshTextureSampler(i), texCoord) * diffuse;
}

```

# Answer
> 1 votes
I'm a newb to DirectX myself, but from what I've read, in HLSL, this:

```
Texture textures[3];

```

Will actually be compiled like this:

```
Texture textures0;
Texture textures1;
Texture textures2;

```

So indexing into the array won't work.

---
Tags: textures, shaders, hlsl, sampler-state
---


title: Memory-leak around SDL_FreeSurface

text:
# Question
Title: Memory-leak around SDL_FreeSurface
When I call my tile engine function, the amount of memory my program uses begins to spike at about 80 - 90 megabytes per second. The memory use continues to go up until the program crashes. The function is below.

After tinkering with it, I figured out that I could reduce this bricking to about 15 megabytes per second if I called SDL\_FreeSurface every time I ran the function. But this confused me, because I thought that you are only supposed to use SDL\_FreeSurface when the program exits so that the images don't continue to occupy the memory.

1. if I don't call SDL\_FreeSurface before I blit the tiles, do the previously blitted tiles continue to exist?
2. If I don't how do I fix the aforementioned bug?

The edit I made to bring the memory bricking down to 15 megabytes per second is commented out.

```
SDL_Surface* loadedTile = NULL;
SDL_Surface* modelIMAGE = NULL;

void enviroment::blitTiles(SDL_Surface* windowENVIRO, int tileAmount, int tileType[], int tileXenviro, int tileYenviro, bool quitTiles)
{
    HDcounter = -1;

//if(loadedTile != NULL)
//{
//    SDL_FreeSurface(loadedTile);
//}

loadedTile = IBFobjectENVIRO.loadIMG("tileClipSheet.png");

        for(int tiles = 0; tiles < tileAmount; tiles++)
        {

            switch(tileType[tiles])
            {
                //Black square (unpassable)
                case 1: IBFobjectENVIRO.blitIMG(tileXenviro - 75, tileYenviro, windowENVIRO, loadedTile, 0, 0, 75, 75);

                        HDcounter += 1;

                        forbiddenX[HDcounter] = tileXenviro - 75;
                        forbiddenY[HDcounter] = tileYenviro;
                        forbiddenSpriteWidth[HDcounter] = 75;
                        forbiddenSpriteHeight[HDcounter] = 75;
                        forbiddenSpriteDepth[HDcounter] = 75;
                break;

                //Grey square
                case 2: IBFobjectENVIRO.blitIMG(tileXenviro - 75, tileYenviro, windowENVIRO, loadedTile, 75, 0, 75, 75);
                break;

                //Brown square
                case 3: IBFobjectENVIRO.blitIMG(tileXenviro - 75, tileYenviro, windowENVIRO, loadedTile, 150, 0, 75, 75);
                break;

                //Invisible square (unpassable)
                case 4: IBFobjectENVIRO.blitIMG(tileXenviro - 75, tileYenviro, windowENVIRO, loadedTile, 225, 0, 75, 75);

                        HDcounter += 1;

                        forbiddenX[HDcounter] = tileXenviro - 75;
                        forbiddenY[HDcounter] = tileYenviro;
                        forbiddenSpriteWidth[HDcounter] = 75;
                        forbiddenSpriteHeight[HDcounter] = 75;
                        forbiddenSpriteDepth[HDcounter] = 75;
                break;
            }

            tileXenviro += 75;

            if(tileXenviro >= level1ObjectENVIRO.level1Width)
            {
                tileYenviro += 75;
                tileXenviro = tileXenviro - level1ObjectENVIRO.level1Width;
            }
        }

    if(quitTiles == true)
    {
        SDL_FreeSurface(loadedTile);
    }
}

```

# Answer
> 2 votes
If loadIMG() is reading the image data from a file, that data needs to be stored somewhere. That somewhere is newly-allocated memory. So each time you call blitTiles() (presumably 60 times a second), you are allocating new memory that is never freed. This is why the memory usage is ballooning.

To solve this, you ought to keep your storage and loading outside of blitTiles(). *loadedTile* is already global, which is one storage option. Now move the image loading to somewhere before your main loop runs and then you can free it just once when your app is exiting.

---
Tags: sdl, memory
---


title: Changing a Sprite When Hit in GameMaker

text:
# Question
Title: Changing a Sprite When Hit in GameMaker
I am making a simple little Galaga style game. I want the objects sprite to change whenever it is hit.

For example if a laser hits an alien then the sprite takes 1 out of 4 damage to its health points (HP). However I want the sprite to change from green to yellow after 1 hit, yellow to orange after 2 hits, orange to red after 3 hits, and red to pixel explosion after all 4 HPs are lost. That way you can easily distinguish the amount of health each alien has left.

How can I do this? Preferably explain it in code.

# Answer
I tried this and it works perfectly, if you would like the gamemaker file, tell me...

So the alien image make three more image indexes.. Or to be way simpler make three more seperate images of the alien, Make a normal image of the alien, a green, a yellow, a red, and look online for some explosion gif.

So if your laser beam is an object and not just a drawn event image, thats good and what we need.

## Alien Object

So in your alien event add a **collision** with the laser beam. now in the **create** event make a variable:

```
hits=0

```

Now back to the **Collision** event. In there add this code:

```
hits=+1

```

Now make a **Step** event and add this code:

```
if hits=1{ action_sprite_set(sprAlienGREEN,0,0) } //Alien gets hit one time
if hits=2{ action_sprite_set(sprAlienYELLOW,0,0) } //Alien gets hit two times
if hits=3{ action_sprite_set(sprAlienRED,0,0) } //Alien gets hit three times

```

Now we need to make that alien explode! so now working **still** in the step event add this code

```
if hits=4{ instance_change(objExplosionGif,1) } //Alien dies with exploding gif'

```

**Now hold on we need to make the explosion object!**

## Explosion Object (objExplosionGif)

Add an event called **Other** and in the list of items click **Amination End** (if i am correct that is what its called). Now enter this code

```
instance_destroy(x,y) //Destroy this explosion when animation is done...

```

## And your done!

Hopefully it worked for you with ease!
> 0 votes

# Answer
I was looking for a solution to a simular problem of making a sprite flash when it was hit. What i would suggest is to add the different colours (or damage states) as images within the same sprite. Then include a piece of code in the enemy object's step event that is something like:

If (hitpoints \>= 10) {image\_index=0} // the original sprite

If (hitpoints \<= 5) {image\_index=1} // the first damage state

And so on...
> -2 votes

---
Tags: sprites, software-engineering, game-maker
---


# Question
Title: Simplified math formula to calculate stock price based on supply/demand
I am making an overly simplified version of a stock simulator game, because I:

1. am fascinated with how the stock market works
2. learn better & faster from a project like this, rather than text-books

Before writing any actual code, I started making an Excel spreadsheet to simulate the fluctuations of 1 company's stock based on how many people buy/sell the stock on any given day, so that when I have the code, I have something to compare it against to know that it works.

Variables I have access to:

* a) Total amount of stock issued - 10000
* b) Starting stock price when the company goes public - $10.00
* c) Stock available on any given day
* d) Stock bought/sold on that day - for example, 150 on day 1
* e) Stock bought/sold the previous day - when first starting the simulation, this number is 0
* f) Company profits on any given day - *For simulation purposes, profits are calculated daily, not quarterly or yearly*
* g) Stock price - **This is what I need calculated**

I tried using (d-e)/a which gives me a difference, like 0.015 which I use to get the stock price for the next day. But it just seems too simple, since buying 100% of the stock on day 1 and then selling 100% of it on day 2, brings down the price to $0.00. Perhaps this would work given enough random participants who all buy/sell the stock, but in this case, I need the simulation to work with just 1 person. And the simple function I wrote just gives too much power to that 1 person.

PS: For simulation purposes, I assume there is always a buyer and always a seller for the stocks.

PPS - Edited to provide the test numbers I'm starting with

# Answer
> 4 votes
Maybe you can have an entity 'Market' that represents a collection of players 'Trader'. Each of those players can be either a real person or a "virtual" one - bot. Each player can be willing to buy or sell certain amount of stock at certain price. Some bots can be optimistic, some pessimistic.

To simplify things all trades will be carried out at certain time(s) within a day. You can open a position to trade specific amount at specific price.

The 'Market' than sums up all the requests at "trade time" and if your position qualifies (within available amount and price) your trade will be carried out.

# Answer
> 0 votes
In finance the simplest model of prices is the lognormal distribution https://en.wikipedia.org/wiki/Log-normal\_distribution

To simulate this you create a random normal variate each "tick" (using Box-Muller https://stackoverflow.com/questions/2325472/generate-random-numbers-following-a-normal-distribution-in-c-c ) and multiply that by the price and a constant to get the change in value of the stock.

Pick a different constant for each stock, and they will need to be small (0.01 is reasonable for daily updates, smaller for shorter periods).

Actually trying to trade these will be a boring game--since the price moves are random there will be no skill involved. To make it more pointed, multiply each stock price (not the stock price move) by a different factor as well as adding the random noise. Factors will be very close to 1 (0.999-1.001) but if the player can work out which ones are going up, he's in with a chance of making a profit.

---
Tags: mathematics
---