# Question
Title: Incrementally processing large number of entitites in an entity-component system
LibGDX/Ashley has a class IntervalIteratingSystem that allows you to process all entities in a particular family every *X* milliseconds. But if you have a lot of entities to process, it might be a bad idea to do all that at once. For example, if you want to process 10,000 entities once every 10 seconds, you might not actually want to wait 10 seconds, and then process all the entities -- you'd want to "spread it out" over many frames. Perhaps every 100ms you process 100 entities, cycling through them all.

To rephrase: I'd like to process a large number of entities but spread out across multiple frames, preferably:

1. providing a reasonable guarantee that all entities will processed at least once every *X* seconds,
2. enabling you to keep track of how much time has passed since that entity was last processed,
3. with a random entity order,
4. all entities are processed an equal number of times.

Here are my ideas so far...(some bad, some good)

1. Every time an entity is added to the `Engine`, add a Group1, Group2, or GroupN component (either randomly or sequentially), and then in my EntitySystem I cycle through the various families based on their Group#.
2. Every 10 seconds, add all 10,000 entities to a list, and then every 100ms, drain and process 100 from that list. (Memory-intensive, and might fall behind)
3. Every 100ms, iterate over all 10,000 entities, but skip 99% of them randomly (either using a PRNG or by checking their hashcode mod prime).
4. Maintain a list (a copy, really) of all relevant entities inside an EntitySystem using `Engine#addEntityListener()` and then process 1% of the list every 100ms by sequentially stepping through it, and wrapping around when reaching the end. (Uses LibGDX's unordered Array so removals are cheap).
5. Same as 4., but rely on `Engine#getEntitiesFor` and just let Ashley handle ordering and tracking entities instead of keeping a separate list.

At the moment, #1 and #5 seem most promising. #1 seems to meet all my requirements, but is a bit pervasive (creating and adding a bunch of components), #5 is less pervasive, but doesn't meet the requirements quite as well (#2 and #3 mostly).

Thoughts? Is there something better than these?

# Answer
I ended up implementing #4 above (in Kotlin). Seems to work alright.

---

```
import com.badlogic.ashley.core.Engine
import com.badlogic.ashley.core.Entity
import com.badlogic.ashley.core.EntityListener
import com.badlogic.ashley.core.Family
import com.badlogic.ashley.systems.IntervalIteratingSystem
import com.badlogic.gdx.utils.Array as GdxArray

/**
 * Partition all applicable entities into [bucketCount] separate "buckets", and then process these incrementally over
 * the full timespan of [interval].
 *
 * How to determine what to set [bucketCount] to? Each bucket should probably not contain more than, oh, around 100
 * elements. So take your expected number of entities, divide by 100, and that's approximately how much buckets you
 * should have.
 *
 * Considerations:
 * 1. This implementation is somewhat memory intensive -- it scales linearly with the number of entities in the provided
 *    family.
 * 2. Deletions (i.e. removing entities from the engine) are moderately expensive -- it has to scan through an array of
 *    average size entities/[bucketCount] to find the entity before removing it.
 * 3. Entities are stored unordered.
 * 4. Every time entities are processed, *approximately* entities/[bucketCount] are processed each time. Only
 *    approximately, though.
 * 5. Each entity is guaranteed to be processed exactly once every [interval] seconds.
 * 6. A reasonable implementation of #hashcode() is assumed for the Entities.
 *
 * Ex. If you have 10,000 entities, an interval of 10 seconds, and a bucket count of 100, then every 100 ms 100 entities
 * will be processed. (One bucket every 10/100 ms, where each bucket contains roughly 100 entities).
 *
 * @param interval the interval (in seconds) during which all entities will have been processed once.
 * @param priority The priority to execute this system with (lower means higher priority). Default 0.
 * @param bucketCount Number of internal buckets to partition all entities into.
 */
abstract class IntervalIteratingSystemBuckets(family: Family, interval: Float, priority: Int, private val bucketCount: Int) :
        IntervalIteratingSystem(family, interval / bucketCount, priority) {
    private val buckets = Array<GdxArray<Entity>>(bucketCount, { GdxArray(false, 8) })
    private val entityListener = MyEntityListener()
    private var currentBucketIdx = 0

    override fun addedToEngine(engine: Engine) {
        super.addedToEngine(engine)
        engine.addEntityListener(family, entityListener)
    }

    override fun removedFromEngine(engine: Engine) {
        super.removedFromEngine(engine)
        engine.removeEntityListener(entityListener)
    }

    override fun updateInterval() {
        buckets[currentBucketIdx].forEach { processEntity(it) }

        incrementBucketCount()
    }

    private fun incrementBucketCount() {
        currentBucketIdx++
        if (currentBucketIdx >= buckets.size) {
            currentBucketIdx = 0
        }
    }

    private inner class MyEntityListener : EntityListener {
        override fun entityAdded(entity: Entity) {
            buckets[entity.bucketIdx].add(entity)
        }

        override fun entityRemoved(entity: Entity) {
            // Moderately expensive; this is why you should favor more buckets
            buckets[entity.bucketIdx].removeValue(entity, true)
        }

        private val Entity.bucketIdx: Int
            get() = hashCode() % bucketCount
    }
}

```
> 1 votes

# Answer
**NOTE**: This is not libgdx specific and is a more general answer.

You could have two variables attached to update (or any specific) components you wish to process: \- frequency \- phase

Frequency decides after how many frames this component should be processed. Example, if you have a frequency of 7, then the component gets updated every 7 frames.

Phase determines how the update should be interleaved. You need to set this value incrementally to every component created, and it determines how many items in a batch will get processed each frame.

E.g.: If you want to process 1000 entities every 50 frames, but need to limit processing to 100 entities at a time, you follow the following steps

* Initialize a `phase` variable to 0, this should be static/global (maybe part of you component builder class/system)
* Then, for each component `c` you create
    + `c.frequency = 50`
    + `c.phase = phase`
    + `phase = (phase + 1) % 100` 100 because you want to limit to 100 items max

With frequency and phase variables in place, you could implement a simple update system like so:

```
class UpdateSystem : System {

    let scheduler = FrequencyScheduler()

    override func update(_ dt: CGFloat) {
        scheduler.update(world, world.manager.updateables)
    }

}

class FrequencyScheduler {
    var frame:Int = 0

    func update(world:GameWorld, updateables: Array<UpdateComponent>) {

        frame += 1

        for updateable in updateables {

            if (frame + updateable.phase) % updateable.frequency == 0 {
                updateable.update(world)
            }
        }
    }
}

```

This approach can be extended to consider time intervals instead of frame intervals.
> 0 votes

# Answer
Gdx-ai has frequency based schedulers https://github.com/libgdx/gdx-ai/wiki/Scheduling
> 0 votes

---
Tags: libgdx, entity-system
---


title: NavmeshAgent not to turn back

text:
# Question
Title: NavmeshAgent not to turn back
Imagine the blue part of this picture is streets and navmesh.
the red object is a car with navmeshAgent.
the green circles are the colliders set as triggered and they are the destination of the car.

when the game starts the car will choose one of them and go to that , after reach that it will choose another one randomly so it means the car will go through all of this forever.

now the problem is sometimes when car reach's one them and choose another since it will choose the closer path to next destination sometimes it will have to turn back which its not realistic and doesn't make sense.

as you can see in this example when reach that point since the middle one is closer from where the car is triggered it will turn back and the red arrow is wrong path , instead it should go through the green arrow and that's the correct path.
how can i do something to not to turn back instead find another way?

# Answer
I think the most obvious solution is to forbid the path you have just taken. This requires two checks. We keep track of where the car has been, and find the next best way it should go.

In the below image I've added four purple squares which exist between the randomly selected destinations. The car object has a variable, let's call it lastPath. Whenever the car enters one of the squares, it assigns that square to lastPath, so it always knows where it has been.

When it arrives at destination it then finds two things. It randomly finds the next destination, and then also finds the closest purple square from its current position to the destination which is NOT lastPath! We shall call this nextPath.

All you do then is pathfind twice, from car to nextPath, and then from nextPath to destination. That way it should avoid the path it has just taken.
> 1 votes

---
Tags: unity, c#, ai, scripting, navmesh
---


# Question
Title: How to make game scene bigger in 2d platformer?
Hi i am current making a 2D platformer game but after i reach an end of screen then it doesn't move forward how to increase the game play screen area so that i will be able to go in vertical direction i am pasting an image of the problem i am new to unity please help me!\]

# Answer
I got the answer of the question increase xMax and YMax to increase the game screen so that camera will follow you

```
public class CameraFollow : MonoBehaviour
{
    [SerializeField]
    private float xMax;
    [SerializeField]
    private float yMax;
    [SerializeField]
    private float xMin;
    [SerializeField]
    private float yMin;
    // Use this for initialization

    private Transform target;
    void Start()
    {
        target = GameObject.FindWithTag("Player").transform;
    }

    // Update is called once per frame
    void LateUpdate()
    {
        transform.position = new Vector3(Mathf.Clamp(target.position.x, xMin, xMax), Mathf.Clamp(target.position.y, yMin, yMax), transform.position.z);
    }
}

```
> 1 votes

---
Tags: unity, 2d, platformer
---


title: Tilting problem in Unity

text:
# Question
Title: Tilting problem in Unity
I want to tilt my object left or right depending on which side I'm moving my mouse. I wrote something like that:

```
    if (Input.GetAxis ("Mouse X") > 1) {
        transform.localRotation = Quaternion.Euler(0, 0, (-35 * Time.deltaTime * speed));
    }
    else if (Input.GetAxis ("Mouse X") < -1) {
        transform.localRotation = Quaternion.Euler(0, 0, (35 * Time.deltaTime * speed));
    }
    else if (Input.GetAxis ("Mouse X") == 0) {
        transform.localRotation = Quaternion.Euler(0, 0, 0);
    }

```

It's working only when I move mouse very fast and it's not 'smooth'. Would be thankful if anyone would help me :)

# Answer
> 1 votes
I suggest you using a class member in order to save the euler angles between the frames. Then, according to the input, just change a little bit the angles, and assign the new computed rotation.

```
private Vector3 eulerAngles;

[SerializeField]
private float tiltSpeed = 50;

[SerializeField]
private float recenterSpeed = 20;

void Update()
{
    float offset = tiltSpeed * Time.deltaTime;
    if (Input.GetAxis ("Mouse X") > 0f)
    {
        eulerAngles.z -= offset;
    }
    else if (Input.GetAxis ("Mouse X") < -0f)
    {
        eulerAngles.z += offset;
    }
    else
    {
        offset = recenterSpeed * Time.deltaTime;
        if( Mathf.Abs(offset) > Mathf.Abs(eulerAngles.z) )
            eulerAngles.z = 0 ;
        else
            eulerAngles.z -= offset * Mathf.Sign( eulerAngles.z );
    }

    transform.localRotation = Quaternion.Euler(eulerAngles);
}

```

---
Tags: unity
---


# Question
Title: Help understanding Unity Profiler time in ms
I'm a little confused about this column shown in the picture above.

When it shows 0.22 does it mean "22 miliseconds" or does it mean a fraction of a milisecond (i.e. in this case, around 1/5 of a milisecond) ?

# Answer
> 3 votes
The time is the time taken, *during a single frame*, in milliseconds. `0.22 ms` is `220 microseconds`. For reference, if you want 60 frames per second, you cannot spend more than `1000/60 = 16.67 ms` per frame.

You can click on the graph above to select a specific frame, which is useful to see what happens if you have some lag "spikes", for example when a new player joins the game, or you transition between different screens.

---
Tags: unity, profiler
---


# Question
Title: Drag and drop card game--NullReference Exception despite object existing?
I am trying to build a Hearthstone-style online TCG. Right now I am just working on getting the cards to drag around on the screen. Since I'm new to Unity, I'm using this tutorial https://www.youtube.com/watch?v=AM7wBz9azyU&index=3&list=PLbghT7MmckI42Gkp2cILkO2nRxK2M4NLo

I've copied the code in the tutorial pretty much exactly. What I have looks like this:

```
public class dragable : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler {

   public Transform parentToReturnTo = null;

   GameObject placeholder = null;

   public void OnBeginDrag(PointerEventData eventData)
   {
       Debug.Log("OnBeginDrag");

       placeholder = new GameObject();
       placeholder.transform.SetParent(this.transform.parent);

       LayoutElement le = placeholder.AddComponent<LayoutElement>();
       if (le) {
           Debug.Log("Found it!"); //Found le here...
       }
       else
       {
           Debug.Log("No dice.");
       }
       le.preferredWidth = this.GetComponent<LayoutElement>().preferredWidth; //can't find le--why?
       le.preferredHeight = this.GetComponent<LayoutElement>().preferredHeight;
       le.flexibleHeight = 0;
       le.flexibleWidth = 0;

       parentToReturnTo = this.transform.parent;
       this.transform.SetParent(this.transform.parent.parent);

       GetComponent<CanvasGroup>().blocksRaycasts = false;
   }

```

The rest of the class doesn't seem to effect the problem I'm having. That problem being: whenever I try to write to the LayoutElement le, the console returns a NullReferenceException error. But when I try to *read* le--for instance, testing if it exists in the if (le) loop (which exists only for debugging this particular issue), it works fine. Also, if you watch the tutorial video, you'll see that there is a "tabletop" on the upper half of the canvas that you can drop cards on to--this doesn't seem to work unless I comment out all code that tries to write to le's attributes. Anyone know how to fix this?

# Answer
You're adding the `LayoutElement` referenced by the variable `le` to a new `GameObject` referenced by the variable `placeholder`

```
placeholder = new GameObject();
LayoutElement le = placeholder.AddComponent<LayoutElement>();

```

But you're then trying to *read* from a different `LayoutElement` attached to `this` script's `GameObject`:

```
 this.GetComponent<LayoutElement>().preferredWidth;

```

It's this second `LayoutElement` that is not being found. Have you verified you have such a `LayoutElement` on every instance that's running this `dragable` script?

You can use a `[RequireComponent(typeof(LayoutElement)]` attribute to enforce this dependency to help catch these errors at edit time.
> 1 votes

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


# Question
Title: Should items in an RPG be hardcoded or loaded in some other way?
Should static weapons (ie.. Iron Sword, Mythril Axe) be their own (static) classes that derive from something like `ItemWeapon`, which itself is derived from a standard `Item` class with their own (inherited) methods?

Or possibly should there be just a standard `Item` class, an `ItemWeapon` class, and then every weapon is just an `ItemWeapon` instance loaded in at the start of the game?

If I was going to do that approach, where would I be loading all the items and weapons into the game? init?

If some weapons have special properties such as doing multiple attacks or a different effect, would it be beneficial to make them the separate classes to do it on an as-is basis instead of having every Weapon in the game have that function except it doesn't do anything?

# Answer
> 11 votes
Weapons are data. You shouldn't really ever keep data hardcoded. Your structs / classes should accommodate all necessary parameters to build a weapon's data from scratch, e.g.:

```
struct Weapon
{
    string name;
    int damageMin;
    int damageMax;
    bool entangle;
    bool canHitNoncorporeal;
    float resistFire;
    float resistElec;
    float attackSpeed;
    //etc. ad nauseam
}

```

And then say in text / .CSV:

```
Mithril Sword,15,30,false,true,0,10,4.5
Leather Whip,2,6,true,false,0,0,11

```

And yes, you would typically load via a `LoadItems` function called in `Init`, but remember to make it separate since you may also have to call `LoadItems` from elsewhere, such as `LoadGame`.

> If some weapons have special properties such as doing multiple attacks or a different effect would it be benefitial to make them the separate classes to do it on an as-is basis instead of having every Weapon in the game have that function except it doesn't do anything?

Nope. You should do it as a single class, as ultimately it's a finite set of options across all weapons in a given game, and doing it this way makes entering items easy (exception could be delegation *much* later; for now, do it as one class, factor out later according to SRP). The other reason is that dealing with combinations of static classes quickly becomes tricky for reasons I won't go into here. There really is nothing wrong with storing a bit of extra data for weapons, that is what CPU cache is for. And at worst, you could always compact your data, bitwise, later on.

If you're going to change options (members) often, you'll need to use a named format such as JSON / XML / YAML, otherwise you'll have to worry about changing order as in the CSV above, which does not mention WHAT each entry is, but only supplies them in-order (this is safer):

```
[
    {
        "name": "Mithril Sword",
        "damageMin": 15,
        "damageMax": 30,
        "entangle": false,
        ...
    },
    {
        "name": "Leather Whip",
        ...
    }
]

```

# Answer
> 1 votes
For the most part, it's really going to be up to personal preference and how you view it. Personally, I would view it as Item being the top base class, and Weapon extending it. Maybe with Equipment in between, something like:

```
Item <- Equipment <- Armor
Item <- Equipment <- Weapon
Item <- Food
Item <- Medicine

```

Then, I would have configuration files that specify all the weapons and their common parts such as damage, attack speed, maybe endurance.

If you have something really unique, you might consider a class that inherits from weapon, or you could just have it in as a field in the configuration files as true/false whether or not each weapon has that capability.

I would stay away from every weapon having it's own class. If you did that, there would be a ton of duplicated code or a ton of classes that inherit everything and have no real code in them.

---
Tags: software-engineering, rpg
---


title: Importance of openGL?

text:
# Question
Title: Importance of openGL?
How important is it to learn openGL when using game enginges such as Unity, cocos2d-x, lib-GDX and generally in game developing? Can you still create very complex, high-quality games without knowing openGL?

# Answer
Well, if you are using a game engine like Unity, or cocos2d-x , game maker(...) you don't *need* to learn Opengl(or any other graphics API, really) but it can be *useful*. "Can you still create very complex, high-quality games without knowing openGL?" Short answer: Yes, you can. Long answer: Making an high quality game, (as long as you use a game engine) doesn't require you to know a graphics Api at all. Making an high quality game requires all sorts of skills other than programming. Art, sound design, level design, ui design are just a few of the many things that make an high quality AAA title nowdays.
> 1 votes

---
Tags: opengl
---


title: Unity3D : Where to put external files?

text:
# Question
Title: Unity3D : Where to put external files?
I want my game to be user-translated friendly.I put .text file to Data folder from where strings will be read. What is Editor alternative for data folder ? Also i know compiler ignore some files, how i can tell compiler to include this one ? thanks.

# Answer
Look at StreamingAssets.

When you build your projects, all folders and files are packed, making it difficult, or even impossible, to edit.

All except one folder. The StreamingAsset folder. Retrieve its path with

```
 Application.streamingAssetsPath

```

This folder is not put in the package when you compiled, but stays next to it, letting anyone edit its content
> 1 votes

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


# Question
Title: How to do 1.5x scaling for pixel art where only one dimension has to scale?
I'm working on a point and click adventure game where the top third of the screen is a 16:3 single piece background with sprites on top. The width has to be edge to edge. It can't be cropped because the screen doesn't move.

The bottom of the screen will be one where you can interact with objects. Think Papers, Please. It can be any dimension, it can be 16:6 for 16:9 screens and 16:9 for 4:3(16:12). The objects on the bottom screen can be scaled imperfectly so say a notebook that is 64x64 on 720p can be 2x scaled to 128x128 on 1080p. It will only be compared to other 2x scaled objects so it won't look out of place.

Shades of green indicate areas where light green can be stretched to fill, orange indicates the area that I don't know what to do with. Black can't be scaled 2x because it wouldn't fit and it can't be cropped.

Am I still forced to make 2 different sets of art if I want it to look right?

# Answer
> 3 votes
So I figured it out. I imagine this is common knowledge but I couldn't find it so I'll leave it here. The solution for me is to make people fit in 32x32, everything else scales relative to humans. Upscale that 2x for 720p and 3x for 1080p.

---
Tags: scale, pixel-art
---


# Question
Title: How to quit current state animation correctly?
I've a 'classic' humanoid player with an animation controller and some animations.

This is the code i'm managing state changin

```
        float h = CrossPlatformInputManager.GetAxis ("Horizontal");
        if (h < 0) {
            m_Animator.SetTrigger ("LeftWalking");
        }
        else if (h > 0) {
            m_Animator.SetTrigger ("RightWalking");
        }
        else if (m_CharacterController.velocity.magnitude != 0) {
            m_Animator.SetTrigger ("Walking");
        }
        else if (m_Jumping) {
            m_Animator.SetTrigger ("Jump");
        }
        else {
            m_Animator.SetTrigger ("Idle");
            m_Animator.ResetTrigger ("Walking");
            m_Animator.ResetTrigger ("LeftWalking");
            m_Animator.ResetTrigger ("RightWalking");
            m_Animator.ResetTrigger ("Jump");
        }
    }

```

My problem is that after i stop to press my "forward" button (that make my player walking), the walking animation continue to play itself till the end.

This is my state machine

This is options of Walking to Idle state

I'm pretty sure I've to "play" with HasExitTime and/or FixedDuration but i'm not sure...

# Answer
Remove the HasExitTime checkbox to allow the transition to trigger at anytime.

See the documentation about HasExitTime
> 3 votes

# Answer
As Basile already said, uncheck HasExitTime. You should also uncheck the fixed duration box and set the transition duration to 0. Good luck:)
> 0 votes

---
Tags: unity, animation
---


# Question
Title: Is my game "shovelware" if it uses images from Google Image searches?
I think this is a stupid question, but i want to know.

I just read Wikipedia about Steam software and i found a new word for me, that is Shovelware. Wiki says that :

> Low-budget, poor-quality games, released in the hopes of being purchased by unsuspecting customers, are often referred to as "shovelware".

So, let's say that i want to make a games. I have no budget, i use free game engine, free software and using free texture from internet (maybe from dedicated texture website like Textures.com or Poliigon.com) or download free image from google and make my own texture + material with that image using free software like GIMP.

Is my game considered as "shovelware" ?

# Answer
No, your game is considered to be simply a bad game. One of the most important part of that definition is "in the hopes of being purchased by unsuspecting customers". If your customer sees a bad game, and buys it because they have money to burn, then they aren't unsuspecting, they probably just have a gambling problem.

Shovelwares are usually based on something popular in hope for someone to accidentally buy it. For instance, if you make a 2d shooter in 2 weeks and call it Holo, then that's shovelware, since it's probably trying to ride on the success of Halo. This is just an example, shovelwares can be based on anything, books, series, movies, etc. and sometimes the developers don't even license what the game is based on.
> 4 votes

# Answer
No.

"Shovelware" is jargon; it's a derogatory term meant to denote software where the apparent goal was to produce *quantity* over *quality*, or to produce something cheaply and quickly to use as a vehicle for furthering some other scam. The underlying intent is often to trick or exploit consumers rather than to produce a game in good faith. One might consider Steam trading card farm games shovelware, for example.

A game that is made on a small (possibly zero) budget is not shovelware just *because* it had a small (or zero) budget. Some people might *call* it shovelware if they perceive it to be so, sure. They also might just settle for calling it a "bad game." People call games with multi-million dollar budgets "bad games" (and other far more unsavory terms) as well. That's just their perception.

---

> or download free image from google

As noted in the comments, however, do make sure to verify the licenses for any images you get this way. Otherwise, your game might not end up being "shovelware" but it may still end up in legal hot water.
> 2 votes

---
Tags: terminology
---


# Question
Title: So, I need to create varied animal textures for my game. How would I go about doing that?
For example, one of the creatures planned is an isopod like animal. Would I need to get pictures of real animals and adjust them to my needs?

# Answer
> 1 votes
I would build them up with multiple layers of randomly selected images using a shader. The images you'd use would be as follows...

First, a collection of base coloration textures. They can be stripes, splotches, single colors, or what ever you think would be appropriate for the animals. They should not have any scale, wrinkle, or other form features, or shininess (specular reflection). Just the base colors.

Next, a collection of normal maps that can be applied to create scales, bumps, or other skin patterns on your base coloration textures. You could combine "purple splotch" with "lizard scales" for example, and get a purple splotched lizard skin. If you google "normal map lizard skin" you'll find a lot of hits that give you an idea of how this works in general.

Lastly, a collection of transparent textures that add scratches, scuffs, dirt splotches, or whatever else you might see as providing some additional variation. You can choose to overlay them in the end to add more variety to the skin.

Given these sets of textures, you can randomly pick one from each category, and combine them using a shader to create a randomized skin style. If the animal is something that gets wet (like an amphibian), you can always throw in some specular reflection to make it glisten.

---
Tags: textures
---


# Question
Title: How can I change a shader alpha color in script?
How can I get access to the Main Color and change the alpha color ? How do I know what is the variable of the main color in the shader code ?

If it's Main Color in the Inspector then this is the parameter I should get in the script "Main Color" ?

# Answer
If the colour is exposed with the name `_Color` in the shader code (most defaults are), then you can access it with material.color, using a reference to the material instance you want to change, something like this:

```
var renderer = GetComponent<Renderer>();
// This getter copies the material to a local instance,
// so cache it and remember to clean it up when you're done with it.
_cachedMaterial = renderer.material;

// Read, modify the alpha, and write back to the material.
Color color = _cachedMaterial.color;
color.a = 0.5f;
_cachedMaterial.color = color;

```

If it has a different name in the shader code, you can use material.GetColor() or material.SetColor(), passing either the internal name of the colour variable as a string, or an integer ID retrieved via Shader.PropertyToID().

Please remember to take at least a cursory search through the available API documentation or tutorials for basic questions like this - you'll often find your own answer far faster than it takes someone else to type it up for you.
> 1 votes

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


title: Letter game board creation

text:
# Question
Title: Letter game board creation
I currently have a game concept similar to the mobile app Alphabetty where you are given a grid of letters and are tasked with spelling words. When you use a letter in a word, it disappears and new letters fall in from the top to replace the used ones.

I have been playing around with ways of making the new letter spawning more "interesting" so that players can get more complex words. I tried making it so each letter spawns based on how common it is, kind of like scrabble but didn't get great results. I have also tried representing each grid tile as a Boggle die which re-rolls each time its used, which was better but far from perfect.

The main issues are:

* Vowels and consonants often end up grouped together, creating unusable areas on the board. This also goes for letters of the same type (i.e. 3 s letters side by side)
* With Boggle dice it's very hard to spell words like "Blizzard" as only 1 or 2 dice have rare letters such as z, v, and k etc
* For the sake of a game mode, I need to be able to seed the grid with words of my choosing slowly (i.e. as new letters fall in) so that players have the ability to spell these special words if they are particularly careful

Are there any solutions, theories or discussions out there that could help?

Thanks!

# Answer
> 2 votes
As mentioned in the comments, these sorts of problems are computationally difficult. First, there's no easy evaluation rule for finding legal words - for each potential string, you have to search through your dictionary of legal words. Choosing a good data structure can help (i.e. hash map, trie, etc), but it's still an unavoidable expense. The bigger problem is there are many potential permutations in terms of possible words to check on the board & possible new words that will result after a given move or play.

Some of these problems can be mitigated with design choices & game mechanics, but keep in mind that the game you are presently imagining might not be possible - you may need to make some compromises between your ideal and reality.

Here's a technique I've recommended in the past from Jesse Schell's Art of Game Design (which he in turn credits to game designer Rob Daviau):

List out all of the assumptions you're making & consider ways to invalidate them. Here are some examples based on what you've described (or left out) about the game so far. Your description leads me to assume:

* The letters can get stuck in certain locations. What if:
    + The player could swap letters, either on the board or from some sort of managed resource?
    + There was a way to destroy unwanted tiles? SpellTower does this with adjacent moves; you could do the same or add your own version.
    + There were rule based changes to the game board? For instance:
        - If a tile was static for too long it could change, either automatically or at the players request.
        - If you had three of anything in a row, the player could change or swap one of them out for another letter.
* The player can only spell 'correct' words. What if:

+ Your dictionary included common typos, but maybe scored them lower the real words?
    + The player could submit incorrect words, but was penalized for errors?
    + The game could analyze the board, detect moves that would result in 'garbage' words (a run of 5 consonants, etc) and incentivize the player to 'take out the trash'?
* Tiles only fill in from one direction. What if:

+ The player could alter the gravity?
    + The special word seeding could by-pass the gravity mechanism to get the letters where they are easy to use?

Some of these will undoubtedly be complete nonsense. That's okay. Each bad idea indicate that the corresponding base assumption (which it failed to invalidate) is probably a good game design choice. And some of the time you'll encounter a really interesting twist that you wouldn't have considered. Statitisitcally, very few desicions are likely to be awesome - the more options you sift through, the more likely you are to find one.

Note: it can be difficult to realize your own assumptions about your own work. If you have a prototype, consider letting person A watch person B play the prototype & then ask A what they perceive to be the ground rules of the game.

Another approach is to watch someone play the game & when it fails out (can't spell a target word) ask them what they wish they could do. While it's possible they will have "the perfect answer", it's also unlikely. Often, players want things that break the fun (and design). Instead, focus on why they are making the request and challenge yourself to find ways to address that without removing the fun. Some of these solutions may alter the design - that's part of iterating.

# Answer
> 2 votes
One small tweak I'd be interested in experimenting with is joint probabilities.

The probability of a Q appearing in any given spot in a word is very very low. But the probability of a Q appearing given that the letter after it is a U is substantially higher. Certain letters "like" being together.

With a little pre-processing on a corpus of words, you can build a table of how often a particular letter appears with particular collections of other letters adjacent to it.

Then, when you're about to drop a new letter into a space, check which other letters it will land next to. Choose the letter from the probability distribution associated with those adjacent letters. (Ensure you always have some chance of any letter, just so it doesn't get locked into rigid patterns)

This will tend to reduce clusters of letters that are hard to use together (like dropping a new consonant into a gap that's already surrounded by other consonants, or likewise with vowels), at least in new drops. It's especially strong when dropping contiguous chunks of new letters at once, especially if you work from the most-constrained letter inward, taking into account your choices of each dropped letter to inform the next drop.

This trick doesn't do much to help with clusters that are formed by eliminating letters between them. For those situations, the mechanics that Pikalek describes will help the most.

---
Tags: procedural-generation, grid, puzzle, word-games
---


# Question
Title: How to split a group of tiles in a grid into separate groups if a break occurs between tiles?
I have a grid where objects can be placed down by the player. Each object that gets placed down is added to a dictionary where the key is the grid position.

Each object that gets placed down either gets added to a new zone, or added to an existing zone if any of the neighbors are in an existing zone. If there are multiple zones, then it just picks the first one it finds and adds it.

The issue I am struggling with is how to handle splitting up zones if an object is removed from the grid.

In the first image I have 2 zones.

In the second image, I add a new object to the grid, because that tile contains 2 neighbor tiles that are in a zone, it merges the 2 zones into one.

In the third image, I remove an object from the grid, which removes it from the zone, and in this case it creates 2 new zones (but could be more depending on neighbors). This is where I am struggling to work out the best way to efficiently do this.

* I have a grid array that holds all objects placed on the grid.
* A zone contains a list of tiles that are in that zone.
* Each tile in a zone also gets a zone id.

What would be a fast efficient way of splitting up a zone into multiple zones?

I thought about checking all the tiles in the zone by checking its neighbors, but thought that it could be quite slow, as a zone can grow to be very big over time (zones can auto merge as well). Also wouldn't there be a chance of an endless loop?

# Answer
> 1 votes
Unfortunately there is no tidy way to do this. Anytime you delete a node that was touching more than 1 other node in the grid you will have the opportunity to split the zone into 4 or more child zones. There is no way of knowing if that split occurs unless you use some sort of flood-fill algorithm to reassign zones.

I would create a stack of points containing each filled node that touches the deleted space. Create a new zone for each of those points. Expand that stack with a flood-fill algorithm, merging zones as they meet. Create a temporary array of bits the size of your grid to track which nodes have already been checked. Below is an example:

Using a stack for this results in Depth-First searching. That means that the zones will grow one at a time while the rest remain a single node, so merging is as simple as reassigning one node. If you solely want checking, then just push one node and run until all the other nodes have been touched. If all the surrounding nodes are reached then the zone hasn't been split. If the stack runs out before they are reached then the zone has been split. In that case you could leave the original zone alone and run the above algorithm with just the nodes that weren't reached.

In the example above nodes in Zone 2 are reassigned back to Zone 1 after the whole process is completed. This may not be required by your program.

This may seem inefficient, but it should be quite fast if your data is stored normally. Don't try to optimize too much prematurely.

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


# Question
Title: How can i draw a curve in modern Opengl?
OpenGl is capable of rendering points, lines, triangles and quads; but what if i want to draw a bezier curve? I read online you should use something called `GL_STRIP`, but the solutions were using either legacy Opengl, or they were not explaining well the process. The question is: How can i render bezier curves in Modern Opengl? I'm using C++.

# Answer
> 7 votes
First of all, the basics:

The bèzier equations are very simple. You basically take the line segment created by the points, get the lines between them, then you linearly interpolate a point between the starting and ending point of each line. This way you get one less point than before. You do the same with the lines defined by these, and so on until you get a single point. This will draw your bezier curve.

You can also just use specialized equations, like for instance for the 4 point version:

$$P = (1−t)^3P\_1 + 3(1−t)^2tP\_2 +3(1−t)t^2P\_3 + t^3P\_4$$

After this you just loop through between 0 and 1 in as many steps as precise you want the curve to be and plug the value into the interpolations or into the equation as t. This gives you 2d vectors. You can put those values into a buffer and render them using `GL_LINES` (make sure to use LINES, LINE doesn't work) and voilá, you have your bézier curve.

A bézier curve has the nice effect of getting denser around curves, so you won't have to make the precision much higher to get a smooth curve

After the happiness of rendering something smooth subsides, forget what I just said and never use built-in lines in production again. They don't work very well, when they're wider than a couple of pixels. Instead create a custom one using triangles, but that topic is far too complicated to cover here. You should be able to either figure out or find a tutorial about it.

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


# Question
Title: Hardcode model data into geometry shader
I have this idea for creating a point cloud and passing an integer into geometry shader to determine which model to draw, each model has the same amount of vertices etc and it would be hardcoded into shader, this would function somewhat like instancing but models have to have the same data size and you can draw multiple meshes in one call. What do you think about it?

# Answer
> 1 votes
All theory here.

Thoughts come to mind is, compress all your models into a single structured unoredered access buffer, not a vertex buffer.

In your Vertex Shader, do not attach a vertex buffer for your geometry, but attach a structured buffer as a resource would Unordered access buffers.

Now the bit im not sure of. Create an instance buffer, attach this as a buffer (slot 1 - when you get to this, you will understand). your instance buffer holds thigns such as the model offset, and colours etc.

Instead, call the draw call without (See reference -\> Using Input Assembler without buffers ). Using the SV\_VertexID, plus instance buffer offset, reference into the structured buffer.

All theory, but what i would try first.

To be honest, I think its no benefit. I would firstly compress your models into 1 buffer, but draw call itself has low overheads are close to 0 (it's queued, and will be dependent on the complexity of the geometry). I would just call the draw calls with the relevant offset. I would get your mind around instance buffering and DrawindexInstanced as I have been able to draw thousands of different items very quickly. Reference my game to see lots of trees rendered quickly and effectively -\> Game link

With the instance call, you can actually tell to render all instances in the buffer to render with a certain vertex or index offset.

---
Tags: rendering, performance, geometry-shader
---


# Question
Title: How can I reflect a point about a line in Unity?
I am drawing a line using the line renderer in the following way:

```
public class MyLineRenderer : MonoBehaviour {
LineRenderer lineRenderer;

public Vector3 p0, p1;

// Use this for initialization
void Start () {
  lineRenderer = gameObject.GetComponent<LineRenderer>();
  lineRenderer.positionCount = 2;

  lineRenderer.SetPosition(0, p0);
  lineRenderer.SetPosition(1, p1);

}

```

}

From the image below, the line `P0P1` is known and so is point A. How can a point B, which is the reflection of A about the line `P0P1` be found?

# Answer
> 3 votes
```
// Form a unit vector in the direction of the line.
var lineDirection = (p1 - p0).normalized;

// Rotate the vector 90 degrees in the XY plane
// to get a vector perpendicular to the mirror line.
var perpendicular = new Vector3(-lineDirection.y, lineDirection.x, 0);
// If you're working in the XZ plane instead, it's
// (-lineDirection.z, 0, lineDirection.x)

// Take away a's perpendicular offset from this line, twice.
// Once to flatten a onto the line, and a second time to make b,
// an equal distance away on the opposite side of the line.
var b = a - 2 * Vector3.Dot((a - p0), perpendicular) * perpendicular;

```

---
Tags: unity
---


# Question
Title: Using seeds for rng. A reliable way of saving bandwidth?
Imagine a server-client game application.

While running, the server is constantly generating numbers for various random events and sending them over the network to inform the clients of the result.

I realized it would save alot of bandwidth if I made my rng deterministic and would only transmit a seed value at the start of the game and the number of random calls that have been made on that random instance in the past so that my clients can reproduce a similar random instance and the next generated value will be the same for all clients. Is that a reliable option in terms of security and synchronization and apart from predictability?

# Answer
## Entropy

Sending random numbers and sending seeds is the same thing: sending entropy.

Consider that in the case of sending random numbers, you can interpret that each random number sent is a seed for a random number generator used by the client, and this random number generator has a cycle of only one number.

Consider also that if you use a random number generator that generates 2^63-1 values with a seed of 32 bits of entropy, then the sequence has very little entropy... which means they are easy to crack.

Have a look at "Cracking Random Number Generators" from all that jazz.

---

> My question refers to an imaginary server-client application and was meant in general. So you can assume a worst case scenario

I do not know about worst case scenario. Yet, I will take a case that I think is fairly high: 2 bit per millisecond.

So, that is 2000 bits per second, or if you prefer it is about 33 bits (roughly an int32) per frame in a 60 fps game.

That mounts to slightly below 7MB per hour. It does not sound that crazy at this scale, does it?

> Numbers are the same for all clients.

Generate a random file, and allow clients to download it. Use something based on TCP so that they all get the same bits. You server would have to generate one file per hour, and there should be some metadata so the clients can synchronize.

Yes, HTTP would work. Note: We are not talking bandwidth yet.

However, when it comes to generate the random numbers, the standard random number generators will start to show patterns.

See Random.org article on statistical analysis.

The following is from "Cracking Random Number Generatos" (part 3):

> A much more popular PRNG algorithm is the Mersenne Twister. This is used by Ruby's rand() function, Pythons random module, and PHP's mt\_rand() function.
>
> The Mersenne Twister was invented in 1997. The most common implementation of it uses an internal state of 624 32 bit words (integers).

So, with only 624 * 32 bits = 19968 bits (a little less than 20 KB) you can work out the sequence, if you are generating numbers this way, sending more numbers gives no more entropy to the client.

In fact, if you need strong guarantees on the random numbers (for example, if you are running an online casino), consider random.org services. They can generate over 2000 bits per second, so I would recommend their service if you need this many random numbers.

Note: For this rate of output, something like Microsoft Crypto API will work ok.

---

## Security

> you can assume a worst case scenario

You want an algorithm that generates random numbers that has the property that an attacker won't be able to predict the next numbers. That is, you want a Cryptographically secure pseudorandom number generator. If we are talking about Java, our first stop is SecureRandom. With SecureRandom you do not have control over the input entropy, the system will gather entropy from whatever source the underlying operating system provides.

From SecureRandom (Java Platform SE 8 ) - Oracle:

> Note: Depending on the implementation, the generateSeed and nextBytes methods may block as entropy is being gathered, for example, if they need to read from /dev/random on various Unix-like operating systems.

Otherwise, you will need a third party solution (or cook one yourself). I suggest looking for an implementation of Fortuna which will give you more control on how you provide entropy.

---

> What do you mean by "stepping between sender and receiver"?

I think Bálint was talking about Man in the Middle attacks.

The bad news is that a third party could try to pretend to be server and give you false numbers. Use a secure channel (SSL, HTTPS, etc...).

The good news is that everybody gets the same numbers. So there is no need for session or tokens, as the client does not need to identify itself. Which also means that session hijacking or impersonation are non issues when it comes to this random number generator.

However, a side effect is that it could be possible (with a bit of reverse engineering) to figure out how to create a tool that can download the data files and run the random number generator ahead of time, and perhaps do predictions of what will happen in the game. Which is another reason to generate small files often (multiple in a day) instead of generating a large file for the day or the week.

Edit: I guess you could use authentication to protect the data files. However that just means that the guys doing the tool need a valid account. I suggest to not bother. Assume they will make the tool.

---

## Synchronization

Every client must do the same rolls. That means that you need to design the game in such way that rolls are not conditional.

The reason is that if a client does a roll but another client does not, they are now out of sync.

This also means that you should have a plan for exactly how the random number generator will be used.

Consider using two random number generators. One for the big stuff that needs to stay in sync, and one for any other stuff that does not have to be as strong as the first one.

Then, there is timing. You wan two things to make this work:

* Publish the data files and the time at which they should start using it.
* Have a side channel to synchronize clocks.

Note: Another thing you can do, is limit the number of times a generator is used. If you game knows how many numbers it has to generate, that is. Which I recommend you to know.

The server should have available the next data file and at what time the clients should use it. Then the clients will download it and prepare a random number generator ahead of time and when the time comes they switch to the new one... and start downloading the next.

However, we need them to switch to the new one at the same time. Which is why we need to synchronize clocks. And synchronize often. A query to an ntp often.

What if you used a generator a few extra times? Go back and redo them with the new one. I would suggest to introduce a natural exit point when the change is happening (having natural exit points is good anyway).

---

## Bandwidth

If you want to run SecureRandom, it must be in the server because you cannot seed it. In this case, you will be serving those 7MB files.

> you can assume a worst case scenario

21 million users?

20 million * 7 MB / hour = 311.1 GB/s.

About 102 PB per month. Note: Those are PetaBytes - *TeraBytes are suddently small*.

I woudl have said *Get a global CDN solution and let them handle the traffic*. But this crazy.

Let us put some of the work on the client. If we use Fortuna random number generators, we can provide about 12KB of useful entropy and have it virtually never run out (Fortuna reseeds itself).

If we stay with the idea of providing entropy once per hour,

20 million * 12 KB / hour = 533.3 MB/s.

About 176 TB per month.

It could work with only 2KB of entropy (I was compensating for the entropy input being infrequent). In that case we would be talking of only about 30 TB per month.

Get Amazon CloudFront.
> 2 votes

# Answer
First of all, it wouldn't save much bandwidth. Even if you send a 1000 integers, that's still just 4000 bytes, which is nothing for today's network connections.

Secondly, what if I step between the receiver and the sender and change every value to something else? For instance if you send the 5 numbers of a lotto game, and I changed them so they match mine?

And also, if you use something like UDP, where packets don't arrive in order every time, and you send "generate 5 numbers" immedialitely followed by "generate 3 numbers", but their order changes, then the numbers won't match up. Same with packet loss, it would mess the whole game up.
> 2 votes

---
Tags: java, networking, client-server, server, random
---


title: Integrating collisions and constraints

text:
# Question
Title: Integrating collisions and constraints
Long story short, I had to roll my own physics engine for my game because box2D and similar packages weren't compatible with the portal based layouts in my game.

So I've made a constraint system and a collision system, which both work somewhat well. But i can't figure out how to combine them, because the constraints are sort of integrated across a time step, while a collision happens at a distinct moment in time, after which the velocity changes drastically, unlike the minor adjustments made in constraints.

How are these two systems integrated with each other?

# Answer
> 1 votes
In most constraint-based physics systems I have seen the contacts are implemented as a constraint, which constrains the two bodies from penetrating the contact. Box2d is no exception. Each degree of a constraint is solved aspart of the jacobian matrix, although some details about ordering of constraints does exist to improve stability. I would study the box2d source as well as Bullet to see what a contact becomes (a constraint) and how that fits into the solver.

---
Tags: collision-detection, physics, joints
---


# Question
Title: How can I make custom progress bar in unreal engine?
I am trying to make a health bar. I want a masked progress bar so I tried making another progress bar and moving according to the percent of the health in blueprint. But I couldn't find any documentation about it. How can I do it? Or is it possible? It should be like this:

# Answer
> 2 votes
You can make your own progress bar by a using shader.

The first thing you should do is mask the uvcoordinates horizontally.`Step function` lets you do this.

> The step() interpolation receives two parameters. The first one is the limit or threshold, while the second one is the value we want to check or pass. Any value under the limit will return 0.0 while everything above the limit will return 1.0.
>
> https://thebookofshaders.com/glossary/?search=step

Unreal doesn't have the `step` function, so you can use if expression.

---

# Making Step Function

You can also use the hlsl `step` function, in the material editor. Make a custom node, with two inputs named A and B.then use below code:

```
if(A < B)
{
return 0;
}
else
{
return 1;
}

```

---

Create widget BluePrint and set this material to your image:

useful link: Gradient Functions

---
Tags: unreal-4, blueprints, hud
---


# Question
Title: How to determine the angular velocity needed move an object to a given position
I am trying to move two lines joint to a fixed position sprite in a way similar to that of a pendulum. I would like the lines to swing from end to end each time. The image below shows what I want to achieve:

I'm moving the lines using angular velocity, but I'm not getting the pendulum/swinging effect (a cycle of the lines generally swinging faster as they move to the center and slowing down a bit when they change from one direction to another). I rather get some brisk movement then it slows down till the movement stops. Please see my SpriteKit code below:

```
extension Int {
  var degreesToRadians: Double { return Double(self) * .pi / 180 }
}
extension FloatingPoint {
  var degreesToRadians: Self { return self * .pi / 180 }
  var radiansToDegrees: Self { return self * 180 / .pi }
}

class GameScene: SKScene, SKPhysicsContactDelegate {

var anchorSprite = SKSpriteNode(imageNamed: "swingPin")
var armLeft = SKSpriteNode(imageNamed: "swingArm")
var armRight = SKSpriteNode(imageNamed: "swingArm")

override func didMove(to view: SKView) {

self.physicsWorld.gravity = CGVector(dx: 0, dy: -1.8)
self.physicsWorld.contactDelegate = self

var tealBg = SKSpriteNode(imageNamed: "tealBg")
tealBg.position = CGPoint(x: frame.midX, y: frame.midY)
tealBg.zPosition = 10
addChild(tealBg)

anchorSprite.position = CGPoint(x: frame.midX, y: frame.midY + frame.midY/2)
anchorSprite.zPosition = 20

anchorSprite.physicsBody = SKPhysicsBody(rectangleOf: anchorSprite.frame.size)
anchorSprite.physicsBody?.categoryBitMask = pinCategory
anchorSprite.physicsBody?.isDynamic = false
addChild(anchorSprite)

armRight.anchorPoint = CGPoint(x: 0.5, y: 1)
armRight.position = anchorSprite.position
armRight.zPosition = 20
armRight.physicsBody = SKPhysicsBody(rectangleOf: armRight.frame.size)
armRight.zRotation = CGFloat(Double(15).degreesToRadians)//CGFloat(Double.pi/6)
armRight.physicsBody!.isDynamic = true

addChild(armRight)

armLeft.anchorPoint = CGPoint(x: 0.5, y: 1)
armLeft.position = anchorSprite.position
armLeft.zPosition = 20
armLeft.physicsBody = SKPhysicsBody(rectangleOf: armRight.frame.size)
armLeft.zRotation = CGFloat(Double(-15).degreesToRadians)//CGFloat(-Double.pi/6)
armLeft.physicsBody!.isDynamic = true
addChild(armLeft)

// Create joint between two objects
//Pin joint
var pinAndRightArmJoint = SKPhysicsJointPin.joint(withBodyA: anchorSprite.physicsBody!, bodyB: armRight.physicsBody!, anchor: CGPoint(x: anchorSprite.position.x, y: self.armRight.frame.maxY))
self.physicsWorld.add(pinAndRightArmJoint)

var pinAndLeftArmJoint = SKPhysicsJointPin.joint(withBodyA: anchorSprite.physicsBody!, bodyB: armLeft.physicsBody!, anchor: CGPoint(x: anchorSprite.position.x, y: self.armLeft.frame.maxY))
self.physicsWorld.add(pinAndLeftArmJoint)

var fixArms = SKPhysicsJointFixed.joint(withBodyA: armLeft.physicsBody!, bodyB: armRight.physicsBody!, anchor: CGPoint.zero)
self.physicsWorld.add(fixArms)

pinAndRightArmJoint.shouldEnableLimits = true
pinAndRightArmJoint.lowerAngleLimit = CGFloat(Double(-60).degreesToRadians)
pinAndRightArmJoint.upperAngleLimit = CGFloat(Double(60).degreesToRadians)

}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
armRight.physicsBody?.angularVelocity = -100.0

}

```

Please note that though I believe this is the most appropriate approach to my problem, I'm open to another approach that would help me achieve the same result.

# Answer
> 0 votes
Use a sine wave:

```
angle = 45 * sin(time)

```

---
Tags: spritekit, swift
---


title: How can I attach a ball to something?

text:
# Question
Title: How can I attach a ball to something?
I'm using Unity 2017 and am writing a game wherein you shoot a ball, and when said ball hit something (a cube for example), I want it to remain in that position that it hit.

I tried this but it didn't work:

```
ball.transform.localPosition = gameObject.transform.localPosition;

```

Something like this picture :

# Answer
> 0 votes
```
ball.transform.parent = gameObject.transform

```

Rotation should look something like this:

```
ball.transform.localPosition.x = sin(time * speed) * distance;
ball.transform.localPosition.y = cos(time * speed) * distance;

```

---
Tags: unity, unityscript
---


# Question
Title: Accessing UAV data in a Pixel Shader SRV
I'm working with a basic compute shader which only task is to modify the input color of an UAV. This UAV data should then be passed to an SRV in a pixel shader which should then output this color. The compute shader looks like:

```
struct Color
{
    float4 color;
};

RWStructuredBuffer<Color> OutputBuffer : register(u0);

[numthreads(1, 1, 1)]
void main(uint3 DispatchThreadID : SV_DispatchThreadID)
{
    //Set the structured buffer to a green color
    OutputBuffer[DispatchThreadID.x].color = float4(0.f, 1.f, 0.f, 1.f);
}

```

And in the pixel shader we have

```
struct Color
{
    float4 color;
};

StructuredBuffer<Color> colorBuffer : register(t0); // SRV
...

float4 main(PS_IN input) : SV_TARGET
{
    return colorBuffer[0].color;
}

```

There is only a single root signature which has two tables, one for the SRV and one for the UAV. There is also a single heap (two descriptors) which is related to the creation of the two buffers (this is omitted since the problem doesn't seem to be related as the SRV works fine without the UAV), but attention should be paid to the binding of the compute shader in the frame function:

```
//Set compute shader to change the color of the UAV
m_commandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(m_uavBuffer.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS));
m_commandList->SetPipelineState(m_shaders->GetComputeShader(Shaders::ID::BasicCompute).pipelineState.Get());
m_rootSignature->SetComputeRootSignature();
m_srvDescHeap->SetComputeRootDescriptorTable(2, m_srvDescHeap->GetGPUIncrementHandle(1));
m_shaders->SetComputeDispatch(1, 1, 1);
m_commandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(m_uavBuffer.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE));

```

Now when I want to access the UAV data in the pixel shader I believe I only have to pass the GPU handle for the UAV to the SRV binding?

```
m_srvDescHeap->SetRootDescriptorTable(1, m_srvDescHeap->GetGPUIncrementHandle(1));

```

Although this only gives me a black color for my primitive and not the green color, something which tells me that the UAV data is not passed correctly. It is also noticeable that I tried the same code on my other computer with a GTX 1060 graphics card and got the green color but with the 960 I get the black color. This is likely driver related but still disturbing. Now, I believe that there are some more steps missing to actually get the UAV data, but I can't find any information about this, does anyone have a clue?

**Edit 1:** I enabled the GPUBasedValidation and received the following error code:

```
D3D12 ERROR: GPU-BASED VALIDATION: Draw, Descriptor type doesn't match shader register type: Descriptor Heap Index To DescriptorTableStart: [1], Descriptor Heap Index FromTableStart: [0], Descriptor Type in Heap: D3D12_DESCRIPTOR_RANGE_TYPE_UAV, Register Type: D3D12_DESCRIPTOR_RANGE_TYPE_SRV, Index of Descriptor Range: 0, Shader Stage: PIXEL, Root Parameter Index: [1], Draw Index: [0], Shader Code: E:\DX12_project\DX12_Project\DX12_Project\DX12_Project\src\res\shaders\FragmentShader.hlsl(18,5-32), Asm Instruction Range: [0x44-0x6f], Asm Operand Index: [3], Command List: 0x056FCB98:'Unnamed ID3D12GraphicsCommandList Object', SRV/UAV/CBV Descriptor Heap: 0x0C907578:'Unnamed ID3D12DescriptorHeap Object', Sampler Descriptor Heap: <not set>, Pipeline State: 0x0C906DE8:'Unnamed ID3D12PipelineState Object',  [ EXECUTION ERROR #939: GPU_BASED_VALIDATION_DESCRIPTOR_TYPE_MISMATCH]

```

thus it seems like the method proposed above is definitely not valid.

**Edit 2:**

The correct way is:

```
m_commandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(m_srvBuffer.Get(), D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COPY_DEST));
m_commandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(m_uavBuffer.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE));
m_commandList->CopyResource(m_srvBuffer.Get(), m_uavBuffer.Get()); //Copy the data
m_srvDescHeap->SetRootDescriptorTable(1, m_srvDescHeap->GetGPUIncrementHandle(0));
m_commandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(m_uavBuffer.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS));
m_commandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(m_srvBuffer.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE));

```

# Answer
Seems like your Root signature doesn't contain an appropriate descriptor range for referencing Shader Resource Views in the pixel shader stage. In your case your root signature should contain a descriptor table for compute shader stage, with a descriptor range of type UAV containing register 0. For your pixel shader stage, you need to have a descriptor table with pixel shader visibility flag and a descriptor range of type SRV, containing register 0. You also need to ensure that the heaps contain the same layout as the root signature and populated accordingly.

You also have to use a UAV barrier besides the resource transition from UAV to SRV. That will force the GPU to stall the draw call until your compute shader finished actually writing the UAV and flushing its caches.

It is a good idea to have the debug layer enabled, but I also suggest using a graphics debugger like Nvidia Nsight which can visualize your descriptor heap and interpret them as tables. Visual studio also has a graphics debugger, which you can use out-of the box from the toolbar Debug-\>Graphics-\>Start Graphics Debugging option.

Good luck!
> 1 votes

---
Tags: c++, directx, directx12
---


# Question
Title: Why does my palette swapping code in D3D9 not have any effect?
I want to do palette swapping in my game, in a fast way and without shaders, so I couldn't replace pixels in a texture, then I tried to use the SetPaletteEntries and SetCurrentTexturePalette method, but it's not working.

```
static int counter = 0;

// Palette swapping experiment
PALETTEENTRY entries[256];

if (counter == 0)
{
    // Fill the palette entries with 0xFFFFFFFF
    FillMemory(&entries, sizeof(entries), 0xFF);

    // Set the palette entries in the palette index.
    if (FAILED(window.device->SetPaletteEntries(0, (PALETTEENTRY*) &entries)))
        throw std::runtime_error("SetPaletteEntries()");

    // Set the current texture palette
    if (FAILED(window.device->SetCurrentTexturePalette(0)))
        throw std::runtime_error("SetCurrentTexturePalette()");

    ++counter;
}
///////////////////////////////////////////
else if (counter == 1)
{
    // Fill the palette entries with 0x8080FFFF
    for (int i = 0; i < sizeof(entries) / sizeof(PALETTEENTRY); ++i)
        entries[i] = {0x80, 0x80, 0x80, 0xFF};

    // Set the palette entries in the palette index.
    if (FAILED(window.device->SetPaletteEntries(0, (PALETTEENTRY*) &entries)))
        throw std::runtime_error("SetPaletteEntries()");

    // Set the current texture palette
    if (FAILED(window.device->SetCurrentTexturePalette(0)))
        throw std::runtime_error("SetCurrentTexturePalette()");

    ++counter;
}

```

I'm loading the textures with DDSTextureLoader, and no exceptions are being thrown. Thanks for reading.

# Answer
To use palettes, your texture must be in a "color index" format; that means `D3DFMT_P8` or `D3DFMT_A8P8`. Make sure your textures are being loaded or created in that format.

I recall that this wasn't an overly well-supported format, although perhaps that's changed since I used D3D9 (although I'd be doubtful, because as Chuck Walbourn notes in the comments, later versions of D3D have abandoned them entirely). You should probably be verifying that the format is supported through `CheckDeviceFormat()` regardless.

If the format isn't supported by the hardware you're running on, you'll have to fall back to another approach or emulate the feature somehow.
> 2 votes

---
Tags: directx9, palette-swapping
---


# Question
Title: Running code after after a few minutes of inactivity
I want to implement a logic that will execude after a while when no input was hapend. Like a screensaver that will get started after a few minutes of no mouse input.

Im using libGDX so I think I should use the Timer-Utilities. But this is a principal engine-agnostic question since Timer and Interval Classes exits for most languages and frameworks.

My first idea was to just start a countdown and than check everytime in my game loop if the input-variable has changed. If so I will reset the countdown. But this seems like a big overhead because I have to reset the whole timer in worst cases 60 times per second.

Is their a general pattern for that common problem?

# Answer
> 1 votes
If you need to touch it every update anyway, you could simply store a numeric variable that accumulates deltaTime, or a timestamp of the last input, and reset it each time you get input. Then when it exceeds a given value / given duration from "now," trigger your OnIdle beheaviour.

Timers work well when they're fire and forget - none of your code needs to continually check them until they reach their scheduled moment, outside of exceptional cases when you need to cancel them. For something that updates every frame anyway, they don't give any particular advantage over simply polling.

# Answer
> 0 votes
Resetting timers is expensive! Instead, keep a single timer firing once a second, and have a variable "seconds\_idle" that you increment inside your timer, and can check if \>= 60, and can call your "now idle" logic when needed. When you get input, have your inputs reset that variable back to zero, no timer reset needed. That way you're doing cheap, 32-bit unsigned integer operations, instead of the heavier timer manipulation.

---
Tags: libgdx, architecture, design-patterns
---


title: Unity or Blender like 3D Views

text:
# Question
Title: Unity or Blender like 3D Views
I'm trying to learn the UI part of Unity and the use case I want to achieve is to setup a windowed user interface which looks like Unity or Blender's one (simplified): with one or more 3D views in it + some canvas with 2D GUI.

What I've tried so far is to make it using a canvas with an image in it, which itself has a raw image component. The raw image has a render texture as 'texture'.

But doing that, the texture is stretched when the rect transform of the image is changing. So I don't know how to handle that if the size and position of the view is changing (I've seen the minimap tutorials but here the size is static).

Another way could be to limit one or several main cameras 'viewport rect'.

But so far I don't know which is the best approach in order to set it up efficiently and have no difficulties to handle camera's movements, centered in the view, etc.

What is the good way to do that?

**Edit**: following the advice of DMGregory, it works perfectly

The idea is to update the camera's rect with something like this:

```
var anchorMin = parenRectTransform.anchorMin;
var anchorMax = parenRectTransform.anchorMax;

Camera.rect = new Rect( anchorMin, anchorMax - anchorMin );

```

Here parentRectTransform is the rect transform of the parent of my 3D view, so that the anchor's position and size are relative to the global space (screen).

The other approach using a render texture is not possible as its size cannot be changed at run time (the only possibility was to recreate one each time).

# Answer
Myself, I'd see how far I could get with cameras' viewport rects first. This can avoid some overhead of rendering to a RenderTexture first then displaying it, with all the possible resizing & sample-mismatching issues that can come with that.

Doing it this way, you can also assign UI to each pane by using a Canvas set to "Screen Space — Camera" pointing at the camera for that pane, and it will scale correctly as the viewport changes.

The render-to-texture / display via RawImage method will work too, and will be desirable for certain kinds of effects, but I think it's more complicated than what you're likely to need.
> 1 votes

---
Tags: unity, gui
---


# Question
Title: How to determine polygon, texture size, and frame time budgets for a game on a custom engine?
I'm currently working on a mid-size group of students developing a classic dungeon crawler game using own engine. I have the task to create a document where it tells:

* What polycount and texture size limits artists should have
* How much time each module of the engine should take

I know that this data is not to be exact by any meanings, because priorities would change depending of the needs of the game. I could try to drop some art in a scene, and seeing how much the framerate is impacted. I can take the 16 miliseconds of a 60fps game and distribute them among all modules, trusting my gut.

The problem is that I do not feel as this method is the correct, and I do not found any references of how I could distribute miliseconds (even for a blurry guide to follow), or how I could do some estimation of what limits the art (and the design) should have, based on our tech.

How can I make these estimates?

# Answer
First you have to decide on your targets. For timings, this is usually easy as it's basically a factor of your desired stable frame rate: do you want a stable 30 FPS or a stable 60 FPS? For content it's a little more difficult, as the aesthetic goals of your title also factor into the decision, and the values for polygon count and texture size and so on also factor into your frame time.

But once you've decided on performance and quality bars you want to hit, you can move on to setting the actual details of the metrics. Generally you will do this through experiments. A common technique, for example, is to prototype out a scene that represents the most visually-dense, expensive part of your game.

Does this scene hit your performance targets? If so, great, you can derive your initial asset constraints from the assets used in the prototype. If not, you will have to start profiling the scene to determine what's making you miss your targets, and adjust accordingly.

For timing budgets, you can certainly start by giving every module an equal share of the frame time, although in practice they won't all need it and some will need significantly more (rendering, pathfinding, AI, usually). Profiling your prototypes is a good way to settle on some rough initial ideas for budget.

No matter what you pick, you may want to bias your initial estimates towards the pessimistic side of things to account for the fact that features and content tend to bloat as development goes on.

You will likely need to revise all of these numbers as the project goes on. Optimizations will shave off time in some system that can then be reallocated to the budget of another, or new content production techniques will lead to cheaper models than you had originally assumed, allowing you to spend a few more megabytes on high-impact textures.

The most important thing is to realize it is impractical to decide on all these metrics and guidelines once at the start and stick to them throughout: you will simply not have enough information about the details of your project (and these numbers are heavily influenced by the details of the project, which is why you don't find a lot of specific guidance about selecting them), and things *always* change during development.

So do what you can to make reasonable, evidence-based guesses at the start and use them to guide you gently, not rigidly, through the project as it grows.
> 3 votes

---
Tags: performance-budgeting
---


# Question
Title: player keeps on firing (Javascript + Canvas)
I'm brand new to game development (with Javascript)... I'm pretty sure my question is very simple, but I have a hard time to figure out myself... I'm starting at the very beginning, so this is pretty simplistic.

This is my whole code in javascript:

```
var fire = false;
function keyUp(evt) {
  switch (evt.keyCode) {
     case SPACE:
        fire = false;
     break;
     ...
  }
}
function keyDown(evt) {
  switch (evt.keyCode) {
     case SPACE:
        fire = true;
     break;
     ...
  }
}
function update() {
    ...
    if (fire) {
        playerHasShot = true;
        shot.x = player.x + player.w;
        shot.y = player.y + (player.h / 2);
        shot.vx += 2;
    }
    if (!fire) {
        playerHasShot = false;
    }
   ...
    shot.x += shot.vx;
   ...
    //Bullet
    if (playerHasShot) {
        playerHasShot = false;
    }
    if (!playerHasShot) {
        playerHasShot = false;
    }
    ...
    if (shot.vx > 4) {
        shot.vx = 4;
    }
    ...
    if (shot.x > canvas.width) {
        shot.x = player.x + player.w;
        shot.y = player.y + (player.h / 2);
        playerHasShot = false;
    }
    ...
    render();
    renderShot();
}

```

I hit the spacebar once, and that guy can't stop shooting... Would any of you mind telling me how to stop him, please ? I'm sure I'm close, but there's something I'm missing somewhere.... Thanks! :)

# Answer
If I understand your code correctly, then `fire` appears to be the flag which says if the player pressed space this frame. When that's true, and you want to spawn one bullet each time the player presses space, you need to reset that flag after spawning the bullet.

```
if (fire) {
    /*
    ...code to spawn the projectile...
    */
    fire = false;
}

```

You won't need to do anything in case of a `keyUp` event, because releasing the spacebar isn't doing anything. That event gets interesting when you want autofire (spawining bullets while the player holds down space). In that case you would do `fire = false` in the keyup event instead of your main loop. But your code currently doesn't seem to be designed to handle more than one bullet at a time, so I don't think that this is what you want to do (at least for the moment).

I am not sure what the `playerHasShot` variable is supposed to mean in your code, because while you set and unset it various times, it doesn't seem to actually *do* anything. But I know that this section of code:

```
if (playerHasShot) {
    playerHasShot = false;
}
if (!playerHasShot) {
    playerHasShot = false;
}

```

doesn't make any sense. After the first three lines, `playerHasShot` will be `false` (or at least "falsey" if that variable can have non-boolean values), no matter what value it had before. The last 3 lines won't do anything at all. It literally means "when `playerHasShot` is falsey, set `playerHasShot` to `false`". Those 6 lines could be replace with `playerHasShot = false` and it wouldn't change anything.
> 0 votes

# Answer
Did you try combining both your switch cases. And just add the keyUp and keydown together switch case,instead of having 2 different switches.
> -1 votes

---
Tags: javascript, game-mechanics
---


# Question
Title: Car driving through walls with transform.Translate()
I need help with a script for a very simple car that uses transform.Translate:

```
public class car1 : MonoBehaviour {

    public PauseMenu pause;
    [Space]
    public Car_Script car_s;
    public float speed;
    public GameObject car;

    void FixedUpdate()
    {

        if (car_s.InCar == true)
        {
            if(pause.isPaused == false)
            {
                if (Input.GetKey(KeyCode.W))
                {
                    car.transform.Translate(Vector3.forward * Time.deltaTime * speed);

                    if (Input.GetKey(KeyCode.A))
                    {
                        if (speed <= 0)
                        {
                        }
                        else
                        {
                            if (speed > 0F && speed <= 50F)
                            {
                                car.transform.Rotate(Vector3.down, 2F);
                            }
                            else if (speed > 50F && speed < 90F)
                            {
                                car.transform.Rotate(Vector3.down, 1.3F);
                            }
                            else if (speed > 90F)
                            {
                                car.transform.Rotate(Vector3.down, 0.9F);
                            }

                        }
                    }
                    if (Input.GetKey(KeyCode.D))
                    {
                        if (speed <= 0)
                        {
                        }
                        else
                        {
                            if (speed > 0F && speed <= 50F)
                            {
                                car.transform.Rotate(Vector3.up, 2F);
                            }
                            else if (speed > 50F && speed < 90F)
                            {
                                car.transform.Rotate(Vector3.up, 1.3F);
                            }
                            else if (speed > 90F)
                            {
                                car.transform.Rotate(Vector3.up, 0.9F);
                            }

                        }
                    }
                }
            }
        }
    }
}

```

Whenever I drive the car it immediately goes through walls.

I have colliders on everything. The car has mesh colliders set to convex.

I've searched around quite a bit for answers and it seems that a common one is using rigid bodies. But whenever I even put a rigid body on the car, it flies out into the sky.

# Answer
When you move an object with its transform, you're telling Unity "I don't care about colliders or physics or whatever, just put the object *exactly HERE*" and it will obey, wedging the object right through solid colliders if you tell it to.

If it has a Rigidbody, then on the next physics step the physics engine will try to do its best to clean up the mess, finding some impulse that will take this object (which is ostensibly stationary - it didn't have any forward velocity carrying it into the wall, it just teleported itself there with its transform) and move it outside of the colliders it's penetrating.

If it's really wedged in there, then that impulse can be quite large, resulting in objects launching out out from each other. Or it could get wedged so deep that the smallest impulse that resolves the collision is to push it out the other side, so the object tunnels right through a solid barrier (the physics engine doesn't know this shouldn't be possible, because there's no velocity information telling it which direction the object impacted from, so pushing it out either side seem like equally plausible ways to resolve this teleport)

If the object has no rigidbody, then its movement is not influenced by the physics engine, and no collision police will enforce that colliders should mean anything to it. You're on your own to use the transform responsibly to put the object where you actually want it. If you pass it right through a collider, well, that's what you told Unity you wanted it to do. Who is it to argue?

So, solutions:

1. Add a rigidbody and do not touch its transform. Move it solely via rigidbody methods like AddForce, velocity, AddTorque, MoveRotation, etc.

This way the motion remains under the control of the physics engine and it can stop the object when it begins to hit something and process the collision correctly, rather than doing its best to clean up after a teleportation accident.
2. Keep your transform-based movement, and take on responsibility for avoiding interpenetration in your own script. That may mean casting rays, boxes, or other shapes to determine how far into its motion the object can go before penetrating another collider, and positioning it at the nearest non-intersecting point.

This gives you complete control of its physics if you want it to behave in ways the normal physics sim does not out of the box (eg. if you want something exaggerated & cartoony), but it can increase the complexity of your code if you need to model more complicated physical interactions yourself, like the torque from striking a wall corner-on, or the push imparted to a pile of debris objects as you try to drive through them.
> 8 votes

---
Tags: unity, collision-detection, physics, vehicle
---


# Question
Title: Can I use a no longer protected by copyrights game's sprites?
I've been looking around but couldn't really find anything conclusive. First of all, as the title says, in case a game's copyrights expire can I use its sprites for my own game and claim copyrights?

Secondly, how do I *know* a game's copyrights have expired? In my particular case I'm interested in ***this*** game's sprites, the website is entirely in Japanese and due to their sole use of images with text, I cannot translate it. Can't seem to find any information regarding its copyright anywhere.

Thanks for your time.

# Answer
> 2 votes
*Disclaimer: This is not a legal advice site. I am not a lawyer. For a definitive legal advice, hire one.*

> \[...\] in case a game's copyrights expire can I use its sprites for my own game and claim copyrights?

As far as I know, copyright laws around the world protect content for so long that any digital game that has ever been created is still protected.

If you think the copyrights have expired "because the company who made it was shut down", think again: the company's IPs have probably been transferred to another company, or a bank that seized their assets. Unless the company has explicitly stated that they give up copyright and made their assets available to public domain, you can't assume the copyright has expired.

Also you have to keep in mind something: even if the game copyrights have expired, if the characters are still used somewhere else, they are probably *trademarked*, which would still prevent you from using the sprites of the characters.

> Unlike copyrights, which do have dates of expiration, company trademarks are valid for as long as the company uses those trademarked items commercially. \[ref\]

So it's not just a question of "copyright expiration".

> In my particular case I'm interested in this game's sprites \[...\]

In this case, even if the copyright has expired, since it's a Nintendo DS exclusive, I would guess that you still can't use the data, because it would imply that you use the software or the hardware in a way not authorized by the EULA.

> Secondly, how do I know a game's copyrights have expired?

You ask the last copyright holder :) Depending on the company, however, you'll probably have to hire a layer to ask them, because their legal departments won't waste their time with non-layers. (From a webinar with a game-industry lawyer, companies like EA will ask you "Are you a lawyer?" as their first question. The source for this is here. The rest of the video is quite interesting.)

It does not cost you anything just to try and talk with them. Depending on the company (and *your* company) you could work a deal or something.

---

Now, this is assuming that the copyright holder has not released their material to public domain.

I guess that if they said "We're done with the franchise, here are the assets, do what you want with it, good luck and have fun", you probably could use the sprites.

# Answer
> 1 votes
This is no legal advice. However: Copyright expires about 70 years after the death of the author (exact time frame depends on your country, it goes up to 95 years). For any computer stuff that is unlikely to be the case anytime soon.

So... you won't find sprites where the copyright expired.

You may find sprites where the license allows usage. That can be that the completely free-to-use ones like public domain or WPL, or slightly more restrictive ones like some flavours of the creative commons one.

In any case: read the license terms carefully! No license terms mean NO PERMISSION whatsoever. You'll have to ask in those cases. And asking doesn't hurt either in the cases where a license is stated explicitly as well. Authors usually can license their stuff however they see fit - and the conditions may vary depending on who asks and for what purpose.

# Answer
> 1 votes
The following is not legal advice. If you would like to verify the situation, you must speak with a lawyer who specializes in copyrights.

**Short answer:** Possibly yet not likely.

**Long answer:**

If a game is no longer under copyright, a person very well can use it how they want, ***HOWEVER*** Stories, characters, and the likeness of an individual can carry copyright for a far longer period of time than the original product.

The prime example everyone is Mickey Mouse. Mickey Mouse made an appearance in the early 1900's. After a great deal of time, Mickey was looking at hitting the public domain and out of copyright protection. Their lawyers had made a bill which was eventually made into law to extend copyright. There are however a few exceptions that can take this a step further.

Corporations are able to sue governments for unjustified laws that cause the corp to lose money without a justified reason. If a character belongs to a company, their more than likely going to fight tooth and nail to keep their character privately owned for financial reason, and to preserve their characters from being put in explicit or demeaning situations.

If you do end up using the character, and your game doesn't launch on a large scale, your possibly going to go under their radar if the company is still around. However if your game gets a decent level of success for the indie world, the company will likely want restitution. Try to stay original as people don't like knock offs, regardless of which country your in.

# Answer
> 1 votes
Several points to keep in mind:

1. Copyright is awarded automatically these days. While some countries let you register for Copyright and many companies apply a Copyright notice, to make litigation easier, all it takes for something to be copyrighted is to make it. (unless you're in one of the countries that didn't sign the Copyright treaty, like Eritrea or Iran)
2. Copyright usually ends 70 years after the death of its author (in some countries, longer, for some very old stuff that was awarded Copyright retroactively, a bit shorter). If something's Copyright says a number higher than 1947, it's unlikely that its copyright has *expired* already.
3. If there is no note that says that something is free to use explicitly, it is Copyrighted. Theoretically, an author can also verbally tell you "sure, use this as you wish", but as they so facetiously say "a verbal contract isn't worth the paper it's written on." How would you prove in court that they ever said that, if they forget and sue you? How would you know what rights they assumed you'd be exercising?
4. Copyright explicitly includes creating derivative works of the copyrighted work. As such, you can not make works based on someone else's and just modify it and claim it as your own.

There are a limited number of circumstances where you can use copyrighted works you don't own: Some countries have "fair use" (mostly for press and quoting purposes), and there is also parody, but these are kind of hard to rely on, as each country defines their limits a bit differently. In any way, if you're making a game similar to an existing one, or a totally different game with the same graphics, chances are you aren't making a parody.

So in your particular case, it's pretty much impossible, as it's unlikely your game sprites are from a game that was made less than 10 years after the first computer was created.

NB - I am not a lawyer, this is not legal advice.

---
Tags: sprites, copyright
---


title: Issue with OpenGL texture rendering

text:
# Question
Title: Issue with OpenGL texture rendering
I am developing a game in Java using LWJGL2 and Slick, and I am encountering an issue when rendering a graphic. Instead of filling the quad with the texture, it appears to be partly repeating it. The image is simply a white box, but this is how it is appearing when the program is run:  I am loading the image using Slick:

```
this.texture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("Res\\image.png"));

```

and I am using this code to render it:

```
texture.bind();
GL11.glBegin(GL11.GL_QUADS);
            GL11.glTexCoord2f(0,0);
            GL11.glVertex2f(position.x,position.y);
            GL11.glTexCoord2f(1,0);
            GL11.glVertex2f(position.x + size.x,position.y);
            GL11.glTexCoord2f(1,1);
            GL11.glVertex2f(position.x + size.x,position.y + size.y);
            GL11.glTexCoord2f(0,1);
            GL11.glVertex2f(position.x,position.y + size.y);
    GL11.glEnd();

```

If I remove all the code for textures and just render a coloured quad, it displays as expected. Could you please point me in the right direction as to where I am going wrong?

# Answer
> -2 votes
I'm aware that this is not exactly the answer to your question, but it can lead you to the solution of your problem.

As @Bálint mentioned in the comments section, you shouldn't use legacy OpenGL anymore, which are all version before OpenGL 3.0. Although the OpenGL 2.0 was the first version to switch from Fixed Function Pipeline to Programmable Pipeline, it was the OpenGL 3.0, that marked Fixed Function Pipeline and most of the previous OpenGL functions and constants as deprecated, thus, really switching into the modern standard graphical API.

I strongly encourage you then, to also switch from the old OpenGL into the modern one. There are a lot of good tutorials on the internet regarding modern OpenGL.

One of them, that I find really interesting and essential is this YouTube series created by **ThinMatrix**. He introduces all of the modern OpenGL aspects in the easy and transparent way and he uses Java and LWJGL. (And he also of course shows how to use textures! :) )

I also recommend these tutorials. Although they are written using C++, the idea of the OpenGL constructs remains the same regardless the language.

Modern OpenGL might look a little bit overwhelmingly at the beginning, compering to legacy OpenGL, but as you follow the learning process, you'll find it fun and - most importantly - you will find a lot of advantages in using Modern OpenGL over the old one.

Also, if you'd like to read more about differences in OpenGL versions and about OpenGL itself, I recommend these links:

1. https://www.khronos.org/opengl/wiki
2. https://www.khronos.org/opengl/wiki/Legacy\_OpenGL
3. https://glumpy.github.io/modern-gl.html

I hope it helps you somehow and that the community won't eat me because of not directly answering your question.

Good luck!

---
Tags: opengl, java, graphics, lwjgl, slick
---


title: Ternary conditional in behaviour trees?

text:
# Question
Title: Ternary conditional in behaviour trees?
When designing a behaviour tree that controls an agent, is it possible to construct the tree so that the agent first attempts task A, then depending on whether task A succeeds it attempts either task B or task C? That is, if A succeeds, the agent attempts task B, otherwise it attempts task C? Kind of like the ternary conditional operator?

The following may at first glance seem to work:

```
* Selector
|
+---* Sequence
|   |
|   +---* A
|   |
|   +---* B
|
+---* C

```

or equivalently, `Selector(Sequence(A, B), C)`. However, if A succeeds and B fails, the sequence will still fail and C will be attempted (which it shouldn't since A succeeded).

This tree does run B if A succeeds and C if A fails and never runs both B and C:

```
* Selector
|
+---* Sequence
|   |
|   +---* A
|   |
|   +---* B
|
+---* Sequence
    |
    +---* Inverter
    |   |
    |   +---* A
    |
    +---* C

```

or equivalently, `Selector(Sequence(A, B), Sequence(Inverter(A), C))`. This is assuming that A yields the same result both times (oterwise either none of B and C will be attempted, or both will be attempted). However, this has the issue that will be attempted A twice if either either A or B fails.

What I want to achieve could be pseudo-coded like `A ? B : C` or like `B if A else C`. Can this be achieved with a behaviour tree?

# Answer
When you don't care about whether the whole subtree returns success of failure, then you could use the first version and wrap B in a Succeeder (a decorator which replaces the return value of its child with success):

```
* Selector
|
+---* Sequence
|   |
|   +---* A
|   |
|   +---* Succeder
|       |
|       +---* B
|
+---* C

```

That way C won't be executed no matter if B succeeds of fails. The problem with this is that the tree one layer above this branch won't be informed correctly about whether B succeeded or failed.

You could also solve this issue by adding the ability to set and check variables to your behavior tree system:

```
* Selector
|
+---* Sequence
|   |
|   +---* A
|   |
|   +---* Set ( "aSuccess", true )
|   |
|   +---* Fail
|
+---* Sequence
|   |
|   |---* Check ( "aSuccess", true )
|   |
|   |---* B
|
+---* C

```

Introducing variables can make behavior trees much more powerful. But be careful to not overuse them, or you will start to lose many of the advantages of behavior trees like re-usability and readability.

And last but not least, there is of course always the option to invent your own nodes. When you really want that `IfThenElse` composite node, just create it. It's far from the weirdest thing I have seen in behavior tree systems.
> 2 votes

---
Tags: behavior-tree
---


# Question
Title: algorithm for Shooting objects that bounce off the wall
I'm trying to make a 2D game where my Hero is standing in a 2D plan and surrounded by enemies(highest 3) that throwing balls. and my hero have a shield in hands and and will stop the balls...

well the problem is i'm not able to found the direction on which enemy shoot the ball to reach to the Hero... i want to make enemy little bit smarter so they don't just shoot straight

as in picture the ball can bounce of the wall same as light bounce off wall, the indecent angle and refractive angle will be same(sorry image angles not perfect. i draw them in paint) so i know that slop of this path line will be same in whole path just interchange in negative and positive.

now i want to find the directions in which i can shoot like 2 coordinates of x,y or something where i can shoot and the ball reaches to the hero.

i not want just one direction... i want the all possible directions where my enemy can shoot and that hit to the hero

and also the ball will be gone after 4-5 times bounce

there is an android game "Stupid zombies" that have exactly this kind system in game

any algorithm and solution to archive this....i'm working in java so later i can port my game to android easily

i also tried below link but my ball hitting more then 2 times and i'm not able to find solution https://softwareengineering.stackexchange.com/questions/290628/algorithm-for-calculating-a-bullet-path-to-a-target-with-max-2-ricochets

please edit if you found anything not properly asked ...i tried to make as simple as possible, but its my first time here.

# Answer
A cool trick you can use for this kind of planning is to imagine what your world would look like if all 4 walls were mirrors.

Like the infinite hall of mirrors effect, you'd see infinite copies of your source and target object, tiling the infinite 2D plane...

The cool thing is that a straight line from your source object aiming at *any* of these mirrored copies of your target will map to a ricochet trajectory that will hit the original.

So, you can iterate over each adjacent mirrored copy of your play field out to some radius, and aim at the reflection of your target in that copy.

To be safe, you should test this line against copies of your source & target object in each cell the line passes through, to make sure you don't pick a trajectory that bounces back through yourself.
> 3 votes

---
Tags: path-finding
---