# Question
Title: How could I do a 2d pixel design in game where you can see though the obstacles/upper floors?
Maybe the question didnt show much... but what I'm trying to do is e.g. if I'm in a train platform with two floors overlapped, or in a place where I'm blocked by some obstacle to see my char. from my view. I want to let my character be visible but have how should I say, have lines? of the obstacles overlapped a bit so i can have an impressing there is an obstacle but you're seeing your char. through, kinda like half-visible, kinda like gradation.

tl;dr - I want to see my character who is normally should be blocked the view from my POV to be visible, while also making the player to see that there's something between the character and the POV. is there a method I can check?

using dots to create this via photoshop.

# Answer
When the sprite is obscured by an object, you could make that object transparent:

You can make a sprite transparent in Unity by setting the alpha-value of the sprite color.

```
Color tmp = sprite.GetComponent<SpriteRenderer>().color;
tmp.a = 0.5f;
tmp.GetComponent<SpriteRenderer>().color = tmp;

```

Another option is to just draw the outlines when the character is behind something. This looks a bit cheaper, but will usually cause less visual clutter:

This requires that you make two versions of every asset you want to be able to become transparent. Simply switch out the sprite image of the renderer.

But how do you detect when you need to do this? There are two options for this I would consider.

1. When the number of objects which are supposed to behave like that is limited, you could give each of these objects a "isTrigger" collider and add a script to them which implements `OnTriggerEnter` and `OnTriggerExit` to make the sprite transparent/opaque when the triggering object is the player-character.
2. When you want objects on the over-layer to behave like that in general, you could use a raycast from the player-character in its Updated method to detect if something is above it and make that thing transparent.
> 5 votes

---
Tags: unity, 2d, pixel
---


# Question
Title: C++ SDL Vector of Textures Storing NULL Objects
I'm attempting to (re)learn C++ by making a top-down shooter game using SDL. In my game, I have created a `Graphics` class that handles all of the drawing, textures, etc.

The game is in its *very* early stages, and at the moment the `Graphics` class has a `textureList`, which is simply a vector of pointers to SDL textures:

`vector<SDL_Texture*> textureList;`

The `Graphics` class has an `int addTexture(const char* filename)` method, which is used by a `GameObject` to add textures to the `textureList` vector, and return the vector ID back to the GameObject, so that it can access its texture when needed:

```
int Graphics::addTexture(const char* filename) {
    SDL_Texture* tx = IMG_LoadTexture(this->renderer, filename);
    this->textureList.push_back(tx);
    return (textureList.size() - 1);
}

```

The `addTexture` method is called by a `GameObject` like this:

`GameObject player(10, 10, g.addTexture("player.png"));`

Later on, a `GameObject` will call an `updateGraphics()` method on the `Graphics` class, which uses the stored ID to draw a texture:

```
void Graphics::drawTexture(int id, int x, int y, int w, int h, int angle) {
    SDL_Texture* tx = this->textureList.at(id);
    SDL_Point* centre = NULL;
    SDL_RendererFlip flip = SDL_FLIP_NONE;
    SDL_Rect rect;
    rect.x = x;
    rect.y = y;
    rect.w = w;
    rect.h = h;
    SDL_RenderCopyEx(this->renderer, tx, NULL, &rect, angle, centre, flip);
}

```

From what I can tell, the `SDL_Texture*` taken from `textureList` and stored in `tx` is `NULL`, and I've read that this is because `textureList` is storing pointers to objects that become `NULL` once the objects are destroyed (after the call to `addTexture()`?).

I've also read about storing deep copies of the textures in the vector, but I'm unsure how to do that, as I only seem to have access to pointers to textures.

Any help or advice greatly appreciated - especially if I'm just going about this the wrong way!

Thanks, Rich.

# Answer
> 3 votes
> From what I can tell, the `SDL_Texture*` taken from textureList and stored in `tx` is `NULL`, and I've read that this is because textureList is storing pointers to objects that become `NULL` once the objects are destroyed (after the call to `addTexture()`?).

No, that's wrong. Pointers are not magic, they don't change value by themselves anymore than other objects do. If `drawTexture` stores a non-null `SDL_Texture *` inside the vector, then it will still be there later, so your code works.

Note, however, that `IMG_LoadTexture` returns `NULL` if it encounters an error, and you don't check for it, so you might store an actual null pointer in `textureList` from the beginning.

# Answer
> -1 votes
Note to future me...

The problem had nothing to do with the use of pointers to textures (as Quentin stated above), but was instead due to `SDL_Texture` not being able to find the image.

I changed the working directory in the build settings and everything works!

Thanks everyone for your help -- I knew it must have been due to a mistake on my part!

---
Tags: c++, textures, vector, sdl
---


# Question
Title: How can I draw image and label on another image
The idea is to make a shop structure like in Arrow game from KetchApp.

As I think I need to create ShopCell class, add objects of this class to Table, then add this Table to ScrollPane(so I can scroll my shop). But not really sure how to implement this.

The main problem for me is to create ShopCell class. It seems reasonable to start this way:

```
public class ShopCell extends ImageButton {

```

But how can I draw a Texture (item image) and Label (price) on another Texture (background)?

# Answer
> 1 votes
You can also use A `Group` class. Like that

```
Group grp=new Group();
grp.addActor(baseImage);        // your background image
grp.addActor(Label) ;           // your Label
grp.addActor(image);           // your 2nd image(item image)

```

# Answer
> 1 votes
You could try and extend an Actor with what you need instead of using the ones supplied in LibGdx.

This example below(not tested) should give you an idea of what's needed.

```
private class ShopCell extends Actor{
    public String text = "Item"; // item text
    private TextureRegion image; // image to show
    private BitmapFont font; // font used for text

    public ShopCell (TextureRegion reg, String itemText, BitmapFont fnt){
        image = reg;
        text = itemText;
        font = fnt;
    }
    @Override
    public void draw(Batch batch, float parentAlpha) {
        super.draw(batch, parentAlpha);
        // draw image in center of actor
        batch.draw(image, getX(), getY(), getOriginX(), getOriginY(),
                getWidth(), getHeight(), getScaleX(), getScaleY(), getRotation());
        // draw text below image
        font.draw(batch, text, getX(), getY() - 10);
    }
}

```

As this extends Actor it reacts like all other actors so can respond to clicks like a button.

---
Tags: libgdx
---


# Question
Title: Forward A-star pathfinding vs Reverse A-star pathfinding
Under what condition does doing Forward path finding or Reverse pathfinding get better result? Most tutorials for open grid tower defence games says to pathfind from the Goal to the monster. Why is it so?

# Answer
> 2 votes
There is no definitive answer, because depending on the scene either can be faster.

But A\* relies on a heuristics function which usually states closer = better = evaluate first. Let's take this example from the Wikipedia article on A\*:

In this particular case, the "closer = better" heuristic leads the algorithm right into a trap. A\* keeps moving on the direct line from red to green and fails very late, short before reaching green. It then wastes time with exploring the interior of the wedge until it has iterated it completely. Only then will it try the path around it.

If you'd have started from green, A\* would have explored towards red, quickly found the wall, explored around the wall, and then head straight towards the destination.

That means in this particular situation, starting from green would give you a much faster solution.

So what you need to consider is: *Does my level design tend to have "traps" like this which always face into one particular direction?* Then you should avoid starting the A\* search from that direction.

# Answer
> 2 votes
It's worth noting that pathfinding backwards (from the goal to the creature) helps when some actions may need to be taken to get to the goal, or may optionally be taken for an even better path.

Examples of this include doors with locks or switches, or gaps that can be crossed with a ladder, or mobility power ups that can be found in the environment.

This may not apply to your specific case, but as a general answer to the question of whether to pathfind forwards or backwards, this is hopefully worth considering.

As a simple example, if you're pathfinding forwards and you come across a locked door, you don't yet know if it would've been worth it to detour to pick up the appropriate key before coming here (which would require pathfinding to start over), or if continuing to search would still yield a better result.

However, if we pathfind backwards from the goal and come across the locked door, we can treat it as unlocked and continue expanding through that node, but towards the key instead of the creature. If it's faster to find a long way around instead of going to the key and then the door, then good A\* will find its way back to the creature before the locked-door-sub-path has found its way all the way back to the creature with the key it needs. But if the locked-door-sub-path gets to the creature first, the creature knows to first go get the key, and *then* go to the locked door before heading to the goal.

This requires some modification -- normally, A\* needn't ever visit a node twice, as once a node is visited, its fastest sub-path has been found (whether forwards or backwards). But if the sub-path changes objective (collecting a key, for example), nodes may be visited by both the key-collecting sub-path and the path that goes around the door if collecting the key is too much of a detour to be optimal.

---
Tags: algorithm, path-finding, tower-defense
---


# Question
Title: Why does scissor test happen after fragment shading?
In OpenGL why is scissor test performed after shading. Wouldn't be more efficient to do the discarding before shading?

Reference pipeline overview, the scissor test is inside the Fragment Processing stage.

# Answer
The short answer: Scissor testing happens before fragment shading.

The scissor test *is* a per-fragment operation, so it is conceptually a part of fragment processing. According to the PDF that you linked, though, scissor testing is performed as the second step (right after Pixel Ownership Test) in fragment processing. This is before fragment shading.

In addition to that, the reference pipeline is only laying out how rendering should appear to work to the user. If something can be optimized further and still work the same way, rendering hardware designers are free to do that.
> 5 votes

---
Tags: opengl
---


# Question
Title: Problem resolving rotation between sphere-sphere collision
I have developed a collision detector that return collision data, as collision normal, collision point, interpenetration, etc.

And now I am developing a collision solver. The collision solver compute correctly the linear motion after the collision but it is not able to compute the rotation after the collision.

This is an image ilustrating the problem

To compute the velocity after collision I apply a `impulse` to each body, this impulse is able to compute correctly linear motion.

Now, to compute the rotation change I need to apply the following formula

```
ImpulsiveTorque = RelativePoint.cross(Impulse);
RotationChange = InverseInertiaTensorWorld.transform(ImpulsiveTorque);

```

The problem is `ImpulsiveTorque` is very small to generate a visible rotation change.

The following correspond to my sphere-sphere collision detector

```
sphereAndSphere : function(one, two){
    var oneToTwo = one.position.sub(two.position);
    var oneToTwoLength = oneToTwo.length();
    if (oneToTwoLength < 0 || oneToTwoLength > one.radius + two.radius){
        return -1;
    }
    var normal = oneToTwo.divideByScalar(oneToTwoLength);
    var data = new Collision();
    data.normal = normal;
    data.point = one.position.add(oneToTwo.multiplyByScalar(0.5));
    data.depth = one.radius+two.radius - oneToTwoLength;
    data.body = [];
    data.body.push(one);
    data.body.push(two);
    data.restitution = Math.min(one.body.restitution, two.body.restitution);
    return data;
},

```

`RelativePoint` is the collision point relative to center of mass of each body in collision. It is computed as follow

```
this.relativePoint[0]=this.point.sub(this.body[0].position);
if (this.body[1] !== undefined){
    this.relativePoint[1]=this.point.sub(this.body[1].position);
}

```

The `impulse` should be applied in the normal direction.

If I am correct `RelativePoint` vector has the same direction that normal collision vector. So, the impulse has the same direction that `RelativePoint` so the cross product will return a very small result. As a result I can't get a visible rotation change.

I think calculations is ok, but it lead to no rotation between sphere-sphere collision and in the real world if sphere-sphere collide I can see a variation in rotation, so I think that I am forgetting something.

Can you give me some tip why I don't get a visible change in rotation?

P.D If you need more information please tell me.

Edit: This is the way how I compute the `Impulse` vector.

First I need to know how change the velocity for each unit of impulse. At this point I compute this quantity in the collision normal (For collision solver I work in collision coordinates). For that reason I use the dot product between normal and ChangeVelPerUnit

```
var changeVelPerUnit = RelativePoint[0].cross(normal);
changeVelPerUnit = body1.inverseInertiaTensorWorld.transform(changeVelPerUnit);
changeVelPerUnit = changeVelPerUnit.cross(RelativePoint[0]);
changeVelPerUnit = changeVelPerUnit.dot(normal);
changeVelPerUnit += body1.inverseMass;

```

Then I need to know the current closing velocity (or separating velocity) with the formula v = v' + (rotation x RelativePoint)

```
var sepVelocity = body1.rotation.cross(RelativePoint[0]);
sepVelocity = sepVelocity.add(body1.velocity);

```

This velocity is computed in world coordinates so I need to change it to Collision coordinates

```
var collisionVelocity = transform.getTranspose().transform(sepVelocity);

```

With this, now I compute the change in velocity that should be given to the body, taking into account the restitution coefficient. I use the x coordinates because I use the normal as X axis for matrix to change from collision coordinates to world coordinates and viceversa.

```
var changeInVel = -collisionVelocity.x * (1 + this.restitution);

```

and finally I compute the impulse in collision coordinates and then pass it to world coordinates

```
var impulseCollision = new ALMath.Vector3(changeInVel/changeVelPerUnit,0,0)
var impulse = transform.transform(impulseCollision);

```

P.S the impulse computation is doing only for one body, it should be necessary to do calculations for second body, but for simplicity I omitted it.

# Answer
The direction of the collision normal between 2 spheres is calculated using the difference in their positions. This is the same direction as the vector pointing from either sphere to the contact point. The cross product of parallel vectors is zero, so your torque impulse is zero.

This is correct; the collision shouldn't induce any angular change absent friction.
> 1 votes

---
Tags: physics, javascript, physics-engine, rigid-body-dynamics, rigidbody
---


title: IAP where I get paid?

text:
# Question
Title: IAP where I get paid?
I have search with every word of my limited English for this question, and I think it's is not appropriate for this site but I just got to try.

I implemented Google IAP for Android. In all the tutorials I have read not one tells where I can check how much money I'm making, or specify where I get paid. I guess what I'm trying to ask is how Google is gonna pay me if I have not specified anything?

# Answer
Google's documentation on in-app billing is here. Note that

> No special account or registration is required other than a Google Play Developer Console account and a Google Wallet merchant account.

The Wallet merchant account is how Google will pay you; the funds will be sent there when appropriate (when above the payment threshold set in your account, and on the monthly billing date, which I believe is the 15th of every month).

You can monitor your revenue from your developer console account dashboard, which will also provide you with downloadable financial reports regularly.
> 2 votes

---
Tags: android, in-app-purchase
---


# Question
Title: Any resources for how to read image files
I'm learning opengl and I'm the kinda guy who likes to write things from scratch and I was searching for how I can read image files data to create my own image importing library to use for textures but I couldn't find anything useful except reading a bmp file. Can you recommend any resources that might help me?

Thanks in advance

# Answer
> 0 votes
What you are looking for is the 'file format'. This is the fancy name you will have to search for when looking up the byte protocols for a file.

For BMP, you can find the info you want here. This is probably denser than you might be used to, so if you want something that you can directly read from then this stack overflow post might be nicer for you.

If you want to get good practice without using any of the above, this might be a great site to practice from since it gives you the higher level stuff for bitmap files succinctly and describes it effectively.

---
Tags: opengl, c++, image-processing
---


# Question
Title: 2D narrow-phase line intersection with square bounding box for calculating height efficiently
I've performed partitioning of my level into broad and narrow phase. I'm down to narrow phase and focusing on the height from the ground.

I want to see what polygon the player is on top of. Since some polygon sectors may be lower than others (this is a birds eye view), I want the player to be stand on top of the highest one. Therefore I thought what I can do is each game tick would be to check which boxes the player intersects, and then find the polygon with the highest 'height' and use that as the base height for the player.

An example would be below:

Is this a viable way of doing it? That this game is 3D, but I only have to do two dimensional calculations for the height which reduces the computation and makes this easier.

The level has been cut up into a BSP tree so the following is a gross misrepresentation of the level, however I don't see any obvious way (immediately) to exploit the BST property to find out the highest sector that the player would be standing in. So far the best way I could think of was to use narrow phase collision detection described above and hope that is *extremely* fast.

I am looking for speed here, so if you know of any better algorithms or some faster way of doing this, please let me know.

EDIT: The focus of this post is for high level algorithms, of which they can be optimized later on. No actual collision detection code has been made yet.

# Answer
> 0 votes
Since there may be very thin slivers that go into the bounding box, there is no choice but to take the bounding box edges and calculate if any of them intersect with the line segments in the surrounding polygon.

Some optimizations that can be done are as follows:

If there can be a bounding box on the polygon elements, it might be possible to not have to do line-to-line intersections by doing yet another "broad phase pass" in the narrow phase by checking bounding boxes (ex: Put a square around a triangle and check boundaries).

If there's a BSP tree, you can check what sector the player is in as a default by traversing it, so if it's not insanely unbalanced then you have approximately an O(log n) runtime. This can be optimized to O(1) if each chunk stores some sector for the entire chunk if nothing is in it. If the map doesn't have too many changing heights, this could amortize the cost from O(log n) to O(1).

Otherwise, using line intersection is something I appear to be stuck with, so thats O(k) which is the number of lines in the narrow phase.

As stated earlier, line intersection is required in case some small sliver/jagged edge is poking into the player. This also has to be handled with collision detection as well.

As a note for algorithms: CLRS has a chapter on efficient intersections in its computational geometry chapter.

---
Tags: collision-detection
---


title: OpenGL Water Waves - gradually advance

text:
# Question
Title: OpenGL Water Waves - gradually advance
I want to make a simulation of water drops producing waves, in OpenGL with C++. I calculated the height for each point of my plane grid in the 'Vertex Shader' with this formula:

The problem is that I don't know how to generate the waves so they gradually advance.

---

This is what my waves look like:

I want to have one circle at the beginning instead of all of them. The first circle should get bigger, like in the photo.

---

How do I do this?

# Answer
> 1 votes
See that `t` there towards the end?

That represents *time.* Replace it with the system clock time in milliseconds, adjust Phi as necessary (so that the waves move at the desired rate: larger phi value means they'll move more quickly, smaller phi and they've move more slowly, negative and they're converge rather than diverge), and you're done.

# Answer
> 0 votes
You probably want to do something like a physics simulation of the water surface. If you break the surface up into smaller polygons and connect neighboring polys by virtual springs, you can move one in the center and that movement should propagate over time. Here is an interesting example with links to papers on how it works.

---
Tags: opengl, vertex
---


# Question
Title: How to transfer drag control from one sprite to another? (Phaser)
I have some sprites that are set to horizontal drag only.

What I want to do is, if someone drags vertically up from one of those sprites, when they leave the bounds of that sprite (top edge), spawn a new sprite and be actively dragging that new sprite. The user should not have to release the mouse button, they should just instantly be dragging the new sprite.

I can successfully calculate when the pointer is leaving the first sprite, and spawn a new sprite at that location, but I can't seem to transfer the drag control.

I tried `Pointer.swapTarget`, but that doesn't seem to work - the new sprite is spawned, but just sits there and I have to release the mouse button and re-click on the new sprite in order to drag it.

How can I make the transfer seamless?

# Answer
Without code I'm not exactly sure what you're doing for the dragging now.

So, I see two options:

1. Spawn a new sprite where the old one was before and let the one that was being dragged continue to be dragged.
2. Instead of using the sprite for your logic, use the pointer itself. (One of the paid Zenva tutorials went this route.)
    1. In your `update()` check if `this.game.input.activePointer.isDown`. If it is, and it's over your sprite, make note that you're dragging the sprite in a 'global' variable, like `this.isDraggingSprite`. You might already have this.
    2. Get the current position of the pointer and spawn a new sprite at that location. ('Globally' accessible so that you can check whether or not it is `alive`.
    3. Let the new sprite follow the position of the pointer until is `isUp`.
    4. Create a new sprite at the finished position and `kill` the one that was being dragged. Set `this.isDraggingSprite = false;`.

Globally accessible meaning somewhere it be accessed across updates, which you might already have defined on your game object.

Depending upon how you have things coded now, and what sort of effect you want, one option might be better than the other.
> 1 votes

---
Tags: input, phaser
---


# Question
Title: How to make a simple game based on navigating a set of videos?
I would like to create a simple video game as an interactive art piece.

The game goes like this:

*A video (with sound!) loops while there are two options on the screen (text labels); when the player chooses one of them, another video plays; once it is finished, there are two options once again with a default video looping (?) and so on and so on.*

It is quite simple, however I have had a really hard time finding a way to make it.

Someone suggested *Youtube*, but I don't want the player to be distracted by anything else, to be able to skip, for the video to end and for the player to choose a suggested Beyonce music video etc.

Someone else suggested *Blender* but it seems the video uploaded does not have audio attached so it would be extremely time consuming to write the python script. Both audio and video channels would be treated separately and the video player would artificially redraw video frames through the renderer. *Unity* seeems to be a similar if not a more complex set-up.

They suggested that *Director* used to do this but it is no longer being sold or supported by *Adobe*. I have a **Mac** and was unable to find a version on the internet that allowed me to use it.

Does anyone know how I can realize this project? *Ideally to just plug in the videos, add the options text labels, arrange the sequences of videos and options and the game would play.*

I cannot code or write script so I am hoping that the solution is simple. Someone was going to help me to make it in *Blender* but it turns out it is too difficult there. I might put it up on *Fiverr* if I need script written, however as I have never used it before I am not sure how reliable it is and how easy it will be to communicate all the finer points, to send over the videos etc.

Then once it is made, what sort of software would be needed to play it? Ideally it would be web-based, but I understand this complicates matters even further. I am working on a **Mac** but might show it on a **PC** \- is this impossible due to incompatibility? Would it be ok running it on a computer eight hours a day?

Would it be possible to make the game run so that the player has *no autonomy over the computer used* \- so they would not be able to exit the game?

**All and any help appreciated! Thank you**

# Answer
I'm not sure you're going to find a solution that completely lacks some sort of configuration language or script. However, this is definitely something that could be done easily using HTML.

```
<html>
    <head>
        <style>
            body
            {
                margin:0;
                padding:0;
                width:100%;
                height:100%;
                background-color:black;
                position:relative;
                font-family:arial;
            }
            video
            {
                position:absolute;
                top:50%;
                transform:translateY(-50%);
            }
            a
            {
                position:fixed;
                top:50%;
                background-color:rgba(0,0,0,.5);
                color:white;
                font-size:24px;
                padding:20px;
                text-decoration:none;
            }
            a.left
            {
                left:0%;
            }
            a.right
            {
                right:0%;
            }

        </style>
    </head>
    <body>
        <video autoplay loop width="100%">
            <source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
        </video>
        <a class="left" href="left.html">Left Button</a>
        <a class="right" href="right.html">Right Button</a>
    </body>
</html>

```

This is a simple page made up of a `<video>` element and two `<a>` (link) elements overlayed on top of the video. The video is scaled to fill the width of the page automatically and centers it in the available vertical space (if any). The `<video>` element automatically plays the referenced video file when the page loads and loops it at the end of playback.

Clicking either button takes you to left.html or right.html, which in your case could be variations of this same page with a different video file playing.

The trickiest bit in getting this to work as you want is locking down the web-browser so that it does not allow the user to escape the site or use the interface, but most browsers have configuration settings to allow this behavior.
> 1 votes

# Answer
**Getting a tool that does it**

Sound like something doable in DVD menus, yet I am unaware of an editor that allows creating complex custom DVD menus.

You may consider building your game on a slides software; I mean something like LibreOffice Impress / Google Docs Presentations / Microsoft PowerPoint. There you can embed videos and have links that jump to a different slide.

Another option is to use Camtasia Studio, which is a video editor that has options to create video quizzes. On that note, you may try to find software dedicated to create quizzes that support video.

If you are looking for a software to do this task, try asking on softwarerecs.stackexchange.com.

---

**Web based**

Aside from that, I would say to build it with HTML5 + JavaScript. You can use the HTML5 video element for playback, and build a simple UI for the options via HTML + JavaScript.

Preventing the user to access, any video is another thing. It is not doable without server side code (the server would have to keep track of the progress of the players and only allow to download what they have access to).

You may obscure the URLs, perhaps by building the interface with flash (or similar), but still there are ways around it.

---

In all honesty, creating the game web based is easier than the options I present below, because of one simple reason: you do not have to worry about compatibility, which becomes problem of the browser.

I suggest to not being afraid of HTML. It is very easy to get started; all you need is a web browser and a text editor. In addition, do not worry about causing harm, the web browsers intend to prevent web pages to cause harm to your computer♪. The worst thing you may do is cause your web page to be unresponsive.

♪: ok, there is malware, but you are not going to do create any previously unseen malware by accident.

---

**Developing a different portable solution**

The next option would be to build it with Java or .NET, which both can run on PC (Windows) and PC (Mac) and PC (Linux) and potentially in other platforms given the proper virtual machine installed. That would be Mono in the case of .NET.

I would suggest to stick to the widgets in the standard library (I guess Swing for Java safe option, and it would be WinForms for .NET). The alternative is to find a portable library that can work in the target platforms; I do not advice this because it would make it harder to find a visual designer for the GUI. Speaking of which, get an IDE with a visual designer for the GUI, since you do not want to get into the details of how that works.

For playing the video, this is matter of opinions. Yet, the fact that you want a portable solution constraints your options. I lack experience on making portable video players, so cannot attest for the quality of the solutions available... Anyway, for what I can find, you can use vlcj for Java, and you could use Monogame for .NET (it implement XNA API which includes a VideoPlayer class).

---

I guess the next option would be to use C++, I'll refrain from making suggesting on this because I don't know enough to build a portable video player in C++ and I don't think this is what you want anyway.
> 1 votes

---
Tags: video
---


title: MMORPG Server [Visible service]

text:
# Question
Title: MMORPG Server [Visible service]
Is there an algorithm for collecting the list of \[to\_spawn\]\[to\_despawn\]\[to\_send\_movement\] players from world on player movement from point A to B.

I have list of player in world. I have function that collects the visible players for a given point. Each player has a list of visible players.

How can I do this fast & efficient?

```
void p_spawn::filter(player_list &p_l)
{
    player_list to_depsawn;
    player_list to_spawn;
    std::shared_ptr<Node> temp = std::atomic_load(&head);
    if (p_l.size() > 0)
    {
        while (1)
        {
            if (!temp) break;

            bool in = false;
            for (size_t i = 0; i < p_l.size(); i++)
            {
                if (p_l[i]->eid == temp->p->eid)
                {
                    in = true; break;
                }
            }

            if (!in)
            {
                to_depsawn.push_back(temp->p);

                temp->p->spawn.add_erase(parent, false);
                add_erase(temp->p, false);

            }
            temp = temp->next;
        }

        for (size_t i = 0; i < p_l.size(); i++)
        {
            if (!inside(p_l[i]->eid))
            {
                add_erase(p_l[i]);
                p_l[i]->spawn.add_erase(parent);

                to_spawn.push_back(p_l[i]);
            }
        }
    }
    else
    {
        while (1)
        {
            if (!head) break;

            head->p->spawn.add_erase(parent, false);
            to_depsawn.push_back(head->p);
            head = head->next;
        }
    }

}

```

# Answer
The short answer to your direct question: generate your list of visible entities in a container (sorted by id or the like) and use `std::set_difference` with the previous sorted list of visible entities.

You are asking roughly about Area of Interest: finding all objects within range of a player for which it should receive network updates.

The simple algorithm for a range-based test like illustrated would be to gather all objects within range (use your game's bounding volume hierarchy for this), and then calculate a set difference with the previous update's AOI set (just about every programming language has a standard library function for doing this efficiently; `std::set_difference` in C++ for example).

The difference in one direction tells you which objects have been removed from the AoI set. The difference in the other direction tells you which objects to added to the AoI set.

Note that you really don't just want a single range like this. You want two ranges: a closer "add to AoI" range and a larger "remove from AoI" range. Otherwise, you easily get into a case where objects ping-pong between being in AoI as they move along the edge of the AoI range, which can lead to excessive amounts of network traffic for add/forget packets, along with whatever client-side work those packets trigger (like loading/unloading resources). Using two separate ranges with a suitable distance between them avoids this from happening in every case except where an object is just moving back and forth, close and far.

You can also apply other AoI schemes on top of this. For instance, you might have an Explicit Object of Interest system that ensures a particular object stays in a client's update set independent of range. This can be useful for enemies that are attacking the player or have recently been attacked by the player. You might also use AoI schemes that aren't just simple ranges, such as using the player's look direction to form a Cone of Interest.

Yet another trick is to add a delay to objects leaving the update set. This is another potential solution for objects sitting near the AoI range, as well as avoiding frequent add/forget messages if using a Cone of Interest and the player is looking around a lot.

Note also that this all applies pretty much equally to other range-based systems like chunk loading in an open world game.
> 1 votes

# Answer
Sounds to me like what you are after is known as `Potentially Visible Sets`. I'd be surprised if there is any 3D game that doesnt implement some form of it.

If you need an implementation, Doom and Quake code implements it.

https://en.wikipedia.org/wiki/Potentially\_visible\_set
> 0 votes

---
Tags: mmo, server, c++
---


# Question
Title: Firing a simple sphere from below the camera at crosshair in the centre of the screen, with or without raycast
I have a game that spawns "enemies" within a sphere around the camera, the player moves the camera to target and simply presses the screen to fire. For now my "ammo" is simply a sphere and for visual purposes the object I'm firing from is a sphere located below the camera. the "ammo" should fire from the "cannon" below the camera directly towards the crosshair and hit whatever target is in the crosshair.

With some online help this is how my crosshair is generated:

```
if(Time.timeScale != 0)
    {
        if(crosshairTexture!=null)
            GUI.DrawTexture(new Rect((Screen.width-crosshairTexture.width*crosshairScale)/2 ,(Screen.height-crosshairTexture.height*crosshairScale)/2, crosshairTexture.width*crosshairScale, crosshairTexture.height*crosshairScale),crosshairTexture);
        else
            Debug.Log("No crosshair texture set in the Inspector");
    }

```

And currently this is how my "Cannon" works

if ( Input.GetButton("Fire1") && Time.time \> mNextFire){

```
        mNextFire = Time.time + mFireRate;

        Rigidbody projectile= (Instantiate (ammo, gameObject.transform.position, Quaternion.identity)).GetComponent<Rigidbody>();
        projectile.AddForce (projectile.transform.forward * mHitForce);
    }

```

Then on the ammo, I have this:

```
  int x = Screen.width / 2;
  int y = Screen.height / 2;
  transform.LookAt(new Vector3(x, y));

```

but it is horribly inaccurate, I had to move the canon around so it appears to be firing from below the camera, the speed/velocity is off and it barely hits what's being aimed at. It also often appears to go through the cross hair but doesn't collide with the target. I know it's not the target cause if I move the canon around a bit and keep the target still, it hits, the target takes damage, life bar decreases and the "ammo"that hit it "disappears".

I know questions like this are all over the internet however none of them describe my problem, and the ones I found somewhat similar have no solutions. After days of frustration I decided to ask the question here, I just started unity last week so I apologise in advance if my problem seems silly.

Also, I've been seeing a lot of things with raycast, I found this script that projected a yellow laser towards the centre of the screen;

```
void Update()
{
    int x = Screen.width / 2;
    int y = Screen.height / 2;

    Ray ray = camera.ScreenPointToRay(new Vector3(x, y));

    Debug.DrawRay(ray.origin, ray.direction * 1000, new Color(1f,0.922f,0.016f,1f));

}

```

it worked perfectly and projected the laser right to the centre but what am I supposed to do with it afterwards? how do I make the projectile follow it? I'd really appreciate the help. Thank you!

# Answer
> 1 votes
The idea of using raycasting to model projectiles is that we assume the projectile moves fast enough that we can treat its motion as instant, not continuous. That is why it works well with gunfire, where the human eye usually wouldn't catch the bullet traveling through the air anyway.

The alternative, to make the projectile a rigidbody, is preferred for slower-moving objects since it updates with each timestep. You can get the path, but if the object moves fast enough, it might entirely skip past the object with which it is supposed to collide, like if it moves 2 units per step and the object is one unit wide.

The problem in your scenario is that you want to both see the path and have accurate collisions when the projectile moves fast. Two possible solutions:

1. Assuming the target does not move, you can use a raycast to check for collisions. Then, you can Lerp from the cannon to the point of impact. You delay the action that happens on impact until it reaches the destination, even though you already decided it would hit. This, however, would register false collisions if the target moves during that time.
2. Launch the projectile normally, with a rigidbody. Then, each step, raycast ahead in the projectile's path, but only about as far as the projectile would move in that step based on its velocity. This means if you get a raycast hit, it would collide between the current step and the next step. Then call the code for when the target is hit either now or, probably better, on the next frame.

**Update**

To clarify the second solution, imagine you fire the projectile with a velocity of \<2,6\> (2 units per second in the x direction per second, and 6 units in the y direction per second. I'll stick to 2 dimensions for simplicity, but the concept is the same in 3 dimensions). Next frame, the object should be located at (oldPosition.x + 2 * deltaTime, oldPosition.y + 6 * deltaTime). Cast a ray from the old position to this new position. If it hits anything, then you know that there should be a collision on the next frame, even if the object is moving so fast that the physics engine fails to catch it.

---
Tags: unity, raycasting, first-person-shooter, projectile-physics
---


# Question
Title: How do I make my character jump on a platform?
This is the code I've written so far:

Html:

```
 <div id="stage">
  <div id="splash" class="screen">
    <h2>Land</h2>
    <button id="howtobutton">Instructions</button>
    <button id="hsbutton">High Score</button>
    <button id="optionsbutton">Options</button>
    <button id="playbutton">Play Game</button>
  </div>
    <div id="instructions" class="screen">
      <h2>How to Play</h2>
      <button class="backtomenu">Back to Menu</button>
    </div>
  <div id="highscores" class="screen">
    <h2>High Scores</h2>
    (Username), your high score is:
    <button class="backtomenu">Back to Menu</button>
  </div>
  <div id="options" class="screen">
    <h2>Options</h2>
    <button class="backtomenu">Back to Menu</button>
  </div>
    <div id="game" class="screen">
      <div id="ground" class="platform"></div>
      <div id="score"> Score:</div>
      <div id="player"></div>
      <button id="btn-quit" class="backtomenu">Back</button>
    </div>

```

CSS:

```
div {
  border: 1px solid black;
} h2 {
  text-align: center;
} button {
  display: block;
  width: 100px;
  margin: 10px auto;
} #stage {
  width: 400px;
  height: 400px;
  overflow: hidden;
  position: relative;
  background-image: url(http://www.hlgjyl888.com/data/wallpapers/151/WDF_1917288.gif);
  background-size: cover;
} #splash {
  display: block;
} .screen {
  position: relative;
  display: none;
  width: 100%;
  height: 100%;
  color: white;
} #player {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  position: absolute;
  background-color: blue;
  bottom: 50px;
  top: 269px;
  left: 100px;
}
} #score {
  position: relative;
  top: 0px;
  right: 5px;
  width: 100px;
} #btn-quit {
  position: absolute;
  margin: 0;
  bottom: 0px;
  left: 0px;
} .platform {
  position: absolute;
  background-color: white;
} .onPlatform {
  background-color: blue;
}
#ground {
  top: 300px;
  width: 400px;
  height: 3px;
}

```

JavaScript:

```
var gravity = 1;
var maxheight;
var timer;
var jump = 32;
var velocity = 0;
var jumppressed = false;
// var username = prompt("What is your name?")

$(document).ready(function() {

  $('#howtobutton').click(function() {
    showScreen('#instructions');
  });
  $('#hsbutton').click(function() {
    showScreen('#highscores')
  });
  $('#playbutton').click(function() {
    showScreen('#game')
  });
  $('#optionsbutton').click(function() {
    showScreen('#options')
  });
  $('.backtomenu').click(function() {
    showScreen('#splash')
  });

maxheight = Math.round($("#stage").height() - $("#player").height());

timer = setInterval(update, 1000/60);

   $(document).keypress(function(e) {
    console.log(e.which);
    if (e.which === 32) {
      console.log("it works");
      jump();
    }});
});

function showScreen(screen) {
$('.screen').hide();
$(screen).show();
};

function jump() {
  if ($("#player").position().top >= maxheight) {
    console.log("Jump is working")
    velocity = -15;
  }
};

function update() {
  if (velocity === 0 && $("#player").position().top === maxheight) {
  } else if (velocity > 0 && $("#player").position().top >= maxheight) {
    console.log(maxheight + " through ground" + $("#player").position().top);
    $("#player").css("top", maxheight + "px");
    velocity = 0;
  } else {
    velocity += gravity;
    var newPos = $("#player").position().top + velocity + "px";
    $("#player").css("top", newPos);
  }
};

```

However I'm very new to game development, I've been stumped for a while now, I can't figure out a way to control my character movement. Can anyone tell me what's wrong with my code? My character should be jumping on the platform whenever the space key is pressed (that's it).

# Answer
The function you are calling (`jump`) is only being defined AFTER the method that is handling the input, so it happens the error "jump is not a function".

Just move your `jump` function code to the beginning and it will work(I have tested it myself).
> 1 votes

---
Tags: javascript, jumping, html, jquery, css
---


# Question
Title: AI Algorithm to make enemy smarter from level to level in Runner game
I am designing a City-Runner game in Unity 3D Engine.I am a beginner in game development (not in programming). The idea is really simple, the Runner will be followed by AI enemies, and if caught by one of them it will be dead or his energy will decrease.

Anyway I cannot find any Algorithm for **implementing a "smart" AI**, in the sense that not only he will follow the player and do Path-finding to the player, but also get smarter from the first level to the second level.

Probably AI must **store some information/state** in regards to the terrain and the runner position.

My question here is :

1. **Is it a good idea to make the AI smarter** (because all the runner does is running in a straight line, only the person who is playing the game can change his direction- left, right; so maybe its not like the learning will be very beneficial)
2. If this is a good idea, do you have any knowledge on what **algorithms may be used (implementing neural-nets or something alike)**
3. If it's not the best idea, what **AI mechanism** can I use expect of path-finding, wandering, seeking, flocking ??

Any kind of advice would be greatly appreciated !!

Thank you.

# Answer
As @JohnHamilton noted, the simplest way to implement this AI is to **always have the "perfect" move**. For example, if you were creating an FPS, the AI can find the *exact* vector to the player, and can precisely adjust for the time it takes for its attack to reach the player, and can calculate the required trajectory to compensate for intervening terrain....

For other types of games, the nature of these parameters may be different but the approach is the same. The AI has a *lot* more information about the world readily available than the player does. It "knows" exactly what move to make every time.

A "dumb" AI just chooses not to make that move sometimes.
> 2 votes

# Answer
Could you please make a screenshot, their movement and algorithm depend on the environment and gameplay style?

I bet it's good to pick a grid of points around player that are free, then calculate best destination for every enemy to catch player. But making this every frame could be overkill, so better put it in coroutine to calculate every second or so, make chosen grid big enough, but relatively to calculation time, pick the best points to go to for enemy, take into account players movement direction.

You can have Manager that records some amount of recent player moves and calculates next destination of the enemy, for example: left, left, right, left, right. Now every enemy gets it desired position depending on how the player moves, so algorithm predicts where the player would probably turn.

Make some bias value and put it into the algorithm, decrease it when level increases. If you want to use a neural network, you can do that, but I would suggest calculating values like bias while loading level, not on runtime, this way you could have more data stored.

You can use current player moves data (they are small like a queue of 10 elements) to put into your algorithm and also put the last move into the algorithm or pick it from the queue if there is a method for it, I guess there is only `Peek()`.

But mostly algorithm will depend on different static values for this level. Like if the player risky, playing safe, trying to defend and all that stuff. You can even modify these values a bit on runtime. As I said I can't really propose any algorithm as I don't know anything about gameplay.

You have to take into account obstacles if you have them.
> 0 votes

---
Tags: unity, game-design, animation, ai, game-mechanics
---


# Question
Title: Legal - Will code-naming a project after Marvel property be a problem?
I am developing a game, and since I haven't decided on a name yet, I've named it say, Project Deadpool. I plan to release the game as a beta. Will this cause any problems. It is just a name until a proper name can be decided.

# Answer
> 3 votes
Imagine your game attracts the attention of Marvel or any other company's lawyer sometime in the future. For whatever reason, sound or unsound, they claim your game is infringing on their intellectual property and tell you to take it offline.

If you go to court to argue that you didn't use any of their IP, and they present evidence showing the original name of the project was literally the name of one of their properties, that doesn't help your case. To a neutral observer it may look very much like you set out to deliberately infringe on their IP, later name changes and other differences notwithstanding. You'd have to work that much harder to change a judge's mind in your favour.

So why put yourself in that position in the first place?

Generally it's better to avoid getting into such a situation from the start. Getting into a legal battle with a huge company can be astronomically expensive, whether or not you've broken any law. The economics and systems of IP law tend to encourage these companies to be very protective of their properties, so the general not-legal-advice recommendation is don't go out of your way to bait them. ;)

---
Tags: legal
---


# Question
Title: How to encourage players to not lessen their own gaming experience with mods and cheats?
In many games (often single-player computer games) there's a built-in way to alter gaming experience; either by modding (e.g. Minecraft, most games on Steam Workshop and Nexus Mods) or by some in-game way to cheat (console commands or retro-style cheat codes). And even if there is no native support, life will find a way. This can be an amazing asset to any players for several reasons:

* It can enhance your gaming experience by adding new content (levels, quests, items, etc.).
* It can remove / change features you dislike about a game (perhaps you dislike the 10 minute long game intro where you cannot move. I'm looking at you, Skyrim!)
* It helps you have some stupid fun (what happens if every force applied to a rag-doll is multiplied by x10?)

These are all great things, but from experience and observation it's very clear that these things can have the complete opposite effect:

* New content can be utterly broken and unbalanced (instant-kill weapon).
* Removing features can lessen gameplay (I don't like questing; let's remove all quests).
* Remove the need to *actually do anything* (I need to gather 1000 gold to buy this item? `give_gold 1000`).

Of course what a player finds fun and what might run their experience is completely subjective, which is why I'm not wanting to remove these features, just discourage extensive the use of them. Because the problem here is not that the player is *able* to do these things; the problem is that the player is *unable* to see that it might affect their gaming experience in a negative fashion and when it does they are often unable to localize the problem and its source leading to them getting bored of the game because of their own actions.

So my question is this; **How do I give players all of the benefits of altering my game but also make them understand that it might lessen their gaming experience so that they (themselves) can regulate their use of it?** Again note that I'm not trying to **completely prevent it**; only **discourage it**.

# Answer
> 11 votes
A very common method is to **disable achievements when gameplay-affecting mods are enabled or cheats are used**. Players want those achievements. But when they are using overpowered mods or cheats, they become meaningless anyway, so disabling them is completely reasonable. This encourages the player to try everything in the game in vanilla mode at least once.

The nice thing about this method is that it only affects players who have not yet unlocked all achievements. The moment where all achievements are unlocked is also the moment where the player runs out of stuff to do. So this is also the ideal moment to bring out the mods and cheats to refresh the game experience.

To still allow the player some convenience mods which improve the game experience without making the game notably easier or harder, you could mark certain functionality in your modding API as "achievement-safe" and still allow achievements with mods which only use the achievement-safe API features.

---
Tags: game-design, modding, user-experience
---


# Question
Title: How do i create a random planet generator and use it on Unity?
For example : https://managore.itch.io/planetarium

Something like this, create random sprite circles who at least are realistic looking, as far as realism can be pixel, I don't think this can be done on Unity alone so i think i might need to implement it after i coded it in another language or another engine, so my how do i do it? can i do it on unity? and how would i implement if i decided that unity isn't fit for this thing?

The usage of the planets will be throughout the game and will be used as the main planet so it is of great value to the game

# Answer
Short Answer:if you want generate random planet, you should generate Random rotation,distance,color,etc for instantiated planets.

you asked about pixel effect to your sprites. you can do this by using shaders:

> Shaders are small scripts that contain the mathematical calculations and algorithms for calculating the colour of each pixel rendered, based on the lighting input and the Material configuration. https://docs.unity3d.com/Manual/Shaders.html

you asked about language:

> In Unity, shader programs are written in a variant of HLSL language (also called Cg but for most practical uses the two are the same).https://docs.unity3d.com/Manual/SL-ShadingLanguage.html

next you mentioned problem with orbiting sprites in 3d position, so instead of using sprites you can shadering 3d objects to 2d objects(like the upper image) or by using World Space UI:

> Creating a World Space UI The UI system makes it easy to create UI that is positioned in the world among other 2D or 3D objects in the Scene. Start by creating a UI element (such as an Image) if you don’t already have one in your scene by using GameObject \> UI \> Image. This will also create a Canvas for you.https://docs.unity3d.com/Manual/HOWTO-UIWorldSpace.html

this is generator and planet script that I explained all thing in my code(by commenting)

Generator Script:

```
using UnityEngine;
using System.Collections;

public class Generator : MonoBehaviour {
    public GameObject prefab;//planet prefab
    public static GameObject Earth;//All object will orbit around this
    public static float lastTime;//last time

    void Update () {
        Earth = GameObject.FindGameObjectWithTag("Earth");//Find Earth
        if (Input.GetKeyDown(KeyCode.Space))//if press space generate planet
        {
        lastTime = Time.time;//when object instantiated store Time.time as last time we use it in planet script
        Instantiate(prefab, Earth.transform.position, Quaternion.identity);
        }
    }
}

```

Planet Script:

```
using UnityEngine;
using System.Collections;

public class Planet : MonoBehaviour {
    [Range(0,100)]//Range for speed
    public float speed = 20;// Rotation Speed
    public float alpha; //will use for cos & sin (as angle)
    public float distance;//distance from center
    public float Rotation;//rotation angle
    public float currentTime;//Time start when Instantiated

    void Start () {
        //Initialize new planet with Random rotation & distance & size

        //Random Rotation between -2 & 2
        Rotation = Random.Range(-2.0f, 2.0f);
        //Random distance  between -1 & 2
        distance = Random.Range(1.0f, 2.0f);
        //Random Size between 0.2f & 0.7f
        var Size = Random.Range(0.2f, 0.7f);
        //Set localScale with random size
        transform.localScale = new Vector3(Size, Size, Size);

        //calculating current time by subtraction Time.time and lastTime
        currentTime = Time.time - Generator.lastTime;

        //GetComponent<MeshRenderer>().material.color = new Color(Random.value, Random.value, Random.value); //Random Color
    }

    void Update () {
        //Timer
        currentTime += Time.deltaTime;

        var X =  (distance * Mathf.Cos(currentTime));//X
        var Y =  (distance * Mathf.Sin(currentTime));//Y
        var R =  (Rotation * Mathf.Cos(currentTime));//Rotation

        //give earth from generator class
        var Earth = Generator.Earth;
        transform.position = Earth.transform.position + new Vector3(X, R, Y);// RotateAround Earth

        //Basic Orbit:
        //this is simple way that you can orbitting objects around other object
        //transform.Rotate(transform.up * speed * Time.deltaTime);
        //transform.RotateAround(Earth.transform.position, Vector3.up, speed * Time.deltaTime);
    }
}

```

I put this project in my github: https://github.com/smkplus/orbit/archive/master.zip
> 2 votes

---
Tags: unity, c#, c++, random
---


title: Sprite wrong position on screen

text:
# Question
Title: Sprite wrong position on screen
I want to render one sprite on top of another one. I create both sprites using same coordinates and while debuging I can see that they have same position but still one is being rendered beneath another and slightly to the left. Could somebody tell me what am I doing wrong? here is my code where I create sprites:

```
Sprite sprite1 = new Sprite(new Texture("1.png"));
sprite1.setScale(1/PPM);
Sprite sprite2 = new Sprite(new TextureRegion(...));
sprite2.setScale(1/PPM);
sprite1.setPosition(x,y);
sprite2.setPosition(x,y);

```

Could it have something to do with scaling? Or maybe the fact that second sprite is created from TextureRegion?

# Answer
> 1 votes
Check the origins of the sprites. if one has its pivot in the middle and the other one top left for example then they appear in different positions.

---
Tags: libgdx
---


# Question
Title: Java - Declaring a random Vector affects a Vector in another class?
I'm working on a 2D game and I've come across something strange which I've been working to fix the whole day but can't.

I'm trying to make an arrow fly, but modifying it's class affects my `Player` class. It seems that any Vector2 variable that is created changes the `Player` velocity somehow.

I have a `GameObject` class which all object classes extends from which looks like this:

```
public abstract class GameObject {

protected Vector2 position;
protected boolean isVisible = true;
protected Rectangle rectangle;
protected int width;
protected int height;
protected boolean solid;
protected float boundsOffset = 0;

public GameObject(Vector2 position) {
    this.position = position;
}

public Vector2 getPosition() {
    return position;
}

public void setPosition(Vector2 pos) {
    this.position = pos;
}

public boolean isVisible() {
    return isVisible;
}

public void setVisible(boolean b) {
    this.isVisible = b;
}

public Rectangle getBounds() {
    return new Rectangle(this.getPosition().x + boundsOffset, this.getPosition().y, (width * Main.SCALE) - boundsOffset, (height * Main.SCALE) - boundsOffset);
}

public Vector2 getCenter() {
    return new Vector2(position.x - (Width()/2), position.y + (Height()/2));
}

public Vector2 getTop() {
    return new Vector2(position.x - (Width()/2), position.y + (Height()));
}

public Vector2 getBottom() {
    return new Vector2(position.x - (Width()/2), position.y);
}

public void setWidth(int n) {
    width = n;
}

public void setHeight(int n) {
    height = n;
}

public int Width() {
    return width;
}

public int Height() {
    return height;
}

public boolean isSolid() {
    return solid;
}

public void setSolid(boolean b) {
    solid = b;
}

public void setBoundsOffset(float value) {
    boundsOffset = value;
}

public float getBoundsOffset() {
    return boundsOffset;
}

public abstract void update(float delta);

public abstract void render(SpriteBatch b);

```

}

I also have a `Player` class which I said previously, extends the `GameObjects` class. The `Player` movement works by using `GameObjects` position Vector2 and adding a `Velocity` vector which is declared in the `Player` class.

Heres the movement:

```
if(gs.getInputManager().isKeyDown(Keys.W)) {
        if(getVelocity().y < maxSpeed) {
            getVelocity().y += accel;
        } else {
            getVelocity().y = maxSpeed;
        }
        if(!rangedMode)
            setDirection(Main.DIR_UP);
    } else if(gs.getInputManager().isKeyDown(Keys.S)) {
        if(getVelocity().y > -maxSpeed) {
            getVelocity().y -= accel;
        } else {
            getVelocity().y = -maxSpeed;
        }
        if(!rangedMode)
            setDirection(Main.DIR_DOWN);
    } else {
        getVelocity().y -= Math.min(Math.abs(getVelocity().y), damp*Math.signum(getVelocity().y));
    }

    if(gs.getInputManager().isKeyDown(Keys.D) ) {
        if(getVelocity().x < maxSpeed) {
            getVelocity().x += accel;
        } else {
            getVelocity().x = maxSpeed;
        }
        if(!rangedMode)
            setDirection(Main.DIR_RIGHT);
    } else if(gs.getInputManager().isKeyDown(Keys.A)) {
        if(getVelocity().x > -maxSpeed) {
            getVelocity().x -= accel;
        } else {
            getVelocity().x = -maxSpeed;
        }
    } else {
        getVelocity().x -= Math.min(Math.abs(getVelocity().x), damp*Math.signum(getVelocity().x));
    }

getPosition().x += getVelocity().x;
getPosition().y += getVelocity().y;

```

And now to the problematic class, the `Projectile` class:

```
public class Projectile extends GameObject {

float speed = 3;
float travelDistance = 0;
float distanceTraveled = 0;
float angle;
Vector2 velocity = Vector2.Zero;
AnimatedSprite projectile;
boolean inAir = true;

public Projectile(Vector2 position, int type, float angle) {
    super(position);

    this.angle = angle;
    LoadItem(type);

}

private void LoadItem(int type) {
    switch(type) {
    case ItemID.WoodenArrow:
        speed = 3;
        travelDistance = 200;
        projectile = new AnimatedSprite(16, 5);
        projectile.isAnimating = false;
        projectile.currentFrame = AssetLoader.arrowRegions[0][0];
        projectile.setRotation(getAngle());
        projectile.setOrigin(32, 8);
        break;
    }

}

@Override
public void update(float delta) {
    velocity.x = (float) ((speed) * Math.cos(getAngle()));
    velocity.y = (float) ((speed) * Math.sin(getAngle()));
    this.setPosition(new Vector2(this.getPosition().x + velocity.x, this.getPosition().y + velocity.y));
}

public float getAngle() {
    return angle;
}

@Override
public void render(SpriteBatch b) {
    projectile.render(b, position);

     }
}

```

I update and render all my objects by adding them in a list and using a `for` loop. Now when I run the game my player starts sliding with the arrow. The funny thing is that I tried to do this with my `Projectile` class:

```
        @Override
    public void update(float delta) {
//      velocity.x = (float) ((speed) * Math.cos(getAngle()));
//      velocity.y = (float) ((speed) * Math.sin(getAngle()));
//      this.setPosition(new Vector2(this.getPosition().x + velocity.x, this.getPosition().y + velocity.y));
        velocity.x = 1;
        this.position.x += speed;
    }

```

And I would get the same thing. I even tried renaming the `velocity` vector to something completely random, but as soon as I assign a vector object a value the player gets affected.

I'm so sorry for just throwing a lot of code in your faces, but I felt that it was necessary since to me this problem is very strange, but I might just be blind and miss something completely obvious. Anyways thanks in advance!

# Answer
```
Vector2 velocity = Vector2.Zero;

```

With that you are effectively assigning each object's velocity to the same vector object, instead you should create a new one for each object.

```
Vector2 velocity = new Vector2();

```

Like this.
> 0 votes

# Answer
In your abstract class, you are using a Vector2 which will be shared by all the subclasses due to how Vector2s work in LibGdx. In order to prevent this, you need to make a copy of the Vector being passed into your abstract class.

```
public GameObject(Vector2 position) {
    this.position = position.cpy();
}

```
> 0 votes

---
Tags: java, 2d, libgdx, vector, oop
---


title: Isometric camera movement

text:
# Question
Title: Isometric camera movement
My camera system has two objects: the isometric camera itself, and an empty object it's attached to which handles both movement and rotation. When the player drags the middle mouse button, the camera (or, rather, the empty object) moves like this:

```
Vector3 diff = lastFramePosition - currFramePosition;

float xchange = diff.x / 5;
float ychange = diff.y / 5;

//flips the direction of movement if the rotation of the object is a certain way
if (transform.rotation.y == 90 || transform.rotation.y == 180)
                ychange *= -1;

if (transform.rotation.y == 270 || transform.rotation.y == 180)
                xchange *= -1;

Vector3 pos = transform.position;

//moves the camera and restrains it within the limits of the map (core.mapx and core.mapy)
transform.position = new Vector3(Mathf.Clamp(xchange + pos.x, 0, core.mapx), 3, Mathf.Clamp(ychange + pos.z, 0, core.mapy));

```

It turns out, though, that since it moves the empty object along the X and Y axes, dragging up/down or left/right moves it along those axes instead of actually moving the camera view up/down and left/right. The best way I can describe it is like those old isometric games that do the exact same thing. Is there any way I can get it to move like this?

# Answer
> 1 votes
You could achieve this affect by rotating the empty parent object 45 degrees in y, and counter-rotate the camera so it still points the original direction. Now, when you move, move the empty object along its `transform.right` and `transform.forward` vectors by `xchange` and `ychange`.

---
Tags: unity, camera, movement
---


title: Fixing collider for existing scene

text:
# Question
Title: Fixing collider for existing scene
I'm trying to add collider to the 3D scene. I have added mesh collider to the floor but I see the character is still floating up when I play.

How can I edit this collider. I don't see any edit collider option here(like we see in case of box collider & other one's)

Question has been updated with further details:

The floor is not perfectly plane. It's raised from some place and down from other. So, I don't see any problem with character properties. The problem with mesh collider is that it tries to join lower & upper parts of plain with a straight line. It doesn't exactly take the size of plane

# Answer
> it tries to join lower & upper parts of plain with a straight line. It doesn't exactly take the size of plane

Your plane mesh is "open" so when you import it into Unity to use as a collider (that's what a mesh collider does: it takes the mesh already being used for rendering and converts it to a collision mesh) it has to guess how best to close it.

You need to make a second model to use for collision that is a closed mesh. Just close up the geometry in whatever program you created it in, export it and import it as a new asset, and assign it to the mesh collider component.
> 0 votes

---
Tags: unity, collider
---


# Question
Title: Is there any term for reverse gamification?
**Gamification** is a process of applying game mechanics to non-game contexts.

**Reverse gamification** is a process of using non-game context or non-game mechanics in games.

For example:

**Gamification** \- you can learn traffic code with leaderboards, badges, etc.

**Reverse gamification** \- you can create a game (something like gta) to teach traffic code inside it.

Is there any better term for that?

# Answer
Extra Credits made an episode about **De-Gamification** a while ago. But I am not sure if that's what you mean. They are talking about removing incentives and obstacles to allow the player to interact with the game world more on their own whims and not be too focused on success.

You could also be talking about the axis of **Gameism vs. Simulationism**. Gameism is when you design your game mechanics to be as fun to play as possible, even if that means to take gross breaks from reality and plausibility. Simulationism, on the other hand, focuses on making your game as realistic as possible without regard for the game experience. An example for this would be how to handle player injuries in a first-person shooter. Let's say the player gets hit in the leg. A simulationist game designer would have the player limp for the rest of the game. A gameist game designer would not impair them at all and have them regenerate their health after a few seconds. Neither extreme is usually desirable. A too realistic game will have poor game balance and be boring to play. A too gameist game will lack immersion and become unintuitive to play. Experienced game designers try to aim for the middle ground.

Or you could be talking about using games primarily as teaching tools. In that case you are developing **educational games**. These games are necessarily simulationist when it comes to teaching the skills they want to teach. But otherwise they use gameism in order to get the player to practice the skill properly. When you skip a red light in a game for teaching car driving, the game tells you immediately and you are teleported back so you can repeat the situation. You don't get a ticket in your mail a week later. They also can and should use gamification to reward the learning progress, so they aren't de-gamificated either.
> 37 votes

# Answer
I'm not entirely sure if I understand your question correctly.

I think you're asking about games that draw inspiration from real live situations/mechanics/physics, without the explicit purpose of teaching the player about these concepts.

Since this is extremely common in games, there's no specific word for it. A somewhat related word is "**Simulation**" (see Farming Simulator, Flight Simulator, Goat Simulator, and Simulated City), but that also includes a wide range of soft- and hardware applications designed specifically to teach. Also partially related is "Realism". Even less related is "Immersion".
> 10 votes

# Answer
**Gamification** is a spectrum. Adding "game-like" incentives to real-world activities is on the shallow end of the spectrum. Creating an actual game to train those activities is on the deeper end. Essentially, they're the same process.
> 5 votes

# Answer
"Reverse gamification" = "Game design" - a term which includes taking inspiration from the real world and applying such mechanics in games - regardless of what the mechanic is.

Sounds like you're trying to reverse an already-reversed term - it's a bit like referring to a power-of-2 texture as non-NPOT i.e. non-non-power-of-2. Use the original term - "game design".
> 3 votes

# Answer
The term is "serious game". The term covers any game not made primarily for entertainment so any educational game or training game falls in that category.

https://en.wikipedia.org/wiki/Serious\_game

https://www.coursera.org/learn/serious-gaming
> 0 votes

---
Tags: game-design, game-mechanics, terminology, gamification
---


# Question
Title: How do I convert data from a custom editor to a static data structure for use in-game?
I have created a custom editor to allow me to structure data regarding "actors" in a scripted dialogue. This allows me to conveniently store information about how that "actors" dialogue should be rendered to the screen, when they talk.

However, throughout all my research, I can only find reference to custom editors being used specifically for editor-only functionality. In contrast, I want to be able to derive a data structure specifically for use in-game, much like how you can set custom data via the InputManager inspector that allows you to create customised data structures for referencing input in-game.

I have played around with simply invoking a static reference, but this seems to break the editor. I would also prefer to be able to convert the editor data to a game-specific structure, so as to not have to include the actual editor script in the build. I consider that I might have to save the data to a custom type in my assets, but I am unsure of how I would save / load such a file; everything I find on saving data in this way requires value types, and I need to store references to images, colour and font type.

I was thinking I should be creating a separate script or data file to store the required information; but I require a static file, so a script does not seem like the correct way to store this information as an asset, and I am unsure how I would store non-text information such as font and sprite references.

How do I create a seperate data structure from my custom editor, for specific use in my actual build?

# Answer
> 2 votes
I think you are looking for `ScriptableObject`s.

Creating a class which extends ScriptableObject is a way to create a custom kind of asset which can be managed in the project outline like any other asset and is usually edited with a custom editor script.

ScriptableObjects can not exist in a scene on their own. They are always referenced by an actual game object.

So when you have an NPC game object in your game scene, that NPC could have a `NPCController` behaviour with a variable `public NPCDialog dialog`. When `NPCDialog` is a ScriptableObject, you would create a new NPCDialog asset, edit it with your custom editor script, and then drag it from the project outline into the `Dialog` field in the inspector of the NPController of the NPC game object.

# Answer
> 0 votes
I've ended up creating the desired functionality by using a static singleton class, and having my custom editor push and pull the data to an array within this singleton. I am still not convinced it is the best solution; but it is a solution, as far as I have tested.

---

First, I moved my class structure to the game script, so it would still be included in a build. I also include logic to turn the game class into a singleton and overload the `[]` operator for convenient access to the array.

```
using System;
using UnityEngine;

// Basic form of my required structure.
public class ActorListing
{
    public string name;
    public Color colour;
}

// MonoBehaviour structure for storing my actor list in a game object.
public class ActorList : MonoBehaviour
{
    public static ActorList hive;
    public ActorListing[] actors;

    // Setting up ActorList to act as a Singleton.
    private void Awake()
    {
        if(hive == null)
        {
            hive = this;
            DontDestroyOnLoad(gameObject);
        }
        else if(hive != this)
        {
            // I do not want to destroy the game object, as I may be
            // using it for other functionality.
            Destroy(this);
        }
    }

    // Overloading the [] operator so I can directly access actors
    // using actorListing[index].
    public ActorListing this[int index]
    {
        get
        {
            return actors[index];
        }
        set
        {
            actors[index] = value;
        }
    }
}

```

I then add logic to the custom editor to retrieve reference to the local instance of `ActorList`, and pull the `ActorListing` data directly from `actors`. If neither exist, they are created; we assume that `actors` has not been filled out, at this point.

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

// Editor window for managing the actor list.
public class ActorListEditor : EditorWindow
{
    public List<ActorListing> actors;

    // When the window is opened, pull the actor list from the __GameManager.
    void Awake()
    {
        PullActorList();
    }

    // When the window is closesd, push the actor list to the __GameManager.
    void OnDestroy()
    {
        PushActorList();
    }

    // Increment through the actors in the __GameManager actor array,
    // and pull each actor listing to the local actors list
    private void PullActorList()
    {
        ActorList actorList = GetActorList();

        actors = new List<ActorListing>();

        for(int actorIndex = 0; actorIndex < actorList.length; actorIndex++)
        {
            actors.Add(actorList[actorIndex]);
        }
    }

    // Increment through the actors, and push each actor listing
    // to the __GameManager actor array.
    private void PushActorList()
    {
        ActorList actorList = GetActorList();

        actorList.actors = new ActorListing[length];

        for(int actorIndex = 0; actorIndex < length; actorIndex++)
        {
            actorList[actorIndex] = actors[actorIndex];
        }
    }

    // Retrieve a reference to the __GameManager actor list;
    // creating one, if one has not already been created.
    private ActorList GetActorList()
    {
        GameObject gameManager = GameObject.Find("__GameManager");

        if(gameManager == null)
        {
            gameManager = new GameObject("__GameManager");
        }

        ActorList actorList = gameManager.GetComponent<ActorList>();

        if(actorList == null)
        {
            actorList = gameManager.AddComponent<ActorList>();
        }

        return actorList;
    }

    /* Additional functions for displaying and managing editor GUI */
}

```

---

This script is still in its early days, so any input is appreciated; but it seems to offer the functionality I require.

---
Tags: unity, c#, data-structure
---


# Question
Title: How do I enable a Box Collider when a timer reaches 0?
I'm pretty new to Unity, and I am trying to enable a `BoxCollider` from another object when the timer reaches 0, using this code:

```
using UnityEngine;

public class Testv2 : MonoBehaviour
{
    public GameObject otherGameObject;

    private BoxCollider Target;
    public float timeLeft = 30.0f;

    void Awake()
    {
        Target = otherGameObject.GetComponent<BoxCollider>();
    }

    void OnMouseDown()
    {
      timeLeft -= Time.deltaTime;
    }

    void Update()
    {
        if (timeLeft < 0)
        {
            Target.enabled = true;
        }
    }
}

```

My issue is that the timer won't go down unless I keep clicking on the object. How do I enable the timer to start when someone clicks an object, and start counting down?

# Answer
Your problem derives from counting down in the `OnMouseDown()` method. Let's take a look at the API:

> ## MonoBehaviour.OnMouseDown()
>
> OnMouseDown is called when the user **has pressed the mouse button** while over the GUIElement or Collider.
>
> <sub>\- MonoBehaviour.OnMouseDown() @ Unity API Reference</sub>

This means that you make a call to this method when you *press* the mouse button. Your logic performs one increment on the timer, and that is it. In the next frame, you are *still* holding the mouse button, but you have not *pressed* the mouse button - it was already pressed! As a result, the method does not call. For future reference, regarding input, there is a clear distinction between *pressing* a button, *holding* a button and *releasing* a button. That is irrelevant, for now. You do not want to have to continue holding your mouse button in order for your timer to work - you want it to just work straight away.

---

Instead of using this method to count down, you want to use this method to *start* counting down. We can easily do that by setting a `bool` to determine if we are currently counting down, and performing the count down in the `Update` method.

```
using UnityEngine;

public class Testv2 : MonoBehaviour
{
    public GameObject otherGameObject;

    private BoxCollider Target;
    public float timeLeft = 30.0f;

    private bool countingDown = false;

    void Awake()
    {
        Target = otherGameObject.GetComponent<BoxCollider>();
    }

    void OnMouseDown()
    {
        countingDown = true;

        // If you want to be able to stop the timer by clicking the
        // button again, replace the above line with
        // countingDown = !countingDown
    }

    void Update()
    {
        if(countingDown)
        {
             timeLeft -= Time.deltaTime;
        }
        if (timeLeft < 0)
        {
            Target.enabled = true;
        }
    }
}

```
> 0 votes

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


# Question
Title: Game (Physics) work in Unity Editor/Remote but won't on Android?
I have a script attached to a car game object that allows the player to tap the screen and then accelerate, the game object has a RB2D and collider set to it , it works fine in Unity Remote , but when I download the APK , as soon as I tap the screen , collisions go completely bezerk and the car just starts ignoring collisions , what's going on? As I need this to work to complete my game , as the player can move side to side with the accelerometer but I also want them to move forward when they touch the screen. Also , my game is 2D. Plus , since then , when the car ( my object) collides with anything else in the scene , it ignores it ( the obstacles just have Box Colliders on them). I had to freeze rotation so it could stop spinning out when it hit soemthing , now it just won't recognize collision at all. What's going on? The code I think is causing the error starts at line 32. I have obstacles the player has to dodge and they all have box colliders and an appropiate script attached to them as well ( so when they collide with my player , it destroys it)

I've figured it out , Collision works when I first start the game , but when the player dies and I press "Replay" , it goes crazy. Here's the script that controls the enemy cars spawning , what the hell do I do to fix this?

```
 Code (CSharp):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyCar : MonoBehaviour {
public float speed ;
public float acceleration = 0.5f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
    speed += Time.deltaTime * acceleration;
    transform.Translate(new Vector3(0, 1, 0) * speed * Time.deltaTime);

}
void OnCollisionEnter2D(Collision2D col)
{
    if (col.gameObject.tag == "Coin")
    {
        Destroy(col.gameObject);
    }
}
}

```

I've done everything in the book trying to solve this , re-install unity , add different colliders etc. What's weirder is that it is FLAWLESS in Unity Remote and the Editor , these issues only arise when I test out the apk.

Here's how my game usually looks when the collisions work.

Now when it collides with a car ( on android) , it just ignores it and is slightly pushed back.

Help me!

Here is my script attached to enemy cars ( the cars that should destroy the player on Collision)

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

public class EnemyCar : MonoBehaviour {
    public float speed ;
    public float acceleration = 0.5f;
 // Use this for initialization
 void Start () {

    }

    // Update is called once per frame
    void Update () {
        speed += Time.deltaTime * acceleration;

        transform.Translate(new Vector3(0, 1, 0) * speed * Time.deltaTime);

 }
    void OnCollisionEnter2D(Collision2D col)
    {
        if (col.gameObject.tag == "Coin")
        {
            Destroy(col.gameObject);
        }
    }
}
```

Also here is the inspector view of my Player Car

Here is the inspector view of an enemy car ( they all have the same things)

# Answer
> -1 votes
currentPlatformAndroid is misspelled right at the top of the file, inside the #IF.

---
Tags: unity, c#, 2d, collision-detection, unityscript
---


# Question
Title: Making a Game Like Pineapple Pen in libgdx - But game is too easy
It is kind of like a theoretical question.

I was trying to make a game like Pineapple Pen just for the sake of learning libgdx more and just for fun .

Pineapple Pen is pretty hard game but there is not much to write code in it as there is a object which keeps on moving to its x-axis and there is a pen at the bottom and you have to tap the screen to hit the pineapple. \<--- This game is quite hard

But the game that I made which is quite similar to the Pineapple Pen, is very easy like one can always expect when can you hit the pineapple.

I am guessing there is a theory behind all this which beyond my understanding, anyone can shed some light in this topic?

# Answer
The difficulty of your game will depend on a couple of time intervals. The first time interval is the maximum amount of time between the pineapple appearing and the player tapping and successfully hitting the pineapple. The second one is the window between the earliest and latest times the player can tap and score a hit.

Understanding how you can adjust either or both of these time intervals will help you tune your game. Some factors will be:

* the movement speeds of the pineapple and pen
* the collision shapes for the pineapple and pen
* the distance between where the pineapple appears and where it can be hit by the pen

If you want to start by reproducing the original game, examine it carefully to figure some of those things out. You can always learn from other designs, even if you decide later to go in a different direction.
> 1 votes

---
Tags: game-design, difficulty
---


# Question
Title: How to handle complex inputs in 2D platform game?
I am trying to add keyboard control for my character in 2D platform game with JavaScript. The character can `walk, dash and jump`. Here is my current code:

```
if(keyboard['LEFT']) {
    //walk to left
    //...
} else if (keyboard['RIGHT']) {
    //walk to right
    if(keyboard['SHIFT'] && !jump) {
        //dash
    }
    if(keyboard['JUMP']) {
        //jump to right
    }
    if(keyboard['SHIFT'] && keyboard['JUMP']) {
        //dash and jump (move further and faster)
    }
    if(keyboard['JUMP'] && keyboard['SHIFT']) {
        //hold the right key, pressed jump key, and then pressed shift key
        //it expected to jump to right here, because character can not dash
        //in midair, but it will conflict the if condition above.
    }
} else if (keyboard['JUMP'] && onGround) {
    //jump
} else if (keyboard['SHIFT']) {
    //dash
    if(keyboard['JUMP']) {
        //dash and jump
    }
}

```

I am confused that there are many if() else() statement in my code, and it seems that I need to control the order of keyboard inputs.Is there an easy way to handle that?Am I going the right way? If not, what is the common way to achieve that? Please, Any help would be appreciated.

# Answer
> 6 votes
This is an excellent question because you are experiencing a problem that's quite commonplace with less experienced programmers: attempting to solve your problem with a purely imperative approach. Luckily this problem has been encountered and solved by people much smarter than I, thanks to the mathematical concept of a finite state machine.

A finite state machine is just a fancy mathematical term of a type of system that can be in any of a *finite* number of *states* at any one time. A finite state machine is just a bunch of states and transitions, and in diagram form it looks a bit like this:

I'm not going to go into great depth because I know of someone who has already written an extensive explanation (with examples and diagrams) about this exact problem. Thus, I am going to refer you to Robert Nystrom's excellent book Game Programming Patterns, in which he discusses the finite state machine pattern in great detail, solving this exact problem.

---

* P.S. Yes, the image is also from his book.
* P.P.S No, I have no affilation to him, I just love his book - it's a damn fine book.

---
Tags: javascript, input, platformer, keyboard
---


title: Load FBX material data

text:
# Question
Title: Load FBX material data
I have the following piece of C++ code which I use to load triangle vertices from an FBX file:

```
FbxNode *node = scene->GetRootNode()->GetChild(0);
FbxGeometryConverter fbx_converter(node->GetFbxManager());
fbx_converter.Triangulate(node->GetNodeAttribute(), true);
mesh = node->GetMesh();
int num_vertices = mesh->GetPolygonVertexCount();
FbxVector4 *fbx_vertices = mesh->GetControlPoints();
int *fbx_triangle_vertices = mesh->GetPolygonVertices();
double x, y, z;
vector<vertex> vertices;
for (int vertex_index = 0; vertex_index < num_vertices; ++vertex_index)
{
    int index = fbx_triangle_vertices[vertex_index];
    x = (double)fbx_vertices[index][0];
    y = (double)fbx_vertices[index][1];
    z = (double)fbx_vertices[index][2];
    vertices.push_back(vertex(vector3(x, y, z), material(color(1, 0.5, 0.5), 0, 0, 0, 0, 1, 0)));
}

```

Currently, I am only loading vertex coordinates from the file. Now I want to load the vertex's material data (instead of assigning it manually like I did in the code snippet using `material(color(1, 0.5, 0.5)...`).

I see that an `FbxNode` object has a `GetMaterial()` method, but I don't know how to obtain this data since I am working with fbx vertices which are `FbxVector4`s, not nodes.

# Answer
> 1 votes
It seems materials can be obtained from the node by `FbxNode::GetMaterial(int pIndex)` and `FbxNode::GetMaterialIndex(const char *pName)`.

This data should be stored in the `node` you are reading, alongside the vector information, i.e. it is stored in the node and not bound to the vectors themselves.

---
Tags: c++, mesh, fbx
---


title: Setting font color, Vulkan

text:
# Question
Title: Setting font color, Vulkan
I am new using Vulkan, and i am trying to learn it looking tutorials and looking the vulkan examples that they provided(vulkan-master: https://github.com/SaschaWillems/Vulkan).

One of them is the Overlaytext project. In this project they teach you how to implement an overlay text in Vulkan.

Using this code, i wanted to change it to add an additional uniform to be able to change the color of the fonts. The problem is that the uniform is not getting set to the color, is always a 0 vec4(0,0,0,0) and i am not getting any warning or error.

If you can please tell me what i am missing i will be really appreciated, i dont know anymore what to do, i am out of ideas.

The code that i added or changed of this project to add this uniform is the following:

Variables in class:

```
glm::vec4   _color = glm::vec4(1.0f,1.0f,1.0f,1.0f);
struct {
VkBuffer buffer;
VkDeviceMemory memory;

```

} \_colorBuffer;

Input binding and attributes of the pipeline(preparePipeline method):

```
std::array<VkVertexInputBindingDescription, 3> vertexBindings = {};
vertexBindings[0] = vertexInputBindingDescription(0, sizeof(glm::vec4), VK_VERTEX_INPUT_RATE_VERTEX);
vertexBindings[1] = vertexInputBindingDescription(1, sizeof(glm::vec4), VK_VERTEX_INPUT_RATE_VERTEX);
vertexBindings[2] = vertexInputBindingDescription(2, sizeof(glm::vec4), VK_VERTEX_INPUT_RATE_VERTEX);
std::array<VkVertexInputAttributeDescription, 3> vertexAttribs = {};
// Position
vertexAttribs[0] = vertexInputAttributeDescription(0, 0, VK_FORMAT_R32G32_SFLOAT, 0);
// UV
vertexAttribs[1] = vertexInputAttributeDescription(1, 1, VK_FORMAT_R32G32_SFLOAT, sizeof(glm::vec2));
// Color
vertexAttribs[2] = vertexInputAttributeDescription(2, 2, VK_FORMAT_R32G32B32A32_SFLOAT, 0);

```

Added starging buffer to copy the content of the color vec4 to a local device buffer(prepareResources method):

```
struct {
    VkBuffer buffer;
    VkDeviceMemory memory;
} colorStaging;

ErrorCheck(renderer->CreateBuffer(
    VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
    VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
    sizeof(glm::vec4),
    &colorStaging.buffer,
    &colorStaging.memory,
    &_color));

ErrorCheck(renderer->CreateBuffer(
    VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT,
    VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
    sizeof(glm::vec4),
    &_colorBuffer.buffer,
    &_colorBuffer.memory));

```

Copy the staging buffer to the colorBuffer uniform(prepareResources, just after the setImageLayout method and before the end command buffer):

```
VkBufferCopy copyRegion = {};

copyRegion.size = sizeof(glm::vec4);
vkCmdCopyBuffer(
    copyCmd,
    colorStaging.buffer,
    _colorBuffer.buffer,
    1,
    &copyRegion);

```

Clean up staging buffer(between stagingBuffer.destroy() and vkFreeCommandBuffers(\_device, \_command\_pool, 1, &copyCmd); in the prepareResources method):

```
vkDestroyBuffer(renderer->GetVulkanDevice(), colorStaging.buffer, nullptr);
vkFreeMemory(renderer->GetVulkanDevice(), colorStaging.memory, nullptr);

```

Added the new binding vertex to the update command buffers(update command buffers method, just next to the other bindings):

```
vkCmdBindVertexBuffers(_commandBuffers[i], 2, 1, &_colorBuffer.buffer, &offsets);

```

Vertex shader:

```
#version 450 core

layout (location = 0) in vec2 inPos;
layout (location = 1) in vec2 inUV;
layout (location = 2) in vec4 color;

layout (location = 0) out vec2 outUV;
layout (location = 1) out vec4 outColor;

out gl_PerVertex
{
    vec4 gl_Position;
};

void main(void)
{
    gl_Position = vec4(inPos, 0.0, 1.0);
    outUV = inUV;
    outColor = color;
}

```

Fragment shader:

```
#version 450 core

layout (location = 0) in vec2 inUV;
layout (location = 1) in vec4 inColor;

layout (binding = 0) uniform sampler2D samplerFont;

layout (location = 0) out vec4 outFragColor;

void main(void)
{
    float color = texture(samplerFont, inUV).r;

    outFragColor = inColor*color;
}

```

I recompiled both shaders.

If i didnt add something will mean that i didnt change it.

Thank you for attention.

# Answer
I was trying to use a input vertex instead of a constant push for a vec4. I have changed the implementation to use a constant push and it works.
> 1 votes

---
Tags: vulkan
---


title: How to change screen resolution in XNA?

text:
# Question
Title: How to change screen resolution in XNA?
I'm making a 2D game in XNA/Monogame and I'm using Stardew Valley as a visual template (it's got the SNES style I'm going for). I'm having trouble mimicking the feature to change screen resolution and even get the game to draw as I'd like it.

As background, Stardew map tiles are 16x16 pixels. On screen the map is about 30 tiles wide by 16 tall. Naively this would make the screen 480x270 pixels, which is way too small on my 1920x1080 monitor. I'd like the game window to match my screen, but to get the game objects to scale properly.

Is there a proper way to change the screen resolution in XNA? Maybe some scaling factor in the SpriteBatch object that I'm not aware of?

# Answer
> 6 votes
The easiest way is to set it through the `GraphicsDeviceManager`.

```
graphics = new GraphicsDeviceManager(this);
graphics.PreferredBackBufferWidth = 480;
graphics.PreferredBackBufferHeight = 270;

```

I think setting the graphics to fullscreen after that should scale everything up properly.

```
graphics.IsFullScreen = false;

```

Note that if you want your game to work on different monitors you'll need a more robust solution because not all monitors have the same aspect ratio.

Also note you can handle scaling manually by creating a `Matrix` to pass to `SpriteBatch` when drawing.

```
// Somewhere accessible
const int TargetWidth = 480;
const int TargetHeight = 270;
Matrix Scale;

// Somewhere in initialisation
float scaleX = device.PreferredBackBufferWidth / TargetWidth;
float scaleY = device.PreferredBackBufferHeight / TargetHeight;
Scale = Matrix.CreateScale(new Vector3(scaleX, scaleY, 1));

// Somewhere with drawing
protected override void Draw(GameTime gameTime)
{
    SpriteBatch.Begin(SpriteSortMode.Immediate, null, null, null, null, null, Scale);
    Root.Draw(SpriteBatch, gameTime);
    SpriteBatch.End();

    base.Draw(gameTime);
}

```

---
Tags: xna, monogame
---