title: Why PHP over C# for PBBG?

text:
# Question
Title: Why PHP over C# for PBBG?
I am a C# developer and wanted to start a hobby project building a persistent browser based game (PBBG). I work with C#, MSSQL and Angular and thought I would use those techniques for my hobby project as well.

When I started to search for do and donts and tips I realized that a lot of projects use PHP and I have actually not found any PBBG using C#, which I find really strange. It seems as the stack I'm working with (C#, MSSQL, Angular) could suit a PBBG.

The only reason I can think of C# not being used is the hefty price of Visual Studio and the fact that it wasn't open source.

Is there any other reason, or am I just bad at finding projects which use C#? Or can it be that I'm just bad at my work and don't realise that this stack is not good for PBBG?

# Answer
> 16 votes
PHP has the advantage that it is very widely supported by cheap webhosters. You can rent some shared-hosting LAMP (Linux, Apache, MySQL, PHP) webspace for peanuts. And that webspace can also host your website and the game client. The setup of most PHP applications is equally easy. Just copy the files to the webserver and you are done. This makes it very easy and convenient to get a testserver running.

A C# gameserver, on the other hand, can be more complicated. You need to rent an actual rootserver, which is more expensive and requires far more work and know-how to set up and maintain properly. You didn't write if C# means an ASP.NET application running on a webserver (a pretty straight-forward solution for a PBBG if you ask me) or a C# standalone application running as a separate process (a bit unorthodox, but might work quite well if you have a more action-oriented game). If you mean the latter, you *also* need to install or rent a webserver for hosting your website and the client-sided parts of your game.

That additional overhead can be a barrier for most hobby developers, which can be a good reason to pick PHP. But when a hobbyist is successful with their game and decides to do this professionally, they already have their existing codebase and certainly won't start from scratch. So they will keep their LAMP technology stack even though their initial concerns for picking it aren't valid anymore (when you are running a serious operation on a LAMP stack you will sooner or later hit a point where shared hosting does not cut it anymore and you need your own servers).

But remember that if you look at the total project cost of developing a PBBG, then you will usually notice that the costs for server hosting and administration during the development phase are just a tiny fraction of the development budget.

So your decision which technology to use should be driven by which technology allows **you** to create the best game in the least amount of time. Picking the best tools money can buy (best for *you and your project*) does not cost you money, it saves you money.

# Answer
> 5 votes
The other answers are correct, but there's a historical factor that hasn't been mentioned.

> When I started to search for do and donts and tips I realized that a lot of projects use PHP and I have actually not found any PBBG using C# which I find really strange.

Until a couple years ago, there was a PBBG development community that mostly existed on two forums: BBGameZone and MakeWebGames, both predominately filled with PHP programmers. Newcommers who didn't know how to make a game were pointed over to the awesome tutorials at BuildingBrowserGames.com which was all in PHP. The "PBBG" term comes mostly from games made by folks connected to these two forums, there was an effort to popularize the term so that the genre would have a recognizable name that players could search for and hopefully slow down the decline of the genre, it's no wonder if you're only getting PHP when you search the term.

> It seems as the stack Im working with (C#, MSSQL, Angular) could suit a PBBG.
>
> The only reason I can think of C# not being used is the hefty price of Visual Studio and the fact that it wasn't open source.

I think you're 100% fine to go ahead with using C#, MSSQL and Angular. You'll find that most of the PHP engines are outdated PHP4 or PHP5.

The BBGameZone folks were mostly against using engines (everyone was writing their own engine, including me) There was an effort by the MakeWebGames people to get new PHP engines in place (McCodes being their main old engine and NWE (New Worlds Engine) being regarded as the probable new one that was half-way done)

Here's a Google doc with an engine comparison from a few years ago, comparing McCode / NWE / ezRPG / GL Script: https://docs.google.com/spreadsheets/d/1WM3axFhYaAtjiKd1KRwibx9jEegwjwCJNhQmXP\_jzss/pub?single=true&gid=0&output=html

There have been past efforts to put the old community back together, but not much luck so far: https://www.reddit.com/r/PBBG/comments/6r34vi/announcing\_pbbgsite/

---

I think you'll be 100% OK going forward using a C#, MSSQL, Angular stack, just remember that you're probably the first person writing a PBBG with your toolchain and you'll have to create everything yourself without any past examples to look back on.

Just remember that the genre is dying right now, but all it needs is one or two popular games to revive itself, if you think you can do that in C# I'll be rooting for you.

# Answer
> 1 votes
* Browser based games rose at a time when C# wasn't very popular, but PHP was. So many projects are done in that languages, many tutorials were written for that language and many experts in such games have adopted PHP as their main language and thus choose it by default,
* PHP is seen as a language that scales easily from small to mid-size applications, while C# (and Java) is often seen as comparatively heavy-weight languages suitable for large business applications; most PBBG would fall into the small to mid-sized project category (at the very least initially/the core game concept without accumulated code-trash).
* LAMP servers were easy to have, many hobby devs simply had one anyway, C# servers were more expensive; this still holds to some degree but not that strongly anymore
* PHP may feel like it fits the job better: it is designed to respond to a web call with HTML based content/data, exactly what you need for the backend of a browser game (depending on the fanciness level); C# can do that too, but may feel more bloated (or powerful),
* it was and probably is easier to get cheap PHP programmers than cheap C# programmers, this falls in line with PHP being easy "to get into" thus often the goto language to quickly get some basic "website thingy" up and running (and then just extend that prototype instead of reconsidering your technology for the long run and replacing it)
* games are often quick shots, developed, publicly tested, then either a success or discarded; again, this ties in with the image of PHP to be comparatively good to get something running quickly

Opinionated Summary: If you don't know any (suitable) language (well enough), I'd assume you get "something" up and running faster with PHP. But if you already know a suitable language like C# and how to setup a server/backend with it, this will not apply (unless if you want to use a particular engine in that language). This prototyping advantage of PHP may also be non-existing the more complex/statefull your game will be.

---
Tags: c#, browser-based-games, php
---


title: efficient 2D light source

text:
# Question
Title: efficient 2D light source
I wanted to add a light source for a project I'm working on, and luckily I had some code based on this article: http://ncase.me/sight-and-light/, but when I ran the code after carefully transplanting it I realized my implementation of lighting was really slow. In the previous project I only ever had to worry about a few polygons at a time, but in my new project there are a metric ton of different polygons that the ray caster is checking against. I can avoid testing every ray against every polygon side.

# Answer
> 1 votes
Optimize using a quadtree so that you only need to check a few polygons instead of all of them.

https://gamedevelopment.tutsplus.com/tutorials/quick-tip-use-quadtrees-to-detect-likely-collisions-in-2d-space--gamedev-374

Edit: Okay, I'll admit I didn't read that well and made a mistake.

Light paths are pretty much the same as lines of sight of a viewer, so many of the same algorithms related to rendering should apply.

One way I can think of is to test only the polygons visible in the screen, and sort them all from closest to furthest each time the viewer moves, preferably using an insertion sort as it's fastest with almost sorted arrays. Test polygons from front to back, while keeping a record of how much of the 360 degree domain around the light has been tested. When all of the domain has been tested, then stop looping through the polygons.

Additionally, only test the lines where the face is visible in the light. This is exactly the same as determining whether a point is on the left or the right of a line, discussed on the link below. This also means the order of the points on the polygon must be consistent, such as going clockwise.

https://stackoverflow.com/questions/1560492/how-to-tell-whether-a-point-is-to-the-right-or-left-side-of-a-line

Another way, probably the most efficient way possible, is to use binary space partitioning. I'm not very familiar with it, and I haven't seen it used specifically in 2D lighting. In old games like DOOM, which is actually a top down 2D shooter on the inside, it is used to determine which faces should be drawn without looping through every face. I am probably not able to explain this properly, so here's a few links.

https://www.youtube.com/watch?v=yTRzfKh4Tg0 https://en.wikipedia.org/wiki/Binary\_space\_partitioning

---
Tags: algorithm, lighting, raycasting
---


# Question
Title: How do you make top down tileable mountain ranges like fire emblem?
TL;DR: my goal is to gain the knowledge necessary to make these kinds of mountains from scratch.

Hello all,

sorry if this has already been asked, and sorry for any incorrect grammar.

I've been searching hard all over for tutorials and dissecting tilemaps but i just can't figure out how to actually go about making an original tileable mountain range.

some examples of what I'm trying to figure out;

first, a fire emblem map, this is ideal for the kind of maps i want to make for a project, but it just doesn't make sense to me how it looks so damn great and is tileable.

second is the same map tiles, dissected to 16x16 tiles;

doing this helped me find that the maps are not the normal 16x16 i thought they where, only increasing my confusion as to how the original arts started making them...

and third; the same 16x16 tileset, now dissected to 8x8 tiles... now its basically to small for me to make heads or tails of it, spent a few hours trying to put them together like a puzzle, but i can only make small mountains when the tiles are... so indistinguishable to me. I'm just still having a hard time understanding how they tile to extend into large mountain ranges.

if anyone has experience or input or even tutorials, just anything, I'd really appreciate it

# Answer
> 3 votes
I've found this tutorial (scroll down to *Exhibit C: Mountains*). It appears that Fire Emblem does use regular tiles for mountains, but there are many different types of mountain tiles and rules you must follow to make them look good.

Here are the mountain tiles:

I assume you know all about transition tiles. That's a given for these mountain tiles, to transition between the grass and mountains, but there are additional tile types for mountains.

If you look carefully, the mountains in Fire Emblem form ridges that go from North to South. The light shines from left to right, so the left-slope is bright and the right-slope is dark. There are *ridges* that transition from a left-slope to a right-slope. Putting the three together, you get something like this:

In addition to ridges, there are *valleys*, which transition from right-slopes to left-slopes. If we add a column of valleys and an additional column of ridges, we get this:

Here's the tricky bit: there are different types of ridge and valley tiles, ones that move the ridge/valley to the left, middle, or right. Mix it up a bit and you can get something like this:

If you look carefully, there are three ridges here, but it looks like the first two merge near the top. You can use *peaks* to provide that illusion, or to break up a ridge. Here are the peak tiles:

Finally, make sure you have variations for each tile type. This helps break the seams and provide the illusion that they are not made of tiles.

That's how Fire Emblem does its mountains; you could come up with your own system to do ridges that go from East-to-West, or maybe a more complicated one for mountains that could go every which way.

# Answer
> 1 votes
I don't know how Fire Emblem did it, but Battle for Wesnoth uses what they call "multi hex" to build mountain ranges.

From https://wiki.wesnoth.org/MultiHexTutorial (note that Wesnoth uses hexagonal tiles)

> Suppose there are these mountain tiles, where the edges are designed to produce no seams:
>
> A larger patch of mountains can be formed by fitting these tiles like a jigsaw puzzle:

It's possible that Fire Emblem used the same technique, although it's hard to identify what tiles they've used. To me that shows its high quality of artwork.

---
Tags: 2d, pixel-art
---


# Question
Title: Game not responding on different computer with Intel graphics
I have a game that uses SDL2 and OpenGL 3.3 with Visual Studio. It runs fine on the computer that built it, but it did not work on other Windows computers.

Initially, it would complain about missing DLLs from the VC++ runtime. I solved the first issue by statically linking the runtime libraries into the EXE.

However, the second issue was that the program freezes right before it could call OpenGL functions to generate vertex buffer and vertex array objects. Of note, not all of the OpenGL functions freeze the program, since glClear appears to work.

I then noticed that some computers with dedicated graphics cards and up-to-date drivers can successfully play the game, but the computers with integrated graphics cards such as Intel HD 4000 still froze up in the same place. This is puzzling, since the specifications for Intel HD 4000 state that OpenGL 3.3 should be supported.

The computers I have tested with all managed to generate an OpenGL context with SDL2 and load OpenGL functions with GL3W without any errors, though some of the unsuccessful ones had a zero-bit depth buffer.

Does anyone know what might be causing the issue?

# Answer
> 3 votes
After I gave my rendering code another look, I noticed that I was using gl**Create**VertexArrays and gl**Create**Buffers instead of gl**Gen**VertexArrays and gl**Gen**VertexBuffers.

While they do the same thing, glCreateVertexArrays and glCreateBuffers were introduced in OpenGL 4.5, which is why my program choked on hardware that did not support that version of OpenGL. Since I am targeting OpenGL 3.3, that is a problem.

After replacing those two function calls, my code runs on the Intel graphics cards just fine.

---
Tags: opengl, sdl2, visual-studio, intel
---


# Question
Title: Serialize classes based on Generics. Is it different?
I have a certain `ScriptableObject`.

```
public class Biome : ScriptableObject { ... }

```

If I write the following in a component:

```
public List<Biome> list1;

```

This is what appears in the inspector:

So far so good. But if I try to make my list more generic, like this:

```
public class DistributedList<T>
{
    public List<T> items;
}

[System.Serializable]
public class BiomeList : DistributedList<Biome> { }

```

This is what I get on the inspector:

All I can seem to be able to add now is just a name, not the Object itself.

Why is this?

# Answer
Unity can't serialize classes that have generic fields. So while it can serialize your list of biomes, it cannot serialize a class containing a `List<T>`.

https://blogs.unity3d.com/2014/06/24/serialization-in-unity/

One of the solutions here may help you: https://answers.unity.com/questions/460727/how-to-serialize-dictionary-with-unity-serializati.html
> 1 votes

---
Tags: unity
---


# Question
Title: SDL_image entry point SDL_acosf not found in SDL2_image.dll
I tried using SDL2\_image (2.0.3) with SDL2 (2.0.7) to load png files, but when I start the application I get

```
SDL_image entry point SDL_acosf not found in SDL2_image.dll

```

This even happens when I just include SDL\_image.h without actually using any of it\`s functionality.

I\`m using x86 versions of both libraries. Dlls are in SysWOW64. Compiling with VS 2017.

What am I missing?

Update: This happens when I link against SDL2\_image.lib. I don't even need to include SDL\_image.h. Also SDL\_acosf doesn't seem to exist in SDL2 or SDL2\_image.

thanks

# Answer
OK I got it. Apparently I missed the release of SDL2 2.0.8 which has SDL\_acosf.
> 1 votes

# Answer
I had the exact same problem. It was solved by copying the .dll files from SDL2 and SDL2\_image into system32 (and the x86 versions into SysWOW64.)
> -1 votes

---
Tags: sdl2, visual-studio, dll
---


# Question
Title: Why does launching an object using Rigidbody2d.velocity not work properly
I am currently trying to launch a gameobject using Rigidbody2d.velocity but whenever I launch it goes backward instead of forwards. I have already tried making the vector 3 that I am using negative, but nothing seems to work. Please help as I don't even know why this happening.

**Here is my code**

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

public class ArmPower : MonoBehaviour {

    //Priority Script

    public ArmAngle armAngle;
    public bool allowLaunch = false;
    public GameObject armPowerSlider;
    public bool ifLaunched;
    public GameObject armPowerPhone;
    public StartAllowStrengthPower startAllow;
    public PhoneController armPhoneController;

    // Use this for initialization
    void Start () {
        armAngle = FindObjectOfType<ArmAngle>();
        armPowerSlider = GameObject.Find("PowerSlider");
        ifLaunched = false;
        armPowerPhone = GameObject.Find("Phone");
        startAllow = FindObjectOfType<StartAllowStrengthPower>();
        armPhoneController = FindObjectOfType<PhoneController>();
    }

    // Update is called once per frame
    void Update () {
        if (allowLaunch)
        {
            LaunchPhone( (int) (Mathf.Round(armPowerSlider.GetComponent<Slider>().value) ));
            ifLaunched = false;
        }
        if(startAllow.allowLaunchChanger <= 0)
        {
            LaunchPhone((int)(Mathf.Round(armPowerSlider.GetComponent<Slider>().value)));
        }

    }

    public void LaunchPhone(int launchAmount)
    {

        Vector3 launchValue = new Vector3(armPowerPhone.transform.position.x, launchAmount, armPowerPhone.transform.position.z);

        armPowerPhone.GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Dynamic;

        armPowerPhone.GetComponent<Rigidbody2D>().velocity = launchValue;

        armPhoneController.armAudio.Play();

        armPowerPhone.transform.SetParent(null);
        armAngle.allowStrength = false;
        allowLaunch = false;
        ifLaunched = true;
        startAllow.allowLaunchChanger = 5;

    }
}

```

# Answer
> 1 votes
It looks like here you are trying to set up a velocity vector:

```
Vector3 launchValue = new Vector3(armPowerPhone.transform.position.x, launchAmount, armPowerPhone.transform.position.z);

```

But you are putting in the absolute position of the GameObject for the x and z components of the velocity, which doesn’t make sense in this context, I think. Try just using zeros.

```
Vector3 launchValue = new Vector3(0, launchAmount, 0);

```

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


title: How to use Glide

text:
# Question
Title: How to use Glide
I want to implement glide in my game but I don't know how. I know that the Glide format is:

`Glide.with(context).load(R.drawable.image).into(imageView);`

But I don't understand how to implement it in my game.class

Game.class:

```
public class Game extends SurfaceView {

    Player player;
    Paint paint;
    Bitmap image_player;

    public Game(Context context, AttributeSet attrs) {
        super(context, attrs);

        paint = new Paint();
        image_player = BitmapFactory.decodeResource(getResources(), R.drawable.player);
        player = new Player(this, image_player);
    }

    public void onDraw(Canvas canvas) {

        paint.setColor(Color.BLACK);
        canvas.drawRect(0, 0, canvas.getWidth(), canvas.getHeight(), paint);

        player.onDraw(canvas);
        invalidate();
    }
}

```

Player.Class:

```
public class Player {

    private Game game;
    private Bitmap player;
    Paint paint;

    int x, y, start = 0, width, height, currentFrame = 0,Horizontal = 1, Vertical = 8, frameLengthInMilliseconds = 150, cantFrames = 8;
    long fps, timeThisFrame, lastFrameChangeTime = 0;

    public Player(Game juego, Bitmap player){

        this.game = game;
        this.player = player;
        this.width = player.getWidth() / Vertical;
        this.height = player.getHeight() / Horizontal;

        paint = new Paint();
    }

    private void update() {

        long startFrame = System.currentTimeMillis();

        if (startFrame > lastFrameChangeTime + frameLengthInMilliseconds) {
            lastFrameChangeTime = startFrame;
            currentFrame++;
            if (currentFrame >= cantFrames) {

                currentFrame = 0;
            }
        }

        long startFrameTime = System.currentTimeMillis();

        timeThisFrame = System.currentTimeMillis() - startFrameTime;
        if (timeThisFrame >= 1) {
            fps = 1000 / timeThisFrame;
        }
    }

    public void onDraw(Canvas canvas) {

        update();

        int srcX = currentFrame * width;
        int srcY = height * start;

        x = canvas.getWidth()/2;
        y = canvas.getHeight()/2;

        Rect src = new Rect(srcX, srcY, srcX + width, srcY + height);
        Rect dst = new Rect(x, y, x + width, y + height);

        canvas.drawBitmap(player, src, dst, null);
    }
}

```

XML:

```
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.example.agusv.MyProject.Game
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/transparent"/>

    </android.support.constraint.ConstraintLayout>

```

# Answer
> 1 votes
glide is used to set the image on an `ImageView`

you need to define an image view in your layout

```
<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageView">
</ImageView>

```

and then you can set an image on this image view using glide:

```
ImageView imageView = (ImageView) findViewById(R.id.imageView);
Glide.with(this).load(R.drawable.image).into(imageView);

```

there's a more detailed explanation on this page

---
Tags: android, android-studio
---


title: Encapsulating parameterised prefabs

text:
# Question
Title: Encapsulating parameterised prefabs
I'm currently using the following general pattern for most of my configurable components (i.e. `MonoBehaviour`s):

```
public class MyComponent : MonoBehaviour
{
    // Configurable fields
    [SerializeField]
    private bool someParameter;
    [SerializeField]
    private int anotherParameter;

    // Fake constructor to act as a replacement for GameObject.AddComponent
    // with additional parameters.
    public static MyComponent AddTo(GameObject gameObject, bool someParameter, int anotherParameter)
    {
        var myComponent = gameObject.AddComponent<MyComponent>();

        myComponent.someParameter = someParameter;
        myComponent.anotherParameter = anotherParameter;

        return myComponent;
    }

    // Public properties and other methods
    // ...
}

```

This works around the lack of constructors for `MonoBehaviour`s but still encapsulates the parameters in such a way, that they can only be set at the time the object is created, or through the Inspector (which is effectively the same thing once the game is built).

Unfortunately, this approach doesn't help once I want to use my component inside a prefab. When I instantiate the prefab, the component has already been created, and I can no longer touch those parameters. And as far as my google-fu can tell, there's no way to pass parameters into prefab instantiation (much like there isn't a way to pass a parameter into `AddComponent`). It seems like everyone just instantiates their prefabs and then fiddles with some public properties to configure them.

So the question is, is there any way to set things up, such that I can configure some fields on my prefabs, but *without* exposing them publicly and breaking encapsulation?

(I realise that I could add a similar static "factory" method which instantiates a specific prefab and then configures the component inside that prefab, but a) this means adding one such method for each prefab and b) it breaks down once I want to configure multiple components within the same prefab.)

# Answer
A naive (simple) approach would be to simply have an object which encapsulates the state you want and store it in a static field, then access that field in `Awake`.

```
    public class MyComponent : MonoBehaviour {
      [SerializeField]
      private bool someParameter;
      [SerializeField]
      private int anotherParameter;

      public class InitInfo {
        public readonly bool someParameter;
        public readonly int anotherParameter;
        public InitInfo(bool someParameter, int anotherParameter) {
          this.someParameter = someParameter;
          this.anotherPatameter = anotherParameter;
        }
        void Apply(MyComponent c) {
          c.someParameter = someParameter;
          c.anotherParameter = anotherParameter;
        }
      }
      public static InitInfo OnAwake;

      //note: you may be able to use the constructor instead of Awake,
      //but you must not interact with Unity in any way (eg instantiating
      //other objects, modifying the
      //transform, adding other components, calling Mathf.Random,
      //etc.) because this may be called on another thread.
      //Assigning a few fields should be fine though.
      //public MyComponent() {

      void Awake() {
        if (OnAwake != null) {
          OnAwake.Apply(this);
          OnAwake = null;
        }
      }
    }

```

and elsewhere:

```
  MyComponent.OnAwake = new MyComponent.InitInfo(true, 5);
  Instantiate(myPrefab);

```

Although this breaks down if you want to configure multiple instances of the same component type within the prefab. I’m not sure if that’s what you were referring to when you were talking about configuring multiple components?

Other options include using `BroadcastMessage` to send the information in after instantiation is complete, or a callback where the caller registers a special method to be called in `Awake`, passing in the current component, and returning the data necessary, although these are just variations on the same theme.

For example:

```
    public class MyComponent : MonoBehaviour {
      [SerializeField]
      private bool someParameter;
      [SerializeField]
      private int anotherParameter;

      public class InitInfo {
        public readonly bool someParameter;
        public readonly int anotherParameter;
        public InitInfo(bool someParameter, int anotherParameter) {
          this.someParameter = someParameter;
          this.anotherPatameter = anotherParameter;
        }
        void Apply(MyComponent c) {
          c.someParameter = someParameter;
          c.anotherParameter = anotherParameter;
        }
      }
      public static Func<MyComponent, InitInfo> OnAwake;

      //public MyComponent() {
      void Awake() {
        if (OnAwake != null) {
          OnAwake(this).Apply(this);
        }
      }
    }

```

and elsewhere:

```
  int i = 0;
  MyComponent.OnAwake = c => new MyComponent.InitInfo(true, i++);
  Instantiate(myPrefab);
  MyComponent.OnAwake = null;

```
> 0 votes

---
Tags: unity, architecture, design-patterns
---


title: Separate objects for hitbox and sprite?

text:
# Question
Title: Separate objects for hitbox and sprite?
I am making a technically top down game with a shifted perspective. It shows more of the characters side, not just above their head. I think most "top down" games have a similar art style.

Due to this, only the bottom of the character sprite should collide and interact with game objects. Should I use two separate objects for the hitbox and the sprite? It seems inefficient to do this. Is there some other solution?

For reference, I am using python3 and the pygame library. I am using the sprite class from pygame. My player class inherits from the sprite class and is comprised of a surface object for the sprite image, and a rectangle object for the coordinates and length/width. Using a separate object for the hitbox and sprite would require to classes for this.

# Answer
Instead of making your player object inherit from the sprite class you could use member variables for the sprite and rect. Your player class can then stand alone, and have separate sprite and rect objects. In this way, when you update the player position, you have to set the sprite and collision rect position, but they can be changed independently.

Eg, as a starting point

```
class Player:
    rect = None
    sprite = None

```
> 3 votes

# Answer
There are two, relatively clean, solutions to this problem:

Either give your sprite a separate `hitbox` attribute (the scaled rect) and pass a customized callback function to `pygame.sprite.spritecollide` in which you check if the hitboxes instead of the rects collide, or alternatively scale the actual `self.rect`, then blit the sprites in a for loop and add a predefined offset vector to the `rect.topleft` coordinates to adjust the blit position.

Here's the `hitbox` solution:

```
import pygame as pg
from pygame.math import Vector2

pg.init()
IMAGE = pg.Surface((70, 110))
IMAGE.fill((0, 80, 180))

class Entity(pg.sprite.Sprite):

    def __init__(self, pos, *groups):
        super().__init__(*groups)
        self.image = IMAGE
        # The rect is still used as the blit position.
        self.rect = self.image.get_rect(center=pos)
        # A deflated copy of the rect as the hitbox.
        self.hitbox = self.rect.inflate(-40, -20)
        self.vel = Vector2(0, 0)
        self.pos = Vector2(pos)  # Actual center position.

    def update(self):
        # Move the sprite by adding the velocity vector to the position.
        self.pos += self.vel
        self.rect.center = self.pos  # Update the rect.
        # Move the hitbox as well. You can also adjust the position
        # of the hitbox here by adding another vector to the pos.
        self.hitbox.center = self.pos

# This callback function is passed as the `collided`argument
# to pygame.sprite.spritecollide or groupcollide.
def collided(sprite, other):
    """Check if the hitboxes of the two sprites collide."""
    # Check if the hitboxes collide (instead of the rects).
    return sprite.hitbox.colliderect(other.hitbox)

def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    all_sprites = pg.sprite.Group()
    player = Entity((300, 200), all_sprites)
    enemies = pg.sprite.Group(
        Entity((100, 250), all_sprites),
        Entity((400, 300), all_sprites),
        )

    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            elif event.type == pg.MOUSEMOTION:
                player.pos = event.pos

        all_sprites.update()
        # Pass the custom collided callback function to spritecollide.
        collided_sprites = pg.sprite.spritecollide(player, enemies, False, collided)
        for sp in collided_sprites:
            print('Collision with sprite', id(sp))

        screen.fill((30, 30, 30))

        all_sprites.draw(screen)
        for sprite in all_sprites:
            # Draw rects and hitboxes.
            pg.draw.rect(screen, (0, 230, 0), sprite.rect, 2)
            pg.draw.rect(screen, (250, 30, 0), sprite.hitbox, 2)

        pg.display.flip()
        clock.tick(30)

if __name__ == '__main__':
    main()
    pg.quit()

```

And the offset vector solution:

```
import pygame as pg
from pygame.math import Vector2

pg.init()
IMAGE = pg.Surface((70, 110))
IMAGE.fill((0, 80, 180))

class Entity(pg.sprite.Sprite):

    def __init__(self, pos, *groups):
        super().__init__(*groups)
        self.image = IMAGE
        # Scale the rect with the inflate method.
        self.rect = self.image.get_rect(center=pos).inflate(-40, -20)
        self.vel = Vector2(0, 0)
        self.pos = Vector2(pos)  # Actual center position.
        # Add this vector to the rect.topleft coords during the
        # blitting to adjust the position.
        self.offset = Vector2(-20, -10)

    def update(self):
        self.pos += self.vel
        self.rect.center = self.pos

def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    all_sprites = pg.sprite.Group()
    player = Entity((300, 200), all_sprites)
    enemies = pg.sprite.Group(
        Entity((100, 250), all_sprites),
        Entity((400, 300), all_sprites),
        )
    # Assign screen.blit to a local variable to increase the performance.
    blit = screen.blit

    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            elif event.type == pg.MOUSEMOTION:
                player.pos = event.pos

        all_sprites.update()
        collided_sprites = pg.sprite.spritecollide(player, enemies, False)
        for sp in collided_sprites:
            print('Collision with sprite', id(sp))

        screen.fill((30, 30, 30))

        for sprite in all_sprites:
            # Add the current offset to the blit position.
            blit(sprite.image, sprite.rect.topleft+sprite.offset)
            pg.draw.rect(screen, (250, 30, 0), sprite.rect, 2)

        pg.display.flip()
        clock.tick(30)

if __name__ == '__main__':
    main()
    pg.quit()

```
> 0 votes

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


# Question
Title: How do I make dialogue only appear once?
So I made it so when I walk over a NPC it brings up 12 lines of dialogue, and you press E to get to the next line. When the dialogue is over you can keep pressing E and it will bring the dialogue up every time. I want it so it only brings the dialogue up once. How do I do that?

This is my script for it:

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

public class dialogHolder : MonoBehaviour
{
    public string dialogue;
    private DialogueManager dMan;

    public string[] dialogueLines;

    public float questComplete;

    // Use this for initialization
    void Start()
    {
        dMan = FindObjectOfType<DialogueManager>();
    }

    // Update is called once per frame
    void Update()
    {
    }

    private void OnTriggerStay2D(Collider2D other)
    {
        if (other.gameObject.name == "Shrump")
        {
            if (Input.GetKeyUp(KeyCode.E))
            {
                //dMan.ShowBox(dialogue);
                if (!dMan.dialogActive)
                {
                    dMan.dialogLines = dialogueLines;
                    dMan.currentLine = 0;
                    dMan.ShowDialogue();
                }
            }
        }
    }
}

```

# Answer
Well you need to record whether or not this npc has already been talked to. The way to store that will vary depending on your code architecture, but the simplest way is to simply add a boolean talkedTo that starts false and turns true when dialogue starts, and add !talkedTo in the if condition.
> 1 votes

# Answer
If this file contains code only to handle the dialog, simply `Destroy` it after displaying the dialog.

```
private void OnTriggerStay2D(Collider2D other)
{
    if (other.gameObject.name == "Shrump")
    {
        if (Input.GetKeyUp(KeyCode.E))
        {
            if (!dMan.dialogActive)
            {
                dMan.dialogLines = dialogueLines;
                dMan.currentLine = 0;
                dMan.ShowDialogue();

                // Destroy this file
                Destroy(this);
            }
        }
    }
}

```

Please note that I don't know how `dMan` works and I assume when you call `ShowDialoge()` it can handle the rest without caring about the script that called it.
> 0 votes

# Answer
Use a boolean at the beginning.

```
hasTalked = false;

if(hasTalked == false)
     {

     //(The rest of your code)

     //end it by turning the boolean to true

     hasTalked = true;
     } else
{
break;
}

```

At the end of the function, we will change hasTalked to true, and then when the function checks and sees that hasTalked == true, it will skip the dialog and not display anything. Maybe you could make it say "..." or something.

Have fun!
> -1 votes

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


title: Verifying client file integrity

text:
# Question
Title: Verifying client file integrity
I am working on a simple game. It will have multiplayer over LAN, and I want to give the host the option to verify that players are not using modified clients (note that this will be disabled by default; this is more of a coding exercise). Both the client and host are identical.

Here's what I have so far:

1.) The host generates a random key.

2.) The host takes this key, combines it with the host IP address, and uses it to salt an MD5 hash of the important game files.

3.) The host then takes the generated key, and sends it in a packet to the client.

4.) The client takes this key, combines it the originating IP address of the packet, and uses it to salt an MD5 hash of the important game files.

5.) The client takes the hash and sends it back to the host.

6.) The host then checks the hash it receives from the client against the hash it generated. If they are unequal, it drops the connection.

Is this sufficient to deter most client modifications? I get that this check can be circumvented by using an unmodified client to generate the hash and sending it with a modified client; is there any way to prevent this?

# Answer
> 3 votes
> I get that this check can be circumvented by using an unmodified client to generate the hash and sending it with a modified client.

So you've handed every player the exact recipe for how to lie to you.

> Is this sufficient to deter most client modifications?

For the exact reason you stated above, no. Every single player has the means to falsify this check.

If you want to absolutely stamp out modified clients, then you can't trust the client to tell the truth about anything you ask it, not even "what are the contents of your game files?"

Instead, you need to create a system in which a player cannot gain advantage by modifying the client. For instance...

* The host should not send the client information that should not be visible to the player (eg. positions of players who are occluded behind walls). Sending this info trusts the client to keep it hidden, leading to wallhack modifications that reveal it.

If you never send that information until it would be visible anyway, the player can't modify the client to get extra info.
* The host should not use the results of client-side simuation (eg. movement & action success checks, player gameplay state). Using this info trusts the client to play by the same rules as everyone else, leading to modifications to move faster, clip through walls, fly, gain invunerability, etc.

If clients send their input and the host determines the authoritative gameplay state by simulating everyone under the same set of rules, then the player with the modified client can't get away with anything that's not possible in the unmodified client. They can make funny stuff happen on their own screen, but only regular gameplay will be simulated and transmitted to the other players.

Granted, they can still modify the client to provide better-than-human input, like perfect aim in a shooter. This requires more sophisticated cheat detection to sort out human input from mods.

If you don't have a trusted authoritative server, you can experiment with groups of peer to peer clients sharing the host role and cross-checking each other's decisions, but this gets far more complicated, and is vulnerable to attack by groups of players using the same modified client that can collude to validate each other's cheats.

# Answer
> -1 votes
if you sure host isent modified :

Add these to your hash code

* size of the game imporant files(dir)
* loaded dll(s)
* size of loaded dll(s)
* threads running by your app(maybe)
* version of the game

---
Tags: java, networking, security, anti-cheat
---


title: Default skybox missing in new scene

text:
# Question
Title: Default skybox missing in new scene
Now on my existing project, if I **create a new scene**, my game view looks like this:

The game view has a solid colour background, instead of a 3D-looking skybox. I'm expecting something like below (my old existing scene):

How can I get my skybox back in new scenes?

# Answer
Check out your lighting settings and the skybox (which you can find inside the lighting settings).

It seems like your new scene doesn't have one anymore. Normally it should have. Are you sure you haven't changed the lighting settings?

See the Unity documentation on the Skybox component for reference
> 2 votes

# Answer
This can happen when you set your project's default mode to 2D instead of 3D.

In 3D mode, new scenes are generated with a skybox (which draws the banding of colours in the background), a perspective camera, and a directional light.

In 2D, new scenes are generated with just an orthographic camera by default.

You can still add the other content yourself (2D/3D mode isn't a hard wall, just some convenient starting values for different kinds of projects)

You can change this default setting under:

```
Edit > Project Settings > Editor > "Default Behaviour Mode"

```

Or read more about 2D & 3D settings and what they affect in the Unity docs.

---

Another possible cause is if the "Clear Flags" on your camera are set to "Solid Colour" instead of "Skybox" - in that case, the camera just draws a flat colour (default greyish blue) into the background instead of the gradient or image coming from the skybox in your lighting settings.
> 1 votes

---
Tags: unity, 3d, c, skybox
---


# Question
Title: .md5mesh - multiple meshes with smooth normals
I have a .md5mesh which contains multiple meshes and I want to calculate smooth normals. The normals are correct but they don't work with multiple meshes.

My first idea was to merge all meshes, then calculate the normals and then render them seperated again, but I'm afraid that something will go wrong with this.

I already tested merging the meshes with blender and it gives me correct normals, but breaks texturing because each mesh has it's own texture.

I need advice on what to do now.

# Answer
If anyone is struggling with the same problem, here is my solution:

I concat all indexed meshes into one mesh and then create smooth normals for it one time. Afterwards I can use these normals for each individual mesh.

This simple idea gave me blender, where you have to keep reference to a joined smooth shaded mesh to get smooth normals for each splitted mesh.
> 0 votes

---
Tags: mesh, normals, md5mesh
---


# Question
Title: How can I determine when colliders of two gameobjects touch one another?
I stop gameobjects from colliding with one another by having box colliders around the gameobjects with dimensions bigger than the gameobjects. It works fine, but I want that when the gameobjects collide with one another, they stop moving. I cannot use OnTriggerEnter as I have turned IsTrigger off. Is there a thing which can determine when two gameobjects' collider touch each other?

# Answer
`OnCollisionEnter(Collision collision)` fires when two colliders enter collision (similar to `OnTriggerEnter` but for non-trigger interactions), provided that the moving collider has a Rigidbody attached.

You can also use Physics.CheckBox / Physics.OverlapBox / Physics.OverlapBoxNonAlloc to scan for overlaps in a given prism of space, if you want to manage the physics yourself.
> 2 votes

---
Tags: unity, gameobject, collider
---


# Question
Title: How do I sort isometric sprites into the correct order?
In a normal top-down 2D game one could use the screen y axis to sort the images. In this example the trees are properly sorted but the isometric walls are not:

Wall 2 is one pixel below wall 1 therefore it is drawn after wall 1, and ends up on top.

If I sort by the isometric y axis the walls appear in the correct order but the trees do not:

How do I do this correctly?

# Answer
Isometric games are functionally 3D, so internally, you should be storing the 3D coordinates for each entity in the game. The actual coordinates you pick are arbitrary, but let's say X and Y are the two on-the-ground axes, and Z is off the ground up into the air.

The renderer then needs to project that into 2D to draw stuff on screen. "Isometric" is one such projection. Projecting from 3D to 2D isometrically is pretty simple. Let's say that the X axis goes from top-left to bottom-right and down one pixel for each two horizontal pixels. Likewise, the Y axis goes from top-right to bottom-left. The Z axis goes straight up. To convert from 3D to 2D then is just:

```
function projectIso(x, y, z) {
    return {
        x: x - y,
        y: (x / 2) + (y / 2) - z
    };
}

```

Now to your original question, sorting. Now that we're working with our objects directly in 3D, sorting becomes much simpler. In our coordinate space here, the farthest sprite has the lowest x, y and z coordinates (i.e. all three axes point out from the screen). So you just sort them by the sum of those:

```
function nearness(obj) {
    return obj.x + obj.y + obj.z;
}

function closer(a, b) {
    if (nearness(a) > nearness(b)) {
        return "a";
    } else {
        return "b";
    }
}

```

To avoid re-sorting your entities every frame, use a pigeonhole sort, detailed here.
> 14 votes

# Answer
Assuming that your sprites occupy sets of tiles that are rectangles (if they occupy arbitrary sets, then you cannot draw the correctly at all in the general case), the problem is that there is no total order relation between the elements, so you cannot sort them using a sort that would result in O(nlogn) comparisons.

Note that for any two objects A and B, either A should be drawn before B (A \<- B), B should be drawn before A (B \<- A) or they can be drawn in any order. They form a partial order. If you draw yourself a few examples with 3 overlapping objects, you may notice that the even though the 1st and the 3rd object may not overlap, thus not having a direct dependency, their drawing order depends on the 2nd object that's between them - depending how you place it, you will obtain different drawing orders. Bottomline - traditional sorts don't work here.

One solution is to use the comparison (mentioned by the Dani) and compare each object to each other object to determine their dependencies and form a dependency graph (which will be a DAG). Then do a topological sort on the graph to determine drawing order. If there aren't too many objects, this may be fast enough (it's `O(n^2)`).

Another solution is to use a (for balancing - pseudo) quad tree and store the rectangles of all objects into it.

Then iterate through all the objects X, and use the quad tree to check if there are any objects Y in the stripe above the object X which starts with the leftmost and ends with the rightmost corner of object X - for all such Y, Y \<- X. Like this, you will still have to form a graph and sort topologically.

But you can avoid it. You use a list of objects Q, and a table of objects T. You iterate all the visible slots from smaller to bigger values on the x-axis (one row), going row by row on the y-axis. If there is a bottom corner of an object at that slot, do the procedure above to determine dependencies. If an object X depends on some other object Y that is partly above it (Y \<- X), and every such Y is already in Q, add X to Q. If there is some Y which is not in Q, add X to T and denote that Y \<- X. Every time you add an object to Q, you remove dependencies of objects pending in T. If all dependencies are removed, an object from T is moved to Q.

We are assuming that object sprites don't peek out of their slots on the bottom, the left or the right (only at the top, like trees in your picture). This should improve performance for a large number of objects. This approach will again be `O(n^2)`, but only in the worst case which includes weird sized objects and/or weird configurations of objects. In most cases, it's `O(n * logn * sqrt(n))`. Knowing the height of your sprites can eliminate the `sqrt(n)`, because you don't have to check the entire stripe above. Depending on the number of objects on the screen, you may try replacing the quad tree with an array indicating which slots are taken (makes sense if there are many objects).

Finally, feel free to inspect this source code for some ideas: https://github.com/axel22/sages/blob/master/src/gui/scala/name/brijest/sages/gui/Canvas.scala
> 4 votes

# Answer
I use a very simple formula that works well with my little isometric engine in OpenGL:

Each of you objects (trees, floor tiles, characters, ...) have a X and Y position on the screen. You need to enable DEPTH TESTING and find the good Z value for each values. You can simply to the following:

```
z = x + y + objectIndex

```

I use and different index for the floor and objects that will be above the floor (0 for the floor and 1 for all the objects that has a height). This should work just fine.
> 3 votes

# Answer
I don't think there is a mathematic solution. You probably don't have enough data in the 2D world your items are living in. If your walls were mirrored on X they would be in the "correct" order. Then again you might be able to do overlap testing with the bounding box of the image somehow, but this is an area I'm not familiar with.

You should probably sort by screen Y per-tile and say that anything more complicated is a "design problem". For example, if you're authoring the content, just tell your designers the sorting algorithm and to shove wall2 2 pixels up to fix the problem. That's how we had to fix it in the isometric game I worked on. This might include taking "long" items and breaking them up into tile-sized chunks.

If you are allowing users to edit the content, the completely safe thing to do is to make everything tile based and at most one tile large. That way you avoid the problem. You might be able to get by with making everything larger than a tile, but possibly only if it's square. I haven't played around with that.
> 2 votes

# Answer
Perfect isometric sorting is hard. But for a first approach, to properly sort your items, you should use a more complex comparision function with each overlaping object. This function must check this condition: An overlaping object "a" is behind of "b" if:

(a.posX + a.sizeX \<= b.posX) or (a.posY + a.sizeY \<= b.posY) or (a.posZ + a.sizeZ \<= b.posZ)

Of course, this is a first idea for a naive isometric implementation. For a more complex scenario (if you want view rotation, per-pixel positions on z-axis, etc.) you'll need to check more conditions.
> 2 votes

# Answer
If you compare the y values at the same x position, it will work every time. So, do not compare center to center. Instead compare the center of one sprite with the same x position on the other sprite.

But, this requires some geometry data for each sprite. It could be as easy as two points from the left to right sides that describes the lower boundary for the sprite. Or, you could analyze the sprites image data and find the first pixel that is not transparent.

An easier approach is to divide all sprites into three groups: diagonal along x axis, diagonal along y axis and flat. If two object are both diagonal along the same axis, sort them based on the other axis.
> 2 votes

# Answer
Extensive answer with multiple solutions, pictures and all the math here:

https://stackoverflow.com/questions/892811/drawing-isometric-game-worlds
> 2 votes

# Answer
This is not really an answer, but just a commentary and an up-vote I would like to give to this axel22's answer here https://gamedev.stackexchange.com/a/8181/112940

I do not have enough reputation to up-vote nor comment other answers, but the second paragraph of his answer is probably the most important thing one should be aware of when trying to sort the entities in an isometric game without relying on "modern" 3D techniques like a Z-buffer.

In my engine I wanted to do things "old-school", pure 2D. And I spent a lot of time busting my brain trying to figure out why my call to "sort" (in my case it was c++ std::sort) was not working correctly on certain map configurations.

Only when I realized that this is a "partial-order" situation was that I was able to solve it.

So far all working solutions I have found on the web used some sort of topological sorting to deal with the problem correctly. Topological sorting seems to be the way to go.
> 0 votes

# Answer
You need to assign unique ids to all objects of the same type. Then you sort all objects by their positions and draw groups of objects in order of their ids. So that object 1 in group A will never overdraw object 2 in group A etc.
> -1 votes

---
Tags: mathematics, isometric, draw-order
---


# Question
Title: How to get a good Force Feedback .dll Feedback for Steering Wheels? || How to access Force Feedback without a .dll?
I want to implement a steering wheel with Force Feedback to my game and I encountered this problem: I couldnt do it with performance. I have found a .dll for that online, but it had issues like:

1. It was not performant
2. It made my steering wheel react too delayed

Otherwise I was not able to access the steering wheel. Is it even possible to make a performant steering wheel and force feedback game with good performance? How else can I access force feedback ?

# Answer
You didn't mention which dll you already tried, so these may be duplicates, but:

There's a Unity asset which can apparently help with this (e.g. https://assetstore.unity.com/packages/tools/integration/ginputcontrollers-multi-joystick-and-force-feedback-manager-94949).

Here's another (currently in development, but forum posts suggest the beta releases work fine with steering wheels): https://vehiclephysics.com/about/demos/

Worst case scenario, you could write your own dll using DirectX's `DirectInput` or `XInput` APIs, which *should* be able to do this.
> 1 votes

---
Tags: unity, dll, force-feedback
---


# Question
Title: Which part of the rendering pipeline compiles shaders?
Generally, video games and other graphical software that use vertex and fragment shaders will have said shaders in the form of actual shader source code (typically in glsl or hlsl), and will compile them for use with the display hardware at runtime. (It is my understanding that shaders cannot really be precompiled into the game binary because the actual shader machine code that the display hardware uses depends on the graphics card brand and even its model/generation, and they may well be incompatible with each other.)

Even though I do myself work on the game programming field and use shaders, I actually don't know exactly which part of the graphics pipeline actually compiles the shaders into the machine code that the graphics card uses. Compiling shaders is essentially a black box: Throw the shader source code into whatever library you are using, and it does its magic behind the scenes.

I would be interested in knowing exactly where this compiling process happens. Which exact part of the entire system takes the shader source code and produces shader machine code from it?

My (wild) guess is that this is done by the graphics card driver (because the driver knows what kind of machine code it should output, and how to optimize it, for the particular brand and model of graphics card).

(If this is indeed so, it would explain at least partially why the graphics driver is so crucial in how efficiently games run, as its optimization of the shader machine code would have great impact on rendering speed.)

Are there any resources out there were I could find more info, in general, about these things?

# Answer
> 3 votes
> It is my understanding that shaders cannot really be precompiled into the game binary because the actual shader machine code that the display hardware uses depends on the graphics card brand and even its model/generation, and they may well be incompatible with each other.

This understanding is incorrect.

The model used by most games is that shaders are first compiled from text-based source code (HLSL, etc) to a hardware-independent binary intermediate language. This produces binary blobs which can be shipped with the game, whether baked into game binary as embedded resources, or in PAK files, or loose files, or howsoever. These binary blobs are then compiled during startup time (**not** at run time) to actual hardware-dependent shader objects.

So shader compilation is therefore a two-step process:

1. Compilation from source code to hardware-independent binary intermediate language.
2. Compilation from hardware-independent binary intermediate language to hardware-dependent shader object.

Step 1 is the slow step; the one that requires text-parsing, error checking, dead-code removal, validation against hardware profiles, etc.

Step 2 is fast.

Step 1 need not be performed by the driver; it can be performed by a standalone compiler on a command-line and it's not even necessary to initialize a graphics device or context to perform it.

Step 2 requires a graphics device or context to be initialized.

---

The important thing to understand is that the model I've described above is *not the model that is used by OpenGL*. If the only API you know is OpenGL, if you assume that other APIs work the same way as OpenGL, you may come to the conclusion that this model does not or cannot happen.

That, however, would be an incorrect conclusion.

*Every other API* uses the model I've described above; Metal, Direct3D, Vulkan; the two-step model is widely-used, well-understood, and works.

---

So, to answer your question, typically shader compilation is *not* done by the graphics card driver but rather by an offline tool, and compilation is done as part of the development process before the game is even shipped. The graphics card driver then takes the output of that offline tool and does a final pass to convert it to something usable on your specific hardware. This final pass is typically *not* done at runtime but rather while the program is first starting up, and drivers may even cache the result of that for faster startups in second and subsequent runs.

OpenGL, however, is the odd-one-out in that the full shader compiler is part of the driver and therefore steps 1 and 2 cannot be separated.

# Answer
> 0 votes
OpenGL and DirectX aren't libraries in the traditional sense (as in "library is a set of functions") , it's a definition. Instead of implementing the functions, they just declared what manufacturers need to implement to support them. That's, why graphics card support a certain version, and not the other way around.

So, with this it should be much clearer what they actually do. They just tells the GPU driver what to do, but not how exactly. Same with shader compilation, they send the source to the driver, which compiles it.

Technically, you could pre-compile every shader, but you would be trading a ton of storage space for little performance, especially since shaders get compiled before gameplay

---
Tags: shaders
---


title: Collision of grenadelauncher shell

text:
# Question
Title: Collision of grenadelauncher shell
The shell of a grenadelauncher is very small (10cm) and the speed is very fast (80m/s). Collision detection using colliders is impossible.

To get the collision point of a rocket launcher I send a Ray out from the rocket with a length of say 5 metres. If the Ray detects an object it will wait for 5/SpeedOfRocket seconds and then detonate. A rocket travels in a straight line, therefore no problem:

Grenades however travel in an Arch. They are not selfpropelled, they slow down due to air resistance and they are pulled down by gravity. If I fire a grenade up into the air and use a Ray to detect the collision, it will simply fall through the floor, or another object. The grenade doesn't rotate towards the direction of travel.

Using a second and third Ray to detect collisions behind and below the grenade catch all collisions successfully. However you will not be able to shoot a grenade closely above a hill or through a narrow window without it triggering a collision if within range of the Ray.

**For now** I have "solved" the problem by using the grenade just like a rocket. I simulate gravity by simply rotating the grenade as it moves. One ray to catch collision is enough because the Grenade will always face the direction of travel.

It works fine if you use the Grenade Launcher "normally". Until you shoot it like a mortar launcher: straight up in the air. I find it mathematically impossible to simulate the trajectory as such. There are too many variables involved and it would be a ridiculous attempt at solving a (what seems to be) a trivial initial problem.

I need to get the grenade to face the direction of travel like this:

# Answer
I think what you're describing is called *tunneling*. It happens with small fast objects in discrete simulations, because the simulation timestep makes them simply skip past other objects without a collision being noticed.

The simplest fix is to use a *swept collider*.

1. For every fast object, store the previous frame's position. Here's how that state would look on the frame that the fast object (red) enters another collider (green):
2. Every frame, construct a collider that "fills in" the space the grenade would have traveled through between its previous and current positions:

Be as fancy with this as you think is necessary for the accuracy that you want. A raycast might be close enough for small objects.
3. When that swept collider hits, raycast from the previous position to find the impact point.

Of course, you don't need to do this separately if you already did a raycast for the previous step. Again you can be as sophisticated as necessary here, potentially using a "thick ray" if the exact bounding volume is important.
> 1 votes

---
Tags: collision-detection, mathematics
---


# Question
Title: How can I convert my list of vertices and indices to a list of triangles?
I have a full 3D collision mesh that is represented by a list of vertices and another list of indices. I need to convert the list of vertices and the list of indices into a set of triangles.

First I tried to group every three vertices from the vertex list into a triangle, so vertices 0-2 were triangle 0, vertices 3-5 were triangle 1, etc. But that method did not produce the same triangles I see on the original mesh.

Then I remembered the indices list, but I didn't know how to use them. So I came here to ask: how can I use the indices list to make my list of triangles?

# Answer
> 5 votes
Typically, your list of indices looks like this:

```
[ 1st vertex index of triangle 0,
  2nd vertex index of triangle 0,
  3rd vertex index of triangle 0,

  1st vertex index of triangle 1,
  2nd vertex index of triangle 1,
  3rd vertex index of triangle 1,

  1st vertex index of triangle 2,
  ...etc
]

```

So the three vertices of triangle `i` are:

* vertices\[indices\[3 * i\]\]
* vertices\[indices\[3 * i + 1\]\]
* vertices\[indices\[3 * i + 2\]\]

# Answer
> 0 votes
Here is what worked for me. Hope it helps someone else:

```
List<Triangle> triangles = new ArrayList<>();

    for(int i = 0;i * 3 < indices.length;i++) {
        Triangle triangle = null;

        Vertex p = new Vertex(vertices.get(indices[3 * i]));
        Vertex p1 = new Vertex(vertices.get(indices[3 * i + 1]));
        Vertex p2 = new Vertex(vertices.get(indices[3 * i + 2]));

        triangle = new Triangle(p,p1,p2);

        triangles.add(triangle);
    }

```

---
Tags: geometry, 3d-meshes, mesh, vertex
---


# Question
Title: Why is there no standard 3d file format that saves models as (collections of) primitives?
I have been looking around for a file format that saves models as a collection of primitives (Boxes, Spheres, Cones, Cylinders, etc.). After some research, I came to the conclusion that pretty much every standard available file format saves models as a collection of vertices and indices (and some other stuff like UVs & materials).

**Real world example**
Why would one need a file format that saves primitives? Well, in my case, I am trying to build a game where I will need to import the physics separately. Since physics are optimized per primitive type, I would deem it wise to not just import everything as a mesh collider but make use of these optimizations.
*For context, I am using Three.js with Ammo.js (Bullet) running server-side.*

**Standard**
So the question really is, why is there no standard for this? Why isn't there a standard like SVG but for 3d models? I will probably end up writing my own format / implementation, so it's not like it's holding me back. It's just that I am a bit cautious, since I feel that there probably *is* a reason for no such standard to exist.

**Related links**
Here are some links I came across during research:
http://wiki.laptop.org/go/Physics\_File\_Format
http://bulletphysics.org/mediawiki-1.5.8/index.php/Bullet\_binary\_serialization

*Edit:*
Since comments aren't for thanking people, I'll just do that here. Thanks to all of you that answered and commented, very insightful! Much appreciated!

# Answer
There has been at least one that I know of: VRML. I believe its predecessor X3D also supported geometric primitives.

That being said, there's a number of reasons why formats favor a vertex approach over a geometric primitive approach:

1. **Universality** \- All models can be described as vertex meshes, including those made from geometric primitives, but the reverse isn't true - it's possible to have a mesh that isn't well defined as a collection of primitives.
2. **Direct usage** \- Modern graphics hardware is not oriented to directly render geometric primitives. They need to be converted into vertex mesh first. Using a format that support that directly cuts down some work.
3. **Control** \- Related to the last point, for a given geometric primitive, there are a number of different ways it can be represented as a vertex mesh. By directly representing the mesh, you have the more control over exactly how it should be represented. For instance, a UV sphere & an icosphere are both ways to represent a sphere. By representing the mesh directly, you have support for both as well as application specific hybrids.
> 0 votes

---
Tags: physics, models, 3d-meshes, file-format, serialization
---


# Question
Title: Is there a way to invert collision detection in unity?
I'm trying to make a drag and drop tool to make maps in my game (dungeon crawl). I would like to use colliders to define geometry, just invert the case so that collisions are good, not colliding is bad. Does Unity do this in a nice way or do I have to build from the ground up?

Ideally, I would like a player to be constrained by a CompositeCollider2D.

# Answer
> 1 votes
It turns out this is actually how Unity's collision system already works. I had thought from using it before that a box would just push out another box, but it seems to simply be 4 edges in a box shape. I would highly recommend this structure (CompositeCollider2D) for making a 2D collision map.

---
Tags: unity, collision-detection, .net
---


title: Building a windows game for Mac.

text:
# Question
Title: Building a windows game for Mac.
I have a game that I made in Unity and I have a windows build for it. It works fine on windows no problems there but I want to make a mac version of it. To make a mac version will it work if I just build it for mac or will I have to reprogram it for mac? I don't have a mac to test this and obviously I dont want to release a broken game. Note that the game uses the command Input.GetMouseButtonDown(0) a lot, not sure if you need a different command for a mac mouse.

# Answer
> To make a mac version will it work if I just build it for mac

Yes, with a giant asterisk.

You can indeed generate a Mac build from your Unity project on Windows, and most things *should* work fine when it's run on a Mac. The whole point of a cross-platform engine like Unity is to insulate your project from platform-specific details, as much as it can. So going via the Unity input system, you can read mouse input no matter what the underlying OS or mouse driver, etc. You should not have to reprogram large parts of your game.

But the only way to be certain is to test.

Some things that do vary between the platforms:

* The numbered order of buttons and axes on gamepads are not guaranteed to be the same (since it's up to the driver to number them)
* When you read from a render target in a shader, under some circumstances your result may be flipped vertically on Mac because of differences in how DirectX and OpenGL address textures (Unity automatically corrects most instances of this, but render textures occasionally pose corner cases it can't fix for you)
* This list is incomplete. I'll leave this as Community Wiki so developers can note other common mismatches between these platforms.

So, find a friend with a Mac and ask for their help testing.
> 1 votes

---
Tags: c#
---


# Question
Title: How to reference and call a function from different script ?
I've a script : Toy .

Depending of toy "type" i need to activate different feature.

For instance, for "Police-Car" i need to activate Siren, for "Truck" i need to activate horn .

I don't want to re-engineer my code creating a classic way like:

> Toy Class
>
> * Truck : Toy
> * Police-Car : Toy

So I want to call a generic public function "Activate", existing in Truck, Police .. from my Toy class.

How can i reference different script ( PoliceCarScript, TruckScript) inside Toy , so i can launch the Activate public method of PoliceCarScript, TruckScript ?

Thanks

# Answer
> 6 votes
You want to take advantage of polymorphism, and not inheritance. Create an interface, such as `IActivatable`. Truck and PoliceCar would then implement IActivatable instead of inheriting from it.

```
public interface IActivatable {
    void Activate();
}

public class PoliceCarScript : MonoBehavior, IActivatable {

    //must be public
    public void Activate() {
        //This method must be present in everything
        //that implements IActivatable
    }
}

```

`GetComponent()` works with interfaces, so you should be able to then call anything attached that can be activated with `GetComponent<IActivatable>().Activate();`.

The advantage of using this over inheritance (which I assume is what you meant by the "classic way") is that the classes can be used in place of each other without expecting anything in common with the implementation details. It is basically a promise that every class implementing IActivatable has an Activate method, even if each Activate method looks very different from the others.

Here's a video that helps explain it better: https://unity3d.com/learn/tutorials/topics/scripting/interfaces

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


# Question
Title: Character collision detection on 2D array tileset based map
I have a very basic collision detection working, but not quite there yet. Now as I understand I'm only checking against the left top corner of the character for collision detection. And it only works if I move character to the left. If I move to the right, the collision is not being detected. How can I check for all the sides of the character for collision and not only left top? Let's say my character sprite size is 36px.

```
var mapArray = [
  [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
  [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
  [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
  [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 3, 3, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 3, 3, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
];

function isPositionWall(ptX, ptY) {
  var gridX = Math.floor(ptX / 36);
  var gridY = Math.floor(ptY / 36);
  if(mapArray[gridY][gridX] != 0) {
    return true;
  }
}

if(isPositionWall(boatPosX, boatPosY)) {
    boatPosX = oldPosY;
    console.log("collision");
  }

```

# Answer
> 1 votes
The simplest way possible to perform a collision detection is checking the next position an object should move to: if there is a free place, move it, if there is a wall, don't move it, etc. Simple implementation:

```
// get tile at position
function getTileAt(x, y) {
    var gridX = Math.floor(x / 36);
    var gridY = Math.floor(y / 36);
    return mapArray[gridY][gridX];
}

// check if the place we want to move an object to is free
function isTileFree(x, y) {
    return getTileAt(x, y) == 0;
}

// x, y are relative coordinates
function move(x, y) {
    if (isTileFree(boatPosX + x, boatPosY + y)
    {
        boatPosX += x;
        boatPosY += y;
    }
}

```

---
Tags: collision-detection, javascript, html-canvas, tilesets
---


# Question
Title: Retrieve multiple images from MySql database via Unity C#
We could say that we are beginners, We can consult and show our data (text) from Mysql but the images don´t show in Unity. Need some help! We hace tried almost everything! We can someone help us.

in C# we have...

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Net.NetworkInformation;
using UnityEditor.Sprites;
public class Detalles : MonoBehaviour {

string url = "https://cdn.designrulz.com/wp-content/uploads/2012/03/unique-house-garden-at-Luxury-and-Stylish-Glass-House-desgnrulz-3.jpg";
Texture2D img;

public string[] items;

public int num ;
public Image imagen;
public Text precio;
public Text tipo;
public Text superficie;
public Text recamaras;
public Text baños;
public Text cocheras;
public Text ciudad;
public Text ubicacion;

//
IEnumerator Start(){
    WWW itemsData = new WWW ("http://localhost/Casas/ItemsData2.php");
    yield return itemsData;
    string itemsDataString = itemsData.text;
    //print (itemsDataString);
    items = itemsDataString.Split (';');
    //num = items.Length - 1;
    //for( int i = 0; i < num; i++ ){
    //  }
    precio.text = " $ "+ GetDataValue (items[num],"Precio");
    tipo.text = " " + GetDataValue (items [num], "Tipo");
    superficie.text = " "+ GetDataValue (items[num],"Superficie")+" m2";
    recamaras.text = " " + GetDataValue (items [num], "Recamaras")+ " Recamaras";
    baños.text = " " + GetDataValue (items [num], "Sanitarios")+" Baños";
    cocheras.text = " " + GetDataValue (items [num], "Cocheras")+" Cocheras";
    ciudad.text = " " + GetDataValue (items [num], "Ciudad");
    ubicacion.text = " " + GetDataValue (items [num], "Ubicacion");
    StartCoroutine (LoadImg ());
}

IEnumerator LoadImg(){
    yield return 0;
    WWW imgLink = new WWW (url);
    yield return imgLink;
    img = imgLink.texture;
}

void Update(){
    imagen.sprite =  Sprite.Create (img, new Rect(0,0,690,345),new Vector2(0.5f, 0.5f));
}

string GetDataValue(string data, string index){
    string value = data.Substring (data.IndexOf (index) + index.Length);
    value = value.Remove (value.IndexOf ("|"));
    return value;

```

In PHP we have...

```
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbName = "casas";

$conn = new mysqli($servername, $username, $password, $dbName);

if(!$conn){
    die("Conection failed".mysqli_connect_error());
}

$sql = "SELECT id,titulo,foto,tipo,precio,superficie,sanitarios,recamaras,cocheras,colonia,ciudad,ubicacion FROM casas ORDER BY id ";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result)>0) {
    while ($row = mysqli_fetch_assoc($result)) {
        echo "Id".$row['id'] ."|Titulo".$row['titulo']."|Tipo".$row['tipo']."|Precio".$row['precio'] ."|Superficie".$row['superficie']."|Sanitarios".$row['sanitarios'] ."|Recamaras".$row['recamaras']."|Cocheras".$row['cocheras'] ."|Colonia".$row['colonia']."|Ciudad".$row['ciudad'] ."|Ubicacion".$row['ubicacion']."|".";";
    }
}
?>

```

# Answer
To start with, you should move the line

```
imagen.sprite =  Sprite.Create (img, new Rect(0,0,690,345),new Vector2(0.5f, 0.5f));

```

from `Update()` to the end of `LoadImg()` as you don't want to be creating a new sprite every time the game updates.

Your code looks mostly ok otherwise. Here's a working code sample which loads an image from a URL. If it still doesn't work, comparing the two and modifying yours to match should fix the issue. https://answers.unity.com/questions/1175862/loading-a-sprite-from-url-c.html
> 1 votes

---
Tags: unity, c#, php, mysql
---


title: PUZZLE MAZE using probability - HOW TO

text:
# Question
Title: PUZZLE MAZE using probability - HOW TO
is there an easier way to do this? perhaps a formula?

# Answer
> 0 votes
you could determine all paths to go through a grid (see Brilliant).

there's a mini python implementation shown on Brilliant, so it seems pointless for me to post more from the blog

also it's obvious that you have to sum up the values for each path and validate it (is its sum 1?) ...

## EDIT

i've provided the python code for a 5x5 (m,n-grid) from Brilliant. You can use this as a guide for any other programming languages... this algorithm is really not hard to translate into whatever you need - details to this algorithm can be taken from the blog....

```
def dp(m, n, arr):
    if m == 0 or n == 0:
        return 1
    if m < 0 or n < 0:
        return 0
    if arr[m][n] != 0:
        return arr[m][n]
    arr[m][n] = dp(m-1, n, arr) + dp(m, n-1, arr)
    return arr[m][n]

m = 5
n = 5
arr = [0] * (m + 1)
for i in range(m + 1):
    arr[i] = [0] * (n + 1)
    print(dp(m, n, arr))

```

---
Tags: probability
---


# Question
Title: What is better: One texture per model or assigning multiple models to one single huge texture?
If I'm making a low-poly car pack of multiple cars for mobile platforms, should I:

* Make a large texture like of 2048x2048 and unwrap all the models to it
* Make separate, smaller (256x256) textures for all cars

Will there be a difference in performance? Which way of texturing is preferred? I've never seen any PC game have one large texture for all the cars, instead every car has its own set of textures and materials.

# Answer
There is no "best" way to do it, in a general sense. That being said, hardware considerations can have an impact on the decision of which way to go.

For example, if you are running on something like an old HD3000 Intel GPU, you may have a decent amount of GPU ram, but the driver has limitations on how many active bound textures you have have at once (at least where OpenGL is concerned). This will cause serious issues with techniques such as deferred shading.

In such a case, a single, large texture would solve the problem, assuming that you have enough GPU ram to hold it, and all the other stuff (shaders, meshes etc) that you wish to use.

However this is unlikely to be the case in modern hardware, which supports 16-32 active bound textures.

Multiple textures have the advantage that you can choose which textures to have loaded, which improves flexibility, but with the drawback that you may have to load/unload textures to the GPU relatively frequently, which will affect performance. This is the preferred method of most game studios I have worked for, simply due to not having to support dated hardware, and that the PCI-E data bus is pretty fast.

However, being more specific to your case, you are talking about very small textures, vs one HD sized texture, so I doubt you would see any noticeable difference in performance either way. You would just have to write your shaders to accommodate the method you choose (mega texture uses UV offsets, whilst smaller textures have more work on the CPU side, in terms of binding texture units).

I appreciate this has not really answered your question, but as I opened with, there is no silver bullet approach.
> 1 votes

---
Tags: models, mobile, multitexturing
---


title: Java image in JFrame rendered weirdly

text:
# Question
Title: Java image in JFrame rendered weirdly
I'm not sure if this is intended or not, if it is, I'd like to know a way of preventing this: I've got this image (which is for testing purposes, the actual one has a texture, but I'm not using it right now): Zoomed in, it looks like this in the JFrame:

These small 'arrangements' are what bothers me, because the image itself should be plain green, just as it is when viewing the tile image with a separate viewer
*(like that:)*

OOO
--O--
O--O

In the end, drawn as a tilemap, it looks like this (I'm changing the rgb values, that's why it's coloured differently on the left):

---

**My Code:** (It draws 15 horizontal tiles and 10 vertical tiles, the orange ones are another piece of code which is irrelevant right now)

```
BufferedImage singleTile;
    try {
        singleTile = ImageIO.read(new File(filename));
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }
    BufferedImage finalImg = new BufferedImage(tilesX*scaledTileSize, tilesY*scaledTileSize, singleTile.getType());
    for(int i = 0; i < tilesX; i++){
        for(int j = 0; j < tilesY; j++){
            finalImg.createGraphics().drawImage(singleTile, i*scaledTileSize, j*scaledTileSize, scaledTileSize, scaledTileSize, null);
        }
    }

```

# Answer
Firstly, It looks to me like whatever app you used to create your blank green texture put that pattern there. Try creating a texture using paint.net and see if the problem still persists. Also please show me the code to render the orange texture it could also be helpful. Also, you said that you are changing the RGB colors. Remove that code and it might solve your problem..
> 1 votes

---
Tags: java, tilemap, image
---


# Question
Title: Collision detection 3d rectangles using SAT
This question builds on a previous post asked by griffinHeart nov 2012. See link below.

How many and which axes to use for 3D OBB collision with SAT

Refering to the explanation/answer by Ken. What if the yellow cube had a rotation so the gap was hidden. This scenario does not necessarily mean that there is a collision/interception. The scenario would look something like this:

Which of the 9 edge - edge vectors would then show that there is no collision.

I am trying to implement an anti- coll algo between two 3d rectangles that might have a rotation around any axis (x, y, z). I am struggling with the projection part. How to project the points onto the face normals.

Hope someone can give me an answer that could lead to a solution. Thanks!

# Answer
Quoting the answer to the linked question, the axes you need to test are:

* 3 axes from object A (face normals)
* 3 axes from object B (face normals)
* 9 axes from all the **pairs of edges** of A and edges of B (3x3)
=15 in total

Emphasis added. The black arrow formed in the diagram above is generated by the cross product of a *pair* of edges: the vertical edge of the yellow cube and the horizontal edge of the blue prism.

A property of the cross product is that the result vector is always perpendicular to both input vectors.

So, when you try to turn the cube A to hide the separation, you also turn the vertical edge used as input to construct the projection axis, which then turns the projection axis to remain perpendicular to that edge. So the projection moves to exactly compensate for your attempt to hide the separation. That's why we choose these particular edges and use the cross product in this way: to always reveal a separation if one exists.
> 2 votes

# Answer
Here is an article that you could help you.

Here also is some pseudo-code that can help you in case the link rots.

```
Vector[] axes = new Vector[shape.vertices.length];
// loop over the vertices
for (int i = 0; i < shape.vertices.length; i++) {
    // get the current vertex
    Vector p1 = shape.vertices[i];
    // get the next vertex
    Vector p2 = shape.vertices[i + 1 == shape.vertices.length ? 0 : i + 1];
    // subtract the two to get the edge vector
    Vector edge = p1.subtract(p2);
    // get either perpendicular vector
    Vector normal = edge.perp();
    // the perp method is just (x, y) => (-y, x) or (y, -x)
    axes[i] = normal;
}

```

Note this only works with convex shapes but you should be able to use a convex decomposition on your concave shapes.
> 0 votes

---
Tags: collision-detection, separating-axis-theorem
---


title: Difficulty with Texture Alphas - HLSL

text:
# Question
Title: Difficulty with Texture Alphas - HLSL
UPDATE 3:

I have fixed the issue by reordering my effects (see my answer for details.) Anyone who wants to post more information based on that answer (either in an answer or in the comments) would be greatly appreciated.

UPDATE 2:

~~I think the issue may be that I've been using the default Magenta as transparent rather than having actual alpha values. It's hard to tell through Monogame what magic is happening to make the Magenta transparent (note: I'm in a 3d camera and not using spritebatch.)~~

~~I will try this again tonight or tomorrow with a set of identical textures using an alpha value instead of magenta.~~

Looks like this was unrelated to my issue. I now have images that have proper alpha values rather than replacement color values and am still having the same issue.

---

I've been able to apply my shader to multiple layered textures, with the issue that I can't seem to get the alpha to detect in my shader.

As you can see in the picture, the Alpha values for the Turret and the Tank-body are not being multiplied in properly ("derp.a") meaning that the lighting pass is hitting certain pixels 2x-3x based on how the textures overlap.

Full shader pasted below:

```
//Texture2D currTexture : register(s0);
sampler currSampler : register(s0);
/*{
    Texture = (currTexture);
    AddressU = clamp;
    AddressV = clamp;
};*/

float4x4 xViewProjection;
float3 tankpos;
float4 shotpos;

struct VertexToPixel
{
    float4 Position : POSITION; // Can't use in pixel shader, but required for it
    float4 Color : COLOR0;      // color for the vertex?
    float2 rPos : TEXCOORDS0;   // world position of the texture
};

struct PixelToFrame
{
    float4 Color : COLOR0;
};

VertexToPixel SimplestVertexShader(float4 inpos : POSITION)
{
    VertexToPixel output = (VertexToPixel) 0;
    output.Position = mul(inpos, xViewProjection);
    output.rPos = inpos.zx;
    return output;
}

PixelToFrame LightAroundAShot(VertexToPixel PSIn)
{
    PixelToFrame output = (PixelToFrame) 0;
    output.Color = PSIn.Color;
    float x = (PSIn.rPos.x * 0.02 - shotpos.z * 0.02) * 1 / (1 + shotpos.w);
    float z = (PSIn.rPos.y * 0.02 - shotpos.x * 0.02) * 1 / (1 + shotpos.w);
    float4 derp = tex2D(currSampler, float2(PSIn.rPos.x, PSIn.rPos.y));

    output.Color.g += (0.75 - sqrt(x * x + z * z)) * shotpos.w * derp.a;
    output.Color.br += (0.35 - sqrt(x * x + z * z)) * shotpos.w * derp.a;

    return output;
}

technique Simplest
{
    pass Pass0
    {
        VertexShader = compile vs_4_0_level_9_1 SimplestVertexShader();
        PixelShader = compile ps_4_0_level_9_1 LightAroundAShot();
    }
}

```

I've attempted to use curr texture at the top in a couple ways and can't seem to find the voodoo to get it working. Any help understanding the relationship (especially in monogame) between Textures, Samplers, and how to get that darn "derp" alpha to apply correctly would be great.

*Note: When I tried using curr texture I was setting it before each call of the graphics device so that it'd be the appropriate texture. I've also attempted to register them in various ways to s1, different ways of setting the texture in graphics device. I'm truly stuck at the moment.*

Thank you for any help!

# Answer
> 0 votes
I ended up having a (hacky) fix of reordering Effects. It seems that what really wants to occur here is part of the Alpha Test/zbuffering that I was letting an AlphaTestEffect do for me. At the moment, **ordering the effects** so that they all apply to the object at the same time and then move on, and doing it oriented by my Depth axis (y in this case) seems to get rid of the boxes (and thus only light once per object, rather than twice.)

The proper way to fix this in the coming week or two is to write *my own* alpha testing and z-buffering shader, now that I'm learning shaders, and then have these effects that rely on transparency perform a similar operation to alpha-testing and z-buffering when applying their color modification.

There is probably a more efficient way than repeating those steps in multiple shaders, but I guess I'll find out in time. Regardless, I got lucky enough to stumble into a working animation.

**To those who end up with this issue;** it seems that by letting Monogame perform some magic with AlphaTestEffect and then writing your own effect for lighting requires you to go back and write your own Alpha-Test OR draw things in Depth-order; even though you have an alpha-test drawing their initial sprites correctly.

Anyone with more information based on the above may still be able to help my understanding.

---
Tags: c#, monogame, hlsl
---


# Question
Title: Runtime Java Module Generation for Game Plugins
Edit: Clarification:

I want to create a named module during runtime and put dynamically loaded classes into the created module.

I am attempting to build a framework that allows for code generation that is compatible with Java 9's module system. I require the ability to load some generated byte code into a "virtual" module.

From what I can tell after looking though the Java code there are no exported and public methods that allow me to do anything like this, but I am sure I am missing something.

For an example, let's say this class is generated for the module "handler".

```
package handler;

public class ModHandler{
    public static String fireEvent(){
        return "This is a string from the generated module!";
    }
}

```

How do I make the "handler" module and load the bytecode into it? How would you add exports and requires into the module? I do not want to write anything to the disk to implement this.

# Answer
> 1 votes
You have to create a `ModuleLayer` from a `Configuration`. This requires a `Set` of `Path`s to pass to a `ModuleFinder` instance that can be created with `ModuleFinder.of`.

This example lists the jars in `plugins` and loads the modules.

```
// List all jar files in ./plugins
File[] pluginFiles = new File("plugins").listFiles((f,n)->n.endsWith(".jar"));
// Convert to Paths
Arrays.stream(pluginFiles).map(File::toPath).collect(Collectors.toSet());
// Create a module finder from those jars
ModuleFinder finder = ModuleFinder.of(Set.of(pluginFiles));
// Get the boot config
Configuration parentConfig = ModuleLayer.boot().configuration();
// Create a new configuration
Configuration configuration = parentConfig.resolve(
    finder,
    ModuleFinder.of(),
    // This gets the names of all the modules and tells the Config to load them
    finder.findAll().stream().map(mr->mr.descriptor().name()).collect(Collectors.toList())
);
// Create the ModuleLayer, you can now interact with the modules
ModuleLayer layer = ModuleLayer.boot().defineModulesWithOneLoader(configuration, ClassLoader.getSystemClassLoader());

```

This was so much harder to find than one might think, with this you can create a custom `ModuleFinder` and do weird and wonderful things.

---
Tags: java, modding, plugin
---


# Question
Title: Would it be inefficient to call LWJGL from C++?
I like LWJGL, but Java? Not so much. I recently found out a way to call Java methods from C++. But would this be inefficient? I mean, calling a C/C++ DLL from Java, just to be called back again into C++? I don't know the native method names in LWJGL. I find it better then GLFW, SDL, and all those libraries. But other than my preferences, how slow would it be?

# Answer
> 2 votes
Yes it would be inefficient. However it's up to you to decide if it is *too* inefficient. It depends on how often you would be calling LWJGL.

See https://stackoverflow.com/questions/7699020/what-makes-jni-calls-slow and `http://192.9.162.55/docs/books/performance/1st_edition/html/JPNativeCode.fm.html`. Chapter *9.2 Examining JNI Costs* from the second link provides a benchmark result where Native-\>Java calls were almost 10 times slower than Java-\>Native calls.

# Answer
> 1 votes
You don't have to use LWJGL. LWJGL is specific for Java.

You could just use bare OpenGL or libraries such as FreeGLUT and SDL.

# Answer
> 0 votes
Inefficient *compared* to what?

Considering that LWJGL3 is mostly a collection of JNI and JNA bindings to C and C++ libraries it would be inefficient indeed, as you would create an overhead of having to have a JVM running and piping each method call to java and back to C++ again (mostly at runtime even), at almost no usability win whatsoever as LWJGL3 mostly mimicks the method calls and structures of the wrapped libraries. Instead of calling LWJGL3 from C++ you should instead directly use the libraries that LWJGL3 depends upon.

In that case, and indeed your case, that would be GLFW which is used by LWJGL3 to do all the windowing, input, OpenGL stuff and other heavy lifting. If you've been using any other of the bindings offered by LWJGL such as the STB libs you can find a full list of them and links to respective repositories on the LWJGL3 GitHub repo README.

---
Tags: c++, java, lwjgl, c
---