# Question
Title: How do I render text in a view in SFML 2.5.1 without artifacts?
I'm using the following code to render text in a letterboxed view.

```
#include <iostream>
#include <random>
#include <math.h>
#include <cstring>
#include <ostream>

#include <SFML/Graphics.hpp>

const float FIXED_UPDATE_TIME = 16.67f;//60fps

const unsigned int DEFAULT_CAMERA_WIDTH = 1280;
const unsigned int DEFAULT_CAMERA_HEIGHT = 720;

sf::View get_letterbox_view(sf::View view, int window_width, int window_height) {

    // Compares the aspect ratio of the window to the aspect ratio of the view,
    // and sets the view's viewport accordingly in order to archieve a letterbox effect.
    // A new view (with a new viewport set) is returned.

    float window_ratio = window_width / (float) window_height;
    float view_ratio = view.getSize().x / (float) view.getSize().y;
    float sizeX = 1;
    float sizeY = 1;
    float posX = 0;
    float posY = 0;

    bool horizontal_spacing = true;
    if (window_ratio < view_ratio)
        horizontal_spacing = false;

    // If horizontal_spacing is true, the black bars will appear on the left and right side.
    // Otherwise, the black bars will appear on the top and bottom.

    if (horizontal_spacing) {
        sizeX = view_ratio / window_ratio;
        posX = (1 - sizeX) / 2.f;
    }

    else {
        sizeY = window_ratio / view_ratio;
        posY = (1 - sizeY) / 2.f;
    }

    view.setViewport( sf::FloatRect(posX, posY, sizeX, sizeY) );

    return view;
}

int main() {
    sf::RenderWindow window(sf::VideoMode(DEFAULT_CAMERA_WIDTH, DEFAULT_CAMERA_HEIGHT), "Adventure of Jaggy Font Edges");
    window.setMouseCursorVisible(false);

    // Set up resource
    sf::Font fnt;
    fnt.loadFromFile("res/fnt/Ruda-Regular.ttf");

    // Set up text
    sf::Text text;
    text.setFont(fnt);
    text.setString("TEXT RENDERING");
    text.setCharacterSize(128);
    text.setFillColor(sf::Color::White);
    text.setOutlineColor(sf::Color::Black);
    text.setOutlineThickness(3.f);

    // Center text (in world space, I believe?)
    sf::FloatRect text_rect = text.getLocalBounds();
    text.setOrigin(
        floorf(text_rect.left + text_rect.width/2),
        floorf(text_rect.top + text_rect.height/2)
    );
    text.setPosition(0, 0);

    // Set up view, and center it on the text
    sf::View camera_view(sf::FloatRect(0.f, 0.f, DEFAULT_CAMERA_WIDTH, DEFAULT_CAMERA_HEIGHT));
    camera_view.setCenter(0, 0);

    sf::Clock clock;

    while (window.isOpen()) {
        // only update 60fps
        sf::Time elapsed_time = clock.getElapsedTime();
        if (elapsed_time.asMilliseconds() < FIXED_UPDATE_TIME) {
            continue;
        }

        // handle events
        sf::Event event;
        while (window.pollEvent(event)) {
            // window closed event
            if (event.type == sf::Event::Closed) {
                window.close();
            } // window resized event/*
            else if (event.type == sf::Event::Resized) {
                camera_view = get_letterbox_view(camera_view, event.size.width, event.size.height);
            }
        }
        window.clear(sf::Color(255, 255, 255, 255));

        window.setView(camera_view);
        window.draw(text);

        window.display();
    }
    return EXIT_SUCCESS;
}

```

At the default resolution, it looks like this:

However, the moment I change the window size, we get artifacts:

# Answer
> 2 votes
Welcome to the world of text rendering. The most common way to get rid of these artefacts is to always make sure that you're keeping font texture resolution 1:1 with the surface it's being rendered on.

Why this happens? SFML uses texture atlases to draw fonts, and when you resize the surface that the font is being drawn on, since font atlas is smaller in ratio than the new surface, texture interpolation is being applied in order to fill in places where we don't know what exact pixel is supposed to be drawn. But for pixels near the edges of the atlas, artifacts may occur with certain texture sampler configurations. This is called texture bleeding.

How to avoid this? You need to disable interpolation, or better yet, change font size every time you resize the window. You should try calculating new font size from the information you get at `sf::Event::Resized` event, by finding ratio between original resolution and new resolution, and then rescaling font size accordingly. You will probably need to take only height ratio into account.

As for interpolation, there is no official way to disable interpolation for fonts, as far as I know, but there is a well-known hack to achieve this through the use of `setSmooth(bool)` on a specific font-size atlas of the `sf::Font`.

```
sf::Texture& texture = const_cast<sf::Texture&>(font.getTexture(font_size));
texture.setSmooth(false);

```

# Answer
> 1 votes
While this may not be the 'correct' solution for sharp text, I've rejigged the approach by rendering the text (and by implication, everything) onto a RenderTexture with smoothing enabled, which is subsequently stretched to fit the screen. This way everything on screen (sprites, text, etc) is rendered at a consistent resolution, which can be manipulated via the RenderTexture's dimensions.

```
#include <iostream>
#include <random>
#include <math.h>
#include <cstring>
#include <ostream>
#include <chrono>
#include <thread>

#include <SFML/Graphics.hpp>

using namespace std;

const float FIXED_UPDATE_TIME = 16.67f;//60fps

const unsigned int DEFAULT_CAMERA_WIDTH = 1280;
const unsigned int DEFAULT_CAMERA_HEIGHT = 720;

sf::View get_letterbox_view(sf::View view, int window_width, int window_height) {

    // Compares the aspect ratio of the window to the aspect ratio of the view,
    // and sets the view's viewport accordingly in order to archieve a letterbox effect.
    // A new view (with a new viewport set) is returned.

    float window_ratio = window_width / (float) window_height;
    float view_ratio = view.getSize().x / (float) view.getSize().y;
    float sizeX = 1;
    float sizeY = 1;
    float posX = 0;
    float posY = 0;

    bool horizontal_spacing = true;
    if (window_ratio < view_ratio)
        horizontal_spacing = false;

    // If horizontal_spacing is true, the black bars will appear on the left and right side.
    // Otherwise, the black bars will appear on the top and bottom.

    if (horizontal_spacing) {
        sizeX = view_ratio / window_ratio;
        posX = (1 - sizeX) / 2.f;
    }

    else {
        sizeY = window_ratio / view_ratio;
        posY = (1 - sizeY) / 2.f;
    }

    view.setViewport( sf::FloatRect(posX, posY, sizeX, sizeY) );

    return view;
}

int main() {
    sf::RenderWindow window(sf::VideoMode(DEFAULT_CAMERA_WIDTH, DEFAULT_CAMERA_HEIGHT), "Adventure of Jaggy Font Edges");
    window.setMouseCursorVisible(false);

    sf::RenderTexture render_texture;
    if (!render_texture.create(DEFAULT_CAMERA_WIDTH, DEFAULT_CAMERA_HEIGHT)) {
        exit(1);
    }
    render_texture.setSmooth(true);

    // Set up resource
    sf::Font fnt;
    fnt.loadFromFile("res/fnt/Ruda-Regular.ttf");

    // Set up text
    sf::Text text;
    text.setFont(fnt);
    text.setString("TEXT RENDERING");
    text.setCharacterSize(128);
    text.setFillColor(sf::Color::White);
    text.setOutlineColor(sf::Color::Black);
    text.setOutlineThickness(3.f);

    // Center text (in world space, I believe?)
    sf::FloatRect text_rect = text.getLocalBounds();
    text.setOrigin(
        floorf(text_rect.left + text_rect.width/2),
        floorf(text_rect.top + text_rect.height/2)
    );
    text.setPosition(0, 0);

    // Set up view, and center it on the text
    sf::View letterbox_view(sf::FloatRect(0.f, 0.f, DEFAULT_CAMERA_WIDTH, DEFAULT_CAMERA_HEIGHT));
    letterbox_view.setCenter(0, 0);

    sf::View camera_view(sf::FloatRect(0.f, 0.f, DEFAULT_CAMERA_WIDTH, DEFAULT_CAMERA_HEIGHT));
    camera_view.setCenter(0, 0);

    sf::Clock clock;

    while (window.isOpen()) {
        // only update 60fps
        sf::Time elapsed_time = clock.getElapsedTime();
        if (elapsed_time.asMilliseconds() < FIXED_UPDATE_TIME) {
            std::this_thread::sleep_for(std::chrono::milliseconds(17));
            continue;
        }

        // handle events
        sf::Event event;
        while (window.pollEvent(event)) {
            // window closed event
            if (event.type == sf::Event::Closed) {
                window.close();
            } // window resized event/*
            else if (event.type == sf::Event::Resized) {
                letterbox_view = get_letterbox_view(letterbox_view, event.size.width, event.size.height);
            }
        }
        window.clear(sf::Color(0, 0, 0, 255));

        render_texture.clear(sf::Color(255, 255, 255, 255));
        render_texture.setView(camera_view);
        render_texture.draw(text);
        render_texture.display();

        const sf::Texture& rt = render_texture.getTexture();
        window.setView(letterbox_view);
        sf::Sprite sprite(rt);

        sf::FloatRect sprite_rect = sprite.getLocalBounds();
        sprite.setOrigin(
            floorf(sprite_rect.left + sprite_rect.width/2),
            floorf(sprite_rect.top + sprite_rect.height/2)
        );
        sprite.setPosition(0, 0);

        window.draw(sprite);

        window.display();
    }
    return EXIT_SUCCESS;
}

```

Resizing the window produces the following (blurry) result:

I would still like to know if there's a way to achieve sharp text at any resolution, preferably without needing an intermediate buffer, so I won't mark this as solved just yet.

---
Tags: rendering, sfml, text
---


# Question
Title: Engaging ways to include party members in a fast-paced action RPG
Imagine a dynamic action RPG, where you constantly need to use your reflex to avoid bullets and fight against hordes of enemies. What would be a best way to incorporate other team members? I can think of several ways but all have disadvantages:

* Giving them orders manually is out of questions when there's so much going around that you need all your attention just to make sure your main is not hit by any incoming attack
* Using a dynamic pause like in classic cRPG such as Baldur's Gate makes the game slower and interrupts action that ideally should be quick, dynamic and engaging
* Making them autonomous is difficult to balance. If they're too weak or ineffective, then the player will constantly gets annoyed at them, that they can't get anything right and die constantly. If they are too efficient then they can ruin the game because player could just sit back and watch them defeat all the enemies. If they just pretend to engage the enemy to left the action to the player this can happen

Most action RPGs seem aware of these difficulties and prefer to have a single character for the player to run and control. This simplify things greatly but I don't want to lose the party, for plot related purposes, banters, interactions etc. What would be a good way to have the best of both words? How can I best include side characters in a fast and dynamic gameplay?

# Answer
At a high level, autonomous control for other party members seems like the best path forward to preserve the "action" aspect of an "action RPG."

You could consider a game where the NPCs don't engage in combat at all by default, leaving it entirely to the player-controlled character. That does seem like it might limit the types of characters you could write as followers, though, as well as making it a little odd, lore-wise, if you can actually swap which character is actively directly controlled -- but mainly only if all characters are on-screen at once. If you hide them with a character swap gameplay conceit, like in, say, Curse of the Moon it may not create such dissonance).

But building on that, you could look at a system where they do participate, but only if explicitly directed via the player, and in ways that are basically on-demand support attacks: for example, a system where the shoulder buttons of a controller correspond to the special moves done by the player-controlled and NPC character on-demand.

Or they could participate using an AI but *also* support allowing the player to tell them directly to use more powerful (possibly resource-expending) moves. This is sort of like what I'd imagine the control feel of Seiken Densetsu 3 / Trials of Mana might be like if that game did not pause the action when you issue follower commands.

Building on *that*, you could offer a way to grow or customize the on-demand abilities of the NPCs, giving the player a customization path for the characters that they can align with their play style or character builds.

And if you're feeling particularly adventurous you might continue that trend and create a mechanism to customize even the basic AI of the NPCs. Something ranging from a simple "prefer support / melee / ranged" toggle to something as complex as the "gambit system" used in Final Fantasy 12 to program character tactics.

The sweet spot you probably want to aim for is for the AI (if you choose to implement it) to be useful for "trash" fights, but for skill and eventually mastery of the player involvement systems to be needed for boss fights or fights where the player is otherwise out of their depth.

(Since most of my references were Square games, it occurs to me you may want to look into the combat system used in the Final Fantasy 7 remake, which looks to involve mainly direct control of one character at a time while the supporting characters do...something; it's hard because it's not out yet, but it may be worth some research.)
> 4 votes

# Answer
You could look into finding a control scheme which allows the player to control the whole party as one single entity. One game which went this route was *Legend of Zelda: Four Swords Adventure*. The player controls a party of four characters which move and fight in a close formation. When the player moves the thumbstick, the whole formation moves. When the player presses the attack button, they all attack. The player can switch between different formations as the situation requires. This particular game did it with characters which were mechanically identical, which kept the gameplay complexity rather low. But I could think of several interesting things you could do with this game mechanic with a more heterogeneous party.

You could also make the game play less like an action-adventure and more like a real-time strategy game where the player gives high-level commands to the characters which they then perform autonomously. One game which went that route was the single player campaign of *Warhammer 40k: Dawn of War 2*. It is usually promoted as a real-time strategy game and uses RTS user interface conventions. But it actually plays more like an action adventure due to the small army size of only 5 units, fast pacing, the focus on character progression and equipment and the frequent boss fights.

I am looking forward to playing your game.
> 3 votes

---
Tags: game-design, game-mechanics, rpg
---


# Question
Title: Collision detection between two arrays with nested loops: why do I get a crash?
I'm creating a game where waves of enemies are coming to me and I have to kill them.

So far, I'm doing great: it took me hours to come up with this nested loop to check for collision detection and when I ran it the game was running great... but for a few kills only. Sometimes I manage to play it even for a few minutes until it crashes, sometimes I shoot twice and it crashes, and I always get this error:

```
"Uncaught TypeError: Cannot read property 'x' of undefined
    at collision (collision.js:6)"

```

I just cannot figure out whats going on. If someone can help me I will be so grateful, I saw similar topic but I couldn't find the answer there.

```
function collision(){
    for(var l = bullets.length - 1; l >= 0; l--){
        for( var k = enemies.length - 1; k >= 0; k--){
            var e = enemies[k];
            var b = bullets[l];
            if(b.x > e.x && b.x < e.x + e.imgWidth/4 && b.y > e.y && b.y < e.y +
            e.imgHeight/4 ){
                e.enemiesHealth -= 50;
                b.deletion(); // basically assigns true to b.toDelete
                e.deletion(); // basically assigns true to e.toDelete
            }
            else if (b.toDelete){
                bullets.splice(l, 1);
            }
            else if(e.toDelete && e.enemiesHealth == 0){
                enemies.splice(k, 1);
                kills += 1;
            }
        }
    }
}

```

# Answer
> 1 votes
Looks like you're cutting off the branch over which you're standing.

In order words, it looks like you change the collection over which you're iterating, invalidating the index.

Specifically, this looks fishy:

```
bullets.splice(l, 1);

```

If the enemy you check is not the last one you'll check, and the bullet is the last from the list, you'll get an out of rage error (or something) when you'll fetch the bullet again with `var b = bullets[l];`.

The way you iterate over your array to delete items from it as you go is an appropriate one, but only when you have one loop, not when you have nested loops.

You could modify your code like this to avoid this behaviour:

```
function collision(){
    for(var l = bullets.length - 1; l >= 0; l--){
        var b = bullets[l];
        var shouldDeleteBullet = false;

        for( var k = enemies.length - 1; k >= 0; k--){
            var e = enemies[k];
            if(b.x > e.x && b.x < e.x + e.imgWidth/4 && b.y > e.y && b.y < e.y + e.imgHeight/4 ){
                e.enemiesHealth -= 50;
                b.deletion();
                e.deletion();
                shouldDeleteBullet = true; // Flag for deletion
                break; // The bullet has been consumed, we can no longer use it.
            }
            else if(e.toDelete && e.enemiesHealth == 0){
                enemies.splice(k, 1);
                kills += 1;
            }
        }

        if (shouldDeleteBullet){
            bullets.splice(l, 1);
        }
    }
}

```

This should fix the crash that you get.

---

I'll go a bit further and suggest another thing that might not be working as you expect:

```
b.deletion();
e.deletion();

...

if(e.toDelete && e.enemiesHealth == 0){
    enemies.splice(k, 1);
    kills += 1;
}

```

With this code, if the bullet is the last on the list, or if the enemy is the last on the list being checked, it will not be deleted until the next frame (the next time you iterate over those arrays).

It's not clear why you defer the deletion to later, so I'll suggest you delete the item right away:

```
function collision(){
    for(var l = bullets.length - 1; l >= 0; l--){
        var b = bullets[l];
        var shouldDeleteBullet = false;

        for( var k = enemies.length - 1; k >= 0; k--){
            var e = enemies[k];
            if(b.x > e.x && b.x < e.x + e.imgWidth/4 && b.y > e.y && b.y < e.y + e.imgHeight/4 ){
                e.enemiesHealth -= 50;

                if (e.enemiesHealth <= 0){ // This will allow a greater variety of damage eventually
                  enemies.splice(k, 1);
                  kills += 1;
                }

                shouldDeleteBullet = true; // Flag for deletion
                break; // The bullet has been consumed, we can no longer use it.
            }
        }

        if (shouldDeleteBullet){
            bullets.splice(l, 1);
        }
    }
}

```

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


# Question
Title: What to call an Object that falls only when it's collided with?
I am currently working on Objects/Blocks for my 2D Jump'n'Run. Now I want to add a new type of block, which falls down only if the player/an actor collides with it. But I don't know what to call this type.

Or more generally: Objects that only do stuff/change behaviour if interacted with.

* How should I name the first type and
* the second more general type?

# Answer
> 1 votes
How you name your objects in your game will really depend on your game and what make sense to you and your team.

However, you seem to be after the more generic term *body*. What you're actually working with is called rigid body and rigid body dynamics, which imply that the objects in your simulation do not deform (or deform so little that we neglect the deformation).

* Bodies that are part of the environment and never move are often called *static bodies*.
* Bodies that can move when interacted with are called *dynamic bodies*.
* Some physics engines have a `disabled` property for disabling the body and not consider it when performing a simulation step. Some have an `auto_disable` flag that allows the body to disable itself when it's not moving for a period of time; these bodies are re-enabled upon a collision with another object.

I hope these details will help you come up with names that fit your game/architecture.

---
Tags: physics, terminology
---


# Question
Title: Why is my player still moving down when I set its gravity to 0?
I'm writing Lode Runner like platformer game. I'm trying to solve player sprite slowly moving down when on ladder by setting `player.body.gravity.y = 0`. I have arcade physics gravity y set to 900 in game config. But game gravity settings seems to override `player.body.gravity` settings.

I even log `player.body.gravity.y` to console. It shows 0 when player is on ladder. But it still slowly moving down.

# Answer
> 1 votes
According to this documentation page, it looks like the total gravity for a body is the one you set the way you did for your body, added to the global gravity:

> **gravity :Phaser.Math.Vector2**
>
> Acceleration due to gravity (specific to this Body), in pixels per second squared. Total gravity is the sum of this vector and the simulation's gravity.

I haven't worked with Phaser 3, but I guess that, since the total gravity is a *sum* of values, you'd want to set the gravity for your player to -900 to counteract the effect of the gravity.

Alternatively, if you just want to disable the gravity for your object, it looks like you could do it through the `setAllowGravity(true/false)` function, as described here.

As an example, you can take a look at this sandbox, setting the gravity to `-60` at line 38 will make the second box stay still.

---
Tags: physics, phaser
---


# Question
Title: How can I use the animation transitions?
So I want to make my animation transitions smooth, thats why I made transitions on the animator, but how can I activate them if I use trigger paramaters??? Heres the code:

```
public float speed = 0.3f;
public float sprintSpeed = 2.5f;
private Rigidbody rigidB;
private float midJump = 1f;
public float rotSpeed = 2;
Animator anim;

void Start()
{
    rigidB = GetComponent<Rigidbody>();
    anim = GetComponent<Animator>();
}
void Update()
{

    //Character rotation with A and D

    var z = Input.GetAxis("Horizontal") * rotSpeed;

    //Character movement with W and S

    var y = Input.GetAxis("Vertical") * speed;

    //Character animations

    if (Input.GetKey(KeyCode.RightShift))
        y = y * sprintSpeed;

    if (Input.GetKey(KeyCode.RightShift) && y > 0.31)
        anim.Play("Sprint");

    if (y < 0.001)
        anim.Play("Idle");

    if (y > 0.001 && y < 0.31)
        anim.Play("Run");

    transform.Translate(0, -y, 0);
    transform.Rotate(0, 0, -z);

    //Character Jump

    if (midJump == 1 && Input.GetKeyDown(KeyCode.Space))
    {
        rigidB.velocity = new Vector3(0, 45, 0);
        midJump = 2;

    }
    else if (rigidB.velocity.y == 0)
        midJump = 1;

}

```

# Answer
You can set the parameters through the animator. And the transitions will play the same as you set it up.

for example if you wanted to set the horizontal speed in the animator parameters then have the transition play if the horizontal speed is \> 0.1

```
var z = Input.GetAxis("Horizontal") * rotSpeed;
anim.SetFloat("HorizontalSpeed", Mathf.Abs(z));

```

another example setting the vertical speed that is linked

```
anim.SetFloat("vSpeed", GetComponent<Rigidbody2D>().velocity.y);

```

you can also Set a boolean, int or Triggers the same way depending on what you need.

edit -added a pic to show the parameters getting set in the animator
> 1 votes

# Answer
You are switching between your animations with `anim.Play(animationName)`. If you do that, the animator switches to the new animation immediately without going through any transitions.

If you want the animator to use transitions, don't trigger the desired animation directly. Trigger the animations indirectly by:

1. Define some parameters in your animation controller
2. Defining conditions for your transitions in the animator window which trigger a transition when certain parameters have certain values.
3. Cause those conditions to become true from your script by setting the values of those parameters with the methods `anim.SetFloat`, `anim.SetInteger` and `anim.SetBool`

One such parameter could be "speed". You could create transitions between "Idle", "Run" and "Sprint" which get triggered when "speed" is under or over a certain threshold. Then you just need to send the current speed from your script to the animator with `anim.SetFloat("speed", y)`
> 0 votes

---
Tags: unity, animation, animator
---


# Question
Title: How to ensure my Sine Wave movement starts from the middle-line of the wave
I am trying to make an enemy for a space game which has Sine style movement. I pretty much have it working how I want, but right now I have to manually fiddle with the 't' value to make the wave equal on both sides from the starting position x.

I tried first using a real time variable i made from incrementing my 'aliveTime' by Time.deltaTime every update frame.

Then I realised I should probably use its Y position as the timeline because that is what i am trying to base the sideways movement from. But no matter how hard I think (and try random permutations of the formula/code below) I cannot get it to always be 'centred' in the wave (ie. when i change the figures for amplitute and speed\_x , it skews the wave off in seemingly unpredictable ways).

Anyone have ideas for what to pass as the 't' parameter in the Mathf Sin line below? (thanks!)

```
public class Enemy_SineWaveAttack : EnemyBehaviour
{
public float speed_x;
public float amplitute;

protected override void FixedUpdate()
{
    base.FixedUpdate();
    Vector2 vel = rb.velocity;
    vel.x = amplitute * Mathf.Sin(transform.position.y * speed_x); // WHAT CAN I USE HERE TO CENTRE THE WAVE START POSITION?

    vel.y = -Game_Manager.instance.Global_Enemy_Speed * Time.deltaTime;
    rb.velocity = vel;

}
}

```

Screenshots (if they help to explain what i need) Note, middle enemy is the only one Im talking about here):

See how it moves in wave, but it started the wave from original position and moves to the right from there, and NOT to the left of the original position ever)

---

Ok, before seeing the answer from DM Gregory I tried my own solution which was to subract half from the overall value of 't' .

I ended up with this and it seems to work with various values for speed and amplitute

```
 protected override void FixedUpdate()
{
    base.FixedUpdate();
    Vector2 vel = rb.velocity;
    vel.x = amplitute * Mathf.Sin((transform.position.y * speed_x) * 0.5f);
    //vel.x = amplitute * Mathf.Sin(transform.position.y * speed_x - ((transform.position.y * speed_x) / 2f));
    vel.y = -Game_Manager.instance.Global_Enemy_Speed * Time.deltaTime;
    rb.velocity = vel;

}

```

# Answer
> 1 votes
If you want your position to vary as the sine of lifetime, then your velocity, as the derivative of position, should vary as the derivative of sine: ie. the cosine of lifetime.

```
public float maxHorizontalSpeed = 5f;
public float oscillationsPerSecond;
float spawnTime = 0f;
Rigidbody2D body;

void Start() {
    spawnTime = Time.time;
    body = GetComponent<Rigidbody2D>();
}

void FixedUpdate() {
     float lifetime = Time.time - spawnTime;
     float phase = lifetime * oscillationsPerSecond " 2f * Mathf.PI;

     Vector2 velocity = body.velocity;
     velocity.x = maxHorizontalSpeed * Mathf.Cos(phase );

     body.velocity = velocity;
}

```

Note that since this is a discrete simulation, we can still accumulate integration errors (we're not sampling the velocity at every point along the curve, only once per physics step, so we can undershoot/overshoot in places). For most applications the errors will be tolerable, but if you find the objects are wandering too far from your desired path, you can instead compute a desired position using sine, then compute a velocity to chase that position. This keeps the object more rigidly "on its rail."

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


# Question
Title: Rotating an image in Slick2D in place in a tiled map?
I just finished writing a parser for TMX data (Tiled maps), and the way Tiled handles rotated tiles is by using three bit flags for flipping an image horizontally, vertically, and diagonally, to allow for rotation. Unless I'm wrong, flipping an image "diagonally" is just rotating 90 degrees CCW (counter-clockwise) and then flipping horizontally.

So I tried to implement this when I create the sub-image of the tileset for each tile:

```
public Image getImage(Image tileset, int w, int h) {
    if(tid == 0) return null;

    int nh = tileset.getWidth() / w; // Number of tiles in this tileset horizontally.

    // Offsets to be multiplied by tile width and height to get origin point of tile.
    int ox = ((tid - 1) % nh); // Subtract 1 because the TID numbers are 1-indexed (why use 0 to indicate nothing? why not -1? stupid Tiled...)
    int oy = ((tid - 1) / nh);

    Image sub = tileset.getSubImage((ox * w), (oy * h), w, h);

    // If any of the flip bits are set, flip the image.
    if(fh || fv) sub = sub.getFlippedCopy(fh, fv);
    if(fd) {
        // To flip diagonally, rotate counter-clockwise, then flip it horizontally.
        sub.setRotation(-90);
        sub = sub.getFlippedCopy(true, false);
    }

    return sub;
}

```

Specifically, the area where I set the rotation of the sub-image is what's causing my problem. Despite setting the rotation, the image is not rotated on the canvas. Doing a little digging into the library (what little information there is), it seems that the Image class' internal rotate methods don't actually do anything to the image, and most rotation is done using the Graphics context's rotate methods, which rotate the entire context and then draw the image.

The only problem with that is that if I rotate my graphics context, which is the map I'm constructing using these tiles, then the coordinates I give to draw the tile are no longer correct because of the rotated context, so my tiles come out all over the place.

What would be my solution here for rotating the images? Is there a transformation I can do to the coordinates once the graphics context is rotated so they draw in the correct position? I don't know anything about linear algebra, so I'm not sure what to do from here.

# Answer
> 0 votes
I doubt anyone will encounter this, but I thought I'd post my solution since I figured it out. First of all, my issue had nothing to do with the transformation I was doing. The problem was that the flip bits I was extracting from the tile ID weren't being read because the "flip horizontal" bit at position 0x80000000 is 2,147,483,648. The max size of an integer is 2,147,483,647... so the tile ID I was extracting was incorrect and the flip horizontal bit was never being extracted. All I needed to do was store the TID in a **long** variable.

As far as the actual rotation... once I had the correct tile IDs and flip bits, I decided to just use the built-in rotation methods for the graphic context because it's only done once, so rotating by specific values instead of flipping the image in weird ways is just easier.

---
Tags: java, 2d, slick
---


# Question
Title: Imported model from Blender stops updating after applying scripts
I am new to Unity3D and I am trying to import a model from Blender. I save the .blend file inside the assets folder and everything works well. I drag and drop my model and apply textures, colliders and insert a player. Up until that point, I am able to change things in Blender, and see the changes inside Unity. But my problem begins when I try to apply scripts in my objects. Then the connection between Blender and Unity breaks and the model is not updated in the later.

What am I doing wrong? Any help would be much appreciated!! Thanks!!

# Answer
1. Check that the scripts are compiling and not throwing an error. This can stop Unity's blender import from working.
2. Try exporting to fbx instead. It is what Unity recommends in their art asset guide - https://docs.unity3d.com/Manual/HOWTO-ArtAssetBestPracticeGuide.html
> 1 votes

# Answer
Not sure, I never use Blender. But I'd suggest using a .OBJ file instead. And when you edit, edit the .obj version. .obj is something unity should natively support so i use it a lot.
> 0 votes

---
Tags: unity, models, blender, scripting, import
---


# Question
Title: How does a custom physics engine connect to a tile graphics engine?
I’ve been looking into adding physics to my tile based side scroller game, and it seems like the best option might be to write my own engine to handle things like collisions and gravity due to the simplicity of what it is I need.

I mostly understand the math that I need and some of the techniques to get the functionality I want (such as slopes), but the part I'm still missing is how the physics relates to the graphics, as well as how to actually implement that connection.

All that I've seen is that physics and graphics are separate, but are updated together (the textures/animations change according to the interactions from the physics engine). Aside from that, however, I have very little idea what I'm doing.

My question is: When it comes to a tile-based game, how do you handle physics bodies and their creation? And on top of that, what would be an efficient way to connect the two engines to one another?

# Answer
The physics engine can be thought of as a data processing job.

It takes in a collection of physics objects including...

* collision shapes
* physical attributes (masses, material friction/elasticity coefficients)
* **last step's transformations** (positions & orientations in the world)
* last step's motion states (velocities & angular velocities)

It does some math on them, and spits out updated versions of the last two:

* **this step's transformations** (how has the object's position & rotation changed)
* this step's motion states (how will it continue to change in the next step)

Your graphics engine is another data processing job, that takes in drawing objects including...

* primitives (meshes / sprites)
* surface descriptions (materials / textures)
* **transformations** (where & in what orientation to draw the primitives)

You'll notice an overlap: the graphics engine consumes the updated transformation data that the physics engine outputs.

So the two engines don't really need to connect or know about one another at all. They just both know about a common data type that describes the position and orientation of a thing.

Not every physics object needs to be drawn (physics sims will often include invisible collider objects), and not every drawn object needs a physics representation (eg. backgrounds or VFX), so you probably don't want to couple the two concepts any tighter than the fact that they both care about positions & orientations.

You run the physics engine's step or integration method to update this data, then the graphics engine's draw step to display the results. Then you loop back and update it again..
> 1 votes

---
Tags: physics, graphics
---


# Question
Title: How to Instantiate enemies (triangles) in the shape of an n sided polygon
I am trying to instantiate a cluster of triangles (enemies) in the shape of a polygon and am unsure how to angle them correctly to all be facing away from the center. Thanks to another question, I got the positions roughly right:

```
for (int i = 0; i < formation.Count; i++)
{
    Vector3 pos = new Vector3(Mathf.Sin((float)i / formation.Count * 2 * Mathf.PI), Mathf.Cos((float)i / formation.Count * 2 * Mathf.PI));
    GameObject tri = Instantiate(gameObj, pos, /*Quaternion.Euler(0, 0, z)*/, parent) as GameObject;
}

```

Now I just need to get the angles such that all triangles face away from the center.

# Answer
> 0 votes
You already have a vector pointing out from the center - it's the one you're using to form the position! So, just orient to point along that direction using `LookRotation`. :D

```
for (int i = 0; i < formation.Count; i++)
{
    float angle = i / (formation.Count * 2f * Mathf.PI);
    Vector3 fromCenter = new Vector2(Mathf.Sin(angle), Mathf.Cos(angle));
    Vector2 position = center + radius * fromCenter;
    Quaternion orientation = Quaternion.LookRotation(Vector3.forward, fromCenter);
    GameObject tri = Instantiate(prefab, position, orientation, parent) as GameObject;
}

```

Here I'm assuming the "nose" of your triangle points in its local y+ direction. If it points a different way, you can apply an additional rotation to make sure the nose points out instead of, eg., clockwise.

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


# Question
Title: How can I achieve this top-down water effect in Unity?
I want to create a virtual fish pond similar to this in Unity (full video):

The ocean floor and fish are not a problem, but the effect of moving water that displaces the content below the surface is a mystery to me. I have googled and looked at the Unity asset store, but most water assets and questions are regarding more general oceans in 3D games, and not this type of top-down clear water effect. My research has led me to believe that the effect can be achieved with shaders, however I don't know much about shaders.

**What I need:**

* Top-down clear transparent water, where the content below the water is displaced by the moving waves
* The waves need to reflect light (highlights on the wave fronts)
* Ripples in the water based on collision, so touches will create ripples in the water

How can I achieve this in Unity? Are there any existing assets / tutorials / open source projects that do this, or do I need to write my own shader for it? And if so, what components do I need to include in that shader?

# Answer
> 2 votes
A full example with all of these effects gets a bit involved, but here's a quick overview of the main components you'd use:

To simulate the ripples there are two main approaches:

* Use RenderTextures to store the height and momentum of each cell of water on your surface. Stamp into these when you want to apply a disturbance to the water. Use a shader that implements the Navier-Stokes equations to integrate the fluid properties each frame.
* Or, approximate. Still using a RenderTexture to represent a heightmap of your waves, draw expanding ripple particle effects into it emanating from each contact. Here rather than doing a full fluid sim, you're just faking the most noticeable feature: circular waves that radiate out from a contact point.

Once you have the heightmap, you can infer the surface normals from its gradient.

To get the surface shimmer:

* For each pixel of water you draw, look up into the normal map computed above. Reflect your view ray by this normal and use this to look up into a cubemap for reflections. Mae the reflection brighter at shallow angles and fade it out as the view ray gets more parallel to the surface.

To draw the scene underneath refracted:

* Use a grab pass to capture the scene rendered so far into a RenderTexture that you can sample in your shader. If you sample this at the same pixel coordinate you're currently drawing on the screen, and output that colour, you'll get the effect of perfect transparency - showing exactly what's behind your water surface. If you shift your sample coordinate using the normal vector, you'll distort the image viewed through the water's surface, creating the appearance of refaction.
* More sophisticated versions of this effect can use the scene depth information too, to raymarch a refracted ray against the scene to better approximate what you "should" see when viewing at that angle. But you can go a long way toward the subjective appearance of refraction even if it's not geometrically accurate like this.

Add your colour sample from the shifted lookup into the grab texture with the reflection value you calculated and now you have a simple approximation of shallow, clear water.

---
Tags: unity, shaders
---


title: Rendering colors from a texcoord output

text:
# Question
Title: Rendering colors from a texcoord output
I'm trying to implement a faster alternative to super-sampling for my isometric 2d monogame game (for when the view is zoomed out). The idea was that I would render the texture coordinates to the render target like so:

```
output.Color = float4(input.TexCoord.xy, 0, 1);

```

...And then I would sample the sprite using the surrounding pixels' texture coordinates to get an anti-aliased color. I first tried my method by only sampling the original pixel to see if I could replicate the original output first, but I can't make it work. This is the result I got:

```
output.Color = sprite.Sample(spriteSampler, tex.Sample(texSampler, input.TexCoord).xy);

```

I used point filtering, I tried disabling mipmaps, I tried offsetting the texture coordinates, and it just doesn't work. For some reason the sampled texture coordinates are linearly interpolated, which gives out nonsense texture coordinates at the edges of textures, producing black lines.

However, if I zoom in close enough and align the camera somewhat, I get the correct output:

So what is causing those black lines? What can I do to remove them?

**Additional info:**

Sprite dimensions: 2048 x 2048

Render target format for texcoords: Vector2

Vertex declaration for the screen quad (not indexed):

```
vertices = new VertexPositionTexture[6];
vertices[0].Position = new Vector3(-1, 1, 0);
vertices[1].Position = new Vector3(1, 1, 0);
vertices[2].Position = new Vector3(-1, -1, 0);
vertices[3].Position = new Vector3(1, 1, 0);
vertices[4].Position = new Vector3(1, -1, 0);
vertices[5].Position = new Vector3(-1, -1, 0);

vertices[0].TextureCoordinate = new Vector2(0, 0);
vertices[1].TextureCoordinate = new Vector2(1, 0);
vertices[2].TextureCoordinate = new Vector2(0, 1);
vertices[3].TextureCoordinate = new Vector2(1, 0);
vertices[4].TextureCoordinate = new Vector2(1, 1);
vertices[5].TextureCoordinate = new Vector2(0, 1);

```

This is the code that converts the the computed coordinates for the blocks to screen space:

```
float4 PixelToScreen(float4 position)
{
    position.x = position.x * ((scale * 2) / resolution.x) - 1;
    position.y = position.y * ((scale * 2) / resolution.y) + 1;

    return position;
}

```

# Answer
> 1 votes
You could try padding your sub textures with zero alpha for the near-misses in sampling.
You could also try `glSetTexParameterI(GL_TEXTURE_WRAP_S , GL_CLAMP_TO_EDGE)` or something similar.

---
Tags: 2d, monogame, hlsl, isometric, fragment-shader
---


# Question
Title: How can I export a 3D model with keyframes to use in Blender?
I'm currently trying to export some 3D data and load it into Blender, but I've encountered some problems at the time of processing the meshes. They all have keyframes (nothing too complex, just texture change and rotation) but I cannot use traditional Wavefront Obj to export it, because it does not support this data.

How can I export this keyframe information in a way Blender will understand?

# Answer
Short answer - find out what formats Blender CAN import that support keyframes. Then use the spec to export it from your mesh library.

See my comments below, if you choose to use Collada, which is perfectly suitable for your purpose.
> -1 votes

---
Tags: 3d, blender, obj, export, asset-workflow
---


# Question
Title: How does a game like Minecraft handle block and entity updates?
I am not asking how Minecraft loads chunks or generates chunks, I am asking about individual blocks and entities and their behaviours.

Suppose you have a dirt block: dirt block can be converted to a grass block if there is a grass nearby. The game can have thousands of dirt blocks loaded at the same time, each checking if there is grass nearby.

Now add some monster spawners which have to spawn monsters periodically and keep track of how many monsters it spawned.

Then there is your large field of wheat, potatoes, carrots and saplings which the game also has to check and update every so often.

Then you have your furnaces that smelt your ores.

Then add into the mix all of the animals, monsters, villagers and their behaviours and pathfinding.

All of these actions are happening simultaneously and the game somehow keeps running smoothly on a decent computer.

How do the games generally handle this many block updates and entity behaviours? Does the game keep a list/collection of all the "updateable" blocks and just iterates every so often through that list and simply calls the ".update()" method? How are games with many updateable blocks/entities structured? Updating in a separate thread?

There are so many questions... Any clue is appreciated. Thank you.

# Answer
> 4 votes
1. **Don't run updates more frequently than necessary**. Many of the things you mentioned don't need to be updated every single game tick. The plant growing mechanic, for example, is something where you can get away with checking for updates in intervals of several minutes. If such an update is expensive, then running it might result in a notable freeze for a couple ms. If this becomes a problem in your game you want to avoid, stagger the updates. Instead of updating each block every 60 seconds, update a 60th of all blocks each second.
2. **Don't simulate what the player doesn't see**. Minecraft (and many other games like it) divide the world into *chunks*. The game only updates the chunks which are near the player. All other chunks are suspended to hard drive. When the player returns, the chunks are restored and the time which has passed is simulated all at once. You can often use a very simplified computation model for this. If the player left for an hour, you don't run 60 consecutive "one minute grass-growing updates", you run one grass-growing update where you multiply the grass growing speed by factor 60.

The same concept applies to timed processes like smelters. You don't actually need to update them all the time. You only need to update them when the player looks at them. When the player opens the smelter UI, you compute how much time passed since the last time they took a look and calculate that there should now be 12 more iron bars and 5 less coal in it than before.
3. **Use the right data structures**. This is a very broad topic people have written whole books about, so I am just going to scratch the surface here. But you generally can greatly speed up the computation if you try to represent information with as little data as possible and keep data which is processed together in continuous sections of memory. This greatly increases the usefulness of CPU cache. In other situations, using more complex data structures like spatial hashes, navigation meshes or octrees can speed up certain otherwise expensive operations like collision detection or pathfinding. A skilled and experienced programmer can get a lot of performance out of a CPU if they know what they are doing.
4. **Parallelization is a double-edged sword** In the past years, CPUs grew more in quantity of cores than quality of cores. So if you really want to benefit from the capabilities of modern hardware, you need to parallelize expensive tasks on multiple threads so they can run on multiple cores. However, this is often easier said than done. Communication between threads is expensive because that communication needs to be synchronized. And running too many threads at once can create a lot of load on the thread scheduler of the operating system. So poorly designed multithreading can be a lot slower than doing the same work on a single thread. There is also the risk of bugs which only happen in very rare timing coincidences. For example a bug which happens only when one thread finishes one task while another thread is in a critical phase of another task. Such bugs are very difficult to fix because you can't reproduce them reliable and you might be completely unable to reproduce them if you enable debugging tools. This is why I usually recommend inexperienced programmers to stay away from multithreading if possible.

I am wishing you the best of luck with the game you are going to create.

---
Tags: architecture, game-loop, voxels
---


title: Render order for 3D meshes

text:
# Question
Title: Render order for 3D meshes
I want to highlight a certain item in an inventory. It is a 3D scene although it looks a bit 2D. That is confirmed.

To do do that I have create a cube with a very small z scale (so that it looks like a plane... yes, I could have used a plane right away, I notice it now that I write it).

I have put a transparent material onto my cube. This material constantly changes its alpha value so that it looks like it's glowing.

I'm doing this because I want to re-do this inventory:

It does work, but my weapon is rendered before the glowing cube is renderer. That is the default behaviour as the weapon is physically in front of the glowing cube.

In the inventory system that I want to redo (see screenshot), the cube however it rendered after the weapon, so that it looks as if the cube was over the weapon (while in fact it is below the weapon. One can see that by the fact how perfectly the glowing cube aligns with the grid, and the weapon is over the grid).

I would therefore like to ask if I can make it so that a certain material / mesh is rendered after a certain other material.

I have only seen Sorting Layers for 2D, but nothing for 3D meshes.

Thank you very much!

Edit: Somebody suggested that I should place the glowing cube over the weapon. I had tried that, but it doesn't look good as the cube isn't "aligned" with the grid anymore, but hovers / floats over it instead. Here is a screenshot:

# Answer
> 2 votes
The Unity bug report team pointed me to the solution:

https://docs.unity3d.com/Packages/com.unity.render-pipelines.high-definition@6.7/manual/Renderer-And-Material-Priority.html

The important thing is: It works only for "Surface Type: Transparent". If you're dealing with 2 materials which have surface type "Transparent", then you can set their render order using the "Sorting Priority".

If you have 2 materials where one has surface type "Opaque", and the other one has surface type "Transparent", then Unity will decide the render order using depth testing, and you have no way to influence the render order.

So the way to solve the mentioned problem is to set the surface type "Transparent" for all meshes involved.

---
Tags: unity, 3d-meshes
---


# Question
Title: How to destroy a clone of an effect attached to an object?
I want to use some particle effects into a bonus object that will be destroyed upon contact with the player object. This object as its name suggests will add a certain benefit for the player for a certain amount of time. I was following a tutorial on Youtube. The code from the Tutorial worked fine but there is one problem I was not able to solve: the explosion will not be destroyed after the object is collided with player and after the script is triggered because it seems that it was cloned into the scene. The instantiation created a clone of the effect's prefab I referenced into the script. After looking into the internet, I tried to affect the instantiation of the effect into a variable called clone and then destroyed it after the bonus is over but the problem was still present. I researched and I really did not obtain any answer.

bonus.cs //

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

public class bonus : MonoBehaviour {

public float multiplier=2.0f;
public GameObject pickup_effect;
public float duration = 10;
private GameObject clone;

private void OnTriggerEnter(Collider other)
{
    if (other.CompareTag("Player")) StartCoroutine( pickup(other));
}

IEnumerator pickup(Collider player)
{
    Debug.Log("You picked a bonus!");
    //spawn cool effect
    clone = Instantiate(pickup_effect, transform.position, transform.rotation);
    //apply effect yo the player
    // our.score_value += 10;
    player.transform.localScale *= multiplier;
    GetComponent<MeshRenderer>().enabled=false;
    GetComponent<Collider>().enabled = false;

    //wait x amount of seconds

    yield return new WaitForSeconds(duration);

    //remove the effect from theplayer
    player.transform.localScale /= multiplier;

    Destroy(gameObject);
    Destroy(clone,4f);

}

}

```

//

I tried disabling the "loop" option in the effect's particle system options but it gave the same results.

I disabled the "Play on Awake" option and the effect will not play at all.

The script is added directly to the object that is a simple 3D cube with MeshCollider, Mesh Renderer and Box collider.

The effect I used is a BigExplosionEffect taken from Unity Particle Pack 5.x from the Asset Store.

I would like to know what is exactly wrong? Is it probably related to the effect itself rather than the script? Or is there a far better solution?

# Answer
Here is the answer.

My mistake is that I destroy the clone after the destruction of the game object.

The initial code is fine. I just needed to call Destroy(clone,4) before I call Destroy(gameobject). Otherwise I am destroying the bonus object before the code to destroy the clone runs and therefore the clone will not be set to destroy after the four seconds.

Since it's a particle, I could also write some code right after instantiating the clone to destroy it after the duration of the particle effect (assuming it doesn't have child or chain effects that last longer than the main).

```
 // As quick example
 GameObject clone = Instantiate(effect, pos, rot);
 ParticleSystem.MainModule particle = clone.GetComponent<ParticleSystem>().main;
 Destroy(clone, particle.duration);

```

Well, I got this answer from a Unity Veteran from another forum and it worked out very well. I thought I had to reply to this question by myself for the benefit of everyone.

So my code will become like this:

\`\`

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

public class bonus : MonoBehaviour {

    public float multiplier=2.0f;
    public GameObject pickup_effect;
    public float duration = 10;

    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Player")) StartCoroutine( pickup(other));
    }

    IEnumerator pickup(Collider player)
    {
        Debug.Log("You picked a bonus!");
        //spawn cool effect
        GameObject clone = Instantiate(pickup_effect, transform.position, transform.rotation);
        ParticleSystem.MainModule particle = clone.GetComponent<ParticleSystem>().main;
        Destroy(clone, particle.duration);
        //apply effect yo the player

        player.transform.localScale *= multiplier;
        GetComponent<MeshRenderer>().enabled=false;
        GetComponent<Collider>().enabled = false;

        // our.score_value += 10;
        //remove the effect from theplayer

        yield return new WaitForSeconds(duration);

        //wait x amount of seconds

        player.transform.localScale /= multiplier;

        Destroy(gameObject);

    }

}

```

\`\`
> 1 votes

---
Tags: unity, graphic-effects
---


# Question
Title: I need help with calculating the angle my character is aiming at
So im doing this program where i want my hero to shoot to the direction its facing , but for this job to get done i need to calculate the angle my hero is facing with Math.atan2() , atleasts thats what i read from this site: "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Math/atan2" but i still couldn't figure out how to do it , if someone can help me ill be greatful.

```
//this is the bullet object i want to move in the direction the player is
facing
function Bullet(x, y){
    this.x = x;
    this.y = y;
    this.toDelete = false;
    this.show = function(){
        ctx.beginPath();
        ctx.arc(this.x, this.y, 7, 2, Math.PI*2);
        ctx.fillStyle = "grey";
        ctx.fill();
        ctx.closePath();
    }
    this.move = function(){
        this.x = this.x + 5;
    }
    this.deletion = function(){
        this.toDelete = true;
    }
}

//this is the hero object the bullets are shooting off of.
function Hero(){
    this.sprite = sprite;
    this.x = 0;
    this.y = canvas.height/2;
    this.imgWidth = 128;
    this.imgHeight = 192;
    this.frameWidth = this.imgWidth / 4;
    this.frameHeight = this.imgHeight / 4;
    this.dx = 5;
    this.dy = -5;
    this.health = 100;
    this.directionMode = 2;
    this.currentFrame = 0;
    this.updateFrame = function(){
        this.currentFrame += 0.2;
    }
    this.showHealth = function (){
            ctx.fillStyle="green";
            ctx.fillRect(this.x,this.y - 10,(this.health/100)*50,5);
            ctx.strokeRect(this.x, this.y-10, (100/100) * 50, 5);
    }
    this.show = function(){
        if(downPressed != true && upPressed != true && leftPressed != true && rightPressed != true){
            this.directionMode = 0;
            this.currentFrame = 0;
        }
        this.updateFrame();
        this.walkingMode = Math.floor(this.currentFrame) % 4;
        ctx.drawImage(this.sprite,this.walkingMode * this.frameWidth, this.directionMode * this.frameHeight, this.frameWidth, this.frameHeight, this.x, this.y, this.frameWidth, this.frameHeight );
    }
    this.update = function(){
    if(rightPressed && this.x < canvas.width - this.imgWidth/4){
            this.x = this.x + this.dx;
        }
    if (leftPressed && this.x > 0 ){
            this.x = this.x - this.dx;
        }
    if (upPressed && this.y > 0 ){
            this.y = this.y + this.dy;
        }
    if (downPressed && this.y < canvas.height - this.imgHeight/4){
            this.y = this.y - this.dy;
        }
    }
}

```

So i want the bullets to go to the direction the player is facing , but how do i calculate the position my hero is facing.

# Answer
If you have a position of your character and position he's aiming at, to calculate angle between those two points, you need to do the following:

```
Math.atan2(aim_y - character_y, aim_x - character_x);

```

By subtracting character coordinates from aim coordinates we get a vector from character to the aim. Then we use this vector coordinates as an argument for the `Math.Atan2(y, x)` function;

`Math.atan2(y, x)` returns radians, so if you need to degrees, you need to multiply the result by 180 and divide by the Pi.

```
degrees = radians * 180 / Math.PI;

```

That is what the documentation page says.
> 0 votes

# Answer
Well if it's a web 2D game then you character direction can be represented as a vector, let's call it playerPointingDirection.

Let say that your character is pointing to the right of your screen, that would mean that your "normalized" vector would be in JavaScript as var playerPointingDirection = {x:1,y:0}.

To move a projectile coming from the player position, you would instantiate the projectile in the player position and add this vector to the current projectile position multiplied by the projectile velocity the result value would be the position of the projectile in the next frame.

You could also use something call raycasting.

If you are very new to game development, I would suggest you to pick up a Math book for game development, I would suggest you:

3D Math Primer for Graphics and Game Development (2nd Edition) by Fletcher Dunn and Ian Parberry
> 0 votes

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


# Question
Title: Entity component system implementation choices
```
// Ex.1
    for (Component& component : m_components)
    {
        UpdateComponent(component, dt);
    }
// Ex.2
    for (Component& component : m_components)
    {
        component.Update(dt);
    }

```

Assume that:

1. `UpdateComponent()` and the class method `Component::Update()` have identical logic.
2. `Component::Update()` is not a virtual function.
3. `m_compoents` is a container that uses a contiguous memory block (e.g. std::vector).

From the caching perspective, is there any performance difference between the 2 examples?

# Answer
If you do the Entity - Component - System pattern by the book, then components should be dumb data-holders while all the logic is in the systems. That means components shouldn't have update methods. They should not have any methods at all.

So the first example would be the canonical one while the second one is more of an OOP approach to game architecture where objects are supposed to be smart and contain their own logic.

But if you are looking at this from a pure performance point of view, then in this case it is likely more of a semantic choice. If you call a method of an object, you are actually calling a function to which you pass a `this` pointer in addition to all the other parameters. If the update method is sufficiently simple, then it wouldn't surprise me if a compiler would generate the exact same code for each (depending on the compiler and optimization settings, of course).
> 1 votes

# Answer
The idea of an ECS architecture is to avoid inheritance-like calls in components.

As you have read already, components are data containers. Any "updating" of a component should be handled by the appropriate sub-system.

As far as caching/performance goes, there is a simple-ish way to avoid cache misses: Use the observer pattern for each component: Each subsystem contains a cache friendly vector/array of observers, which copy data from the actual component, whenever it's data changes(via notification).

In such a way the component data is always available to the cache with no additional RAM fetches.

Having Logic and Data in the same object/class/structure is considered bad practice, and allows hackery that is likely to cause as many issues as it solves.

Restrict each subsystem to only read from, and change, a small subset of total data available (A motion system, which updates position according to velocity, should not be able to read/change character data, for example). By separating logic and data, you simplify your code, and restrict the upper limit of complexity, making it **much** easier to debug.

Now whilst the following is not a direct answer to your question, it does address some misconceptions that you seem to have:

You mentioned in a response to another answer that you wish to retain "the convenience of writing OOP code (having the logic and data in the same place)" :- This goes against one of the core tenets of OOP SOLID design: The Single Responsibility Principle.

OO Design is all about separating and minimizing concerns, and dependencies within a given software module. The convenience of OO code is that of maintenance and being extensible, not that of writing a megalithic (and thus, difficult to maintain, and impossible to extend) class to store all your game entity code.

Such a class also violates the Open/Closed Principle, in so far that it will require significant modifications over the course of the project's life, as you add more and more functionality and data storage to it. Additionally, if you attempt to create a family of entity like objects, you run the risk of the "deadly diamond" scenario.

A true ECS architecture avoids these issues *completely*.

By favouring data component composition over inheritance, and separating logic concerns into subsystems, you can create a simple game entity class, whose only concern is the storage, and retrieval of components, with no regard to component type, allowing the construction of any type of entity, just by adding new components, or omitting others, in new patterns.

No new logic or sub-classes necessary.

And if that wasn't enough to convince you: Because each subsystem only cares about a small part of the logic for each entity, it is *very* easy to write, debug and test.

This means fewer difficult-to-diagnose bugs in the long term, which will mean your coding experience will be more productive and enjoyable.
> 0 votes

---
Tags: c++, optimization, entity-component-system
---


# Question
Title: Is there a name for this algorithm for 2d shape collision?
A while ago I was considering my possibilities for implementing collisions between 2D shapes, and after much googling (which mostly turned up SAT), I came up with this:

```
let A, B = two shapes
let V = Speed of A relative to B

for a:point in vertices of A
  for b:segment in segments of B
    if segment(a, a+V) intersects b
      return intersection point
return false

```

Now, I'm far from the smartest person out there, so I am 99.8% sure someone must have come up with that before me and, what's more important, since I didn't find anything describing this method, I assume it's a bad one.

**Can anybody identify this algorithm and/or point me towards any literature on it explaining if, when and why it should be used?**

I've failed to see any significant problems at first sight; all the complex calculations can be hoisted outside of the loops and then it's just matrix multiplications within both loops, and I couldn't find any algorithm that makes do without any nested loops over two sets of elements (be they vertices, segments or normals)

Feel free to trash-talk my algo all you like, I never expected it to be the second greatest discovery right after general relativity or anything ;)

---

PS: Sorry for the poor title, but I can hardly explain the entire algo in one line :)

# Answer
> 1 votes
The reason why this algorithm might not have a name is because there are a lot of cases it isn't able to handle. For example this one:

The shapes are clearly overlapping, but shape A can move around quite a lot without any of the movement paths of its vertices ever intersecting with any of the edges of B.

It is in fact even able for A to completely pass over object B if B is small enough to fit through the edges of A:

---
Tags: collision-detection
---


# Question
Title: Unity3d: Get a direction vector parallel to plane
I need to send a raycast from my camera which is parallel to the plane (Ground) and in the same direction of its forward vector (Represented by the black color vector)

I cant use world space direction because the global forward vector of the camera points at the same direction no matter how much I rotate it (Since its a VR camera)

I tried to use Vector3.ProjectOnPlane, but not sure how it works.

Can someone help me?

# Answer
> 1 votes
So, you want to get a forward vector parallel to the ground plane relative to the camera's rotation, from what I can get.

The solution is as simple as using **Vector3.Cross(Vector a, Vector b)**, it is not commutative, so you'll have to give the vectors in the correct order. What the cross product gives you, is a vector C perpendicular to 2 vectors A and B. So, both vectors you'll have to pass as parameters in the function are the camera's **transform.right** and the plane's normal (as an Y vector) as A and B respectively, so you get a forward vector parallel to the ground's plane.

One of the ways to get a ground's normal is by using **Physics' API** functions such as Raycast, Spherecast, Boxcast, etc., where you can obtain the RaycastHit information of the ground you are contacting.

For the sake of a simple example, you could try this with **Raycast**:

```
public class GetForwardVector : MonoBehaviour
{
    public LayerMask mask;
    public float distance;
    public Vector3 forward;

    public void Update()
    {
        RaycastHit hit;

        if(Physics.Raycast(transform.position, -transform.up, out hit, distance, mask))
        {
            forward = Vector3.Cross(transform.right, hit.normal);
        }
    }
}

```

Here, if the script was attached to the camera, a ray is casted from the camera's position, taking the camera's relative down direction, to obtain the information of the ground below it.

Hope it helps.

---
Tags: unity, mathematics, vector, raycasting, projection
---


title: Phaser 3 physics bug in platformer game

text:
# Question
Title: Phaser 3 physics bug in platformer game
I'm writing a platformer lode-runner-like game. I would like to ask experienced people to see what's wrong. Everything seems to be ok but I am absolutely confused about 3 bugs.

1. Why is the player jumping on top of the ladder?
2. I tried to put the physics of the player's sprite body to -gameSettings.gravity.v to prevent a slow slide down the stairs but after that when the player rises to the top he cannot get off the ladder.
3. When you collect all the boxes, a ladder appears on the uppermost platform. It is no different from other ladder, but sometimes I can climb on it and sometimes I can't.

I know that I ask too many questions, but I am sure they are all related to physics error I made somewhere in my code.

https://platformergametest.000webhostapp.com/ here I uploaded my game on free hosting

# Answer
> 0 votes
First: Try to add some code to your question so we can know what may be wrong more easily.

From what I could see, just by laying it, I can answer your questions very vaguely (most you have already noticed by yourself):

> 1. Why is the player jumping on top of the ladder?

It's because of the gravity. I noticed that if you release the 'up' key, the player falls slowly, as if it's being pulled by gravity, when you are on top of the stairs, you can still fall from there, then if you keep pushing 'up' it will momentarily leave the stairs, but then gravity pulls you back down and this becomes a cycle, giving the illusion of "small jumps".

> 2. I tried to put the physics of the player's sprite body to -gameSettings.gravity.v to prevent a slow slide down the stairs but after that when the player rises to the top he cannot get off the ladder.

Probably because the **top** most part of the ladder is not perfectly aligned with the ground

> 3. When you collect all the boxes, a ladder appears on the uppermost platform. It is no different from other ladder, but sometimes I can climb on it and sometimes I can't.

Probably because the **down** most part of the ladder is not perfectly aligned with the ground when the stair spawns, maybe the way you wrote your physics behaviour is affecting the placement.

Could you provide some code that can be analyzed?

---
Tags: platformer, phaser
---


# Question
Title: Unity - How to tell which objects in scene are creating the most triangles?
I have been working on a game and every time a player prefab is instantiated, it creates 1M+ triangles. That is a nightmare considering the model itself is not even close to 1M. The only thing on the player prefab is the soldier model and some objects for holding the weapons. Nothing more then the model. How can I see which objects in the scene are utilizing the most triangle count? I need to get to the bottom of this.

# Answer
Get every child game object in the scene, Do GetComponents for each, go over all the MeshFilters and count Mesh.triangles.

```
foreach( GameObject g in UnityEngine.SceneManagement.SceneManager.GetActiveScene().GetRootGameObjects())
{
    int triangleCount = 0;
    foreach(MeshFilter m in getComponentsInChildren(typeof(MeshFilter)))
    {
        triangleCount += m.mesh.triangles;
    }
    Debug.Log(g.name + " has " + triangleCount.ToString() + " triangles");
}

```
> 2 votes

---
Tags: unity, rendering
---


# Question
Title: SteamVR Unity Skeleton Pose NullReferenceException
I'm developing an application using SteamVR in Unity. When running my app, the console keeps getting flooded with hundreds of instances of this error:

```
NullReferenceException: Object reference not set to an instance of an object
Valve.VR.SteamVR_Action_Boolean.GetState (Valve.VR.SteamVR_Input_Sources inputSource) (at Assets/SteamVR/Input/SteamVR_Action_Boolean.cs:94)
Valve.VR.SteamVR_Skeleton_Poser+PoseBlendingBehaviour.Update (System.Single deltaTime, Valve.VR.SteamVR_Input_Sources inputSource) (at Assets/SteamVR/Input/SteamVR_Skeleton_Poser.cs:420)
Valve.VR.SteamVR_Skeleton_Poser.ApplyBlenderBehaviours (Valve.VR.SteamVR_Action_Skeleton skeletonAction, Valve.VR.SteamVR_Input_Sources inputSource, Valve.VR.SteamVR_Skeleton_PoseSnapshot snapshot) (at Assets/SteamVR/Input/SteamVR_Skeleton_Poser.cs:230)
Valve.VR.SteamVR_Skeleton_Poser.UpdatePose (Valve.VR.SteamVR_Action_Skeleton skeletonAction, Valve.VR.SteamVR_Input_Sources inputSource) (at Assets/SteamVR/Input/SteamVR_Skeleton_Poser.cs:212)
Valve.VR.SteamVR_Skeleton_Poser.GetBlendedPose (Valve.VR.SteamVR_Action_Skeleton skeletonAction, Valve.VR.SteamVR_Input_Sources handType) (at Assets/SteamVR/Input/SteamVR_Skeleton_Poser.cs:177)
Valve.VR.SteamVR_Behaviour_Skeleton.CopyBonePositions (UnityEngine.Vector3[] positionBuffer) (at Assets/SteamVR/Input/SteamVR_Behaviour_Skeleton.cs:784)
Valve.VR.SteamVR_Behaviour_Skeleton.UpdateSkeletonTransforms () (at Assets/SteamVR/Input/SteamVR_Behaviour_Skeleton.cs:619)
Valve.VR.SteamVR_Behaviour_Skeleton.UpdateSkeleton () (at Assets/SteamVR/Input/SteamVR_Behaviour_Skeleton.cs:382)
Valve.VR.SteamVR_Behaviour_Skeleton.SteamVR_Input_OnSkeletonsUpdated (System.Boolean skipSendingEvents) (at Assets/SteamVR/Input/SteamVR_Behaviour_Skeleton.cs:358)
Valve.VR.SteamVR_Input.UpdateSkeletonActions (System.Boolean skipSendingEvents) (at Assets/SteamVR/Input/SteamVR_Input.cs:360)
Valve.VR.SteamVR_Input.UpdateVisualActions (System.Boolean skipStateAndEventUpdates) (at Assets/SteamVR/Input/SteamVR_Input.cs:320)
Valve.VR.SteamVR_Input.OnPreCull () (at Assets/SteamVR/Input/SteamVR_Input.cs:303)
Valve.VR.SteamVR_Behaviour.PreCull () (at Assets/SteamVR/Scripts/SteamVR_Behaviour.cs:219)
Valve.VR.SteamVR_Behaviour.OnBeforeRender () (at Assets/SteamVR/Scripts/SteamVR_Behaviour.cs:189)
UnityEngine.BeforeRenderHelper.Invoke () (at C:/buildslave/unity/build/Runtime/Export/BeforeRenderHelper.cs:105)
UnityEngine.Application.InvokeOnBeforeRender () (at C:/buildslave/unity/build/Runtime/Export/Application.cs:324)

```

I do not understand the error. I have my project's SteamVR input settings configured to their defaults, and the skeleton interaction on the HTC Vive controllers act normally.

What is this error trying to tell me and how can I fix the issue?

Thank you for your help!

# Answer
This means that your code is trying to access an object that does not exist (did not use new). This either means you need to create the object before you do or that you need to check to see if the object exists before calling those functions.
> 0 votes

---
Tags: unity, skeletal-animation, steam-vr
---


# Question
Title: Relative vertical alignment of 3 Texts on Canvas
This is a menu that appears if I press Enter on the RE4 inventory if an item is selected. I have drawn a thin red rectangle around it:

And here is a video that shows some of the menu's effects.

I am familiar with a simple text canvas. I understand that I need to make each line a separate "Text" object so that I can scroll up and down through them.

Here is what I have so far:

The problem that I'm facing now is that the Canvas will be scaled at runtime. I don't work with fixed values. This is a problem since I don't see how I could easily make it so that each TextLine object fills 33,3% of the canvas.

Am I right to assume that I can only solve this by making a scripts that holds a reference to each TextLine object and which then calculates their position when the scale of Canvas is known?

Or is there any easier solution?

Thank you!

# Answer
This looks like a straightforward application of the anchor properties in the UI layout system:

All three lines should have their Min X and 0 and Max X at 1, so the anchors span the full width of the container.

Then you vary the Min & Max Y of each item. The bottom line runs from 0 to 0.3333, the middle line from 0.3333 to 0.66666, and the top line from 0.6666 to 1.

Set the Left Top Right Bottom parameters to zero, so the corners of the text area snap exactly to the anchor points, and you're done.

Since the anchors are specified as fractions of the parent's size, anything you do to change the size of the parent will automatically adjust the layout of the text to preserve these ratios.

Of course, if you don't want to fiddle with these percentages every time you add or remove an item from your list, you can also just nest them inside a parent with a Vertical Layout Group that will handle positioning & sizing them for you:
> 1 votes

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


# Question
Title: How can I make a custom mob that looks like the Enderman?
I have previously made two other mods that added in mobs. In order for the mob to look like a wolf, I needed the wolf.java file (Found online).

Without setting a defined java file, the mob will use the villager's java file, which can lead to some messed up mobs.

Now, I have a requirement that a mob looks like the Enderman; how would I achieve this?

# Answer
> 2 votes
Minecraft does not support remodeling entities yet, therefore the Vanilla datapack also does not contain entity models. Where you would find the specifics of entity models is in the code.

# Answer
> 1 votes
Minecraft stores skins for all creatures in Minecraft as .png files.

These can be found in the .Minecraft folder, under the "resourcepacks" sub folder. You can open each one with a program like WinZip, 7Zip, WinRAR, etc. You can also find this folder by opening the Minecraft launcher, choosing "Resource Packs" the "Open Resource Pack Folder".

The contents of each holds a file for each and every texture in the game, including the textures, or "skins" for each mob in the game. The enderman skin can be found under

> `<resourcepack.zip>\textures\entity\enderman\`

However, if you're looking to change the actual model of the mob, this can only be found in the Vanilla Resource pack. The Official Minecraft Wiki has a tutorial for Editing these.

# Answer
> 1 votes
What you need to do is go to your files app or just your windows search bar and type in %appdata%. In this folder, go to .minecraft, which is your minecraft directory. Go to your versions folder and select your version, and then in that folder right click the .jar file. Use 7zip to extract the files, and then go inside to the assets folder. Navigate through the folders until your filepath looks like this (example for 1.14.3, it will look *slightly* different for other versions):

`AppData\Roaming\.minecraft\versions\1.14.3\1.14.3\assets\minecraft\textures\entity`.

This should be where you can find all of the entities. All of the textures for the entire game are around this file too, so if you want the dirt or golden sword texture they aren't far away either.

---
Tags: minecraft-modding
---


# Question
Title: Is it ok to remake a 2D game into first person and then releasing it for free?
I saw a video online where someone made a first person version of flappy bird, so I was wondering...

If I were to remake a 2D game into a 3D game and change the perspective to first person, and then proceed to release it online (like on itch.io) for free, would there be any repercussions?

The game concept and gameplay would be nearly identical with maybe a few changes, and while the art would be very similar, they'll still be original 3D models that I made myself, and differ from the actual assets used in the original game. All the code is original.

And could I just name it "First person (+ game name)" outright or is it better to name it something original?

# Answer
I'm not a lawyer, but

Fair use legally protects parodies. If you redo most assets in the game, it will be certainly fine.

Relevant parts:

> In its most general sense, a **fair use is any copying of copyrighted material done for a limited and “transformative” purpose, such as to comment upon, criticize, or parody a copyrighted work**. Such uses can be done without permission from the copyright owner. In other words, fair use is a defense against a claim of copyright infringement. **If your use qualifies as a fair use, then it would not be considered an infringement**.
>
> \[...\]
>
> **A parody is a work that ridicules another, usually well-known work, by imitating it in a comic way**. Judges understand that, by its nature, parody demands some taking from the original work being parodied. Unlike other forms of fair use, a fairly extensive use of the original work is permitted in a parody in order to “conjure up” the original.

From https://fairuse.stanford.edu/overview/fair-use/what-is-fair-use/
> 0 votes

---
Tags: legal
---


# Question
Title: Is std::deque the best option for storing my graphics objects?
I am currently implementing an object buffer, which stores all the objects used in the game at one place. All other components of the game, like the user interface, the level loader, etc, add objects to this buffer and then the objects are accessed by the rendering engine to render them all at once.

I need to store the graphics object in the object buffer contiguously in memory, so that i can take advantage of cpu caching while rendering. I also need to have stable pointers to the objects stored in the buffer as they have to be editable by their pointers by the components that created them, like the user interface must be able to access the graphics it put into the buffer in response to mouse movement with a pointer to that graphic.

These are the reasons i could not use either std::lists, which are not contiguous, or std::vectors, which invalidate all pointers when they reallocate. One data container i found useful was the std::deque, which though doesn't have complete contiguity, does allow some and keeps pointers valid, but what i wanted to ask was is

*is there any other data structure out there which is better at what i want?*

As far as i understand deques, they are implemented as vectors of arrays of all definite sizes. Is there a data structure that is able to allocate arrays with increasing size, like vector does?

# Answer
First, your concerns are definitely valid and this is not "premature optimization."

The problem is, `std::deque::insert` invalidates all iterators and references, so `deque` is not actually useful for this. What I did to solve this problem is create a wrapper data structure around `std::vector` (I called it a perma\_vector) that stores a vector of `std::pair<int, T>`. The vector is in increasing order by integer. When you insert something, it pushes it at the end, with an integer one greater than the previous last element. This integer is wrapped in an "perma-ref" object and returned. The upshot of this is that you can pass in the "perma-ref" and look up an object in logarithmic time (via `std::lower_bound`). They are never invalidated unless the object itself is deleted.

Some concerns with this: You will have to put some thought into what interface you expose to maintain the data structure's invariants. You will probably have an interface similar to, but slightly smaller than, a `std::vector`. You will also have to write your own iterator class, (although you might be able to get around that with a two vectors instead of a vector of pairs.) Also, it might behoove you to make it easy to switch the underlying data structure. You might find that having a deque is better if you're adding or removing a lot of stuff.

*PS. My code isn't that great and I'm not going to clean it up and post it unless this gets a ton of votes.*
> 2 votes

# Answer
I am assuming you are using something like OpenGL for your graphics (Correct me if I am wrong about this), so a typical, minimal data structure for rendering a game object would be:

```
struct RenderData
{
    //Ctor
    RenderData(GameObject* p)
        :owner(p),
         meshHandle(0),
         numVerts(0)
    {
        meshHandle = owner->getMesh();
        numVerts = owner->getVerts();
        transform = owner->getTransform();
        colour = owner->getColour();
    }
    // Member data
    GameObject* owner;
    unsigned int meshHandle; // This is the vertex array object (VAO) handle
    unsigned int numVerts; // Number of vertices in the mesh
    mat4 transform; // for homogeneous 3D transformations
    vec4 colour; //assumes RGBA
};

```

So when a new object is added to a collection of renderables, you emplace it, like so:

```
void addRenderable(GameObject* o)
{
    renderables.emplace_back(o);
}

```

Then, when you wish to render (render code ommitted):

```
void renderScene()
{
    for (size_t i = 0; i < renderables.size(); ++i)
    {
        renderObject(renderables[i]); //renderObject takes a const RenderData& as argument,
        //or replace with rendering code here.
    }
}

```

This way, the memory in the vector is contiguous, and so the CPU can decide on the most efficient fetches from memory, reducing cache misses to a minimum.

If you need to remove a gameObject (and order is not important), then you need to ensure that the memory remains contiguous:

```
void remove(GameObject* p)
{
    // linear search and remove
    for (size_t i = 0; i < renderables.size(); ++i)
    {
        if (renderables[i].owner->getID()==p->getID())
        {
            renderables[i] = std::move(renderables.back());
            renderables.resize(renderables.size()-1);
            return;
        }
    }
}

```

Of course, this all assumes you wish to have a collection of renderables, that is persistent between frames, but you could still use this technique on a frame by frame basis, and populate the vector based on some rule/logic.

Because the struct I used in my example effectively proxy's for the actual game object, it is throwaway, so can be safely destroyed without affecting the actual gameobject, or causing memory leaks.
> 1 votes

---
Tags: c++, data-structure, storage
---


# Question
Title: What exactly makes up a screen in a typical C64 game?
I'm trying to figure out the basics of C64 game development past BASIC, and I could use some advice on something very basic, but important: What is all that stuff on the screen actually, and how to draw it?

Take a look at Katakis/Denaris:

There are at least 9 different things on the screen:

1. The Score bar, with different fonts
2. The ship itself
3. A satellite attached to the ship, detachable
4. Secondary Weapon Projectiles
5. Primary Weapon Projectiles
6. Moving objects (can be enemy ships)
7. The Status bar, featuring an image of the ship, the number of lives and three sections that can fill
8. The primary weapon charge bar, can fill to the end
9. A scrolling starfield in the background
10. (not numbered on the screen) Solid objects like rocks or metal walls that are part of the background

The C64 only supports 8 sprites per horizontal scan line, so I don't think that everything in the middle of the screen can be a sprite? I would assume that anything requiring a collision would be a sprite (since I can get hardware collision detection with sprites), but even then I quickly hit the limit of 8 sprites. Also, my weapons can fire much more than one projectile - my ship, the satellite and 6 bullets would already be 8 sprites on a row (look at about 50 seconds into the video).

Also, which graphics mode would a game like this use? The Programming Handbook lists Bit Map Mode which essentially modifies screen memory directly. Is this the mode I should usually be working in? How would I compose all the non-sprite elements together to get them on screen?

A lot of the stuff in the score and status bar is static ("Area: 01" or the "frame"), so I guess I'll just populate them once when the level starts. Things that need updating - the score, the charge bars at the bottom - would be updated by filling the screen memory with black and then drawing the new score every frame?

Or do I have to draw the entire screen on every frame?

# Answer
> 13 votes
On c64 you can "multiplex" sprites. After they're drawn, you move them to new place and re-use them. Most objects in the middle are likely multiplexed sprites. In c64 it's very easy to use more than 8 sprites as long as they are not occupying same horizontal scanlines. Besides that you can actually make software sprites using font graphics if needed (projectiles atleast in this case).

2, 3, 6. Those are likely to be sprites.

4, 5, 9. Those are likely to be character graphics (8x8 pixel) software "sprites"

Game would use not bitmap mode, it would require too much moving of a memory (unless you do some VIC chip tricks...). Used mode would be character graphics mode.

What you need to draw would depend. In this case, if you look closely enough, there's certain size (x * y pixel) pattern stars are repeated so basically you'd update character memory of those fonts to emulate scrolling of starfield.

Score/status you populate on start, and then update them when needed.

You would have to update sprites and their position each frame. You would also update projectiles. Also you would update that x * y pixel starfield pattern.

# Answer
> 2 votes
I read an article some time ago in the german C64 Magazine. The bullets are characters that act as sprites as someone already pointed out. Ship and enemies are sprites.

Levels are made of characters also but with a twist. Since the levels are so huge, and memory is precious, Trenz wrote his own set of tools to group characters into modules.

So he can use bigger modules and compose those. Also he would use certain patch-modules to get the intersection of modules nice and clean.

All in all its a kind of compression, where levels are described building blocks instead of char by char.

Also you might noticed that in Katakis some levels have parallax backgrounds.

That is made by having a pattern to fill the background, mostly made of 2x2 or 3x3 characters, and animating it (bit-shifting) against the direction of scrolling. E.g. the level scrolls 2 pixels to the left, the background-pattern is scrolled 1 pixel to the right, hence it appears to be scrolled at a slower pace.

Hope that helps

One more thing you can actually see the single modules and such here https://archive.org/details/64er\_1989\_10/page/n27 scroll to page 24

---
Tags: graphics, commodore-64
---


# Question
Title: How can I delete an object when it's not stored in an array?
I have a boss appearing in my game, but since it's only one character I didn't put it in an array. Now I'm trying to make disappear if its health is less or equal to 0 but I don't know how to do that. Is there a way to remove the object? I only know how to remove a property of an object.

Here's the boss object:

```
function Boss1(x, y) {
    this.sprite = boss1Sprite;
    this.x = x;
    this.y = y;
    this.imgWidth = 160;
    this.imgHeight = 224;
    this.frameWidth = this.imgWidth / 4;
    this.frameHeight = this.imgHeight / 4;
    this.health = 1500;
    this.directionMode = 1;
    this.currentFrame = 0;
    this.SPEED = 1;
    this.delta = 1;
    this.updateFrame = function () {
        this.currentFrame += 0.2;
    }
    this.showHealth = function () {
        ctx.fillStyle="red";
        ctx.fillRect(this.x,this.y - 10,(this.health/100)*3.3,5);
        ctx.strokeRect(this.x, this.y-10, (100/100) * 50, 5);
    }
    this.show = function () {
        this.updateFrame();
        this.walkingMode = Math.floor(this.currentFrame) % 4;
        ctx.drawImage(this.sprite, this.walkingMode * this.frameWidth, this.directionMode * this.frameHeight, this.frameWidth, this.frameHeight, this.x, this.y, this.frameWidth, this.frameHeight);
    }
    //target == hero
    //position == this
    this.move = function () {
        this.dx = hero.x - this.x;
        this.dy = hero.y - this.y;
        this.length = Math.sqrt(this.dx * this.dx + this.dy * this.dy);
        if (this.length) {
            this.dx = this.dx / this.length;
            this.dy = this.dy / this.length;
        }
        this.x += this.dx * this.delta * this.SPEED;
        this.y += this.dy * this.delta * this.SPEED;
    }
}

//enemy wave object
function random(min, max) {
    return Math.random() * (max - min) + min;
}
function Enemy(x, y){
    this.sprite = enemySprite;
    this.x = x;
    this.y = y;
    this.imgWidth = 128;
    this.imgHeight = 192;
    this.frameWidth = this.imgWidth / 4 ;
    this.frameHeight = this.imgHeight / 4;
    this.toDelete = false;
    this.dx = random(1, 3);
    this.enemiesHealth = 100;
    this.directionMode = 1;
    this.currentFrame = 0;
    this.updateFrame = function(){
        this.currentFrame += 0.2;
    }
    this.showHealth = function (){
        ctx.fillStyle="red";
        ctx.fillRect(this.x,this.y - 10,(this.enemiesHealth/100)*50,5);
        ctx.strokeRect(this.x, this.y-10, (100/100) * 50, 5);
    }
    this.show = function(){
        this.updateFrame();
        this.walkingMode = Math.floor(this.currentFrame) % 4;
        ctx.drawImage(this.sprite,this.walkingMode * this.frameWidth,
        this.directionMode * this.frameHeight, this.frameWidth, this.frameHeight,
        this.x, this.y, this.frameWidth, this.frameHeight );
    }
    this.move = function(){
        this.x = this.x - this.dx;
    }
    this.deletion = function(){
        this.toDelete = true;
    }
}

//this is when the boss is spawning
//the game loop
function draw() {
    bullets = bullets.filter((bullet) => bullet.x <= viewLimit);
    enemies = enemies.filter((enemy) => enemy.x >= viewLimit1);
    while (enemies.length <= enemiesPerTick && kills <= 5) {
        var enemy = new Enemy(canvas.width, random(0, canvas.height - 60));
        enemies.push(enemy);
    }
    for (var v = 0; v < enemies.length; v++) {
        enemies[v].showHealth();
    }
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    hero.show();
    hero.update();
    hero.showHealth();
    for (var i = 0; i < bullets.length; i++) {
        bullets[i].show();
        bullets[i].move();
    }
    for (var j = 0; j < enemies.length; j++) {
        enemies[j].show();
        enemies[j].move();
    }
    for (var t = 0; t < enemies.length; t++) {
        enemies[t].showHealth();
    }
    collision();
    drawScore();
    if (enemies.length == 0) {
        boss1.show();
        boss1.move();
        boss1.showHealth();
    }

    requestAnimationFrame(draw);
}

console.log(enemies, bullets);
draw();

```

# Answer
Only show and update the boss when its health is larger than 0:

```
        if (enemies.length == 0 && boss1.health > 0) {
            boss1.show();
            boss1.move();
            boss1.showHealth();
        }

```

However, for a more extensible architecture you might want to handle the boss just like any other enemy. Push it onto the enemies array when the spawn condition is met and remove it from the enemies array when its defeat condition is met.

In order for your `draw`-loop to work with the boss just like it works with any other enemy, it needs all the same fields and functions. An elegant way to do that in Javascript is to create the boss as a regular enemy and then overwrite all functions and fields on that enemy object where the boss differs from a regular enemy.

Or even use prototype inheritance. Create an enemy base-class with all the functionality all enemies in your game have in common. Then create classes for every type of enemy you have in your game, including boss enemies, which use that base class as a prototype.
> 2 votes

# Answer
If simply not drawing it when its health is 0 isn't enough, you can just set the variable to null. This won't affect the memory immediately, but since JavaScript is garbage collected, unless you have multiple global references to it, it will eventually get deleted when space is needed
> 0 votes

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


# Question
Title: Does SDL_SetThreadPriority work with std::thread
I'm trying to set the priority of my threads so that my UI thread can be given priority over background calculations. I noticed that SDL has a `SDL_SetThreadPriority` method, however I still prefer the standard `std::thread` syntax rather than `SDL_CreateThread`. Does `SDL_SetThreadPriority` work with threads created with `std::thread`, or do I need to update everything to use `SDL_Thread`?

# Answer
> 2 votes
I did some digging in the SDL source code, and seems like this might vary based on what threading backend you have SDL using. There is a `SDL_Thread` implementation using the C++ standard library, which like you said does not support setting the thread priority, so in that backend, SDL does nothing.

However, if SDL is running on one of the other backends, there seems to be valid implementations that fetch the currently running thread from the platform, and set its priority correctly. Fro a quick googling it seems that those backends match whatever you would get from `std::thread`'s native handle.

At least on window's `SDL_SetThreadPriority` is just a call to `SetThreadPriority(...)`, so it might be a cleaner solution to just write your own small wrapper, but using SDL should be just as valid if you make sure that SDL doesn't target C++'s STL threading library as its backend (which it at least for me automatically doesn't). Your own solution could also apply the priority to a specific thread instead of the current one, which at least to me seems like cleaner API design.

---
Tags: c++, sdl2, multithreading
---


# Question
Title: How do I set up a beta channel for my Steam game?
I have a released game on Steam. I'm working on a new version, but before releasing it to the public, I want to be able to test it with my friends on Steam, through a beta channel that can be accessed through this menu:

Can I do this, and how?

# Answer
> 4 votes
From the same page you set your builds live, there's a branch list and a button to create a new branch at the top. Just press the button, create a branch, and set your beta build upload live to that branch.

---
Tags: steam, beta
---