title: How to make a character jump in SFML?

text:
# Question
Title: How to make a character jump in SFML?
How could I made a character jump with SFML in C++, a simple example could be very helpful.

Thanks in advance.

This is the code I currently have; how can I make the sprite jump?

```
#include <SFML/Graphics.hpp>
#include <iostream>
using namespace sf;

int main(){
    sf::RenderWindow ventana(sf::VideoMode(800,600),"mi ventana");
    ventana.setFramerateLimit(60);
    sf::Texture Image;
    Image.loadFromFile("tortuga.png");
    sf::Sprite sprite(Image);
    sprite.setPosition(-230,100);
    bool isPlay=true;
    bool presionarW(false);
    bool presionarA(false);
    bool presionarS(false);
    bool presionarD(false);
    //Controlar cualquier evento
    int x=30;
    int y=3;
    sf::Event miEvento;
    sf::CircleShape figura(10);
    while (isPlay)

    {
        //Eventos

        while(ventana.pollEvent(miEvento)){
            if (miEvento.type==sf::Event::Closed){
                isPlay=false;
            }
            if (miEvento.type==sf::Event::KeyPressed && miEvento.key.code==sf::Keyboard::W){
                presionarW=true;
            }
            if (miEvento.type==sf::Event::KeyPressed && miEvento.key.code==sf::Keyboard::A){
                presionarA=true;
            }
            if (miEvento.type==sf::Event::KeyPressed && miEvento.key.code==sf::Keyboard::S){
                presionarS=true;
            }
            if (miEvento.type==sf::Event::KeyPressed && miEvento.key.code==sf::Keyboard::D){
                presionarD=true;
            }

        }

        //Logica del juego
        if(presionarW){
            sprite.move(10,-20);
            presionarW=false;
        }
        if(presionarA){
            sprite.move(-20,5);
            presionarA=false;
        }
        if(presionarS){
            sprite.move(0,25);
            presionarS=false;
        }
        if(presionarD){
            sprite.move(25,0);
            presionarD=false;
        }

        //Renderizado
        ventana.clear();
        ventana.draw(sprite);
        ventana.display();
    }
    ventana.close();
}

```

# Answer
I do not know how familiar you are with movement physics, but for this instance, you ideally want to work with **Velocity** and **Acceleration**.

Basically, Acceleration impacts Velocity which impacts Position.

```
float x = 0;
float y = 0;
float velocityX = 0;
float velocityY = 0;
float accelerationX = 0;
float accelerationY = 0;

void updateMovement() {

    velocityX += accelerationX;
    velocityY += accelerationY;

    x += velocityX;
    y += velocityY;

}

```

By working like this, you don't move a character by modifying its position, instead you modify its **Velocity**.

Now, gravity works like acceleration, meaning it should eventually cancel out a velocity. As a higher Y-coordinate means downwards, the gravity in this case is positive.

```
float gravity = 5;

void updateMovement() {

    velocityY += gravity;
    velocityX += accelerationX;
    velocityY += accelerationY;

    x += velocityX;
    y += velocityY;
}

```

However, we only want to apply gravity while we are in the air, so we need to check that first.

```
float gravity = 2;

void updateMovement() {

    if(y < 500)                  //If you are above ground
        velocityY += gravity;    //Add gravity
    else if(y > 500)             //If you are below ground
        y = 500;                 //That's not supposed to happen, put him back up

    velocityX += accelerationX;
    velocityY += accelerationY;

    x += velocityX;
    y += velocityY;
}

```

Now we can finally do the fun stuff! The actual jump will now be very easy to perform.

```
if (miEvento.type==sf::Event::KeyPressed && miEvento.key.code==sf::Keyboard::Space){
    velocityY = -10;
}

```

Basically, we tell the character to start lifting off. The character will then be affected by gravity, and the actual jump will become weaker and weaker, until the velocity becomes positive, pushing the character back to the ground.

That should cover all of it.

If you have any questions, feel free to comment and I'll do my best to answer.

EDIT: Something like this.

```
#include <SFML/Graphics.hpp>
#include <iostream>
using namespace sf;

float x = 0;
float y = 0;
float velocityX = 0;
float velocityY = 0;
float accelerationX = 0;
float accelerationY = 0;

float gravity = 2;

void updateMovement() {

    if(y < 500)                  //If you are above ground
        velocityY += gravity;    //Add gravity
    else if(y > 500)             //If you are below ground
        y = 500;                 //That's not supposed to happen, put him back up

    velocityX += accelerationX;
    velocityY += accelerationY;

    x += velocityX;
    y += velocityY;
}

int main(){
    RenderWindow ventana(VideoMode(800,600),"mi ventana");
    ventana.setFramerateLimit(60);
    Texture Image;
    Image.loadFromFile("tortuga.png");
    Sprite sprite(Image);
    sprite.setPosition(-230,100);

    CircleShape figura(10);

    while (ventana.isOpen())
    {
        //Eventos

        while(ventana.pollEvent(miEvento)){
            if (miEvento.type==Event::Closed){
                ventana.close();
            }
            else if(miEvento.type==Event::KeyPressed && miEvento.key.code==Keyboard::Space){
                velocityY = -10;
            }
        }

        if(Keyboard::isKeyPressed(Keyboard::Left))
            velocityX = -5;
        else if(Keyboard::isKeyPressed(Keyboard::Right))
            velocityX = 5;

        updateMovement();
        sprite.setPosition(x, y);

        //Renderizado
        ventana.clear();
        ventana.draw(sprite);
        ventana.display();
    }

    return 0;
}

```
> 7 votes

# Answer
```
float x = 0;
float y = 0;
float velocityX = 0;
float velocityY = 0;
float accelerationX = 0;
float accelerationY = 0;

float gravity = 2;

void updateMovement() {

    if(y < 500)                  //If you are above ground
        velocityY += gravity;    //Add gravity
    else if(y > 500)             //If you are below ground
        y = 500;                 //That's not supposed to happen, put him back up

    velocityX += accelerationX;
    velocityY += accelerationY;

    x += velocityX;
    y += velocityY;
}

int main(){

    sf::RenderWindow ventana(sf::VideoMode(800,69),"mi ventana");

    ventana.setFramerateLimit(69);
    sf::Texture Image;
    Image.loadFromFile("tortuga.png");
    sf::Sprite sprite(Image);

    sprite.setPosition(-2319,100);

    sf::CircleShape figura(10);

    while (ventana.isOpen())
    {
        //Eventos

        while(ventana.pollEvent(miEvento)){
            if (miEvento.type==sf::Event::Closed){
                ventana.close();
            }
            else if(miEvento.type==sf::Event::KeyPressed && miEvento.key.code==sf::Keyboard::Space){
                velocityY = -10;
            }
        }

        if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
            velocityX = -5;
        else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
            velocityX = 5;

        updateMovement();
        sprite.setPosition(x, y);

        //Renderizado
        ventana.clear();
        ventana.draw(sprite);
        ventana.display();
    }

    return 0;
}

```
> 1 votes

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


# Question
Title: How do I increase object movement speed after some time?
I'm new to Unity, and am making a game where an object goes up, falls down and is destroyed. This object has been instantiated. I want to increase the object movement speed by 1 after 10 seconds, but not by more than 12, because the object moves off screen.

How do I do that? This is what I have, so far:

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

public class DestroyScript : MonoBehaviour
{
    public Rigidbody2D rb;
    private float destroyTime = 2.0f;
    private int speed = 8;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        Destroy(gameObject, destroyTime);
    }

    void FixedUpdate()
    {
        transform.Translate(Vector2.up * speed  * Time.deltaTime, Space.World);
        transform.Rotate(0, 0, 1);
    }
}

```

Thank you for your answer and sorry for my incomplete question actually object are spawned. here is the spawned script

```
public class SpawnItems : MonoBehaviour {

    public Transform[] SpawnPoints;

    public GameObject[] Coins;

    float createRate = 1.5f, createRateTimer;
    float rateIncrease = 0.1f, intialCreateDelay = 1.0f;
    int callCounter = 0, callBeforeRateIncrease = 15;

    // Use this for initialization
    void Start () {
        createRateTimer = createRate + intialCreateDelay;
    }

    private void Update()
    {
        createRateTimer -= Time.deltaTime;
        if(createRateTimer <= 0)
        {
            CustomInvoke();
        }
    }

    void CustomInvoke()
    {
        int spawnIndex = Random.Range(0, SpawnPoints.Length);
        int objectIndex = Random.Range(0, Coins.Length);
        Instantiate(Coins[objectIndex], SpawnPoints[spawnIndex].position, SpawnPoints[spawnIndex].rotation);
        callCounter++;
        if(callCounter >= callBeforeRateIncrease)
        {
            createRate -= rateIncrease;
            callCounter = 0;
        }
        createRateTimer = createRate;
    }
}

```

# Answer
> 2 votes
Just a little tip: have you tried using 'Rigidbody.AddForce()' ? all you have to do is use a 'Vector3()' and specify the axis and the force will be applied to the object. like this:

```
public float force = 10f;
public float multiplier = 1000f;

void FixedUpdate()
{
    //during the update method move the object on the Y axis with a force "force"
    Rigidbody rb;
    rb.AddForce(new Vector3(0,force * Time.fixedDeltaTime * multiplier,0));
}

```

this is just a tip, because this is driven by physics instead of translating the object, which is not as smooth as actually moving the rigidbody! :) this is not really the answer but hope it helps better your game!

# Answer
> 1 votes
Increase the object movent speed by 1 after 10 seconds is equal to increase speed by 0.1 after 1 second. You can also call speed increase "acceleration"

so add acceleration declaration :

```
   private float acc = 0.1;

```

make speed a float

```
   private float speed = 8;

```

increase speed in FixedUpdate

```
void FixedUpdate()
{
    speed  = speed  + acc * Time.deltaTime;
    transform.Translate(Vector2.up * speed  * Time.deltaTime, Space.World);
    transform.Rotate(0, 0, 1);
}

```

finaly for the

> but not by more than 12, because the object moves off screen.

i think you can set destroyTime to 12.0f instead of 2.0f;

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


title: Block collision doesn't work

text:
# Question
Title: Block collision doesn't work
I'm making a top-down tiled game in Java, and now I'm coding the collision test, but it doesn't work. This collision function work only for top and left side of the blocks, and when I'm colliding, the player moves up without I do anything.

What is my mistake?There are better collision system? Thank you!

My code:

```
  public void update() {
        collide();

        if(up) y -= vely;
        if(down) y += vely;
        if(right) x += velx;
        if(left) x -= velx;
    }

    private void collide(){
        for(int i = 0; i < handler.objects.size(); i++){
            GameObject obj = handler.objects.get(i);
            if(obj.id() == ID.Block){
                if(getBounds().intersects(obj.getBounds())){
                    x += -velx;
                    y += -vely;
                }
            }
        }
    }

// is the same in all the classes
public Rectangle getBounds() {
    return new Rectangle((int)x,(int)y,width,height);
}

```

# Answer
Your current implementation moves the player up and left whenever it collides with the block. Instead move it relative to it's velocity:

```
private void collide(){
    for(int i = 0; i < handler.objects.size(); i++){
        GameObject obj = handler.objects.get(i);
        if(obj.id() == ID.Block){
            if(getBounds().intersects(obj.getBounds())){
                if (right) x -= velx;
                if (left) x += velx;
                if (up) y += vely;
                if (down) y -= vely;
            }
        }
    }
}

```
> 1 votes

---
Tags: java, collision-detection
---


title: How can I store and read dialogue?

text:
# Question
Title: How can I store and read dialogue?
How can I store dialogue so that it could be read for a kinetic (linear) Visual Novel type of game in XNA/MonoGame?

I'm currently using a .txt file, but I noticed that I can't read from a specific line using the System.IO.StreamReader class.

# Answer
> 0 votes
You'll want to use TitleContainer.OpenStream in place of the stream reader.

The reason they do it differently in XNA / MonoGame is for cross platform compatibility. Essentially, the TitleContainer abstracts away the details about how to read the file on whatever platform you're targeting.

There's also two other things you'll need to be aware of:

1. When you're loading raw content that isn't processed with the Content Pipeline tool, you'll need to set the properties of the file in Visual Studio to *Content* and *Copy if newer*.
2. You'll need to use the path and file extension (not just the name like you would with `Content.Load`

For example:

```
using (var stream = TitleContainer.OpenStream("Content/data.txt"))
using (var reader = new StreamReader(stream))
{
    // Do your thing here as you normally would
}

```

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


# Question
Title: how to prevent a ball from bouncing only vertically
I am trying to make a ball bounce off (and also sideways) when it gets into contact with another object. I am having an issue shown in the image below, where the ball rests on the triangle instead of falling off sideways. I tried playing round values for the bounciness and friction, but that didn't solve my issue. How can I solve this issue. I've added the inspector settings on the ball.

# Answer
You can add a little randomness into your physics like so:

```
// Populate this with how much you want to nudge the ball.
public float jitterAmount = 1f;

// Populate this with a layer ID that identifies your triangles to bounce off of.
public int pinLayer;

// Populate this in the Inspector or in Start to point at the ball's Rigidbody2D
Rigidbody2D myBody;

void OnCollisionEnter2D(Collision2D collision) {
    if(collision.otherGameObject.layer != pinLayer)
        return; // Only jitter sideways off the pins, not other balls / the floor.

    if(Mathf.Abs(myBody.velocity.x) >= 1f)
        return; // Object already has substantial sideways motion.

    Vector2 normal = collision.contacts[0].normal;

    if(Mathf.Abs(normal.x) > 0.01f)
        return; // We've fallen onto a slope that doesn't need help.

    // Add a little nudge left or right:
    myBody.velocity += jitterAmount * (Random.value > 0.5f ? Vector2.right : Vector2.left);
}

```

You can also do this in OnCollisionExit to catch bounces that exactly cancel the incoming horizontal velocity. Here I used OnCollisionEnter to catch non-bouncing collisions too, where the ball falls and rests on the pin.
> 2 votes

---
Tags: unity
---


# Question
Title: Why Are These 3D Square's Pixels Spaced?
So i'm currently attempting to write a 3D renderer. From no prior knowledge because I want to challenge myself. But I'm stuck here, and thought I'd bring it to StackExchange because I always see brilliant solutions! If more code is needed please just ask!

This Is My Square Render Code:

```
public void renderSquare(int xPos, int yPos, float zPos, int width, int height, int color) {
    clearArray();

    for(int y = 0; y < height; y++ ) {
        int yy = y + yPos;

        for(int x = 0;x  < width; x++) {
            int xx = xPos + x;

            float xS = -1f, yS = -1f;

            if(xx < centerX ) {
                xS = ((xx / zPos)) + centerX;
            }else {
                xS = ((xx / zPos)) - centerX;
            }

            if(yy < centerY) {
                yS = ((yy / zPos) - 0.5f) + centerY;
            }else {
                yS = ((yy / zPos) - 0.5f) - centerY;
            }

            setPixel((int)xS, (int)yS, color);

        }
    }
}

```

Plus How I Set Pixels:

```
public void setPixel(int xPix, int yPix, int color) {
    if(xPix < 0 || xPix > width || yPix < 0 || yPix > height)
        return;
    try {
        render_buffer[xPix + yPix * width] = color;
    }catch(Exception e) {
        return;
    }
}

```

Any help is appreciated\]

# Answer
You're scaling the square by approximately 4 (1 / 0,27 = 3.7 ~ 4), but you always draw the same amount of vertices, this way the distance between two pixels becomes 4 instead of one.

Instead of drawing width * height vertices and scaling their positions accordingly, scale the width, height and position of the square, then go through the pixels in that area, in pseudo code:

```
// xPos, yPos and zPos are the position, width and height are the sizes
// Calculate new position and size
newXPos = (int)(xPos / zPos)
newYPos = (yPos / zPos)
newWidth = (width / zPos)
newHeight = (height / zPos)

// Loop through pixels
for (integer x from newXPos to newXPos + width) {
    for (integer y from newYPos to newYPos + width) {
        setPixel(x, y, "#ffffff")
    }
}

```

Working demo in javascript:

```
let xPos = -30, yPos = -30, zPos = 0.25, width = 60, height = 60;

let c = document.getElementById("canvas");
let ctx = c.getContext("2d");
ctx.fillStyle = "black";

function change() {
  zPos = parseFloat(document.getElementById("z").value);
  console.log(document.getElementById("z").value)
}

function draw() {
  ctx.clearRect(0, 0, 300, 300);
  let newXPos = Math.floor(xPos / zPos) + 150;  // The + 150 part centers the (0; 0) coordinate
  let newYPos = Math.floor(yPos / zPos) + 150;
  let newWidth = Math.floor(width / zPos);
  let newHeight = Math.floor(height / zPos);

  for (let x = newXPos; x < newXPos + newWidth; x++) {
    for (let y = newYPos; y < newYPos + newHeight; y++) {
      ctx.fillRect(x, y, 1, 1); // Draw pixel
    }
  }
  console.log(newXPos, newYPos, width, height)
}

setInterval(draw, 33)
```

```
<canvas id="canvas" width="300px" height="300px" style="border: 1px solid black"></canvas><br />
<span>Z coordinate:</span> <input id="z" type="number" value="0.25" onchange="change()"/>
```
> 0 votes

---
Tags: java, 3d, mathematics
---


# Question
Title: Lua script for World of Warcraft: Get Quest Info
I'm looking to make a very simple addon or even a macro where I can enter a quest ID and get the quest completion status. As it is, I know I can use `IsQuestFlaggedCompleted` to get the quest status, but I wanted to also get the name of the quest so the return in the chat log will show something a little more understandable. For example: Enter `/questDone 43502` instead of just `43502: true` as the output, I want it to look like `A Change of Seasons: Quest Completed`.

I see a function `C_TaskQuest.GetQuestInfoByQuestID` that's supposed to return the quest's title, but it doesn't seem to work as expected. It always seems to return `nil` for the quest name...

# Answer
> 1 votes
Try the following which creates a tooltip and scans the name:

```
local MyScanningTooltip = CreateFrame("GameTooltip", "MyScanningTooltip", UIParent, "GameTooltipTemplate")

local QuestTitleFromID = setmetatable({}, { __index = function(t, id)
    MyScanningTooltip:SetOwner(UIParent, "ANCHOR_NONE")
    MyScanningTooltip:SetHyperlink("quest:"..id)
    local title = MyScanningTooltip.TextLeft1:GetText()
    MyScanningTooltip:Hide()
    if title and title ~= RETRIEVING_DATA then
        t[id] = title
        return title
    end
end })

```

Then use this table like this:

```
print(QuestTitleFromID[43502])

```

---
Tags: lua, world-of-warcraft-modding
---


title: Why is my movement always active?

text:
# Question
Title: Why is my movement always active?
I can't quite figure this out, no matter the various modifications I make.

What *should* happen: I want this to only move the player on left click/left up if i have previously right clicked

What actually happens: Regardless of which mouse button I click/unclick, it activates the direction function.

The offending code:

```
class Controller_Mouse : public Component
{
public:

    Component_Transform *transform;

    void init() override
    {
        transform = &entity->get_component<Component_Transform>();
    }

    void update() override
    {
        if (Game::event.type == SDL_MOUSEBUTTONDOWN)
        {
            if (SDL_BUTTON_RIGHT)
            {
                transform->active = true;
            }

            if (SDL_BUTTON_LEFT)
            {
                if (transform->active == true)
                {
                    std::cout << "transform vals: " << transform->position.x << ", " << transform->position.y << std::endl;
                    std::cout << "click vals:     " << Game::event.motion.x << ", " << Game::event.motion.y << std::endl;

                    transform->target.x = Game::event.motion.x; transform->target.y = Game::event.motion.y;
                }

                transform->active = false;
            }
        }
        if (Game::event.type == SDL_MOUSEBUTTONUP && SDL_BUTTON_LEFT)
        {
            transform->direction(transform->position.x, transform->position.y, transform->target.x, transform->target.y);
        }
    }
};

```

# Answer
You are not comparing anything to the mouse constants in your if-statements. You need to include the event's mouse button member there.
> 4 votes

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


# Question
Title: Cannot use sprite sheet to add texture to RawImage?
I am basically trying to recreate this sample image

from this sprite sheet

(Source)

I split the sprite sheet in the sprite editor of unity, now I want to use the top left texture for ground. But when I add UI-\>Raw Image, I cannot add the split texture to the texture source. How do I add it as a texture? In the source it does not show the split assets but the full sprite sheet.

How do I add this one single texture? That I have already split in the unity sprite editor.

# Answer
> 1 votes
As the comments state, `RawImage` is for showing textures, but what you have are sprites (a thin veneer over parts of a texture). You'll want to use `SpriteRenderer`s or `Image`s instead. I would recommend sprites over images, since you are building a game scene, not a user interface. Note that both images and sprites have the ability to tile their contents.

---
Tags: unity, 2d, textures, spritesheet
---


# Question
Title: How do I apply touches to images, using Swift?
I need code this game for iOS, using Swift; but I don't know how to apply touches to images, using Swift. My attempts thus far have failed; `touch!.view != image`.

```
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touchesSet = touches as NSSet
    let touch = touchesSet.anyObject() as? UITouch
    let location = touch?.location(in: self.view)
    if touch!.view == bee1 {
        bee1?.center = location!
    } else if touch!.view == bee2 {
        bee2?.center = location!
    }
}

```

# Answer
I am still new to Sprite Kit but I think you can solve your problem with this function. It's easy and simple.

I would split your unfilled image in 3. unfilled\_left\_wing, unfilled\_right\_wing, unfilled\_head.

Then I would move the image to the desired position. If the filled image intersects with the unfilled one, check how far it's from it's center, if it's smaller than 30 px apply it.

```
func touchDown(atPoint pos: CGPoint, atTime t: TimeInterval) {
        // have to start inside the left_wing
        guard left_wing.contains(pos) else {
            return
        }
    }

func touchMoved(atPoint pos: CGPoint, atTime t: TimeInterval) {
    // move wing to cursor position
    left_wing.position = pos
}

func touchUp(atPoint pos : CGPoint, atTime t: TimeInterval) {
     left_wing.position = pos

     // check if it intersects with unfilled image
     if (left_wing.frame.intersects(unfilled_left_wing.frame)
      {
          //check if it's close to center
          if (fabs(left_wing.frame.origin.x - unfilled_left_wing.origin.x) < 30 && fabs(left_wing.frame.origin.y - unfilled_left_wing.origin.y) < 30)
         {
             left_wing.position = unfilled_left_wing.position
         }

      }

    }

// overridden touch method to call our touch method for each touch
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    for t in touches { touchMoved(atPoint: t.location(in: self), atTime: t.timestamp) }
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    for t in touches { touchUp(atPoint: t.location(in: self), atTime: t.timestamp) }
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for t in touches { touchDown(atPoint: t.location(in: self), atTime: t.timestamp) }
}

```

Based on this method, you can further optimise your code and save the images on NSArray for a dynamic check.
> 0 votes

---
Tags: ios, swift
---


title: Host game client online

text:
# Question
Title: Host game client online
so the question is simple (i hope).

Say i have a game client, where i can run around on some tiles.

now if i want my friend to be able to log in and play the game aswell, what exactly is needed for me to make the game "online"?

I have basic experience in making websites, but hosting a game is new to me!

# Answer
Multiplayer simply requires a special client (Server) that communicates constantly back and forth with all the game clients playing together. Since you want the players to play from different computers, you need to learn how to use standard network protocols (Sockets/Packet formatting) that are used by every machine on the internet.

The server is a separate program with special logic, though it can run on the computer of one of the players (i.e you) or even be integrated in the original application itself so that one player can host a small server without using another executable.

If you want a lot of players at the same time (i.e, a MMO), then the server client needs to be on a huge machine with a lot of internet bandwidth and a lot of processing power to handle instantly the actions of all the players.
> 0 votes

---
Tags: multiplayer, server, online
---


# Question
Title: Why doesn't my computer paddle move in my Pong game?
I'm making a pong game and I can't figure out why the computerPaddle won't move up or down when it's supposed to to hit the ball automatically!

Please help me.

Here's code:

```
<html>
<h3>- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PONG- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -</h3>

<canvas id="gameCanvas" width="800" height="600"></canvas>

<script>
var canvas;
var canvasContext;
var ballX = 50;
var ballY = 50;
var ballSpeedX = 11;
var ballSpeedY = 5;

var playerPaddleY = 240;
var computerPaddleY = 240;
const paddleHeight = 120;
const paddleThickness = 12;

function calculateMousePos(evt) {
    var rect = canvas.getBoundingClientRect();
    var root = document.documentElement;
    var mouseX = evt.clientX - rect.left - root.scrollLeft;
    var mouseY = evt.clientY - rect.top - root.scrollTop;
    return {
        x: mouseX,
        y: mouseY
    };

}

window.onload = function() {

    canvas = document.getElementById('gameCanvas');
    canvasContext = canvas.getContext('2d');

    var framesPerSecond = 30;

    setInterval(function() {
        moveEverything();
        drawEverything();
    }, 1000 / framesPerSecond);

    canvas.addEventListener('mousemove',
        function(evt) {
            var mousePos = calculateMousePos(evt);
            playerPaddleY = mousePos.y - (paddleHeight / 2);
        });

}

function ballReset() {
    ballX = canvas.width / 2;
    ballY = canvas.height / 2;
    ballSpeedX = -ballSpeedX;

}

function computerMovement() {
    if (computerPaddleY < ballY) {
        computerPaddleY += 5;
    } else {
        computerPaddleY -= 5;
    }
}

function moveEverything() {

    ballX += ballSpeedX;
    ballY += ballSpeedY;

    if (ballX > canvas.width) {
        if (ballY > computerPaddleY && ballY < computerPaddleY + paddleHeight) {
            ballSpeedX = -ballSpeedX;
        } else {
            ballReset();
        }
    }

    if (ballX < 0) {
        if (ballY > playerPaddleY && ballY < playerPaddleY + paddleHeight) {
            ballSpeedX = -ballSpeedX;
        } else {
            ballReset();
        }

    }

    if (ballY > canvas.height) {
        ballSpeedY = -ballSpeedY;
    }

    if (ballY < 0) {
        ballSpeedY = -ballSpeedY;
    }

}

function drawEverything() {

    canvasContext.fillStyle = 'black';
    canvasContext.fillRect(0, 0, canvas.width, canvas.height);
    canvasContext.fillStyle = 'white';
    canvasContext.fillRect(2, playerPaddleY, paddleThickness, paddleHeight); //
    player

    canvasContext.fillRect(786, computerPaddleY, paddleThickness, 120);
    //computer player

    canvasContext.beginPath();
    canvasContext.arc(ballX, ballY, 12, 0, Math.PI * 2, true); //ball
    canvasContext.fill();

}

</script>

</html>

```

# Answer
The only code that ever appears to modify `computerPaddleY` is in the `computerMovement` function. You never call `computerMovement` anywhere.

Presumably your intent was to call it during `moveEverything`, but you're currently not.
> 1 votes

---
Tags: javascript
---


title: Movement & arriving using forces

text:
# Question
Title: Movement & arriving using forces
3D. Given a point mass **m**, inital position **p0** initial velocity **v0**, and a desired location **d**, how do I apply forces (with magnitude no greater then **fMax**) to move **m** to **d** and stop. I know *how* to apply forces, it's the strategy for determining what force to apply each frame.

You would think this would be easy - but it's turned out to be difficult.

A solution that only converges at the limit is not acceptable (i.e. having the mass oscillate back/forth over the destination by smaller and smaller distance)

Edit: This is not the same as this question. Finding the stopping distance is trivial, but is (maybe) only part of the solution.

Edit: Also not the same as this question, because the highest answer is incorrect (as stated by my constraints)

# Answer
What you're describing is a classical controls problem. An old subject and widely studied by most engineering students.

There are two approaches you can take, one that involves tweaking (PID controller) and one that's based on math & control theory.

1. PID controller: proportional-integral-derivative controller (more on Wikipedia) relies on the difference in your position and the destination (proportional), your total error distance (integral), and the speed (derivative). This video explains it very well. It works by multiplying each input value by a constant factor (called the gains) to obtain a force to apply. So you'd have a function, `getControl()`, which provides how much force to apply.

```
def getControl(gains, dist2dest, totalError, speed):
    P, I, D = gains
    control = P*dist2dest + I*totalError + D*speed

```

Picking values for the gains is called 'tuning' and can be done interactively with your physics model. Once you're satisfied with the behavior, save the values.

Info on how you move (i.e. what is the position as a function of force?) is required to solve this with maths.

2. Root Locus (more on Wikipedia). Once you have a transfer function, G (function that describes your system dynamics --\> pos/force = G(s), in Laplace-space), you can plot the root locus (matlab fxn 'rlocus') to visualize the dynamics and add controller zeros/poles automatically (matlab fxn 'place') or by hand to place the closed-loop poles where you want in order to obtain desired behavior (no overshoots, short transient time, etc.)

Force can be constrained by simply setting any force greater than fMax to fMax.
> 1 votes

---
Tags: physics, ai
---


# Question
Title: Changing a rotation and position of the camera smoothly when a button was clicked
How can I change a rotation and a position of the camera smoothly when a button is clicked in Unity?

I do not want to use Update function to implement this and I do not have a GameObject or Transform which it should look at, rather I want to tweak everything manually.

I would like to see the approach using C#.

# Answer
> 0 votes
Instead of manually moving camera it was easier for my just to use Unity\`s built in feature to record an animation. It is pretty straightforward, I just clicked on camera in upper tab chose Window and opened Animation tab, next I clicked to add a new animation. When the location for the new animation was specified I pressed red circle in Animation tab to record my camera. There is such long bookmark symbol in Animation tab it adds a key frame. I added it at the beginning, having my camera in initial position and at the end, moving my camera to the final position. Then I stopped recording by again pressing red circle in Animation tab. Here my animation was ready and the only thing I should have to do was to use my knowledge of animating in Unity.

Then I got a problem of needing to create more than one animation with the same GameObject. It was easy tackled by just clicking on the name of the current animation under red circle button in Animation tab and choosing created beforehand blank animation and filling it with the content I needed.

---
Tags: unity, c#, rotation, transformation
---


# Question
Title: Can I run old projects after updating Unity?
Today I decided to upgrade unity from 5.0.0 to 5.5.0.

But before updating it, I wanted to know: Can I run/build my projects made in Unity 5.0.0 in Unity 5.5.0?

# Answer
The projects will need to go through an upgrade process to work in the new version of the editor. It's likely your project will convert to the new version just fine. However, there's a possibility that the project will have issues. For example, if you were using features that were made obsolete or using assets/plugins that haven't been updated.

The upgrade process will change your project configuration and you may have issues if you want to revert your editor to 5.0.0, so ensure you make a backup.
> 2 votes

---
Tags: unity
---


# Question
Title: Why do I get this error when converting an XNA .fx to a MonoGame .fx?
I am learning game development in Monogame via book for XNA 4.0. In the code below which is for drawing the terrain, I get the error in the comment. Im using an effect from Monogame content pipeline folder, and I noticed that there are some differences between the effect file described in the book and the pipeline generated effect. how do i convert the syntax of XNA to Monogame?

```
    public void Draw(ArcBallCamera camera, Effect effect)
    {
        effect.CurrentTechnique = effect.Techniques["BasicColorDrawing"];
        effect.Parameters["WorldViewProjection"].SetValue(Matrix.Identity * camera.View * camera.Projection);
        foreach (EffectPass pass in effect.CurrentTechnique.Passes)
        {
            pass.Apply();
            device.SetVertexBuffer(vertexBuffer);
            device.Indices = indexBuffer;
            device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, vertexBuffer.VertexCount);
            //ERROR: An error occurred while preparing to
            //draw. This is probably because the current vertex declaration
            //does not include all the elements required by the current
            //vertex shader. The current vertex declaration includes these
            //elements: SV_Position0, NORMAL0, TEXCOORD0.

        }
    }

```

the effect file:

```
#if OPENGL
#define SV_POSITION POSITION
#define VS_SHADERMODEL vs_3_0
#define PS_SHADERMODEL ps_3_0
#else
#define VS_SHADERMODEL vs_4_0_level_9_1
#define PS_SHADERMODEL ps_4_0_level_9_1
#endif

matrix WorldViewProjection;

struct VertexShaderInput
{
float4 Position : SV_POSITION;
float4 Color : COLOR0;
};

struct VertexShaderOutput
{
float4 Position : SV_POSITION;
float4 Color : COLOR0;
};

VertexShaderOutput MainVS(in VertexShaderInput input)
{
VertexShaderOutput output = (VertexShaderOutput)0;

output.Position = mul(input.Position, WorldViewProjection);
output.Color = input.Color;

return output;
}

float4 MainPS(VertexShaderOutput input) : COLOR
{
return input.Color;
}

technique BasicColorDrawing
{
pass P0
{
    VertexShader = compile VS_SHADERMODEL MainVS();
    PixelShader = compile PS_SHADERMODEL MainPS();
}
};

```

the book is "XNA 4 3D Game Development by Example Beginners Guide" BY Kurt Jaegers, published in 2012

# Answer
The type of vertex you're passing in is not consistent with what is expected. The vertex has the types `SV_Position0, NORMAL0, TEXCOORD0`, whereas the shader expects `SV_POSITION, COLOR0`. Either change the shader input, or change your vertex type.
> 1 votes

---
Tags: c#, xna-4.0, monogame
---


# Question
Title: Unity Ambient Occlusion not working with Orthographic camera
It seems like the `Ambient Occlusion` setting from the Unity Post Processing stack (obtained from the asset store) only works with a Perspective camera, yet I haven't come across any documentation stating that this is the case or that it lacks support for Orthographic.

All the other settings in the stack seem to be working in both Perspective and Orthographic.

Is this a bug, or something I'm not doing right or understanding?

# Answer
> 0 votes
I might be wrong here but SSAO is dependent on the depth buffer of the camera. Since a orthographic projection does not take into consideration the distance of the object from the camera this will result in a depth buffer that cannot be used with the SSAO shaders.

---
Tags: unity, lighting, post-processing, ambient-occlusion
---


# Question
Title: What is more efficient in Unity recorded animation or Slerp/Lerp?
What is more efficient in Unity recorded animation or Slerp/Lerp? What will be faster?

It is obvious that the animation will take a lot more space.

# Answer
> 0 votes
Well, there is almost no difference, but this is often true. Its when you are doing something a large number of times where you start noticing a significant difference. And then, those small optimizations stack up and save you a significant amount of frames. In this case, animations should be more optimized. Wether or not it is best for your game? Depends on what you prefer. If you have frames to spare, but would like to keep your game's size to a minimum, slerp/lerp. Would you like to ensure as many people as possible can play your game? You are probably best off using animations.

---
Tags: unity, memory-efficiency, efficiency
---


title: Good way to manage multiple game modes?

text:
# Question
Title: Good way to manage multiple game modes?
**/UPDATE:**
I took one of the suggested solutions and tried to implement them. I implemented a `BaseGameWorld` class that contains the basic tetris gameplay. Every game mode extends this base class. If any of the game modes differ from that classic gameplay they will simply override any methods needed or add new ones. My `GameScreen` class is now structured like this:

```
public class GameScreen  {
    private BaseGameWorld gWorld;
    private GameRenderer gRender;

    public GameScreen (int gameMode) {
         // PuzzleGameMode extends BaseGameWorld
         gWorld = new PuzzleGameMode();
         // Constructor of GameRenderer takes a BaseGameWorld object
         gRender = new GameRenderer(gWorld);
    }

    public void render() {
         // Update Game World
         gWorld.update();
         // Draw Game World
         gRender.draw();
    }
}

```

This is ofcourse not the complete code, but it should show everything important. The idea behind the `GameWorld` and the `GameRenderer` classes is to reduce any clutter in the `GameScreen` class and seperate the game world and the drawing of the game world in two seperate steps with the goal to improve maintainability. So far this approach works quite well.
The type `gWorld` get's initiated with depends on the `gameMode` input variable and is handled through a switch-case in the actual code. Just as an example I used the class `PuzzleGameMode`.

Now my problem is that any new things added in the `PuzzleGameMode` class can't be drawn inside the `GameRenderer` class, since the `GameRenderer` constructor takes a `BaseGameWorld` object. It can only draw things that are in the `BaseGameWorld`.

Is there a way to resolve this situation that doesn't involve making a seperate `GameRenderer` for every game mode? My hope was to only have different classes for each game mode but to have one universal `GameRenderer` class.

---

I am currently making a tetris clone to get back into game programming using libGDX. The game is currently seperated in different screens. `MenuScreen` (includes Options, Highscore, Credits etc.) and the `GameScreen` itself. The `GameScreen` also has one member (named `GameWorld`) that manages all the calculations and game states, aswell as another one (named `GameRenderer`) that does all the drawing.

This works fine for the moment, however I plan on adding multiple game modes. I could probably add them to the `GameWorld` class, but it is already very full and managing multiple game modes inside a single class would end up very confusing and not very nice to maintain later down the line.

I could make a different class for every game mode and just use one of them depending on the selected game mode. This would be a solution, however this seems like a waste since I would just copy most of the original code for some of the game modes.
Alternativly I could make a Superclass that all game modes inherit from, however I am not sure how well it would work since game modes can differ quite a bit from each other. One mode might change the fundamentals like collision or intoduce new mechanics that need to be implemented on a deeper level, while others only differ a bit from the classic tetris mode and use most of the already implemented stuff.

What would be a good way to implement different game modes?
If more information is needed or if I should specify something better, just tell me and I will add the missing information. :)

# Answer
> 1 votes
Take a look at GOF (Gang of four ) state machine , and Hierarchy State machines patterns state pattern State Pattern

In a Hierarchical state machines, A state can have a superstate (making itself a substate). When an event comes in, if the substate doesn’t handle it, it rolls up the chain of superstates. In other words, it works just like overriding inherited methods, So no code Duplication.

# Answer
> 1 votes
Consider the following UML diagram:

This is what is known as a finite state machine. In this way, an application, or game, can have several states, or behaviours. When certain conditions are met, such as a key being pressed, or a menu choice selected, a change in state is triggered, which changes how the application or game behaves.

Additionally, each state can have a set of sub-states themselves, which further granulates the behaviours.

# Answer
> 0 votes
I use what is essentially a simplified version of libgdx (no OpenGL, for example). It has a basic class called Screen. Of course there are other classes for saving the scores, etc., but the main classes in my game just extend this class: the opening screen, the menu screen, the setting screen, the game screen, the end of level screen, etc. Because the basic functionality I need is built into Screen -- recognising touch, drawing, updating, pausing, etc. -- it is relatively easy to build the different types of screen that I need and there is relatively little duplication of code.

In your case, I would build a basic game screen and then override the methods that need to change. I don't know libgdx well, but I would guess that you leave GameWorld alone and just focus on what you want on the screen. I could be wrong about that.

---
Tags: libgdx, architecture
---


title: Rotating a group of bodies in Phaser

text:
# Question
Title: Rotating a group of bodies in Phaser
I want to create a game where enemies spawn, fly toward the player's ship, and stick to the side of it. The player can then rotate the ship and the stuck enemies will rotate with it.

The way I have this working now, the ship and the enemies are each part of a group and a collision group; when an enemy collides with the ship, it leaves its old group and collision group and joins those of the ship. The player is then able to rotate the ship's group, including the stuck enemies.

But from there, things get weird. If you rotate the ship 90 degrees to the left and then stick an enemy to its right edge, the enemy vanishes and appears at the top edge of the ship. Try to stick another enemy to the same point on the right edge, and it too will teleport to the top of the circle, colliding with the other enemy there. Also, enemies that have been "stuck" won't collide with those that have not.

If I move everything into one collision group, rotating the ship with enemies stuck to it will be reflected onscreen but not in the physics. You can spin the ship around all you like, and the enemies stuck to it will appear to rotate around it, but the non-stuck enemies will act as if they aren't moving.

How can I get a group of physics bodies to act like one body, rotating together and colliding with other objects in the gameworld? Code is below; try it out here.

```
var game = new Phaser.Game("100%", "100%", Phaser.AUTO, '', { preload: preload, create: create, update: update, render: render });
var debug = false;

var ship, enemy, enemies, shipCollisionGroup, enemyCollisionGroup, spawnEnemy;

function preload() {
    game.load.image('ship', 'simple-ship.svg');
    game.load.image('enemy', 'square-enemy.svg');
}

function create() {
    game.physics.startSystem(Phaser.Physics.P2JS);
    game.physics.p2.setImpactEvents(true);
    game.physics.p2.updateBoundsCollisionGroup();
    game.stage.backgroundColor = '#1C1C1C';

    shipCollisionGroup = game.physics.p2.createCollisionGroup();
    enemyCollisionGroup = game.physics.p2.createCollisionGroup();
    enemies = game.add.group();
    enemies.enableBody = true;
    enemies.physicsBodyType = Phaser.Physics.P2JS;
    ship = game.add.sprite(200, 200, 'ship');
    shipGroup = game.add.group();
    shipGroup.enableBody = true;
    shipGroup.addChild(ship);
    shipGroup.x = 200;
    shipGroup.y = 200;
    shipGroup.pivot.x = 200;
    shipGroup.pivot.y = 200;
    spawn();

    game.physics.p2.enable([ship, enemies], debug);
    ship.body.setCircle(200);
    ship.body.setCollisionGroup(shipCollisionGroup);
    ship.body.collides([shipCollisionGroup, enemyCollisionGroup], collision);

    cursors = game.input.keyboard.addKeys({
        'left': Phaser.KeyCode.A,
        'right': Phaser.KeyCode.D,
        'space': Phaser.KeyCode.SPACEBAR
    });
}

function update() {
    ship.body.setZeroVelocity();
    ship.body.setZeroRotation();

    if (cursors.left.isDown) {
        shipGroup.rotation -= .1;
    } else if (cursors.right.isDown) {
        shipGroup.rotation += .1;
    } else if (cursors.space.isDown) {
        spawnEnemy = true;
    } else if (cursors.space.isUp && spawnEnemy) {
        spawn();
        spawnEnemy = false;
    }
}

function render() {
    game.debug.text('A and D to rotate; spacebar to spawn enemies', 32, 32);
}

function collision(shipBody, impactorBody) {
    var enemy = impactorBody.sprite;
    // enemies.remove(enemy);
    shipGroup.addChild(enemy);
    enemy.body.removeCollisionGroup(enemyCollisionGroup);
    enemy.body.setCollisionGroup(shipCollisionGroup);
    enemy.body.setZeroVelocity();
    enemy.body.setZeroRotation();
}

function spawn() {
    var enemy = enemies.create(700, 200, 'enemy');
    enemy.body.velocity.x = -100;
    enemy.body.setCollisionGroup(enemyCollisionGroup);
    enemy.body.collides([shipCollisionGroup, enemyCollisionGroup]);
    enemy.body.sprite = enemy;
    enemy.anchor.x = 0.5;
    enemy.anchor.y = 0.5;
}

```

# Answer
A solution for the ships colliding after being added to the shipgroup is to call enemy.body.clearCollision() before adding it to the shipcollisiongroup.

To not have them all go to the same place you could save their x,y before adding them to the shipgroup and then set their position to what you saved, remember to do it relatively to the group's position.
> 1 votes

---
Tags: physics, phaser
---


title: Tag object in map in Unreal

text:
# Question
Title: Tag object in map in Unreal
Is there a clean way in unreal to place text in the map to tag different buildings and areas for developper that can easily be turned on/off for all the tags in the map?

# Answer
This really depends on the scale of your project. If it's small scale, you could create a custom component (that can be added to any actor) to display what you want. The downside is that this is per-actor so you cannot easily enable or disablw it for all actors in the scene. If your project is larger scale or you want reusability, I'd go with a custom editor plugin; however this is a serious rabbit-hole and can end up being more work than necessary.

Once you decide, I may be able to suggest more appropriate steps.
> 1 votes

# Answer
Two ways that I can think of off the top of my head:

1. A parent blueprint for all placeable objects. Pros: everything behaves the same. Cons: some objects may need another parent class.
2. An editor plugin that adds a text component to all objects in a level. Pros: lots of control because it's an editor plugin, and it can bind directly to menus and toolbars. Cons: harder to write and may be overkill for what you want.

There may be other more appropriate options if we know a little nore about the intended functionality and usage.
> 0 votes

---
Tags: unreal-4, unreal, text
---


# Question
Title: What is the difference between genre and game mechanics?
In some local vacancies I read something like "a genre = match3", or like "a game mechanics = adventure". I thought, a game mechanics is match3, or any sequences of operations that do something to solve something. A verb. For example, to connect three candies of one color in a line.

And genre is just a structure about what elements should be in a story. Like in "The Hero with a Thousand Faces". For example, an adventurer + an artifact + a map (or any key) to find it + competitor (or a let) = adventure.

Am I wrong?

# Answer
> 9 votes
Genres are a way to group games together that share similiar elements, wether they are game mechanics or specific story elements or just perspective or setting.

In some genres games have to have specific mechanics. An FPS has to be first person and has to have a shooting mechanic, hence the name.

Mechanics are basically actions that the player can take and their consequences.
So if you match 3 and they disappear, that's a game mechanic, if you jump on an enemies head and the enemy takes damage, that's a game mechanic.

So to answer your question, genre can describe many things, it doesn't have to be the setting (see FPS). So it doesn't directly relate to game mechanics. A genre can imply certain game mechanics. But other than that there isn't really a connection.

Hope that explains it well enough.

# Answer
> 3 votes
* Games are sets of mechanics with unique mathematical properties

This holds for all games, regardless of medium of medium or genre (i.e. board & card games, computer games, puzzle games, sports.) The field of Combinatorial Game Theory is devoted to the mathematical analysis of games toward the goal of solving a given game. The scope of CGT is ever expanding per the capabilities of mathematics and computation to solve problems of increasing complexity.

Games may also include elements (tokens, players, objects, etc.) and these elements are governed by the mechanics.

* Mechanics, simply put, are the specific rules of a given game

By contrast, genre refers to categories of gameplay, which is often conflated with mechanics. But "gameplay" and genre are terms used to connote and categorize games with similar properties and player experience.

Keeping to mathematical definition of structure, m,n,k is a class of games based on connecting k tokens on an m\*n game board. All m,n,k-games share this structure and a common set of fundamental mechanics (place tokens, victory condition based on k in a row), and include Tic-tac-toe, Gomoku and Connect Four. The wider genre is "connection games", which includes Hex and TwixT.

Gameplay is a little fuzzier, but all of the connection games listed here can be called "combinatorial" which sometimes refers to a special class of "non-chance, perfect information, sequential, partisan" games.

The concepts of mechanics, gameplay and genre can extended to any type of game, with distinction being that the latter two tend to reflect market-based considerations, specifically relating to players the type of game experience.

* **Genre and "gameplay" are distinct from game mechanics in that they are *stylistic***
* **Game mechanics are purely logical/mathematical, which is to say *algorithmic***

---
Tags: terminology
---


title: problem in texturing

text:
# Question
Title: problem in texturing
the first picture is the texture I'm using. and the second is result. problem!

the model file it self is no problem. I think the mode is problem.

I saw uv coordinates is more than 1.

what kind of sampler state I should use?

I used default sampler state that is wrap mode for u,v,w.

# Answer
I searched MSDN AND I saw default sampler is wrap. But! that was XNA not dx11 if you don't setting your sampler state it's fine dx11 will set default sampler state.

check here what is default state https://msdn.microsoft.com/en-us/library/windows/desktop/ff476207(v=vs.85).aspx thank you DMGregory. I just find this out when I'm trying to fill D3D11\_SAMPLER\_DESC structure
> 1 votes

---
Tags: textures, directx11, rendertexture
---


# Question
Title: How to find the minimum number in a float array C# Unity
i have a for loop that detects the position of every game object in a list and gets the difference between that object and an object anchored in the center and then stores all values in a float array. what should happen next is find the minimum distance in that array and make that object (the object with the smallest distance) move towards the anchored center. the problem is that no matter what i do, it always gets the maximum number (which is the furthest game object). here is what i have so far:

```
public RectTransform panal;
public GameObject[] characters;
public RectTransform center;
private float[] distance;
private float minDistance;
private bool isDragging = false;
private int distanceBetweenCharacters;
private int minCharNum;

private void Start()
 {
   int charLength = characters.Length;
   center = GameObject.Find("CenterCompare").GetComponent<RectTransform>();
   distanceBetweenCharacters = 200;
 }

private void Update()
 {
     for (int i = 0; i < characters.Length; i++)
     {
         distance[i] = Mathf.Abs(characters[i].transform.position.y - center.transform.position.y);
     }

     float minDistance = Mathf.Min(distance);
     Debug.Log(minDistance);

     for (int a = 0; a < characters.Length; a++)
     {
         if (minDistance == distance[a])
         {
             minCharNum = a;
         }
     }

     Debug.Log(minCharNum);

     if (!isDragging)
     {
         LerpToChar(minCharNum * distanceBetweenCharacters);
     }
 }

 void LerpToChar(int position)
 {
    float newY = Mathf.Lerp(panal.anchoredPosition.y, position, Time.deltaTime * 5f);
    Vector2 newPosition = new Vector2(-386, newY);
    panal.anchoredPosition = newPosition;
 }

 public void StartDrag()
 {
     isDragging = true;
 }

 public void EndDrag()
 {
     isDragging = false;
 }

```

I assume that the problem is with the array because when i set the minCharNum to a specific integer, it works just fine. What am i doing wrong exactly? Any help is very much appreciated.

# Answer
No reason for so many loops:

```
private void Update()
 {
     float minDistance = float.MaxValue;
     for (int i = 0; i < characters.Length; i++)
     {
         distance[i] = (characters[i].transform.position - center.transform.position).sqrMagnitude;
         if(distance[i] < minDistance)
         {
             minDistance = distance[i];
             minCharNum = i;
         }
     }

     if (!isDragging)
     {
         LerpToChar(minCharNum * distanceBetweenCharacters);
     }
 }

```

I would also suggest moving this outside of the Update method, if you don't actually need this every frame and if you have a large number of characters.
> 2 votes

---
Tags: unity, c#, character, scrolling, menu
---


title: Unreal point light error message

text:
# Question
Title: Unreal point light error message
How to fix this issue with point lights ?

# Answer
> 1 votes
This happens when you have more than 4 stationary lights overlapping.

> Only 4 or fewer overlapping stationary lights can have static shadowing, because the lights must be assigned to different channels of a shadowmap texture.

The solution then would be to make the lights not overlap or to change their shadow type to dynamic.

See the documentation about the correct use of these type of lights.

---
Tags: lighting, unreal
---


# Question
Title: How to make old cards still usable to players in CCG games?
In CCG games, as the player progresses further and unlocks stronger cards alot of the old cards are ignored and not used anymore. Like for example a CCG with 1000 cards, 100 of them are very strong cards and the others not so much. All players will just use those 100 cards and ignore the rest 900 cards! What can be done in such case to make old cards still usable to players?

# Answer
> 2 votes
One option is to use a crafting system that allows a player to recycle lower tier cards into a higher tier. Depending on the game & your perspective, this may be a potential negative as it creates a way to grind. On the other hand, you could also include special cards that cannot be crafted which allows the designer a bit more control over the experience. I think that Card City Nights had an optional game system that supported crafting, but prevented the player from grinding out cards required to progress the single player story.

A different option is to give some cards powers that require extra cards. Some of the Ascension deckbuilding game sets did this. For instance, some of the Void faction cards from the Storm of Souls set had abilities that could only trigger by removing cards from your deck - typically, you want to hold onto higher power cards, so it was useful to have some low level cards to burn. And in various sets there are cards that trigger from having cards of the same faction in hand, so sometimes it's worth buying more cheap cards from faction X because it increases the chance that when your powerful faction X card is drawn you'll have a matching faction to trigger it.

So the overarching idea is to find ways to turn low level cards into resources of one type or another. Burning them for specials, matching sets in hand for specials, gaining a counter based on the number of type X cards in the discard pile.

Finally, consider alternatives to a linear measure of card strength. For example, having high level cards that only affect other high level cards (perhaps thematically, those low level cards are beneath their notice). By making the card strengths cyclic instead of linear, you support a richer meta game as players try to second guess what their opponent might field. Going back to the example, a player with mostly high power cards that can only hit other higher power cards could easily lose to someone who fielded a lot of low level cards.

# Answer
> 1 votes
From a commercial point of view, a bit of power creep can actually be good. It forces your players to buy the new cards when you release an update in order to stay competitive. But when you exploit this too much, players will notice, call you out on your obvious cash-grabbing and abandon your game. So you need to be careful to not become too greedy here.

Methods you can use to prevent power creep:

* Make sure your game mechanics have the proper tools to allow you to balance cards against each other. In the idealized case, every single card you release and will ever release in the future would be equally good. Not equally good in every possible situation, but all cards should have a justification for existing. In practice this will be impossible to achieve (at least if you want to keep your game interesting), but that shouldn't stop you from trying. One very useful tool for this is having some form of cost mechanic which makes powerful cards harder to play.
* Have new cards which interact with underpowered old cards in interesting ways. Adding a card in a new edition which gives a considerable powerup to some underpowered cards in the previous edition can give them the power boost they need to become competitive again.
* Similarly, get those cards you accidentally made too powerful back in line by adding cards which specifically counter them.
* In a virtual CCG, you always have the last resort option to simply change cards when they turn out to be under- or overpowered. Players tend to hate it when you ruin their decks by nerfing their most powerful cards, but they might forgive you if you don't do it too often and when the end result is a much better game. Making changes to already printed card might be hard in a physical CCG, but it is not unheard of either. Some CCGs publish regular lists of errata which change how some cards work or even outright ban some cards. Casual players likely won't know that these lists even exist and will play with the cards like they are printed, but tournament players will know them.

For further watching, I recommend these two video by Extra Credits: Power Creep and the IMO even more informative followup Power Creep in Hearthstone.

---
Tags: game-design
---


# Question
Title: how to choose the board design in a multiplayer game?
I'm making a Nine Men's Morris board game in which players can play with other online players.

But my problem is in steps before starting the game between two players.

This is what I thought about:

> 1- Player B requests to play with Player A
>
> 2- If player A accept the request, the game will start.

I need a step in between, so that they can choose a board design, but I don't know who should choose it or how.

Is there any better way in maching two players or how to select a borad map? Any ideas is much appreciated.

# Answer
> 1 votes
One option would be to have the request include a proposal for the board design. The receiver can either

* reject the challenge completely
* accept the challenge with the proposed board, or
* make a counter-proposal with a different board

When a player is just looking for an opponent and does care more about the board they play on than about who their opponent is, you could also do matchmaking in the other way: When a player wants to play, they announce that they are available for play. When they do that, they decide which board they would like to play on. Other players can view the list of available players with their chosen boards and pick one to challenge.

---
Tags: game-design, multiplayer
---


# Question
Title: In Game Maker, how do I make invisible platforms the player can walk on, and reveal with an item?
I'm using Game Maker and looking for help with these:

1. I'd like to have invisible platforms and walkways for the player to move on. I want the platform to be slightly visible in this option so the player can find them but still be invisible while being fair to the player.
2. Platforms are invisible, but a special item (like the Lens of Truth in *Legend of Zelda: Ocarina of Time* turns the invisible things visible within a given area for the time the player is using the item.

# Answer
Looking at the pieces one by one:

## Invisible floor

You can make invisible floor tiles by choosing your usual floor image as the collision mask, and setting the object to have no sprite.

## Partially transparent floor

You'll want to write a script for the object's Draw event, using `draw_sprite_ext`, tuning the `alpha` parameter to whatever works best (`0` is completely transparent, `1` is completely opaque).

## Lens of Truth

If you want the tiles to sometimes be visible and sometimes not (depending on a *condition*, you'll need to write a Draw event script with an appropriate conditional.

Something approximately like—

```
if ( obj_Player.hasLensOfTruth && distance_to_object(obj_Player) < 100 ) {
    // Put a call to draw_sprite or draw_sprite_ext here
}
// ... Otherwise: Nothing is drawn.

```

That `distance_to_object` is intended to check that the player is close enough. I imagine you'd have an instance variable `hasLensOfTruth` set to `true` when the player finds that item.

---

The first one (invisible floor) is doable without writing a GML script. I can't think of a way of doing the other two using only drag-and-drop actions, and you might need the Pro version for the partial transparency.
> 3 votes

# Answer
Disable "visible" and enable "visible" when you need to. It is a built-in variable and it works well for your case.

If the platform is invisible type "visible = false", if it turns visible then "visible = true".

It is extremely easy.
> 1 votes

---
Tags: rendering, platformer, game-maker
---


# Question
Title: ECS: removal of group of related components
Currently I'm working with LibGDX and using Ashley for ECS. Everything is fine, until i need to remove groups of related components.

Say we have a player that may use different weapons. For now, in my game a weapon is described by one or more components.

For example we have weapons, each is described by its own components:

```
weapon1: [ c0, c1, c2 ];
weapon2: [ c3, c4 ];
weapon3: [ c5, c6, c7 ];

```

It's ok when I want to add a weapon. I know which components are required and can put them to entity. The issue comes when I need to replace one weapon with another.

I can deal with if-else when it's only 3-5 weapons. But what if there are 20?

For now, my idea is to have additional component called `WeaponComponent`. Which will contain a family (I mean Ashley Family instance) that contains all information i need to remove the unnecessary components. But for me it looks more like a workaround, not a solution.

So, does anybody know how to deal with this? Are there any other approaches?

**UPDATE**

OK, For now I have tried few implementations. And here is the one that seems to be the best for me. I have combined object-oriented and entity-component designes. The `WeaponComponent` holds a reference to a `Weapon` implementation. The `Weapon` implementations know exaclty which components to attach/remove to/from an entity.

```
interface Weapon {
    void attachTo(Entity entity);
    void removeFrom(Entity entity);
}
class WeaponComponent {
    private Entity owner;
    private Weapon weapon;
    public void setWeapon(Weapon weapon) {
        if(this.weapon != null)
            this.weapon.removeFrom(owner);
        if(weapon != null) {
            this.weapon = weapon;
            this.weapon.attachTo(owner);
        }
    }
}

```

So, using this design, changing weapons is very easy now. And I don't have to care what weapon is already attached, and how to remove it: `engity.getComponent(WeaponComponent.class).setWeapon(whatEver);`.

# Answer
You can add an `enum` for the type of component, and add a type attribute to the `Component` base class.

```
...
enum EComponentType {
...
    ECT_Weapon,
...
}
...
class Component {
...
    EComponentType _type;

public:
    EComponentType getType() const;
...
}

```

Then, you just need to check that attribute

```
if (component->getType() == EComponentType::ECT_Weapon) {
    entity->remove(component);
}

```

I have no idea about LibGDX but hope this helps.
> 0 votes

# Answer
If the weapon entity only contains weapon components you could just drop all components using

```
entity.removeAll();

```

Or drop the entity from the engine completely and remake with the new components.

Using the remove method to remove component will return null if a component doesn't exists so won't cause any issues if you want to try and remove all weapon components.

```
entity.remove(component.class);

```
> 0 votes

---
Tags: java, libgdx, entity-component
---


title: How to keep Unity data after reinstall?

text:
# Question
Title: How to keep Unity data after reinstall?
After the use uninstall/reinstalls my app, all of his serialized data is gone. Is there a way to store a file on a mobile device permanently - which persists through various installs? Without using a server/cloud service or requiring the user to log into Google Play Games?

# Answer
If you delete an app on a mobile device, its data is gone.

If you want to retain data between uninstalls, the data will need to be saved on a server.
> 1 votes

# Answer
For those reading, I found this genius piece of code (first snippet): https://forum.unity3d.com/threads/load-video-files-from-sd-card.477593/ which I used to write my data to the phone's sdcard. It remained after completely un- and re-installing the app! Eureka! Now only to figure out how to do this on IOS...

UPDATE: still haven't tried IOS but improved it so it works with Internal Memory and no sdcard (but you need "Write External Storage" permission still for some reason):

```
     string s = Directory.GetParent(
                     Directory.GetParent(Application.persistentDataPath)
                         .Parent.Parent.FullName).FullName;

     if (!Directory.Exists(s + "/.GAMENAME/"))
         Directory.CreateDirectory(s + "/.GAMENAME/");

     myPath = s + "/.GAMENAME/GAMENAME.save";

```
> 1 votes

# Answer
Generally, the answer isn't that you can't, it's that you **shouldn't** create application specific data on a device that remains after removing the application. Otherwise the data of previous apps will uselessly stay on the device indefinitely, until it slowly fills up all of the device's storage. This is extremely bad form and may result in your app being rejected from the store.

You need to distinguish between files that belong to the device, such as music, photos, ... , and files that belong to the application, such as savegames. This applies regardless of mobile or not. The convention on desktop OSes is that during uninstall you ask the user if they want to keep their savegames.

How to do store data on the device is OS specific, so for an actual example you'll need to specify the OS.
> 0 votes

---
Tags: unity, savegame
---


# Question
Title: Rotate an object with 'Quaternion.Slerp' in world space
I'm currently working on a multiplayer skydiving Unity game in which i rotate the players like this:

```
transform.rotation = Quaternion.Slerp(transform.rotation, desiredRotation, delta);

```

Now this rotates the player relative to it's own rotation. I know rotation in world space is done by multiplying the quaternion of the desired positon with the quaternion of the current position like this:

```
localRotation = transform.rotation * desiredRotation
worldRotation = desiredRotation * transform.rotation

```

But how do i slerp to that position in world space?

*Thank you all in advance and have a great day!*

# Answer
> 1 votes
First you grab the total rotation quaternion.

```
fullRelativeRotation = Quaternion.inverse(transform.rotation)*desiredRotation;
rotationTime = 0;
//persist over frames

```

then every frame until you complete the rotation you slerp the identity quaternion with it.

```
if(rotationTime < 1){
    rotationThisFrame = Quaternion.Slerp(Quaternion.identity, fullRelativeRotation, min(delta, 1-rotationTime));
    rotationTime+=delta;
    transform.rotation = transform.rotation * rotationThisFrame;
}

```

# Answer
> 1 votes
Usually, in order to get from a local coordinate frame to world coordinates, you need to go through the rotation hierarchy, like `worldToParent.rotation * parentToLocal.rotation = worldToLocal.rotation`.

So, in order to rotate towards a desired orientation in world space, your computation look something like `transform.rotation = Quaternion.Slerp(worldToLocal.rotation, desiredRotation, delta)`. Note that `desiredRotation` in this case is not transformed, as it is a relative rotation anyways and will thus be applied within the same coordinate frame as the base rotation (in this case `worldToLocal`, defined as above, which resides in the world frame).

---
Tags: unity, c#, mathematics, rotation, quaternion
---


# Question
Title: Performance issues when loading maps in XNA / Monogame
I'm new to Monogame and I'm having some perfomance issues, I'm loading a matrix of 9 maps (3x3) each with 50x50 tiles of 32x32 pixels each. I store that in a list of maps from 0 to 8 and call them by their filename from \[0,0\] ( \[X,Y\] ) up to \[2,2\] completing the 3x3 matrix in order to know what and where to load each new map.

Whenever my player goes to the border of the "playzone" \[1,1\] (the middle map) I load the respective three maps that follow, in this case I implemented the right loading, when the player heads to the right, over to \[1,2\] I need to load \[0,3\]\[1,3\]\[2,3\] and I unload \[0,0\]\[0,1\]\[0,2\] but whenever my game does this it stutters for a second. I might have overcomplicated things a bit and I'd love to be pointed in the right direction to optimize this. Thank you!

GameScreen class

```
namespace Game1.Screens
{
    public class GameplayScreen : GameScreen
    {
        Player player;
        List<Map> maps;
        float chunkWidth;
        Vector2 viewChunk;
        MapConfig mapConfig;
        XmlManager<Map> mapLoader;
        XmlManager<MapConfig> mapConfigLoader;
        bool loadingMaps;

        public GameplayScreen()
        {
            chunkWidth = 0;
            viewChunk = new Vector2(0, 0);
            mapLoader = new XmlManager<Map>();
            mapConfigLoader = new XmlManager<MapConfig>();
            mapConfig = mapConfigLoader.Load("Load/Gameplay/Maps/MapConfig.xml");
            loadingMaps = false;
        }

        public override void LoadContent()
        {
            base.LoadContent();
            XmlManager<Player> playerLoader = new XmlManager<Player>();
            player = playerLoader.Load("Load/Gameplay/Player.xml");
            player.LoadContent();
            LoadMaps(new Vector2(0,0));
            if (maps.Count > 0)
                chunkWidth = maps[0].Layer[0].TiledMap.Row.Count * maps[0].TileDimensions.X;
        }

        public void LoadMaps(Vector2 startingPosition)
        {
            maps = new List<Map>();
            int mapX = 0;
            int mapY = 0;
            int currentMapX = (int)(Math.Floor(player.CurrentPos.X / mapConfig.TileDimensions.X / mapConfig.ColumnCount));
            int currentMapY = (int)(Math.Floor(player.CurrentPos.Y / mapConfig.TileDimensions.Y / mapConfig.RowCount));
            for (int i = 0; i < mapConfig.ChunkMatrixAmount.Y; i++)
            {
                mapY = currentMapY + (i - 1);
                for (int j = 0; j < mapConfig.ChunkMatrixAmount.X; j++)
                {
                    mapX = currentMapX + (j - 1);
                    maps.Add(mapLoader.Load("Load/Gameplay/Maps/Map" + mapX + mapY + ".xml"));
                }
            }
            for (int i = 0; i <= maps.Count - 1; i++)
                maps[i].LoadContent(i, startingPosition);
            loadingMaps = false;
        }

        public override void UnloadContent()
        {
            base.UnloadContent();
            player.UnloadContent();
            foreach (Map map in maps)
                map.UnloadContent();
            maps = new List<Map>();
        }

        public override void Update(GameTime gameTime)
        {
            Vector2 endingMatrixPos = new Vector2(0, 0);
            Vector2 currentMatrixPos = new Vector2
            {
                X = (float)(Math.Floor(player.CurrentPos.X / mapConfig.TileDimensions.X / mapConfig.ColumnCount)),
                Y = (float)(Math.Floor(player.CurrentPos.Y / mapConfig.TileDimensions.Y / mapConfig.RowCount))
            };

            //Load a new RIGHT and unload LEFT
            if (currentMatrixPos.X >= Math.Floor(maps[5].Layer[0].Image.Position.X / mapConfig.TileDimensions.X / mapConfig.ColumnCount) &&
                maps[8].Layer[0].Image.Position.X != 0 &&
                !loadingMaps)
            {
                loadingMaps = true;
                foreach (Map map in maps)
                    map.UnloadContent();
                endingMatrixPos.X = maps[0].Layer[0].Image.Position.X + mapConfig.TileDimensions.X;
                endingMatrixPos.Y = (maps[0].Layer[0].Image.Position.Y + mapConfig.TileDimensions.Y) - (mapConfig.TileDimensions.Y * mapConfig.RowCount);
                LoadMaps(endingMatrixPos);
            }

            base.Update(gameTime);
            player.Update(gameTime);
            foreach (Map map in maps)
                map.Update(gameTime, ref player);
            if (player.CameraFollow)
            {
                Camera.IsFollowingObject = true;
                Camera.Pos = -player.CurrentPos;
            }
            Camera.Update();
        }

        public override void Draw(SpriteBatch spriteBatch)
        {
            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null, null, Camera.Transform);
            base.Draw(spriteBatch);
            foreach (Map map in maps)
                map.Draw(spriteBatch, "Underlay");
            player.Draw(spriteBatch);
            foreach (Map map in maps)
                map.Draw(spriteBatch, "Overlay");
            spriteBatch.End();
        }
    }
}

```

If you need more information I'll provide it when possible! Thank you for your help again!

# Answer
> 0 votes
First, don't load every file in every time. If you load in a 3x3 square when you leave the center square, then you'll throw away 6 or 4 tilemaps based on the player's direction. That's a huge waste.

Second, 3x3 is very small. In fact, if your map isn't literally thousands of tiles in each direction, then the Memory should be able to handle it. Yes, memory is expensive, but if a 2011 PC could handle a big chunk of Skyrim's world at once, then it should be able to work with a tiled map.For example, my MonoGame project could load in 10,000 different tiled maps in a very inefficient format, each having 32 x 32 tiles without even remotely maxing out my 4GBs of memory (that's 10,240,000 integer if you're curious, which is around 40,960,000 bytes or around 39 MB). Just apply some sort of culling so only the visible maps are drawn.

And last, if you need to do any kind of IO do it in a separate thread. There's no reason to make the player wait for

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


# Question
Title: How to make a cartoon like trail particle system?
I'm currently working on an little Android game, it's a reaction casual game. Because the user needs to tap some balls flying around at the right moment, I want to add some new effects to them.

So I looked at some other games and found this cool looking cartoon like effect.

As you can see the ball there has an cool tail.

So my question is, does anyone know how to recreate such a trail with the Unity particle effects or some other tools?

# Answer
> 1 votes
You might be able to do this with the TrailRenderer component. When you want your game object to have more than one trail, you might have to add some sub-objects to it with their own trail renderers.

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


title: Fixed camera rotate to follow character

text:
# Question
Title: Fixed camera rotate to follow character
I have a camera in a fixed position in the middle of a field, and I would like to rotate the camera to follow the character as it moves around. There is no point lower than the camera, but I would like it to follow vertically as well. Given the point/euler angle of the camera, and the point of the character, what math could I use to implement this?

# Answer
> 1 votes
*(Since the question states only one angle this answer assumes rotation on one axis in 3D-space)*

Given these inputs on a y-up coordinate system:

```
cameraPos    = (cx, cy, cz)
currentAngle = θ
playerPos    = (px, py, pz)

```

We can first calculate the vector pointing from the camera to the player position:

```
playerCamVector = playerPos.xz - cameraPos.xz = (px - cx, pz - cz)

```

We can then calculate the angle of this vector using `atan` (a.k.a. arc tan or tan-1):

```
playerCamAngle = atan(playerCamVector.y, playerCamVector.x)

```

We now calculate the difference between this angle and the current camera angle:

```
angleChange = playerCamAngle - currentAngle

```

Given this difference we can now rotate the camera by this much so we face the player:

```
// Rotate on the Y-vector (up)
camera.rotate(Vector.Y, angleChange)

```

If you want smoother movement you should probably use some sort of interpolation to gradually change the camera's rotation instead of instantly moving it.

---

A more compact version would be to just calculate the angle directly:

```
angle = atan(pz - cz, pz - cx)
angleChange = angle - currentAngle
camera.rotate(Vector.Y, delta)

```

---
Tags: 3d, camera, ios, scenekit
---


# Question
Title: How can I fix zig-zagging UV mapping artifacts on a generated mesh that tapers?
I am creating a procedural mesh based on a curve and the size of the mesh gets smaller throughout the curve as you see below.

And the problem is UV gets zig-zagged as the size changes (it works perfectly when the size of the mesh is same throughout the curve).

```
 Vertices.Add(R);
 Vertices.Add(L);
 UVs.Add(new Vector2(0f, (float)id / count));
 UVs.Add(new Vector2(1f, (float)id / count));
 start = Vertices.Count - 4;
          Triangles.Add(start + 0);
                 Triangles.Add(start + 2);
                 Triangles.Add(start + 1);
                 Triangles.Add(start + 1);
                 Triangles.Add(start + 2);
                 Triangles.Add(start + 3);

 mesh.vertices = Vertices.ToArray();
         //mesh.normals = normales;
         mesh.uv = UVs.ToArray();
         mesh.triangles = Triangles.ToArray();

```

How can I fix this?

# Answer
> 17 votes
Typical UV mapping is what's called an affine transformation. That means the mapping of each triangle between 3D space and texture space can include rotation, translation, scaling/squash, and skew (ie. anything we can do with a homogeneous matrix multiplication)

The thing about affine transformations is that they're *uniform* across their whole domain - the rotation, translation, scale, and skew we apply to the texture near vertex A is the same as what we apply near vertex B, within any one triangle. Lines that are parallel in one space will be mapped to parallel lines in the other, never converging/diverging.

But the gradual tapering you're trying to apply is not uniform - it's mapping parallel lines in the texture to converging lines on the mesh. That means the scale of the texture measured across the band is changing continuously as we move down the strip. That's more than the affine transformations of 2D UV mapping can accurately represent: interpolating 2D uv coordinates between adjacent vertices will get one consistent scale along the whole edge, even the diagonal edge which should be shrinking in scale as it moves down the strip. That mismatch is what creates this warbling zigzag.

This issue crops up anytime we want to map a rectangle to a trapezoid - parallel sides to converging sides: there's just no affine transformation that does this, so we have to approximate it piecewise, leading to visible seams.

For most purposes you can minimize the effect by adding more geometry. Increasing the number of subdivisions along the length of the strip, and splitting the strip into two or more segments along its breadth, with the diagonals of the triangles arranged in a herringbone pattern, can make the effect much less noticeable. It will always be present to some extent as long as we're using affine transformations though.

But there is a way around it. We can use the same trick we use for 3D rendering to draw trapezoids in perspective given rectangular walls & floors: **we use projective coordinates!**

Affine texturing:

Projective texturing:

To do this, we need to add a third uv coordinate (uvw) and modify our shaders.

Given a scale factor at each point (say, equal to the breadth of your strip at that spot), you can construct the 3D projective uvw coordinate from your regular 2D uv coordinate this way:

```
Vector3 uv3 = ((Vector3)uv2) * scale;
uv3.z = scale;

```

To apply these 3D uvw coordinates to your mesh, you'll need to use the Vector3 overload Mesh.SetUVs(int channel, List uvs)

And be sure to change your shader's input struct to expect a 3D texture coordinate (shown here using the default unlit shader):

```
struct appdata
{
    float4 vertex : POSITION;
    float3 uv : TEXCOORD0; // Change float2 to float 3.
};
// Also do this for the uv sent from the vertex shader to the fragment shader.

```

You'll also need to cut out the TRANSFORM\_TEX macro in the vertex shader, since it expects a 2D uv:

```
// o.uv = TRANSFORM_TEX(v.uv, _MainTex);
o.uv = v.uv;
// If you define a float4 with the special name _MainTex_ST,
// you can get the same effect the macro had by doing this:
o.uv.xy = o.uv.xy * _MainTex_ST.xy + _MainTex_ST.zw;

```

Finally, to turn back to a 2D texture coordinate for texture sampling, you just divide by the third coordinate in your **fragment shader**:

```
float2 uv = i.uv.xy / i.uv.z;

```

Since we made this 3D uvw coordinate from our desired 2D coordinate by multiplying by the same number, the two operations cancel out and we get back to our original desired 2D coordinate, but now with non-linear interpolation between the vertices. :D

It's important to do this division per fragment and not in the vertex shader. If it's done per vertex, then we're back to interpolating the resulting coordinates linearly along each edge, and we've lost the nonlinearity we were trying to introduce with the projective coordinate!

---
Tags: unity, procedural-generation, mesh, uv-mapping
---


title: Quality deterioration on a device

text:
# Question
Title: Quality deterioration on a device
I am using Unity. When I try the game out in the IDE everything looks pretty good:

But when I am trying to play the same game on a device the quality becomes a great deal worse and you can see it for yourself:

I am using Xiame Redmi 4X and I do not think that it is because of device.

So, how can I fix it? How can I preserve the quality?

I would like to try out this solution, but there is no Android settings in my Inspector for quality:

I would like to preserve at least colors.

And here are setting for my player sprites:

# Answer
The render quality settings apply mostly to 3d games. Very few of the features you would usually use in a 2d game are affected by them.

It seems like your play-window uses a different resolution than your device. Click on "16:9" in the upper left corner of the play window, and set it to a custom resolution which is identical to your target device. You should now see the same degration due to scaling which you see on the device and then should be able to troubleshoot it properly.

Regarding *why* there is that degration: There are a couple of possible reasons. But which one is responsible in your specific case is hard to tell without seeing how you set up your camera, how you render your sprites, etc.

But keep in mind that it wouldn't be wise to look for a solution which looks good on that particular resolution but not on any others, because Android devices come in all kinds of screen resolutions. To keep the image quality ideal you should try to always keep the scaling 1:1 no matter what resolution you have. But that means the amount of game world which is visible on the screen depends on the screen resolution, so different devices will have different game experiences. There is no silver bullet solution to this conundrum. You will have to find a game-specific compromise.
> 1 votes

---
Tags: unity, color, aspect-ratio
---


# Question
Title: Guidelines for determining what should be a component?
Background:

So I'm developing my first 2d C++ fighting game (for learning purposes) and I have a setup where I have 'components' which are really just data holders with maybe some simple utility functions such as GetComp(), AddToComp(), etc. All components get passed to component systems which are just functions which act on certain components (e.g. MovementSystem(PositionComp pos, VelocityComp vel), etc.) which are split up into their respective domains (Graphics, Animation, Physics, etc.). All components are held by 'Fighter' class which acts as the component holder that keeps everything together.

Issue:

The problem I'm having is I'm not sure how I decide what exactly should be made into a component vs what shouldn't. For example, for my animations I have a system which essentially takes a 'spriteComponent' and a 'animationClip' obj like so `SetAnimation(spriteComponent sprite, animationClip anim)`. As it stands, my animationClip class is not considered a component and is not currently attached within my Fighter class, though I guess I could implement it that way. How do I decide what classes/types should be made into components? How is this typically handled in other ECS like systems?

# Answer
> 1 votes
I have always somewhat preferred to think of a component as a container of values that influences a specific behavior in a data-driven way.

So when we talk about animation, we're designing a system that is meant to allow some external source to request that the system play and optionally blend various animations. That would mean that we need some component that allows those values to be driven

1. Flag that controls whether animations are enabled.
This could optionally be influenced by whether or not the component exists; however, the same entity might be rendered for different purposes and being able to toggle this may be useful for cases where animations aren't important.
2. Default animation to be played.
3. List of available animations that can be played.
4. Define animation blending overrides.

From here its simply a matter of the system taking these values from the component and implementing the desired behavior.

When it comes to the next behavior, you follow the same process.

The one aspect I will mention is that i have found it useful in the past when systems deal with multiple components to manage some internal system data structure that relates the multiple components together somehow that is memory efficient for that system.

This may mean cloning values from the components to this internal data structure when some update event fires and then simply iterating that internal data structure on the system's update rather than trying to do multiple look-ups for all the various components.

---
Tags: architecture, component-based, entity-component
---


title: Should I compress the game data files?

text:
# Question
Title: Should I compress the game data files?
I am working on packaging my game resources into a single file. I have chosen the format but I don't know whether I should use compression or not. I understand the possible pros and cons:

1. Compression means less installation time (happens rarely).
2. Compression means less game size on the disc and during downloading process.
3. Compression means the data should be extracted every time the game resource cache mechanism decides to cache some data in RAM from the archive.

Did I miss anything? What do other game developers usually do and why?

# Answer
Why don't you grab the best part of both sides and compress files to download, then extract them on installation?

This way you will have less data to transfer during download (so faster download), some overhead on installation (theoretically, once?) and then better runtime performance.
> 1 votes

---
Tags: assets, resource-management, compression
---


# Question
Title: Trying to make a game entity jump. Can't figure out what is dt?
At it's core what is delta time? In every equation to make a player jump I see that it is multiplied by delta time. Is this a constant value or a changing one? How does this value help? I don't understand why it's needed for velocity, acceleration and jumping.

# Answer
> 2 votes
**Delta time is the time elapsed since the previous frame**.

It can be a constant value but is not required to be; typically it will be dependent on factors including, but not limited to:

* how fast your hardware is,
* whether or not you have vsync enabled,
* what your monitor's refresh rate is,
* whether your program is framerate limited or not,
* etc.

It's important because otherwise movement would be done at a rate that is framerate-dependent: if your program was running at a faster framerate then movement would likewise be faster.

# Answer
> 0 votes
Great answer by '**Le Comte du Merde-fou**'.

Small practical pseudo-code example:

```
game(){
 previousTime = systemTime.now() // initial time

 //gameloop
 while(){

  currentTime = systemTime.now() // current time
  dt = currentTime - previousTime // difference between current and previous time
  previousTime = currentTime //save the current time to be used to calculate dt for the next cycle

  update(dt)
  //render etc...
 }
}

```

---
Tags: 2d
---


# Question
Title: How to simulate camera turbulence for in-game cinematics
Are there any good algorithms for generating a convincing turbulence effect that can be applied to an in-game camera.

For example, in use cases such as the viewpoint of a plane flying low and fast over a landscape.

# Answer
It sounds like you might just want a basic camera shake.

```
// Maximum offset of shake, per axis. Keep this small - millimetres usually.
Vector3 max_amplitudes;

// Number of oscillations per second, per axis.
// Keep this lower than half your framerate to avoid temporal aliasing.
Vector3 frequencies;

Vector3 ShakePosition( Vector3 unshakenPosition, float trauma ) {
   // Making amplitude proportional to the square or cube of the input trauma
   // helps give a gentler ramp-out to the shake, and clearly distinguishes intensities.
   Vector3 amplitude = max_amplitudes * trauma * trauma * trauma;
   Vector3 phases = time * frequencies;

   Vector3 offset;
   // Using trig functions gives a periodic shake, like the camera's mount
   // has a little wobble in it like a stiff spring. Using different frequencies
   // on each axis helps the shake look chaotic instead of repetitive.
   offset.x = cos(phases.x) * amplitude.x;
   offset.y = cos(phases.y) * amplitude.y;
   offset.z = cos(phases.z) * amplitude.z;

   // You can use your favourite continuous noise function instead of cos if you like,
   // eg. Perlin noise with different frequencies / offsets per axis.

   return unshakenPosition + offset;
}

// You can incorporate this into your camera update something like this...
void UpdateCamera() {
    camera.unshakenPosition = UpdateCameraPosition(camera.unshakenPosition);

    // You can also track & decay trauma frame-to-frame,
    // to layer speed-based rumble with spiky shakes due to impacts.
    float trauma = speed / max_speed;

    camera.shakenPosition = ShakePosition(camera.unshakenPosition, trauma);

    // Note that we keep the shaken and unshaken positions separate.
    // We always update camera behaviour using the unshaken position,
    // and use the shaken position for final rendering only.
    // This keeps the shake from exploding in a feedback loop,
    // or interfering chaotically with carefully-tuned gameplay behaviours.
}

```

This models small vibrations of the camera mount and airframe. Try that and see how it feels. If you need more complexity, you can use this same template to add more layers like...

* Rotational shake - same idea, but shake in local Euler angles instead of xyz position
* Gusts & air pockets - add a second shake with a bigger max amplitude on a lower frequency (you can even apply this fractally, but two layers is probably enough)
> 2 votes

---
Tags: 3d, algorithm, camera, simulations, cutscene
---