title: How do I implement Pokemon-style moves?

text:
# Question
Title: How do I implement Pokemon-style moves?
I'm developing a Pokémon/classic Final Fantasy inspired game, in the sense that game play consists in many **creatures**, possessing many **moves** with different effects (attacking, healing, buffing, debuffing, etc) taking turns fighting each other.

I'm having some doubts on how to implement the movement system, especially the part of how to organize the code responsible for the effects of the move.

Some important characteristics of the system:

* Creatures should be able to learn and forget moves
* All moves can be learned by more than one creature

I have come up with some ideas, but none seem very good. Is there any known standard in the industry for doing this, or any known optimal solutions?

---

Here are the ideas I had:

* Every move inherits from an abstract class Move, overriding an execute() method.
* A MoveProcessor class, containing a method executeMove(), called every time any move is made, receiving the move id code. Something like:

```
switch(moveCode){
     case 1: //Attack code
     break;
     case 2: //Heal code
     break;
     //...
}

```

I am developing in Unity and C#, but answers need not be specific to said platform and language.

Please note that this is not a duplicate of Modeling what moves a pokemon can learn or Storing data for a pokemon-like game, since those questions ask about storing move information, not implementation.

# Answer
I see no other solution that having distinct 'moves' that are implemented in some mechanism that allows the 'owner' to invoke them without really knowing what those moves are.

However, it is unclear if you want to make the logical break on implementing distinct moves as a 'Move' with subclasses. You may find it more useful to think about the content (animations, sounds, particle effects), effects(buffs, debuffs), actions(damage) as the actual abstract objects, and the 'Move' as simply a container of animations, effects and actions performed when 'Invoke' is called. Trying to create a unique subclassed Move for every move available is going to be be brittle and will lead to you having to rework your hierarchy often. Instead I would consider a Move as having a bunch of different objects inside it, perhaps scheduled in steps, with timers. The values for the different actions, effects and content (like range of heals, time of a buff) would be provided as parameters, not hard coded in derived classes, when possible. It would make sense that a lot of this data come from a text, json, excel or xml file. I would further suggest that you should be able to define these objects as code, created on demand from the text file. Then you may plug them together in different combinations simply using the text system so you can mix and match them.

By making the Move a container, and breaking the pieces down into smaller elements you will find it easier to reuse them.
> 3 votes

# Answer
An alternative to every move inheriting from an abstract class Move, you can instead use interfaces in C#. This has the advantage of allowing your move classes to be more flexible while still sharing the execute method. An example of this could be:

```
public interface IMove
{
    void Execute();
}

```

The different moves:

```
public class Attack : IMove
{
    public void Execute()
    {
        //Attack logic here
    }
}

public class Heal : IMove
{
    public void Execute()
    {
        //Heal logic here
    }
}

```

And the creature class:

```
public class Creature
{
    public Creature()
    {
        Moves = new List<IMove>();
    }

    public List<IMove> Moves { get; set; }

    public void AddMove(IMove move)
    {
        if (!Moves.Contains(move))
        {
            Moves.Add(move);
        }

    }

    public void RemoveMove(IMove move)
    {
        if (Moves.Contains(move))
        {
            Moves.Remove(move);
        }
    }

    public void ExecuteMove<TMove>()
        where TMove : IMove
    {
        var move = Moves.OfType<TMove>().SingleOrDefault();
        if (move != null)
        {
            move.Execute();
        }
        else
        {
            throw new DoesNotContainMoveException();
        }
    }
}

```

It can be used as follows:

```
Creature creature = new Creature();

creature.AddMove(new Attack());

creature.ExecuteMove<Attack>();

Console.ReadKey();

```
> 3 votes

---
Tags: performance, rpg, data-structure, turn-based
---


# Question
Title: Find a vector 90 degrees to the right of a given angle
Can you help transform this function to move the point not only by Forward distance but also by a distance to the right or left?

```
#define FORWARD_DISTANCE 100.0

// Initialize vectors
static float vEntPosition[3]; static float vEntAngle[3];

// Gets the origin
....GetAbsOrigin(nEntity, vEntPosition);

// Gets the  eye angle
....GetEyeAngle(nEntity, vEntAngle);

// Calculate effect area origin
vEntPosition[0] = vEntPosition[0] + (FORWARD_DISTANCE * Cosine(DegToRad(vEntAngle[1])));
vEntPosition[1] = vEntPosition[1] + (FORWARD_DISTANCE * Sine(DegToRad(vEntAngle[1])));

```

# Answer
Assuming your coordinate system has the y+ axis 90 degrees counter-clockwise from x+, then:

```
float angle = DegToRad(vEntAngle[1]);
float cosine = Cosine(angle);
float sine = Sine(angle);

vEntPosition[0] = vEntPosition[0]
                 + cosine * FORWARD_DISTANCE
                 + sine * RIGHTWARD_DISTANCE;

vEntPosition[1] = vEntPosition[1]
                 + sine * FORWARD_DISTANCE
                 - cosine * RIGHTWARD_DISTANCE;

```

This is a straightforward application of the unit circle - so brush up on your trigonometry and you'll find this kind of vector math can go very smoothly. :)
> 1 votes

---
Tags: 2d, vector, c
---


# Question
Title: How do I export Physique animations without breaking them?
I've been trying to export a simple footstep animation that I made in 3ds Max, but it either fails to export or is broken (imports into unity missing a few frames, or appears to have imported but won't play) every single time.

I've tried `.fbx` and `.3ds`, but neither works. I'd rather not use the Skin modifier, because it would require starting from scratch and learning a new system. Any ideas?

# Answer
Here is a workaround, as originally by provided by Paul Ferris himself in an edit to the question, and reproduced here as community wiki:

> I found a workaround, here it is if you're curious:
>
> * Create your biped, and make sure it lines up with your mesh.
> * Animate it
> * Export the mesh without Physique (or with Physique turned off), then delete it (the mesh)
> * Export the biped
> * Recombine in Unity (or whatever your game engine of choice is)
> 1 votes

---
Tags: animation, 3dsmax, skeletal-animation, skinning, biped
---


# Question
Title: Can a developer change their product name on Steamworks?
I recently got access to Steamworks and paid the product submission fee. Now I am able to create an app on Steam.

The app I'm working on is still untitled, but I want to start playing around with the Steamworks functionality.

Unfortunately, when I try to create a new app, Steamworks asks me for my product name. I am not sure if I will be able to change this later, so I am hesitant to proceed.

So my question is: **If I use a tentative name for my product on Steamworks, will I be able to change it later?**

I tried googling around, but couldn't find anything. There is too much noise from questions about changing one's username, etc.

# Answer
> 59 votes
Steamworks does allow you to change your product name.

If you want to change your product name, you need to make the change in three places. Each place is accessible from the app's landing page.

> 1. Edit Store Page \> Basic Info \> under "Game Name" (see here)
> 2. Store packages, pricing, & release dates \> click package title \> "Edit Package Name" on the right side of this page
> 3. Edit Steamworks Settings \> Application \> under "Application Name and Type"

# Answer
> 24 votes
**Yes**, you can change your product name. Several games that I own have changed names over the years. Some examples include:

* **Arma 2: Operation Arrowhead Beta (Obsolete)**. Previously called **Arma 2: Operation Arrowhead Beta**.
* **Serious Sam Fusion 2017 (beta)**. Previously called **Serious Sam Fusion**.
* **Skyrim Script Extender (SKSE)**. Previously called **SKSE**.

---
Tags: steam
---


# Question
Title: Work out the point on an ellipse given centre, radius, and direction vector?
I have a vector (white line), a centre and a radius along each of the semi-major and semi-minor axes of an ellipse (green line). I need to find the point where the white line intersects the green.

I have tried to work it out using `Atan2`, `Sin` and `Cos` but that doesn't quite work (blue line). It works when parallel to an axis but doesn't otherwise, I have a feeling this is because I am trying to perform the calculation on an ellipse where the horizontal and vertical radii are different.

```
Vector2 delta = (screenPos - canvasCentre).normalized;
float angle = Mathf.Atan2(delta.y, delta.x);
Vector2 position = canvasCentre + new Vector2(
                Mathf.Cos(angle) * radius.x,
                Mathf.Sin(angle) * radius.y);

```

# Answer
First, we invert the squash/stretch of the ellipse, so we're working in "unit circle space"

```
Vector2 delta = (screenPos - canvasCentre);

delta.x /= radius.x;
delta.y /= radius.y;

```

Now we can normalize the vector to snap it onto the unit circle, then re-introduce our squash/stretch to map the result back onto our original ellipse:

```
delta = normalize(delta);
delta.x *= radius.x;
delta.y *= radius.y;

Vector2 position = canvasCentre + delta;

```
> 1 votes

---
Tags: mathematics, geometry
---


# Question
Title: Problem when trying to use rb.MoveRotation in Unity
OK so I learned that rb.MoveRotation is different from rb.transform.Rotate(). But I am having trouble using it and hoping you can help me.

I usually use transform.translate(Vector3.forward) (after using transform.Rotate(x,y,z)) , so that I know that will always make object move in the direction its facing. But this isnt working when I use rb.MovePosition. The object rotates when i remove the MovePosition line, but then for some reason doesn't when its there. I've tried multiple things as you'll see in the code.

I cant understand also why, if I use the bottom commented attempt in my code, and then press D in game, it will go in the direction its facing and then get stuck. I've commented in my code to try to explain whats happening.

What is the correct way to move the position of the player now I am using MoveRotation? I want to base my movement of the direction that the object is facing and not in world coordinates.

Thanks

```
    void HandleKeys()
{
    if (Input.GetKey(KeyCode.A))
    {
        if (!facingLeft)
        {
            rb.MoveRotation(Quaternion.Euler(0,-90,0));
            facingLeft = true;
        }
        //rb.transform.Translate(Vector3.forward * speed * Time.deltaTime); // if I remove this line, the character does turn and face left . But when its in he doesn't and both keys make him move right (and face right)
        // also tried:
        //rb.MovePosition(transform.position += Vector3.forward * speed * Time.deltaTime); // this results in it going Vector3.forward in world coords
        //**rb.MovePosition(transform.position += rb.transform.forward * speed * Time.deltaTime); // this makes him go RIGHT>?? and the objects facing RIGHT why????
    }
    if (Input.GetKey(KeyCode.D))
    {
        if (facingLeft)
        {
            rb.MoveRotation(Quaternion.Euler(0f, 90f, 0f));
            facingLeft = false;
        }
        rb.transform.Translate(Vector3.forward * speed * Time.deltaTime); // if i leave this in, and the one marked * above, then it works but only once, so if I press A then, D he heads right but wont turn round, if I press D first he just goes right
    }
    if (Input.GetKeyDown(KeyCode.Space) && IsGrounded())
    {
        rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
    }

}

```

# Answer
> 2 votes
**Caution**: The trick shown here of using input in FixedUpdate worked at the time it was written in 2017 — Unity at the time had fresh input available from the very beginning of the frame, contrary to the documentation and common wisdom.

As of my last tests however, it does not work in Unity 2019 — input is not updated until after the FixedUpdate step, so this trick to compress perceived latency no longer works.

Test the version you're using to be sure.

---

As I mentioned in chat, I haven't been able to reproduce this issue. Just uncommenting the first rb.transform.Translate line let the object rotate & move as expected.

That said, I'd be tempted to rejig things a little like this:

```
bool pressReleaseHandled;

private void FixedUpdate() {
    // I tucked the movement code into FixedUpdate,
    // so it happens reliably before each Physics step.
    // This keeps our simulation consistent under
    // varying framerates, and can reduce visible
    // latency when using physics-based movement.
    HandleHold();
    HandlePressRelease(true);
}

void Update () {
    // If our framerate is faster than the physics rate,
    // we might not get a physics step every frame, so
    // this call ensures we don't miss any fleeting
    // button down / button up events.
    HandlePressRelease(false);
}

void HandlePressRelease(bool isFixedStep) {
    // This pattern ensures we handle button down/up events
    // exactly once in the frame that they happen. Either in
    // the first physics update of this frame, or in the regular
    // Update() as a fallback if physics doesn't step this frame.

    // This can reduce perceived latency compared to jumping in Update
    // (since we're jumping with physics, we don't get to see the rise
    // until a physics step happens, and those come before Update)
    if (pressReleaseHandled == false) {
        if (Input.GetButtonDown("Jump") && IsGrounded()) {
            rb.AddForce(Vector3.up * jumpImpulse, ForceMode.Impulse);
        }
    }
    pressReleaseHandled = isFixedStep;
}

void HandleHold() {
    // Held inputs are safe to process in every timestep.
    // They're valid for every time step in the frame, not
    // just instantaneously in one time step.

    // This lets us get a pure -1, 0, 1 value from the A & D keys
    float horizontal = Input.GetAxisRaw("Horizontal");

    // If we're facing opposite the direction of input, turn.
    if(transform.forward.x * horizontal < 0f)
        rb.MoveRotation(Quaternion.Euler(0, 90f * Mathf.Sign(horizontal), 0));

    // Move in the desired direction at our configured speed.
    // We set only the x component, so we don't interfere with jumping/falling.
    Vector3 velocity = rb.velocity;
    velocity.x = horizontal * speed;
    rb.velocity = velocity;
}

```

What's happening here:

* **I changed the GetKey methods to GetButton / GetAxis versions**

This lets players remap your controls, and means you can tweak your default button assignments in one place - the Input Manager - rather than having them distributed across multiple files.

Treating left/right movement as an axis also lets us exploit some symmetry and simplify the code, rather than duplicating similar logic inside two `if` blocks.

I used the `Raw` version of the axis method to get pure -1/0/1 values, without any gradations in-between, so the results would match the code you already had. If you take out the `Raw` part, Unity will apply some smoothing so the keys behave more like an analog stick, passing briefly through intermediate values when you change direction suddenly.
* **I changed the horizontal movement to use velocity**

While it's true we should be careful when setting the velocity, because this can inadvertently overrule other physics effects on the object, the original version using `Translate`/`MovePosition` has similar issues. Both say "move this way now" without asking if there are any other motions to take into account. ;)

So, if we're confident that we really want to move this way, doing it with velocity isn't strictly more harmful, and it gets us a couple of wins:

+ Objects we push into along the way will be knocked away in correct proportion to our speed, rather than nudged out of intersection by the collision resolver (which might impart too little or too much speed, depending on the depth of the overlap)
    + We can enable rigidbody interpolation to smooth the result between physics steps, so we don't see a judder as we might with Rigidbody.MovePosition

This does have a caveat: moving with velocity, your object will experience friction, which will make its net speed slightly lower than your speed constant (bump it up by a small fraction to compensate) and can impart a torque which can make your object tumble (lock rotation on the rigidbody to prevent this)

If you want to go further with the physics-based motion, you can try accelerating the object left & right, rather than setting the velocity directly. This can give a pleasant juicy feel when the acceleration is tuned well, and can play nicer with competing influences on the object (eg. if I'm skidding backward after getting hit by something, I have to exert a few frames of acceleration to overcome the backward velocity before I can proceed forward). You can also vary the max acceleration based on the terrain (whee, ice levels!) or character state (eg. a knockback stun or fast reversal of direction when running).

Here's a method you can use to accelerate toward a particular velocity horizontally while respecting a given maximum acceleration:

```
 void AccelerateHorizontally(float targetXVelocity, float maxAccel) {
     float change = targetXVelocity - rb.velocity.x;

     // If the delta-V is more than we're allowed in a single time step,
     // clamp to the max we're allowed, in the same direction.
     if(Mathf.Abs(change/Time.deltaTime) > maxAccel) {
         change = maxAccel * Time.deltaTime * Mathf.Sign(change);
     }

     rb.AddForce(change * Vector3.right, ForceMode.VelocityChange);
  }

```
* **I distributed the updates between Update and FixedUpdate**

Here's what it looks like when we do physics-based movement in Update:

```
FU = FixedUpdate
PS = Physics Step
U = Update
D = Display (new rendered frame visible to the player)

Frame 1                          Frame 2
--------------------------  | ---------------------------------|
FU   PS   FU  PS   U        D   FU   PS   FU   PS   U          D
                   ^                 ^         ^               ^
Input modifies velocity      Velocity moves object    Player sees result

```

Because the effects of our physics nudges don't get integrated until the next physics step, we get at least one rendered frame of latency before we can see the result.

Compare this to doing it in FixedUpdate: (on frames where we get at least one physics step, that is. On frames where we don't, the two methods are equivalent)

```
Frame 1
--------------------------  |
FU   PS   FU  PS   U        D
^    ^        ^             ^
|   Velocity moves object   |
Input modifies velocity    Player sees result

```

Now we can see the results of our input as early as the same frame it was issued. Our worst-case latency hasn't changed, but our best case has improved (and by tuning the physics update rate, we can ensure we're usually or always in the best case)

Another nice perk is that, since our movement logic is now running at a fixed timestep, our simulation stays consistent & fair even when running at different rendered framerates. This can help maintain the same feel on different devices, and prevent certain classes of timing bugs.

There's a common belief that input isn't usable in FixedUpdate, so you'll see some experienced Unity users consider code like I wrote above to be heresy. But while that might have been true in older versions of Unity, it doesn't seem to hold today. Test it and see. ;)

The caveat here is that not every display frame gets a physics step if our rendering framerate is higher than the physics frequency, which is why I check input in Update to ensure we don't skip any momentary button down/up events if our timing is unlucky. (I kind of wish Unity had a guaranteed-to-run-every frame EarlyUpdate that precedes physics, to simplify cases like this)

---
Tags: unity, physics, rotation, rigidbody, rigid-body-dynamics
---


# Question
Title: Pretty Sure I have Support for OpenGL 4, but it's not running. What can I do?
Many Game Engines require OpenGL to run. I have one of those. I've confirmed that the program and any benchmarks for OpenGL above OpenGL 2 fail to run.

Is there, like, a way to confirm I have dependencies or something to that effect? Is it installed or is it just a library included in other programs?

Specifically using Ubuntu Linux 17.10, computer specs are fairly low but I've run the Engine on Windows on the same machine before. Linux should have more up to date graphics drivers, so I'm not sure what the root of the problem might be.

# Answer
First of all, Opengl is not a library, it's callled a "specification". Libraries like GLEW (OpenGl Extension Wrangler) just *specify* the functions you need to control your gpu. At that point, it's the graphics card manifacturer's job to *implement* those functions.

"*The OpenGL specification specifies exactly what the result/output of each function should be and how it should perform. It is then up to the developers implementing this specification to come up with a solution of how this function should operate. Since the OpenGL specification does not give us implementation details, the actual developed versions of OpenGL are allowed to have different implementations, as long as their results comply with the specification (and are thus the same to the user).*"

One way you could verify if you are able to run Opengl is by creating a simple program with it. In C++ for example, you could write a s imple "hello world" program, using glfw(winidowing Api) and Glew. In the main.cpp file ypu should set the OpenGl context version to 4.0 and see if it runs. You can also check what the currrnt version of Opengl is, by calling `glGetString(GL_VERSION);` Now, this might not be the ideal way to do it, I'm sure there is an easier way to check for OGL drivers, so i would really appreciate if someone corrected me in the comments section :)

I also would like to leave some useful resources here and here
> 1 votes

---
Tags: opengl, graphics, support
---


# Question
Title: How can I make a sprite slow down to the speed of another sprite while following it?
I'm making a SpriteKit game where two SpriteNodes are in a maze. That maze is represented as a grid. One sprite (A) travels faster than the other (B). Items randomly pop up, and the sprites have to collect them.

Pathfinding is easy (GKGridGraph is simple to use).

Here's the problem: At any given time, A and B could be on the same stretch of the maze. If A is behind B, I want A to be forced to go the same speed as B (cannot pass through or around). How can I accomplish this?

Thank you for your time!

# Answer
> 0 votes
A possible solution would be to simply make the faster player check for collision with the slower player when it moves.

You would first move the slower player, then try moving the faster one. If the faster player collides with the slower one (you should probably use dynamic/swept AABB for this), then you make it stop (or if you use swept aabb, you make it touch the slower player).

---
Tags: ios, spritekit, swift
---


# Question
Title: Log in by pressing enter while password text is in focus
I have a very simple script which is supposed to Check if the return key is pressed while the password text is in focus. The issue is that I've tried all 3 methods `Input.GetKeyUp`, `Input.GetKeyDown` and `Input.GetKey` and they all work when the user presses the Return key 2 times at least. I need to be able to log in on one press of the return key. Here is the code I'm using:

```
InputField _input;
bool focused;
public System.Action Callback = () => { };
void Awake()
{
    _input = GetComponent<InputField>();
}

void Update()
{
    focused = _input.isFocused;
    if (focused)
    {
        Debug.Log("Passowrd field is in focus");
        if (Input.GetKey(KeyCode.Return))
        {
            Debug.Log("ENTER KEY PRESSED via getkey");
            Callback();
        }
    }
}

```

# Answer
`InputField.ActivateInputField()` is what you are looking for. Here is an example snippet that I wrote for one of my projects:

```
using System;
using UnityEngine;
using UnityEngine.UI;

public class SomeClass : MonoBehaviour
{
    public event Action<string> Entry;

    [SerializeField] private InputField _inputField;

    void Awake()
    {
        _inputField.onEndEdit.AddListener (InputField_OnEditEnd);
    }

    private void InputField_OnEditEnd (string input)
    {
        if (Input.GetKeyDown (KeyCode.Return))
        {
            OnEntry (input);
            _inputField.ActivateInputField();
        }
    }

    private void OnEntry (string entry)
    {
        if (Entry != null)
        {
            Entry.Invoke (entry);
        }
    }
}

```

To understand why this works you need to understand how `EventSystem` handles selection.

Once you press `Return` on an `InputField` while editing, `EventSystem` ends the edit mode but leaves the `InputField` selected. When you press `Return` for the first time after end of the edit mode, the key press is consumed for entering the edit mode again. Then you would need a second `Return` to submit the content.

`InputField.ActivateInputField()` activates the edit mode for you. So when the user presses `Return`, it submits the content instead of being consumed for entering the edit mode.
> 1 votes

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


title: Multiplayer Synchronization

text:
# Question
Title: Multiplayer Synchronization
I am developing multiplayer game in unity. For multiplayer i am using photon networking library. I created room and join client successfully.

But Problem is I am doing gameobject movent by this code:

```
public GameObject player;
IEnumerator Moving (String temp)
{

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

        player.transform.DOMove (CurrentPositionHolder, 0.5f).SetEase
           (Ease.Linear);
        yield return new WaitForSeconds (0.5f);
    }
}

```

DoMoveis library here.

Problem is player movement is not synchronized.

For Synchronization I add photonview component to player gameobject.

And i call coroutine though RPC like this.

```
player.GetComponent<PhotonView>().RPC ("Moving", PhotonTargets.All, "temp");

```

Accordingly i changed coroutine like this:

```
[PunRPC]
IEnumerator Moving (String temp)
{

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

        player.transform.DOMove (CurrentPositionHolder, 0.5f).SetEase
           (Ease.Linear);
        yield return new WaitForSeconds (0.5f);
    }
}

```

I got this error

Illegal view ID:0 method: Moving GO:player UnityEngine.Debug:LogError(Object)

# Answer
Problem gets solved. I call Moving enumerator from method not directly using RPC. And Make method call using RPC.

And Most important thing is use transfrom instead of gameobject like this:

```
transform.DOMove (CurrentPositionHolder, 0.5f).SetEase(Ease.Linear);

```
> 0 votes

---
Tags: unity, multiplayer
---


# Question
Title: Can I use fictional city/country names from public domain/fiction etc. in a potentially monetized browser game?
I'm currently developing a browser game with a focus on economy, trading and industry. For that I'm building a fictional world with countries and cities. To avoid political drama within the games player interactions, I'd like to avoid using real countries that currently exist/are recognized. I tried to come up with several fictional country names, but I'm reaching the limitations of my creativity where they are still OK-sounding... My questions are now...

* Can I use fictional countries e.g. from movies/comics etc (e.g. Sokovia from the Marvel universe)? Maybe with slight adjustments?
* Can I use older country or empire names (e.g. Babylonia)? Maybe also with slight adjustments.
* Can I use city names from the real world? I need a lot of them, so coming up with thousands brings me to my limit and there may probably be overlaps without me knowing. Based on the following question that should be fine, also since they have nothing to do with the real-life equivalents. Do I need licensing to use real city names in my game?
* What about using planet or galaxy names which are public domain (or how are they protected, if at all)?

I found some generators in the internet which are helpful to a certain degree, but I'd rather write my own to be honest. Since the game might be monetized, are there any licensing issues involved? I'm pretty new to this from a legal perspective.

Another thing are the fictional company names the users can choose. I guess I can set certain restrictions there to exclude real world companies and provide a "report" button for real companies to request the removal/change to be on the safe side.

Thanks in advance

PS: Since I also needed flags, I already found a nice generator, in case someone is interested: https://www.reddit.com/r/vexillology/comments/4ha19q/flagmaker\_20/?st=jb6e4qyk&sh=c1544079

# Answer
> 2 votes
First of all, I am not a lawyer. This is a laymen interpretation of intellectual property laws. Larger game studios have a legal department for a reason. If you are really serious about your game, you might want to hire an IP lawyer and get some advise before release.

---

Names are not protected by copyright, because they usually don't fulfill the necessary threshold of creativity. But they can be protected by Trademarks, which is an entirely different beast. So before you use a name, check if it is trademarked for use in games. Larger media companies tend to register a trademark on every name they come up with in case it ever gets marketable. You can look up trademarks registered in the United States on the website of the US Patent and Trademark Office.

Any historic names not recently trademarked are fair game. Copyright expiration rules vary around the world, but usually it's the death of the author plus ~70 years. So when you take a name from mythology you are pretty safe. And most names from astronomy are taken from mythology, by the way. Andromeda, Pollux, Cassiopeia, Ganymede... all people from Greek legends.

Just make sure you don't loan too much from recent fiction when you design the country itself, or you might run into a copyright lawsuit regarding the content. For example, if you have a country named *Sparta* inspired by classical Greek culture, that's fair game, because the historic Sparta was thousands of years ago (yes, the city still exists today, but I guess they got used to being overshadowed by their own history). But when everyone there talks in quotes from the movie *300*, then Warner Bros. legal department might get interested in you. (remember: in civil lawsuits, it's not just about being right but about having the money to prove it).

# Answer
> 1 votes
> I am not a lawyer. This can't be considered proper legal advice. You may want to contact a lawyer.

Using names from comics is definitely illegal. There's an exception though. If the comic is old enough to reach public domain, then it's possible to use those names without legal issues. However, since Marvel is only 78 years old and public domain is a bit messy since Disney tried to keep Mickey Mouse from "expiring", it's safe to say that none of the places are in it.

Even if old country names were "licensed", for the same reason I stated above (domains becoming public domain after X years) would mean you're allowed to use them.

Public domain is pretty self explanatory. If something's in public domain, you can use (and usually abuse) it. Since galaxy names are in public domain, you can use them legally.

---
Tags: legal
---


# Question
Title: Compare two x and y if they are in a valid range
Today my mind is a little foggy, the right thing was for me to do it the other day, but I will not, I will continue today. XD I need some help to think and find a way that works without bugs.

What I'm trying to do is compare two vector2 which are nothing else in my implementation in **javascript/nodejs** than an array with two floats.

I want to be able to compare if oldVector2 has any of its float x or y values in a range much different from floats x and y values of newVector2.

Example:

```
// When newVector2 is in a valid range less than 10
oldVector [0] = 1.55; // This is x
oldVector [1] = 0.22; // This is y

newVector2 [0] = 2.55; // This is x
newVector2 [1] = 1.55; // This is y

// When newVector2 is not in a valid range less than 10
oldVector [0] = 1.55; // This is x
oldVector [1] = 0.22; // This is y

newVector2 [0] = 21.55; // This is x
newVector2 [1] = 1.55; // This is y

if (the x and y of newVector2 is in a valid range less than 10 compared to the x and y of the oldVector?) {
     // You are in a valid range
} else {
     // Not in a valid range
}

```

My question is this: and when there are signs? Negative and positive numbers, how would this comparison compare?

what I'm trying to do here I already use **abs()**, I've done this before, but I did differently, because it was in *unity3D* that I did once, it was like this:

```
var distance = (a-b).magnitude;

```

where a and b are two 2D vectors, here is what magnitude does https://docs.unity3d.com/ScriptReference/Vector2-magnitude.html.

Then he compared

```
if(distance> 10)...

```

I'm confused at why I did it that way.

And the Vector2 are the position of an entity, I want to verify that it is not going faster than the permitted.

# Answer
> 1 votes
You need the "absolute" method: `abs()`. This will return a value that is always greater than or equal to zero. This way, you only have to check once for each axis:

```
var range = 10;

if ( abs(oldVector[0] - newVector2[0]) < range && abs(oldVector[1] - newVector2[1]) < range ) {
  // valid
}
else {
  // not valid
}

```

This will allow you to check if the newVector2 is within the range of the oldVector in a **square** pattern.

To check if the newVector2 is within the range of the oldVector in a **circle** pattern, which is generally desired when you want to limit the movement of an entity, you have to check the distance, we do that by using the Pythagorean theorem and we need square root method (`sqrt()`).

```
var range = 10;
var diffVector = [newVector2[0] - oldVector[0], newVector2[1] - oldVector[1]];

var distance = sqrt(diffVector[0]*diffVector[0] + diffVector[1]*diffVector[1]);

if (distance < range) {
  // valid
}
else {
  // not valid
}

```

Now if you need to do that often, the square root operations are typically costly on computers, so you can take a shortcut, you compare to the squared range distance:

```
var range = 10;
var diffVector = [newVector2[0] - oldVector[0], newVector2[1] - oldVector[1]];

var squaredDistance = diffVector[0]*diffVector[0] + diffVector[1]*diffVector[1];

if (squaredDistance < (range * range)) {
  // valid
}
else {
  // not valid
}

```

The first method will give you the range covered by the light blue square in the image below, while the second will give you the fuchsia circle:

---
Tags: mathematics, javascript, vector, node.js
---


# Question
Title: How does layer based collision affect performance
In Unity3D, and others, there are Layer Based Collision System which makes collisions only happen between specified Layers.

It defaults to all layers colliding with all others.

Does making use of these setting decrease performance, or increase performance?

I could imagine it decreases it if every potential collision had to be checked for it's layer. Or are those collisions completely bypassed?

# Answer
> Does making use of this setting decrease performance, or increase performance?

It (generally) increases performance. If you only have a handful of colliders in a scene, this could result in a slight performance hit, but it wouldn't be noticeable. Best practice is if you don't ever intend two layers to interact with each other, go ahead and disable it in the Matrix.

> I could imagine it decreases it if every potential collision had to be checked for it's layer. Or are those collisions completely bypassed?

Your assumptions are correct.

The Matrix is a filter on objects: If the object currently being checked belongs to this group, then check for collisions against object belonging to checked groups.

This means, for layers where you've disabled some collisions in the matrix, you are only checking for collisions between subsets of the colliders in the scene. Since there's less checks to perform, you gain some performance.

This is really only necessary as a performance optimization when you have a large number of objects in a scene. Most of the time this is used to support game functionality. For instance if you want bullets to only impact with players and walls, but not balloons that get pushed around the room by players as they move.
> 4 votes

# Answer
> I could imagine it decreases it if every potential collision had to be checked for its layer. Or are those collisions completely bypassed?

I don't have the first-hand knowledge about how Unity handles its internal connections with PhysX, but I imagine those layers would be bypassed. If anything, I imagine disabling collisions between layers should increase the performance since the physics engine would have fewer calculations to perform.

---

On the other hand, I imagine this question is a typical scenario of premature optimization, which I usually interpret as *trying to optimize your code without actually even having a working code*.

Instead of trying to predict the performance effects, I would suggest building a test project and actually measuring it.

Even better, forget about optimization and build your game. After you have a game that works but runs at 2 FPS, then you can begin optimization phase with a clearer state of mind.
> 1 votes

---
Tags: unity, collision-detection, physics, performance, layers
---


title: Rotate a single member of a group

text:
# Question
Title: Rotate a single member of a group
I have a Group object comprised of 2 actor members. Each member in the group can have their height, width, and positions scaled and set independently with no issues. However, attempting to utilize setRotation() or rotateBy() on an individual member of the group does not cause the member to rotate. The entire group can be rotated at once, but not an individual member in the group. Is there a way to rotate a single actor member that is part of a group?

# Answer
> 0 votes
I was trying to do a similar thing with a Label in my case. Setting the rotation on the Label didn't seem to behave as expected, so I ended up wrapping it in a Table.

A table may have been a bit overkill as a Container may have been sufficient. Here's what I did (I've trimmed it down to just the important parts, so this is untested code -- but it should convey what I did):

```
public class RotatedLabel extends Table {
    public RotatedLabel(String labelText, Skin skin) {
        super();
        innerLabel = new Label(labelText, skin);
        innerLabel.setOrigin(Align.center);
        innerLabel.setAlignment(Align.center);

        setTransform(true);
        setFillParent(false);
        add(innerLabel);
    }
    .
    .
    .
}

```

I am able to create the labels with minimal effort by just instantiating it with `new RotatedLabel("Hello World", skin);`

Keep in mind that the rotation is around the Table's origin (in this case). My label has more custom code in the `act(float delta)` method that sets the rotation and I update the origin and rotation in that function:

```
@Override
public void act(float delta) {
    super.act(delta);
    .
    .
    .
    setOrigin(getWidth() / 2, getHeight() / 2);
    setRotation(rotation);
}

```

---
Tags: libgdx
---


title: Civilization Style Borders With Sprites

text:
# Question
Title: Civilization Style Borders With Sprites
I am making a civilization style game in Unity. The game uses square tiles and has a 2d sprite style. I am currently implementing a border system like in civ4 where a line is drawn around you civilization's borders, but I cannot find a way to create the correct sprites to draw the border.

My first thought was to have a sprite corresponding to each neighbor, the sprite would toggle on if the tile it is over is in the bordered area and the corresponding neighbor is not. This would work but It would require 8 (one for each neighbor) sprite renderers per tile and I assume that would be pretty inefficient.

I thought of making a separate sprite for each configuration to cut it down to one sprite renderer per tile but that would require 2^8 sprites which just is not feasible.

I also thought that maybe I should stick to the first idea but only instantiate or move sprite renderers to where they are needed which would greatly reduce the amount of sprite renderers used at once. This seems like my best option but it seems unnesicarily complicated and still pretty inefficient.

I do not know of any simple way to dynamicaly draw sprites to fit a pattern, so it seems I am stuck with one of these solutions. Does anyone know of a better way to handle this?

# Answer
> 1 votes
This answer applies to **Unity2017.2** or newer, utilizing the **Grid/Tilemap** functionality included.

The `Grid` supports multiple layers by adding a new `Tilemap` for each draw layer you want in your tiles.

For Civ-like borders, add a `Tilemap` to the `Grid` called *Borders*. Then take a look at the Scriptable Tile Tech Demos, particularly the TerrainTile. Simply use corresponding sprites, paint them to the layer, and voila: Civ-like borders.

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


# Question
Title: Why is my picture distorted after switching from D3D9 to D3D11?
I have moved app from Directx9 into Directx11.

After this upgrade strange thing happened with my world. Objects get skewed and became 2D, also they are clipped in unexpected places.

The two arrows at the image I attached point to my HUD reference frame - three nice cones, arranged to point along the 3 axes, which are supposed to be shown in the lower left corner of the window.

Also you can see that sphere got clipped in difference positions and all objects are 2D. There side and front view. Thanks for your suggestions.

Need to point out that sphere is moving.

I use XMMatrixPerspectiveFovLH to get projection matrix.

Example of matrices:

```
World
2  0  0  0
0  10 0  0
0  0  1  0
0  0  10 1

View - Identity

Proj
1.72 0    0   0
0    2.41 0   0
0    0    1.  1.
0    0   -1.  0

```

Both previous images are wrong rendered. Just side view and fromnt view of wrong rendering. Thanks to Tordin i got this:

This one is almost correct, only some problems with culling in cones which form reference frame.

EDIT: Question was answered, but nobody wants to frame his comment as an asnwer. First was

> Tordin: transpose your matrices. All of them, World, View, Projection. DX11 is Row major and not Colume major like dx9 was

# Answer
Transposing the matrices will fix the issue. As noted by Chuck Walbourn, most of D3D itself expects row-major, but matrix packing for uniforms in HLSL is column-major by default.

This means you could also address the issue using `#pragmapack_matrix row_major` in HLSL as well.
> 2 votes

---
Tags: 3d, directx11, directx9
---


# Question
Title: In Unity/UNet: How do you properly spawn a `NetworkPlayer`?
In Unity/UNet: How do you properly spawn a `NetworkPlayer`? Right now, I'm doing it like this from inside a `NetworkManager` derived class:

```
   public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId) {
        NetworkPlayer newPlayer = Instantiate<NetworkPlayer>(m_NetworkPlayerPrefab);
        DontDestroyOnLoad(newPlayer);
        NetworkServer.AddPlayerForConnection(conn, newPlayer.gameObject, playerControllerId);
   }

```

This code snippet works pretty well and both **clients** can communicate with each other. However, there are a few little issues that arise only on the **host**:

1. In **Unity's hierarchy-view** on the **host**, there are only two `NetworkPlayer` instances. Shouldn't there be four **NetworkPlayer** instances on the **host**? Two **client** instances and two **server** instances? If so, do you have any ideas what could cause the missing `NetworkPlayer` instances?
2. The two **NetworkPlayer** instances have both, their `isClient` and `isServer` flags set to `true`. But only one of the has it's `isLocalPlayer` flag set. Now I wonder if this behavior is as intended? And if so, how do you distinguish between the **client** and the **server** instance of a `NetworkPlayer`?
3. Two player behavior: If the **remote client** sends a `[Command]` that changes a `[SyncVar]` on the **server**, then on the **host**, the `[SyncVar]-hook` is called only on the `NetworkPlayer` instance that represents the **remote** `NetworkPlayer`. The `[SyncVar]-hook` is not called on the **host's** `"isLocalPlayer-NetworkPlayer"` instance. Shouldn't the `[SyncVar]-hook` be called on both `NetworkPlayer` instances?

Any advise is welcome. Thank you!

# Answer
> 0 votes
> In Unity's hierarchy-view on the host, there are only two NetworkPlayer instances. Shouldn't there be four NetworkPlayer instances on the host? Two client instances and two server instances? If so, do you have any ideas what could cause the missing NetworkPlayer instances?

No, two is the correct number. The only difference between the `Host` and the `Client` when it comes to things, is that the `Clients` defer to the `Host` about the position of the `GameObjects` and their state. If the `Host` moves an object 1 unit to the left, the `Clients` will all move their version to match.

> The two NetworkPlayer instances have both, their isClient and isServer flags set to true. But only one of the has it's isLocalPlayer flag set. Now I wonder if this behavior is as intended? And if so, how do you distinguish between the client and the server instance of a NetworkPlayer?

`NetworkPlayer` doesn't have those attributes, `Network` has them. `Network.isClient` will be `true` if the `Network` instance is a `Client`, likewise `Network.isServer` will be `true` if the `Network` instance is the `Host`.

`isLocalPlayer` will be `true` if the `NetworkPlayer` instance is the instance representing the local machine in the game. Only one `NetworkPlayer` instance will have an `isLocalPlayer` value of `true` in a running instance of your game. Think of this variable as the "me" flag: think "this object is me".

> Two player behavior: If the remote client sends a \[Command\] that changes a \[SyncVar\] on the server, then on the host, the \[SyncVar\]-hook is called only on the NetworkPlayer instance that represents the remote NetworkPlayer. The \[SyncVar\]-hook is not called on the host's "isLocalPlayer-NetworkPlayer" instance. Shouldn't the \[SyncVar\]-hook be called on both NetworkPlayer instances?

No. As before, the `isLocalPlayer=true` `NetworkPlayer` instance is the avatar/character controlled by the human on the `Host` machine. The `[Command]` is being called by the `Client` to ask the `Host` to update the state of the `Host's` copy of the `Client's` `NetworkPlayer` instance. The `Host` will update the value on it's copy of the `GameObject` representing the remote human player, then forward the change to the other `Clients` in the game.

--

One thing to consider here is the directionality of the various pieces of the networking code:

`[Command]`s are sent from `Client` to `Host`

`[ClientRPC]`s are sent from `Host` to `Clients`

`[SyncVar]`s are sent from `Host` to `Clients`

See the documentation HERE for more information.

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


title: How can I make tiny sprites larger?

text:
# Question
Title: How can I make tiny sprites larger?
I used a 16x16 sprite pack to make a 640x640 map in pygame:

The problem is that everything is extremely tiny. How could I go about making the expected "JRPG" look, like this for instance:

I have tried so far to double the size of the map tiles using `pygame.transform.scale(tile,(32,32))` but that makes everything look terrible:

Here is how I am rendering the map:

```
import pygame
import pytmx
from pytmx.util_pygame import *

class tileRender:
    def __init__(self,filename):
        tm = pytmx.load_pygame(filename)
        self.width = tm.width * tm.tilewidth
        self.height = tm.height * tm.tileheight
        self.tmxdata = tm

    def render(self,surface):
        ti = self.tmxdata.get_tile_image_by_gid
        for layer in self.tmxdata.visible_layers:
            if isinstance(layer,pytmx.TiledTileLayer):
                for x,y,gid in layer:
                    tile = ti(gid)
                    tile = pygame.transform.scale(tile,(32,32))
                    if tile:
                        surface.blit(tile,(x * self.tmxdata.tilewidth, y * self.tmxdata.tileheight))

    def makemap(self):
        temp_surface = pygame.Surface((self.width,self.height))
        self.render(temp_surface)
        return temp_surface

```

Is there a way of "zooming in" on the sprites in order to get the expected look?

# Answer
You need to offset the tiles with the scaled size, not the original size. Currently you render at `(x * self.tmxdata.tilewidth, y * self.tmxdata.tileheight)`, but instead you want to render at `(x * 32, y * 32)`.
> 1 votes

---
Tags: sprites, python, pygame
---


# Question
Title: Allowing a secondary market for online content
Many games with an online component, allow players to buy various kinds of content. As far as I know, none of them allow a secondary market where players resell purchased content to other players. Presumably this is because the developers think disallowing the secondary market will get them more sales.

However, there seems to be a widely held school of thought regarding Magic: the Gathering (the nonelectronic card game) that the existence of a secondary market actually increases revenue by encouraging people to buy more cards in the hope of being able to resell them. Whether that theory is true or false, the mere fact that many people believe it, should encourage at least some video game developers to try allowing a secondary market.

Given the existence of a reasonably widely held theory that this is a good idea, why is it that *no* video game developers whatsoever allow a secondary market?

# Answer
In general, it's more trouble than it's worth.

* Money Laundering and fraud: can the player buy a magic sword from anywhere in the world? What if the credit card is stolen? Can items be moved through half a dozen anonymous users, before cashing out in Nigeria? This is why Kongregate shut down their tip jar.
* If you can sell it for real money, it's worth something. Does that mean stealing it in game is a crime? Is opening a loot box gambling? If a player claims an object is lost to a glitch, are you obliged to replace it? Can you afford to defend yourself against legal challenges from anywhere in the world where your game is sold?
* If hacking your game is worth real money, it will be targeted with dedicated, well funded attackers. This is Trouble that you do not want.
> 3 votes

---
Tags: marketing, sales
---


# Question
Title: How do I detect a given sprite's bounds automatically using Java?
**Background**

---

I have the following `png` file that contains the player sprite.

As with any `png` file, the *non-colored* pixels are transparent.

(Width: `16px`; Height: `16px`)

Currently, I can erect a rectangle (*collision-bounds*), using `java.awt.Rectangle` around the image using the image's width and height, as seen below.

I would like to **crop** the image so that the width and height are changed to the edges of the colored portion of the image, much like what is shown below.

This will allow for more accurate collision-detection between entities or objects in a game.

I want to construct a method that handles this modification dynamically, as seen below.

```
//Method calculates how far in from [top, bottom, left and right]
//the [non-zero] or [transparent] pixel-data of an image are
//in order to construct a new image that starts at the edges
//of the colored portion of the image.
public BufferedImage adjustImage(BufferedImage image)
{
    BufferedImage result = null;

    return result;
}

```

**Problem**

---

However, I am uncertain as to the algorithm to use to achieve the result above.

*Can anyone give a step-by-step on how to detect these bounds and how to implement such a fuction as described above?*

# Answer
> 3 votes
You first need to scan the image for the edges. You need to loop through each pixel in the image and store the position of the pixel closest to the left, the pixel closest to the right, etc.

Pixels are stored in the

```
 ARGB
 8 bit alpha | 8 bit red | 8 bit green | 8 bit blue

```

format in integers. This means that you need to use the

```
int alpha = (color >> 24) & 0xFF;

```

method to get the alpha value of a pixel.

```
int minX = Integer.MAX_VALUE;
int maxX = integer.MIN_VALUE;
int minY = Integer.MAX_VALUE;
int maxY = integer.MIN_VALUE;
for (int x = 0; x < img.getWidth(); x++) {
    for (int y = 0; y < img.getHeight(); y++) {
        int color = img.getRGB(x, y);
        int alpha = (color >> 24) & 0xFF;
        if (alpha != 0) {
            // This sets the edges to the current coordinate
            // if this pixel lies outside the current boundaries
            minX = Math.min(x, minX);
            maxX = Math.max(x, maxX);
            minY = Math.min(y, minY);
            maxY = Math.max(y, maxY);
        }
    }
}

```

Then you need to create an image and copy the pixel data to it:

```
BufferedImage result = new BufferedImage(maxX - minX, maxY - minY, BufferedImage.TYPE_INT_ARGB);

for (int x = 0; x < maxX - minX; x++) {
    for (int y = 0; y < maxY - minY; y++) {
        result.setRGB(x, y, img.getRGB(x + minX, y + minY));
    }
}

```

---
Tags: java, algorithm, sprites, image, image-processing
---


title: Libgdx Texture change

text:
# Question
Title: Libgdx Texture change
I have been working for several days to try and figure out how to change a texture whenever a scene2d Table is clicked in libgdx, I am using pixmaps to dynamically change the textures colors instead of changing the texture completely.

everything works fine when i detect key presses so whenever i press 1 the color of the players hair changes to a random color but now i want it to happen when i press a Table.

to change the texture i use this method

```
public static Texture genDynamicTexture(String path, HashMap<String,Color> colors) {

    //load texture from asset handler
    Texture texture = GameUtils.getGame().manager.get(path,Texture.class);

    //create pixmap from texture
    if(!texture.getTextureData().isPrepared()) {
        texture.getTextureData().prepare();
    }
    //transfer pixel data from gpu to cpu
    Pixmap pixmap = texture.getTextureData().consumePixmap();

    //grey-scale colors
    Color gsHair = toColor(207,31,201);
    Color gsSkin = toColor(207,97,31);
    Color gsShirt1 = toColor(39,207,31);
    Color gsShirt2 = toColor(65,65,160);
    Color gsPants = toColor(90,9,22);
    Color gsShoe1 = toColor(253,255,66);
    Color gsShoe2 = toColor(43,58,50);
    Color black = toColor(0,0,0);

    //loop through pixels in the pixmap
    for(int x = 0; x < pixmap.getWidth(); x++) {
        for(int y = 0; y < pixmap.getHeight(); y++) {
            int pixelColor = pixmap.getPixel(x, y);
            if(pixelColor != 0 && pixelColor != Color.rgba8888(black)) {
                if(pixelColor == Color.rgba8888(gsHair)) {
                    pixmap.setColor(colors.get("hair"));
                    pixmap.drawPixel(x, y);
                }else if(pixelColor == Color.rgba8888(gsSkin)) {
                    pixmap.setColor(colors.get("skin"));
                    pixmap.drawPixel(x, y);
                }else if(pixelColor == Color.rgba8888(gsShirt1)) {
                    pixmap.setColor(colors.get("shirt1"));
                    pixmap.drawPixel(x, y);
                }else if(pixelColor == Color.rgba8888(gsShirt2)) {
                    pixmap.setColor(colors.get("shirt2"));
                    pixmap.drawPixel(x, y);
                }else if(pixelColor == Color.rgba8888(gsPants)) {
                    pixmap.setColor(colors.get("pants"));
                    pixmap.drawPixel(x, y);
                }else if(pixelColor == Color.rgba8888(gsShoe1)) {
                    pixmap.setColor(colors.get("shoe1"));
                    pixmap.drawPixel(x, y);
                }else if(pixelColor == Color.rgba8888(gsShoe2)) {
                    pixmap.setColor(colors.get("shoe2"));
                    pixmap.drawPixel(x, y);
                }
            }
        }
    }

    //transfer pixel data from cpu to gpu
    Texture tex = new Texture(pixmap);
    pixmap.dispose();
    texture.dispose();
    return tex;

}

```

like i said everything works fine if it is a key press but when i detect it using a Table it does not work ( i have already added it to the stage and am calling stage.act() and stage.draw() )

```
color.addListener(new ClickListener() {
        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
            return true;
        }
        @Override
        public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
            characterPack.reloadSpriteSheet("Players/greyscale-player.png", 2, 2, characterPack.colors, "skin");
        }
    });

```

thanks in advance.

# Answer
I solved my problem by resetting what frame of the texture region was being rendered so in my code it was

```
characterPack.skin = characterPack.frames[0];

```

another option i found was i had my direction set to UNUSED so once i set it to down it updated itself.

the result reloads the colors to change the textures colors based on what options the user clicks.
> 0 votes

---
Tags: java, libgdx, android, textures, scene2d
---


title: How to destroy multiple bodies

text:
# Question
Title: How to destroy multiple bodies
In my game(2D game) I have these fireball objects. When I launch a fireball I want to destroy the object (because I'm not going to use it anymore). I tried deleting the fireballs, but, from what I can see, I'm just deleting the images, not the whole object. Now, this doesn't have a huge impact on performance when the fireballs are just a few, but my game becomes pretty slow if the object count increases.

For an example, when I fire three fireballs, the third one is the only one that disappeares, while the first and second one are still alive, just without any image.

I hope someone can help me out.

**Weapon.java**

```
public abstract class Weapon extends Sprite {

public PlayScreen screen;
public static World world;
public float stateTime;
public boolean rightside;
public boolean setToDestroy;
public boolean destroyed;

protected  Body body;

public  Weapon(PlayScreen screen, float x, float y, boolean rightside){
    this.screen = screen;
    this.world = screen.getWorld();
    this.rightside = rightside;
    setBounds(x, y, 6 / Advanture.PPM, 6 / Advanture.PPM);
    defineWeapon();
    stateTime = 0;
}

public void draw(Batch batch){
if(!destroyed)
    super.draw(batch);
}

public void update(Float dt){
    if(setToDestroy&&!destroyed){
        destroyed = true;
        world.destroyBody(body);

    }
}
protected abstract void defineWeapon();

public void setToDestroy(){
    setToDestroy = true;
}
public boolean isDestroyed(){
    return destroyed;
}

}

```

**FireBall.java**

```
public class FireBall extends Weapon {

private static TextureRegion tex;
private float rotate;
public boolean remove = false;
public static ArrayList<Body> bodies = new ArrayList<Body>();
public float destroyTimer = 3f;

public FireBall(PlayScreen screen, float x, float y, boolean rightside) {

    super(screen,x,y, rightside);

    tex = new TextureRegion(screen.getAtlas().findRegion("fireball"),0,0,40,40);
    setRegion(tex);
    defineWeapon();
}

public void update (float deltaTime) {
     super.update(deltaTime);
     destroyTimer-= deltaTime;
     rotate +=100;

     rotate(rotate);
     setPosition(body.getPosition().x - getWidth() / 2, body.getPosition().y - getHeight() / 2)  ;

    if(destroyTimer <= 0){
       setToDestroy();

    }

 }

@Override
protected void defineWeapon() {

    BodyDef bdef = new BodyDef();
    bdef.position.set(rightside ? getX() + 12 / Advanture.PPM : getX() - 12 / Advanture.PPM, getY());
    bdef.type = BodyDef.BodyType.DynamicBody;

           if (!world.isLocked()) {
                body = world.createBody(bdef);
           }
   FixtureDef fdef = new FixtureDef();
   CircleShape shape = new CircleShape();
   shape.setRadius(3 / Advanture.PPM);
    fdef.filter.categoryBits = Advanture.FIREBALL_BIT;
    fdef.filter.maskBits = Advanture.GROUND_BIT
           | Advanture.Enemy_Head_BIT
           | Advanture.BRICK_BIT
           | Advanture.COIN_BIT
           | Advanture.Enemy_BIT;
   fdef.shape = shape;
   fdef.restitution = 1;
    fdef.friction = 0;
   body.setLinearVelocity(new Vector2(rightside ? 2 : -2, 2.5f));
   body.createFixture(fdef).setUserData(this);

}
public void draw(Batch batch){
    if(!destroyed)
        super.draw(batch);
        //batch.draw(tex,x,y);
}
public void render (SpriteBatch batch) {
    batch.draw(tex,x,y);
}

 }

```

**PlayScreen.java**

```
   private ArrayList<FireBall> fireballs = new ArrayList<FireBall>();
    ......
   @Override
   public void render(float delta) {
  if(Gdx.input.isKeyJustPressed(Input.Keys.SPACE)){
  // generating fireball by pressing space key
        fireballs.add(new FireBall(this, b2body.getPosition().x, b2body.getPosition().y, Blue.runRightSide ? true : false));

    }

 ArrayList<FireBall> fireBallToRemove = new ArrayList<FireBall>();
    for (FireBall ball : fireballs) {
        ball.update(delta);
        if (ball.remove)
            fireBallToRemove.add(ball);
    }
}
fireballs.removeAll(fireBallToRemove);

   game.batch.begin();
    ArrayList<FireBall> FireballToRemove2 = new ArrayList<FireBall>();
    for (FireBall ball : fireballs) {
        // System.out.println(PlayScreen.touchController.getDeltaX()+"###");
        if(ball.isDestroyed()){
            FireballToRemove2.add(ball);
        }

        ball.draw(game.batch);
    }
    FireballToRemove2.removeAll(itemToRemove2);
    game.batch.end();

```

# Answer
> 1 votes
It's not enough to remove the fire balls from your `fireBalls` collection, you also have to destroy the **Box2D** `Body`.

Try adding a `destroyBody` call when cleaning up destroyed bodies.

```
   if (ball.remove) {
        fireBallToRemove.add(ball);
        world.destroyBody(ball.body);
   }

```

---
Tags: java, libgdx, box2d
---


# Question
Title: Good ways to implement cutscenes in 2d RPG
I want to know of some different ways to implement cutscenes in a 2D RPG game with SDL2 and C++.

My current idea is creating different functions in different files for different cutscenes and running them whenever I need to show a cutscene.

However, this doesn't seem like a very easy or simple way to render cutscenes. How would I effeciently implement cutscenes?

# Answer
I personally implemented a cutscene "scripting" language for my cutscenes using XML. XML isn't necessarily the best choice, and since it's not a real scripting language with programming language features, it can be a little limiting, but for my needs it worked just fine.

My cutscene definition files look like this:

```
<CutScene disableBars="1" replayOnRestart="1">
    <Parallel>
        <CameraTarget tag="Bomb" time="1.0"/>
        <DelayExecution time="0.4">
            <CameraZoom zoom="4.0" time="0.6"/>
        </DelayExecution>
    </Parallel>
    <Wait time="5.0"/>
    <WaitForKey/>
</CutScene>

```

When I want to display a cutscene, I create a cutscene object, that is updated and rendered from my level class.

The cutscene object loads the file, and converts each XML element into an instruction, that gets updated. Only the current instruction gets executed, which is why a `Parallel` instruction exists. The instructions let the cutscene object know when the next instruction can be executed.

The instruction loading might look something like this (pseudo-C++):

```
void CutScene::Load()
{
    XMLFile* file = new XMLFile(...);

    for (XMLElement* element : file->GetElement("CutScene")->Children)
    {
        m_Instructions.push_back(InstructionFactory::Create(element));
    }
}

Instruction* InstructionFactory::Create(XMLElement* element)
{
    if (element->Name == "CameraTarget")
    {
        std::string tag = element->GetStringAttribute("tag");
        float time = element->GetFloatAttribute("time");

        return new CameraTargetInstruction(tag, time);
    }

    ...
}

```

I use tags to reference entities in the level, so I have set the name of the bomb-entity in the level editor to "Bomb", and I use that same string to tell the camera zoom target instruction to center on the correct entity.

Creating cutscenes in a neat way can be a pain and a lot of work, but with a data-based approach like mine, you can improve your content interation speed, since you don't have to recompile every time you want to change the way a cutscene plays out.

You could of course look into integrating something like Lua into your framework/engine, but that can be a lot of work too.

The fastest approach to code might be just pure C++ code, but you'll get faster iteration speed with a data-based approach, and using a full-fledged scripting language will get you fast iteration speed and a lot of flexibility.
> 4 votes

---
Tags: c++, rpg, sdl2, cutscene
---


# Question
Title: Is this an optimal way to architect an OpenGL Renderable object class?
I want to create a class which is a "Renderable class". Basically, world objects will use this as a Base class to create objects that can be drawn into an OpenGL window. This is what i 've got so far:

```
typedef struct {
    GLfloat pos_x_, pos_y_, pos_z_;
    std::string object_path_;
    std::string texture_path_;
} OpenGLObjectParams_t;

class OpenGLObject {
public:
    OpenGLObject(OpenGLObjectParams_t params);

    int Init(OpenGLContext * context_);

    int Destroy();

    int Draw();

    void SetPosition(GLfloat pos_x, GLfloat pos_y, GLfloat pos_z);

private:
    bool is_inited_;
    glm::mat4 model_;
    OpenGLObjectParams_t params_;
    OpenGLShaderVariables_t shader_vars_;

    GLuint VAO, vertex_buffer_, color_buffer_;
};

```

And the implementation (Right now the object/texture are not used, and a rectangle is painted instead). The OpenGLContext is just used to take the shader variables:

```
OpenGLObject::OpenGLObject(OpenGLObjectParams_t params) {
        params_ = params;

        is_inited_ = false;
    }

    int OpenGLObject::Init(OpenGLContext * context)
    {
        if (is_inited_) return -1;

        SetPosition(params_.pos_x_, params_.pos_y_, params_.pos_z_);

        shader_vars_ = context->GetShaderVariables();

        static const GLfloat vertex_buffer_data[] = {
            -1.0f, 1.0f, 0.0f,
            -1.0f, -1.0f, 0.0f,
            1.0f, 1.0f, 0.0f,
            -1.0f, -1.0f, 0.0f,
            1.0f, -1.0f, 0.0f,
            1.0f, 1.0f, 0.0f,
        };
        glGenBuffers(1, &vertex_buffer_);
        glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer_);
        glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_buffer_data), vertex_buffer_data, GL_STATIC_DRAW);

        static const GLfloat color_buffer_data[] = {
            1.0f,  0.0f,  0.0f,
            0.0f,  0.0f,  0.0f,
            1.0f,  1.0f,  1.0f,
            0.0f,  0.0f,  0.0f,
            1.0f,  0.0f,  0.0f,
            1.0f,  1.0f,  1.0f,
        };
        glGenBuffers(1, &color_buffer_);
        glBindBuffer(GL_ARRAY_BUFFER, color_buffer_);
        glBufferData(GL_ARRAY_BUFFER, sizeof(color_buffer_data), color_buffer_data, GL_STATIC_DRAW);

        /* Configure a VAO */
        glGenVertexArrays(1, &VAO);
        glBindVertexArray(VAO);
        /* Attribute number 0 is the model vertices */
        glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer_);
        glVertexAttribPointer(shader_vars_.attr_vertex_position_, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
        glEnableVertexAttribArray(0);
        /* Attribute number 1 is the colors */
        glBindBuffer(GL_ARRAY_BUFFER, color_buffer_);
        glVertexAttribPointer(shader_vars_.attr_vertex_color_, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
        glEnableVertexAttribArray(1);

        is_inited_ = true;
        return 0;
    }

    int OpenGLObject::Destroy() {
        if (!is_inited_) return -1;

        glDeleteBuffers(1, &vertex_buffer_);
        glDeleteBuffers(1, &color_buffer_);
        glDeleteVertexArrays(1, &VAO);

        is_inited_ = false;
        return 0;
    }

    int OpenGLObject::Draw(double delta_time) {
        if (!is_inited_) return -1;

        glBindVertexArray(VAO);
        glUniformMatrix4fv(shader_vars_.uni_Model_, 1, GL_FALSE, &model_[0][0]);

        glDrawArrays(GL_TRIANGLES, 0, 2 * 3);

        return 0;
    }

    void OpenGLObject::SetPosition(GLfloat pos_x, GLfloat pos_y, GLfloat pos_z) {
        params_.pos_x_ = pos_x;
        params_.pos_y_ = pos_y;
        params_.pos_z_ = pos_z;
        model_ = GetTranslateMatrix(glm::vec3(pos_x, pos_y, pos_z));
    }

```

And the main loop will call the Draw function on the objects that use the above as a Base class.

Is this the way to implement such a mechanism?

Because if the world has thousands of objects, then there will be a loop on a data structure to call thousands of Draw calls. I assume that the Draw() above cannot be called from multiple threads?

What's the best architecture for such a feature? Is it possible to call a Draw() from different threads?

Edit: I don't ask about the drawing method itself, since it's better to use glDrawElements() but the whole architecture.

# Answer
> Is this the way to implement such a mechanism?

I would argue that no, it's not. It will work -- games have certainly shipped using a similar approach -- and if your project is simple enough and the set of "drawable subclasses" you expect to implement is small, it will be fine. But in my experience, it tends to scale poorly, introducing a lot of maintenance overhead and forcing you to contort your code to adapt to rendering techniques that require different information than your base class supports. See also, "Should actors in a game be responsible for drawing themselves?"

> I assume that the Draw() above cannot be called from multiple threads?

The way you've implemented it, no. Generally draw submission needs to be synchronized onto a single thread, if you want to multithread "drawing," you tend to instead do the construction of a command buffer necessary to draw on various threads (without actually touching the underlying graphics API), and synchronize access to that onto the render thread when all the buffers have been built up and can simply be submitted.

> What's the best architecture for such a feature?

I'd advise you to invert the relationship: the renderer itself knows how to draw (as in, how to translate to OpenGL) a variety of basic primitives (static meshes, animated meshes, 2D sprites, debug lines, et cetera -- broad categories). Your game objects themselves hold an instance of some "drawing description" that says how that object should be presented.

This lets you parallelize the setup of those description objects: since they are just independent chunks of data, you can do any per-frame reflection of game state into the draw description on multiple threads if you like.

Perhaps most importantly, when you then loop over all your objects and enqueuer their render descriptions in the renderer, the *renderer* can rearrange the submission order to batch the objects most efficiently. For example you generally want to avoid state switches, so the ideal way to render objects would be "everything that uses this render state" or "everything that uses these textures" together, or similar. By moving the actual rendering of objects out of the objects themselves, you don't need to mandate that those objects themselves be sorted in optimal render order. You just let the renderer reorganize them on submission. This frees you up to organize the actual game objects in a fashion that is more optimal for their other, game-logic-related needs.

It also centralizes the majority of your render state management in one place, making it easier to debug and eventually (if you like) to port to a different rendering back end.
> 4 votes

---
Tags: opengl, c++, architecture, multithreading
---


# Question
Title: Running Unreal Build Tool with CreateProcess vs command line
I'm working on a tool that generates some files for Unreal Projects. The only thing is if I try to get it to compile the project through CreateProcess the command doesn't run the same as the command line. I just get an error message from UBT about rule files not existing.

Command being run from CreateProcess:

```
STARTUPINFO si;
PROCESS_INFORMATION pi;

ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));

CreateProcess("C:/path/to/UnrealBuildTool.exe",
       "ProjectEditor Win64 Development C:/path/to/project.uproject -waitmutex -Deploy",
            NULL,
            NULL,
            FALSE,
            0,
            NULL,
            NULL,
            &si,
            &pi
        );
WaitForSingleObject(pi.hProcess, INFINITE);

CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);

```

In the command line `C:\path\to\UnrealBuildTool.exe ProjectEditor Win64 Development C:\path\to\project.uproject -waitmutext -Deploy` successfully compiles the project from any directory. Is there any other variables I need to pass into CreateProcess to get this command to run?

EDIT: Adding space to the start of the argument string fixed the issue. Is there any reason why Windows would need that space?

# Answer
> 1 votes
This is happening because you're not *actually* passing the project ("ProjectEditor") to UnrealBuildTool when you invoke it via `CreateProcess`, which causes it to not build anything.

The first argument of a Windows command-line should be the name of the process or executable being invoked. `CreateProcess` does not join the process name you specify to the front of the command-line you specify. You need to do that yourself.

UnrealBuildTool is a C# application. The .NET runtime takes this first space-delimited argument and stores it elsewhere, passing the subsequent arguments to the `Main()` function of UnrealBuildTool, so the first argument *it* sees is "Win64." That's why when you add a space in front of your project name, you "fix" it. You've changed it so that the first space-delimited argument is an empty string.

You can verify this by writing a simple C# program that just prints all the arguments supplied to main, and trying to invoke it similarly. Using a tool like Process Explorer would also let you examine the actual command lines for the processes and see how they differ.

A more correct solution would be to call `CreateProcess` like this:

```
CreateProcess("C:/path/to/UnrealBuildTool.exe",
              "C:/path/to/UnrealBuildTool.exe ProjectEditor ..etc...",
              ...);

```

---
Tags: c++, windows, tools
---


# Question
Title: How is money made from Steam Trading Card Farming Generators?
in this SidAlpha Video, SidAlpha talks about how Valve may be doing something that could stop or interrupt Steam Trading Card Farming Generators by preventing them from generating keys.

This got me thinking. from my understanding you get Trading Cards either playing the game which gets you only so many, the rest you then need to create booster packs with Gems or buy them from the marketplace with your own funds. but what i don't get is

1) the name for this practice implies using Steam Trading Cards to make money, however i can't see how "developers" can make money as,

* you have to originally own the card you're selling on the market place
* when it's brought it goes to your wallet which you can't transfer Steam wallet fund off Steam

and i wouldn't think Valve would allow "developers" to create any number of trading cards for their games at will then sell them because this is obviously very easily abused

2) in the video SidAlpha mentions that reducing/blocking Key generation may have an impact to those who use Steam Trading Card Farming Generators, noting that a certain user base is actually worried it. but i'm not sure how key generation fits in to the scam.

So my question is how is money made from Steam Trading Card Farming Generators? and how do Steam Keys fit in to this?

# Answer
> you get Trading Cards either playing the game which gets you only so many, the rest you then need to create booster packs with Gems or buy them from the marketplace with your own funds. but what i don't get is

Developers get a small percentage of trading card sales, that's how they make money on trading cards. It doesn't matter that the money earned by the seller of the card is locked up in a given account's Steam Wallet, nor does it matter that you only get a fixed number of drops before needing to create booster packs, et cetera. Those mechanisms prevent a *player* from trivially generating an unlimited amount of money in their Steam wallet. They don't provide guard rails for *developers* looking to abuse the system.

> and i wouldn't think Valve would allow "developers" to create any number of trading cards for their games at will then sell them because this is obviously very easily abused

But this is, in fact, exactly what they did. Probably not *intentionally*, but they permitted it all the same:

Developers can generate an unlimited number of keys for their games. They can also create an unlimited number of throwaway Steam accounts, because Steam accounts are free to create. Accounts earn trading cards simply by running a given game for a specific period of time. In this fashion, an unscrupulous developer can generate an unlimited number of trading cards for all of their games by making throwaway accounts, generating keys for those accounts, and simply launching and idling in their games. Simple bots can accomplish this without much effort.

Since the developer earns a small amount of money on every trading card sold, they can then sell off stock of their unlimited number of cards and take the profits.

The only serious hurdle to overcome here, before Valve made changes to attempt to address this, was that you needed to get your games on Steam in the first place. But once you'd overcome that the first time it was much easier to generate a bunch of "asset flip" games to create a multiplicative factor on the amount of money one could "farm" this way.
> 3 votes

---
Tags: publishing, steam
---


# Question
Title: Better texture downscaling at 9xMSAA than at 8xMSAA
I'm drawing my game on a render-to-texture FBO with multisampling. The multisampling works as expected, except for one thing:
No MSAA
8xMSAA
9xMSAA
(left is a untextured quad, right is a textured quad--the texture is much larger than the quad, the cross in the center of the texture is 2 line primitives)

As you can see, textures seem to suddenly have better downscaling at 9+ samples. Im trying to figure out why this is, because I'd prefer to have this quality of downscaling all the time (even if I'm at, say, 4 samples). The artefacting in the first two images is pretty ugly. I'm not using any mipmapping here, but I did try that as an alternative to this, and it does look much better. However, mipmapping looks a bit blurry compared to the third image, and is still not preferable in comparison.

This was rendered with an NVIDIA GeForce 980M, and it appeared to have the same behavior on other nvidia cards.

# Answer
Strict multisampling only executes the fragment shader once per pixel affected by the triangle, *regardless* of the number of samples. The sample coverage for the triangle affects each fragment's sample coverage mask. So on the edge of triangles, a fragment may only cover a portion of the samples for that pixel.

As such, strict multisampling *does not* anitalias the interior of triangles. It only antialias the edges.

However, OpenGL does not require strict adherence to multisampling. And even if they did, NVIDIA has been known to outright ignore the specification.

As such, what you are likely seeing here is NVIDIA employing some additional anti-aliasing technique. My immediate thought would have been Coverage Sample Anti-Aliasing (CSAA), but that apparently doesn't exist for the post-Kepler-based GPUs. Regardless of exactly what it is doing, it clearly decided to give you something that the strict multisampling algorithm doesn't call for.

The sudden difference you're seeing between 8 and 9 reflects the fact that NVIDIA doesn't give you 9xMSAA. It's really giving you 16xMSAA. That probably triggers the use of their additional antialiasing technologies.
> 2 votes

---
Tags: opengl, textures
---


# Question
Title: Unity Shadow shows on my Android device but NOT my Windows Mobile device
Unity version: 2017.1.1f1
**Problem:**
I'm using Directional Light. Shadow is not showing in my Windows Mobile device (Lumia 640 XL), but works fine when I run the **exact same UWP project as PC (Local Machine)** as well as Android.
**Attempted solutions:**
1) Quality Setting: I even removed the rest of levels and left only 1 level of quality.
2) Both soft and hard shadows, 10 Shadow distance, Stable Fit of shadow projection, very high resolution, low resolution, No Cascade.
3) Tried *realtime* and *mixed* light mode.
any idea? Thanks in advance for read my question.
**Screenshots:**
*Windows 10 Mobile (Lumia 640 XL)*
*Android (Redmi Note 3)*

# Answer
> 1 votes
OK. So the only conclusion I can make here is Lumia 640 XL cannot support anymore advanced 'fancy' stuff compared to other normal devices. Thats all I can assume. Thanks.

**Why I say so:**

I even changed to a very bright, obvious, closed to floor point light so that we *should* be able to notice that point light very clearly right in front my character and bright spot of light shine on floors. However, all of these simple effects cannot be seen on my Lumia 640 XL device.

Therefore, I have to give up on that. I'm sad about it but it's the truth.

---
Tags: unity, windows, shadows
---


title: Enemies and item drops issue

text:
# Question
Title: Enemies and item drops issue
Disclaimer: I'm relatively new to developing games so bear with me.

In my scene I have enemies and when they die, they drop items. No matter which item is dropped, the same prefab (the physical representation of the dropped item) is instantiated. That physical orb on the ground may represent different items. It could be a pile of coins, a sword, etc. Depending on which item is dropped, I want its name to appear in a UI label attached to the top of the item. Basic ARPG stuff really. The problem I'm running into is that I can't seem to get the references right.

DisplayItemNameLabel is a script which is attached to each item when it is dropped. I did it this way so each item can be in charge of its own UI label.

ItemDrops is attached to each enemy. SpawnItem(Item item) is a function which is called when the enemy dies.

The last relevant Monobehaviour script is the ItemData script which is attached to an Item Manager game object which is there from the beginning and persists forever. This class just defines the different items that are possible in the game.

So basically the structure is that when an enemy dies, if the random number generated is within some range, then some item will drop.

```
If (randomNumber < 0.5)
{
    SpawnItem(itemData.coin);
}

```

where SpawnItem(Item item) is something like...

```
private void SpawnItem(Item item)
    {
        itemDropped = true;
        nameOfDroppedItem = item.itemName;

        Instantiate(itemPrefab, transform.position - offset, Quaternion.identity);
    }

```

Again, this is attached to each enemy.

In the DisplayItemLabel script then, I would like to set itemNameText.text to that nameOfDroppedItem. But the DisplayItemLabel script is attached to each item. I don't think I can make each item a child of each enemy because enemies are destroyed when they are killed so the scripts would be destroyed. I also can't use `GameObject.FindGameObjectWithTag("Enemy").GetComponent<ItemDrops>()`; because it wouldn't always grab the enemy I want. I thought maybe I could set the text in SpawnItem but it would have to reference the correct item, so I couldn't use GameObject.FindGameObjectWithTag...

What should I do?

# Answer
> 2 votes
You need to have your `Item` as prefab:

and item has `ItemLabel` as it's child:

What you could do now is:

```
public class EnemyOrSomething: MonoBehaviour {

    public Item itemPrefab;

    private void SpawnItem(Item item)
    {
        itemDropped = true;
        nameOfDroppedItem = item.itemName;

        Item item = Instantiate(itemPrefab, transform.position - offset, Quaternion.identity);
        item.transform.parent = null; // unparent it so it won't get destroyed with the enemy
        item.label.SetTextOnLabelOrSomewhere(item.name);

    }
}

```

You just have to add some functionality to the `ItemLabel`, add a `Text` component or something.

Is this what you meant?

# Answer
> 1 votes
It looks like you just want this:

```
private void SpawnItem(Item item) {
    itemDropped = true;

    // Capture the new instance you've spawned:
    var itemInstance = Instantiate(
                    itemPrefab,
                    transform.position - offset,
                    Quaternion.identity);

    // Get the label component on it.
    // (You can combine this with the step above
    // if your prefab variable is of the component
    // type that you want in the first place)
    var label = itemInstance
             .GetComponent<DisplayItemLabel>();

    // Push your name to the label.
    label.SetDisplayName(item.name);

    // You probably also want to push the
    // item instance itself, so when the player
    // collects the item, you know what to award
    // to them, without a string lookup.
}

```

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


# Question
Title: Definition & Implementation Always Causes Linker Errors
I'm making a simple game in c++, using Visual Studio.

I have a bunch of functions for various things on a file called "engine.h" and then in "main.cpp" I have actual game stuff (levels and map)

I've been trying to put these into classes and then separate the classes into files and include the header files (I think this is called definition and implementation or something like that.)

But every time I try to do this, I get a ton of LINKER errors and have no choice to revert to the 1 header file system. The Linker errors are mostly "LNK2005" and "LNK2001"

Does anyone know how to do this properly? Other than organization, are there any other adverse affects of having all my functions on one header file?

Thanks!

EDIT: Here is my error console

Severity Code Description Project File Line Suppression State Error LNK1169 one or more multiply defined symbols found Game\_Multi\_File C:\Dev\Game\_Multi\_File\Debug\Game\_Multi\_File.exe 1
Error LNK2005 "struct SDL\_Window * window" (?window@@3PAUSDL\_Window@@A) already defined in build.obj Game\_Multi\_File C:\Dev\Game\_Multi\_File\Game\_Multi\_File\saving.obj 1
Error LNK2005 "struct SDL\_Renderer * renderer" (?renderer@@3PAUSDL\_Renderer@@A) already defined in build.obj Game\_Multi\_File C:\Dev\Game\_Multi\_File\Game\_Multi\_File\saving.obj 1
Error LNK2005 "int playerY" (?playerY@@3HA) already defined in build.obj Game\_Multi\_File C:\Dev\Game\_Multi\_File\Game\_Multi\_File\saving.obj 1
Error LNK2005 "int playerX" (?playerX@@3HA) already defined in build.obj Game\_Multi\_File C:\Dev\Game\_Multi\_File\Game\_Multi\_File\saving.obj 1
Error LNK2005 "int playerStrength" (?playerStrength@@3HA) already defined in build.obj Game\_Multi\_File C:\Dev\Game\_Multi\_File\Game\_Multi\_File\saving.obj 1
Error LNK2005 "int playerResistance" (?playerResistance@@3HA) already defined in build.obj Game\_Multi\_File C:\Dev\Game\_Multi\_File\Game\_Multi\_File\saving.obj 1
Error LNK2005 "int playerIntelligence" (?playerIntelligence@@3HA) already defined in build.obj Game\_Multi\_File C:\Dev\Game\_Multi\_File\Game\_Multi\_File\saving.obj 1
Error LNK2005 "int playerHealth" (?playerHealth@@3HA) already defined in build.obj Game\_Multi\_File C:\Dev\Game\_Multi\_File\Game\_Multi\_File\saving.obj 1
Error LNK2005 "int playerFlee" (?playerFlee@@3HA) already defined in build.obj Game\_Multi\_File C:\Dev\Game\_Multi\_File\Game\_Multi\_File\saving.obj 1
Error LNK2005 "int playerCurrency" (?playerCurrency@@3HA) already defined in build.obj Game\_Multi\_File C:\Dev\Game\_Multi\_File\Game\_Multi\_File\saving.obj 1
Error LNK2005 "int playerChase" (?playerChase@@3HA) already defined in build.obj Game\_Multi\_File C:\Dev\Game\_Multi\_File\Game\_Multi\_File\saving.obj 1
Error LNK2005 "int playedFlag" (?playedFlag@@3HA) already defined in build.obj Game\_Multi\_File C:\Dev\Game\_Multi\_File\Game\_Multi\_File\saving.obj 1
Error LNK2005 "int placeHolderConfig" (?placeHolderConfig@@3HA) already defined in build.obj Game\_Multi\_File C:\Dev\Game\_Multi\_File\Game\_Multi\_File\saving.obj 1
Error LNK2005 "int fullscreen" (?fullscreen@@3HA) already defined in build.obj Game\_Multi\_File C:\Dev\Game\_Multi\_File\Game\_Multi\_File\saving.obj 1
Error LNK2005 "int continueKey" (?continueKey@@3HA) already defined in build.obj Game\_Multi\_File C:\Dev\Game\_Multi\_File\Game\_Multi\_File\saving.obj 1
Error LNK2005 "int checkpointY" (?checkpointY@@3HA) already defined in build.obj Game\_Multi\_File C:\Dev\Game\_Multi\_File\Game\_Multi\_File\saving.obj 1
Error LNK2005 "int checkpointX" (?checkpointX@@3HA) already defined in build.obj Game\_Multi\_File C:\Dev\Game\_Multi\_File\Game\_Multi\_File\saving.obj 1
Error LNK2005 "float resizeValue" (?resizeValue@@3MA) already defined in build.obj Game\_Multi\_File C:\Dev\Game\_Multi\_File\Game\_Multi\_File\saving.obj 1
Error LNK2005 "class std::basic\_fstream \> playerData" (?playerData@@3V?$basic\_fstream@DU?$char\_traits@D@std@@@std@@A) already defined in build.obj Game\_Multi\_File C:\Dev\Game\_Multi\_File\Game\_Multi\_File\saving.obj 1
Error LNK2005 "class std::basic\_fstream \> config" (?config@@3V?$basic\_fstream@DU?$char\_traits@D@std@@@std@@A) already defined in build.obj Game\_Multi\_File C:\Dev\Game\_Multi\_File\Game\_Multi\_File\saving.obj 1

# Answer
As you can clearly see from the console errors, the compiler is telling you that you alrealdy defined things like SDL\_window, SDL\_renderer and so on. In a tipical program, for a function/struct class etc.. you have what's called a definition, and a declaration. The definition of a function/struct/class tells the compiler "hey, this function/struct/class exists, it returns this, and has these parameters, so compile this code without any error". The declaration of this function/struct/class is basically what the function should actually do with these parameters and it should return a value(except if the return type is void of course). When the compiler does his work, the next step is the linker: the work of the linker is to go *find* the functions/structs/classes(their definition according to their declaration) and link everything togheter. If the linker *cannot* find the declaration of a definition it's going to return an *"unresolved external symbol"* error. In this case the linker is telling you "hey i found multiple definitions for one declaration, which one should i pick?". It also tells you that it found the declaration of the structs/classes into the build.obj file(.obj files are the result of the operation of the Compiler btw). So you need to verify there is *just one* declaration of those struct/classes in your program
> 0 votes

---
Tags: c++
---


# Question
Title: Translating ChainShape to world coordinates according to touch drag input
I'm trying to draw a ChainShape according to touch screen coordinates, however the coordinates are slightly off from my touch coordinates. I translate the chain drawn on the screen to world coordinates but don't think I've done it correctly.

I tried setting the shape's position to the first vertex but it positions it even further from the original touch coordinates. Can someone please help me understand where I'm going wrong?

```
public class Play implements Screen {
    private static final float TIMESTEP = 1 / 60f;
    private static final int VELOCITYITERATIONS = 8, POSITIONITERATIONS = 3;

    private Box2DDebugRenderer debugRenderer;
    private OrthographicCamera camera;
    private PolygonSpriteBatch batch;
    private World world;

    private List<Float> chain_verts = new ArrayList<Float>();
    private float[] chain;

    @Override
    public void show() {
        world = new World(new Vector2(0f, -9.81f), true);
        debugRenderer = new Box2DDebugRenderer();
        camera = new OrthographicCamera();
        batch  = new PolygonSpriteBatch();

        InputProcessor input_0 = new GestureDetector(new Gesture() {
        }) {
            @Override
            public boolean touchUp(float x, float y, int pointer, int button) {
                if (chain_verts.size() != 0) {
                    chain = new float[chain_verts.size()];
                }

                for (int i = 0; i < chain_verts.size(); i++) {
                    chain[i] = chain_verts.get(i);
                    System.out.print(chain[i] + " ");
                }

                ChainShape chainShape = new ChainShape();
                chainShape.createChain(chain);

                Vector3 mouse = new Vector3();
                camera.unproject(mouse.set(Gdx.input.getX(), Gdx.input.getY(), 0));

                BodyDef bodyDef = new BodyDef();
                bodyDef.type = BodyType.StaticBody;
                bodyDef.position.set(mouse.x , mouse.y);

                FixtureDef fixtureDef = new FixtureDef();
                fixtureDef.shape = chainShape;

                world.createBody(bodyDef).createFixture(fixtureDef);

                chain_verts.clear();
                chainShape.dispose();

                return super.touchUp(x, y, pointer, button);
            }

            @Override
            public boolean touchDragged(float x, float y, int pointer) {
                chain_verts.add(x);
                chain_verts.add(Gdx.graphics.getHeight()-y);
                return super.touchDragged(x, y, pointer);
            }
        };

        Gdx.input.setInputProcessor(input_0);
    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        world.step(TIMESTEP, VELOCITYITERATIONS, POSITIONITERATIONS);

        camera.position.set(0, 20, 0);
        camera.update();

        batch.setProjectionMatrix(camera.combined);

        debugRenderer.render(world, camera.combined);
    }

    @Override
    public void resize(int width, int height) {
        camera.viewportWidth = 1200;
        camera.viewportHeight = 800;
    }

    @Override
    public void pause() {}

    @Override
    public void resume() {}

    @Override
    public void hide() {
        dispose();
    }

    @Override
    public void dispose() {
        batch.dispose();
        world.dispose();
        debugRenderer.dispose();
    }
}

```

# Answer
> 1 votes
I was only translating the starting coordinate and incorrectly setting the body's position to that coordinate. Instead I now translate each screen coordinate in `touchDragged()` before adding it to the `ArrayList` (chain\_verts), works now. Also set starting position to `(0, 0)`.

```
public class Play2 implements Screen {
    private static final float TIMESTEP = 1 / 60f;
    private static final int VELOCITYITERATIONS = 8, POSITIONITERATIONS = 3;

    private Box2DDebugRenderer debugRenderer;
    private OrthographicCamera camera;
    private PolygonSpriteBatch batch;
    private World world;

    private List<Float> chain_verts = new ArrayList<Float>();
    private float[] chain;

    @Override
    public void show() {
        world = new World(new Vector2(0f, -9.81f), true);
        debugRenderer = new Box2DDebugRenderer();
        camera = new OrthographicCamera();
        batch  = new PolygonSpriteBatch();

        InputProcessor input_0 = new GestureDetector(new Gesture() {
        }) {

            @Override
            public boolean touchUp(float x, float y, int pointer, int button) {
                if (chain_verts.size() == 0) {
                    return false;
                } else {
                    chain = new float[chain_verts.size()];
                }

                for (int i = 0; i < chain_verts.size(); i++) {
                     chain[i] = chain_verts.get(i);
                }

                ChainShape chainShape = new ChainShape();
                chainShape.createChain(chain);

                BodyDef bodyDef = new BodyDef();
                bodyDef.type = BodyType.StaticBody;
                bodyDef.position.set(0, 0);

                FixtureDef fixtureDef = new FixtureDef();
                fixtureDef.shape = chainShape;

                world.createBody(bodyDef).createFixture(fixtureDef);

                chain_verts.clear();
                chainShape.dispose();

                return super.touchUp(x, y, pointer, button);
            }

            @Override
            public boolean touchDragged(float x, float y, int pointer) {
                // translate each coordinate here before adding to vertices list
                Vector3 mouse = new Vector3();
                camera.unproject(mouse.set(x, y, 0));

                chain_verts.add(mouse.x);
                chain_verts.add(mouse.y);

                return super.touchDragged(x, y, pointer);
            }
        };

        Gdx.input.setInputProcessor(input_0);
    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        world.step(TIMESTEP, VELOCITYITERATIONS, POSITIONITERATIONS);

        camera.update();
        batch.setProjectionMatrix(camera.combined);
        debugRenderer.render(world, camera.combined);
    }

    @Override
    public void resize(int width, int height) {
        camera.viewportWidth = 1200 / 30;
        camera.viewportHeight = 800 / 30;
    }

    @Override
    public void pause() {}

    @Override
    public void resume() {}

    @Override
    public void hide() {
        dispose();
    }

    @Override
    public void dispose() {
        batch.dispose();
        world.dispose();
        debugRenderer.dispose();
    }
}

```

---
Tags: libgdx, box2d
---