# Question
Title: Unity2D: Creating a Cross-Platform Multi-Player Game in Unity Error!
i'm following this tutorial on raywenderlich to do with multiplayer, since Unity updated, they have added a new method for the participant lefting the event. So I am getting this error on Unity:

> Assets/Script/Multiplayer/GPG Multiplayer/MultiplayerController.cs(8,14): error CS0738: `MultiplayerController' does not implement interface member` GooglePlayGames.BasicApi.Multiplayer.RealTimeMultiplayerListener.OnParticipantLeft(GooglePlayGames.BasicApi.Multiplayer.Participant)' and the best implementing candidate `MultiplayerController.OnRoomSetupProgress(float)' return type`void' does not match interface member return type \`void'

Whilst following the tutorial, I saw that someone in the comment section had the same error as me and someone replied back, however I wasn't sure how I should implement it as he didn't really explain it in great and clear detail!I also do not know how to create my own OnParticipantLeft(Participant leavingPlayer) method, which is why I was following the tutorial!

> Hmm... looks like since this tutorial was written, they've added a new method or two to that interface. Here's the new method they're expecting to see
>
> /// /// Raises the participant left event. /// This is called during room setup if a player declines an invitation /// or leaves. The status of the participant can be inspected to determine /// the reason. If all players have left, the room is closed automatically. /// /// Participant that left void OnParticipantLeft(Participant participant); If you just want to get your project going again, you can add your own OnParticipantLeft(Participant leavingPlayer) method to your MultiplayerController object and have it print out a debug message or two.
>
> In an actual game, you could probably use this to make sure, say, your lobby display doesn't get messed up if a player joins, then leaves while you're waiting for a third or fourth player to join.

So anyway does anyone know how to fix this error? Below is my code:

```
 using UnityEngine;
 using UnityEngine.SceneManagement;
 using System.Collections;
 using GooglePlayGames;
 using GooglePlayGames.BasicApi.Multiplayer;
 using System.Collections.Generic;

 public class MultiplayerController : RealTimeMultiplayerListener
 {
public MPLobbyListener lobbyListener;
private static MultiplayerController _instance = null;
private uint minimumOpponents = 1;
private uint maximumOpponents = 1;
private uint gameVariation = 0;
private byte _protocolVersion = 1;
// Byte + Byte + 2 floats for position + 2 floats for velcocity + 1 float for rotZ
private int _updateMessageLength = 22;
private List<byte> _updateMessage;
public MPUpdateListener updateListener;

public string GetMyParticipantId() {
    return PlayGamesPlatform.Instance.RealTime.GetSelf().ParticipantId;
}

public List<Participant> GetAllPlayers() {
    return PlayGamesPlatform.Instance.RealTime.GetConnectedParticipants ();
}

private void StartMatchMaking() {
    PlayGamesPlatform.Instance.RealTime.CreateQuickGame (minimumOpponents, maximumOpponents, gameVariation, this);
}

private MultiplayerController() {
    _updateMessage = new List<byte>(_updateMessageLength);
PlayGamesPlatform.DebugLogEnabled = true;
    PlayGamesPlatform.Activate ();
}

private void ShowMPStatus(string message) {
    Debug.Log(message);
    if (lobbyListener != null) {
        lobbyListener.SetLobbyStatusMessage(message);
    }
}

public void SendMyUpdate(float posX, float posY, Vector2 velocity, float rotZ) {
    _updateMessage.Clear ();
    _updateMessage.Add (_protocolVersion);
    _updateMessage.Add ((byte)'U');
    _updateMessage.AddRange (System.BitConverter.GetBytes (posX));
    _updateMessage.AddRange (System.BitConverter.GetBytes (posY));
    _updateMessage.AddRange (System.BitConverter.GetBytes (velocity.x));
    _updateMessage.AddRange (System.BitConverter.GetBytes (velocity.y));
    _updateMessage.AddRange (System.BitConverter.GetBytes (rotZ));
    byte[] messageToSend = _updateMessage.ToArray();
    Debug.Log ("Sending my update message  " + messageToSend + " to all players in the room");
    PlayGamesPlatform.Instance.RealTime.SendMessageToAll (false, messageToSend);
}

public void SignInAndStartMPGame() {
    if (! PlayGamesPlatform.Instance.localUser.authenticated) {
        PlayGamesPlatform.Instance.localUser.Authenticate((bool success) => {
            if (success) {
                Debug.Log ("We're signed in! Welcome " + PlayGamesPlatform.Instance.localUser.userName);
                StartMatchMaking();
            } else {
                Debug.Log ("Oh... we're not signed in.");
            }
        });
    } else {
        Debug.Log ("You're already signed in.");
        StartMatchMaking();
    }
}

public void SignOut() {
    PlayGamesPlatform.Instance.SignOut ();
}

public bool IsAuthenticated() {
    return PlayGamesPlatform.Instance.localUser.authenticated;
}

public void TrySilentSignIn() {
    if (! PlayGamesPlatform.Instance.localUser.authenticated) {
        PlayGamesPlatform.Instance.Authenticate ((bool success) => {
            if (success) {
                Debug.Log ("Silently signed in! Welcome " + PlayGamesPlatform.Instance.localUser.userName);
            } else {
                Debug.Log ("Oh... we're not signed in.");
            }
        }, true);
    } else {
        Debug.Log("We're already signed in");
    }
}

public static MultiplayerController Instance {
    get {
        if (_instance == null) {
            _instance = new MultiplayerController();
        }
        return _instance;
    }
}

public void OnRoomSetupProgress (float percent)
{
    ShowMPStatus ("We are " + percent + "% done with setup");
}

public void OnRoomConnected (bool success)
{
    if (success) {
        ShowMPStatus ("We are connected to the room! I would probably start our game now.");
        lobbyListener.HideLobby();
        lobbyListener = null;
        SceneManager.LoadScene("MainGame");
    } else {
        ShowMPStatus ("Uh-oh. Encountered some error connecting to the room.");
    }
}

public void OnLeftRoom ()
{
    ShowMPStatus ("We have left the room. We should probably perform some clean-up tasks.");
}

public void OnPeersConnected (string[] participantIds)
{
    foreach (string participantID in participantIds) {
        ShowMPStatus ("Player " + participantID + " has joined.");
    }
}

public void OnPeersDisconnected (string[] participantIds)
{
    foreach (string participantID in participantIds) {
        ShowMPStatus ("Player " + participantID + " has left.");
    }
}

public void OnRealTimeMessageReceived (bool isReliable, string senderId, byte[] data)
{
    // We'll be doing more with this later...
    byte messageVersion = (byte)data[0];
    // Let's figure out what type of message this is.
    char messageType = (char)data[1];
    if (messageType == 'U' && data.Length == _updateMessageLength) {
        float posX = System.BitConverter.ToSingle(data, 2);
        float posY = System.BitConverter.ToSingle(data, 6);
        float velX = System.BitConverter.ToSingle(data, 10);
        float velY = System.BitConverter.ToSingle(data, 14);
        float rotZ = System.BitConverter.ToSingle(data, 18);
        Debug.Log ("Player " + senderId + " is at (" + posX + ", " + posY + ") traveling (" + velX + ", " + velY + ") rotation " + rotZ);
        // We'd better tell our GameController about this.
        if (updateListener != null) {
            updateListener.UpdateReceived(senderId, posX, posY, velX, velY, rotZ);
           }
       }
   }
}

```

# Answer
You're missing some members from the interface `RealTimeMultiplayerListener`. According to your error, you need to implement `GooglePlayGames.BasicApi.Multiplayer.RealTimeMultiplayerListener.OnParticipantLeft(GooglePlayGames.BasicApi.Multiplayer.Participant)`

You could fix it adding this code to your `MultiplayerController`:

```
public void OnParticipantLeft(Participant participant)
{
    // Your code for this case (log, message, etc)
}

```
> 1 votes

---
Tags: unity
---


# Question
Title: Combat System - Class Objects as Package and Listener
So I've been trying to map out a combat system and I have an idea I'm laying out that I'm looking for a sanity check on, as well as suggestions.

The idea is that all things that can do damage (weapons, spells, environmental traps, monsters that deal damage sans weapon) will have a `CombatTalker()` object attached that will contain information about the amount of damage and damage types (fire, frost, physical, magical, etc.), modifiers that it might have, and any special effects (apply DoT, blind, slow, etc.).

Everything that can take damage will have a `CombatListener()` object that takes that information and transmogrifies it with the receivers resistances and any special properties it may have.

The `CombatTalker()` will create a `CombatPackage()` from a collection class any time there is a collision, and send it to the `CombatListener()` on the collided objects, supposing it has one. The `CombatPackage()` is basically the raw data about the damage and effects. The `CombatTalker()` is a wrapper of sorts that generates the `CombatPackage()` based on the weapon (or whatever) base damage, then the specific details of that individual weapon, and sends it (like a network packet) to the `CombatListener()`. The `CombatListener()` unwraps the package, and in reverse applies the resistances then applies any relevant damage and effects.

I know some of that was slightly repetitive, but I was trying to outline the idea completely, which apparently took two paragraphs.

I know this might be slightly complex, but the creatures and players and weapons and spells can change over time, so there isn't just a pool of static data that can be attached to the item. It needs to be able to read stats from JSON, apply specific information about the damage and send it. The same goes on the other side in reverse.

Is there a reason that this is "too complex"? Am I considerably overthinking it, or is this a reasonable method for a combat system?

Thanks!

# Answer
> 2 votes
This feels right to me. `CombatTalker() ...generates combatPackage()...--> combatListener()-->Processed-->output values`

But it would be more efficient to just send the values stored in `CombatTalker()` as parameters for `combatListener()` instead of generating `CombatPackage()` and then sending over to `combatListener()`.

So your process becomes `CombatTalker()--> combatListener()-->Processed-->output values`

(I program using javascript, but since this is a concept I feel I can help)

---
Tags: unity, c#, architecture, combat
---


title: Does Unity support hair?

text:
# Question
Title: Does Unity support hair?
As we know, Unity has a cloth component, but is there something to simulate human hair?

# Answer
> 0 votes
No; natively, Unity does not currently have a specific component to simulate hair.

There are various resources on the Asset Store that center around hair. You might find what you are looking for, there. If not, you will likely have to forgo the inclusion of hair, or otherwise create your own custom game component.

---
Tags: unity, game-component
---


# Question
Title: Raycast implementation in order to optimizate collision-detection
I want to know if a gameobject (a plane) is facing another one to prevent collisions. Right now I have an array that contains all planes in the scene and, for each one, compare position in order to detect if is facing it or not. The number of planes is small, but I want to increase it and this method is a little... Mean.

I was thinking to implement a raycast to detect if the gameobject has another one in front of it. Is it worth? Will it be less expensive? I think that raycast it's very expensive. In addition, I think that I will have to run three raycasts for every plane.

Obviously this is not executed every frame, but every two seconds.

# Answer
> 0 votes
Both situations that you are describing will be expensive. Having multiple objects casting 3 raycasts each every 2 seconds can have very negative effects on your game optimization (depending on the number of objects you are doing this for). An idea I tried a while back for something like this is I used box colliders on objects that I didn't want to collide. Making the box collider a certain size bigger than the object itself can basically let you use an OnTriggerEnter() call to determine if they are getting too close since the method will be called before any actual collision with the objects would have happened.

---
Tags: unity, collision-detection, raycasting
---


# Question
Title: What is the fastest and most convenient way to draw a number of identical objects at once in OpenGL?
I am writing a little game, in C++, using OpenGL. I have a varying number of enemies that are identical objects; each one uses the same animated mesh and shader, with skinning performed by GLSL-shader. I need to draw all of these objects at once, and I am confused about the fastest and most convenient way to do it.

I see several ways to solve my problem:

1. Creating a single Vertex Buffer Object (VBO) for the vertices and indices, and binding it to a Vertex Array Object (VAO) to draw it ten times by ten draw calls. In this way, after creating the VBOs we, can free the memory that stores the mesh vertices in the RAM, because we don't need it anymore.
2. Upload all of the meshes into a single VBO for the vertices and indices, and draw this VAO at once. In this case, there is a need to add a lot of additional info, such as the attributes such as position of the mesh, bone matrices, etc. In this case, we continue to store vertex info in the RAM, in order to add vertex data into that global VBO.
3. Upload all of the meshes into a single VBO for the vertices and indices, and bind it to a VAO. This time, we draw models one by one, sending uniforms for uniform skinning and animation for each model before the draw call. Like in the previous case, we store mesh vertices in the RAM.
4. Using instancing - passing a uniform array of bone transform matrices and accessing it within the shader by instance id. In this case, we might get rid of the CPU-side mesh data, as we don't need it anymore; much like with the first option. I'm not sure about this option, because instancing is usually used for drawing a large number of mesh instances, rather than drawing 10 instances.

I'm currently not sure which method is faster, and just overall convenient. What is the fastest and most convenient way to draw a number of identical objects at once in OpenGL?

# Answer
Obviously instancing is the fastest solution. But the question is: Do you really need it?

I'd say that generally for anything under 1000 instances you don't really need instancing. You seem to be writing your own engine. I'd say you write it in such a way, that if at a later time you need instanced rendering, you can implement it without changing your game logic code.

Also please note that as with any performance-related question: Profile it. How much does it cost for you to do that many calls? What platforms are you planning to support? etc...

**TL;DR:** Do it the simplest way(to me that is VAO), and come back and optimize it, when you need it(after profiling)
> 1 votes

---
Tags: opengl
---


# Question
Title: How to use dynamic resources with SharpDX by detail?
I've looked through a lot of archives but still cannot figure out how it works. Taking this overridden one for example. `public DataBox MapSubresource(Buffer resource, MapMode mode, MapFlags flags, out DataStream stream)`

1. Is this method aiming to change the resource with stream. If it is, why would the stream be marked `out` as if it is an output value rather than input?
2. If the above one is true, where can I stream my data into the stream to update the buffer? Has it to be between the Map and Unmap methods? And typically how should I stream it (Take vertex buffer for example, what would the format of streaming be like?)
3. Is it advisable to call the `MapSubresource` method whenever GPU access is finished(after every frame), and call the `UnmapSubresource` next frame to allow GPU access so it may save more time when I am keep updating the data?

Thank you!

# Answer
> 0 votes
Best way to write to a dynamic buffer is like this:

```
//Build Grass Buffer
 Dim BufferDescription As New BufferDescription() With {
       .BindFlags = BindFlags.ShaderResource,
       .SizeInBytes = GrassNode.Stride * 85000,
       .StructureByteStride = GrassNode.Stride,
       .OptionFlags = ResourceOptionFlags.BufferStructured,
       .CpuAccessFlags = CpuAccessFlags.Write,
       .Usage = ResourceUsage.Dynamic
   }
    Dim srvDescription As New ShaderResourceViewDescription() With {
       .Dimension = ShaderResourceViewDimension.Buffer,
       .Format = DXGI.Format.Unknown,
       .Buffer = New ShaderResourceViewDescription.BufferResource() With {
           .FirstElement = 0,
           .ElementCount = 85000
       }
   }
    GrassNodesBuffer = _Device.CreateBuffer(BufferDescription)
    GrassNodesView = _Device.CreateShaderResourceView(GrassNodesBuffer, srvDescription)

//Map
Dim dbox As DataBox = _context.MapSubresource(GrassNodesBuffer, 0, MapMode.WriteDiscard, Direct3D11.MapFlags.None)
Dim offset As IntPtr = dbox.DataPointer

//Write
 For gg As Integer = 0 To ccnode.Grass.Count - 1
    offset = Utilities.WriteAndPosition(offset, ccnode.Grass(gg))

 Next
//Unmap
_context.UnmapSubresource(GrassNodesBuffer, 0)
dbox = Nothing

```

This way you don't need a datastream and you can write directly to the unmanged memory. Its faster and much less garbage.

I call map just before I need to write to the buffer, with MapMode.WriteDiscard you get new memory each time, that way you don't really need to worry about whats happening on the GPU, just write the data and render when needed.

I try do all my mapping and updatesubresource stuff at the start of the frame and use copyresource or copyresource if I need to update stuff later in the frame.

I update most of my perframe buffers this way.

As per the MSDN docs on the usage pattern D3D11\_MAP\_WRITE\_NO\_OVERWRITE, can only be used for vertex or index buffers

> D3D11\_MAP\_WRITE\_NO\_OVERWRITE
>
> Resource is mapped for writing; the existing contents of the resource cannot \> be overwritten (see Remarks). This flag is only valid on vertex and index buffers. The resource must have been created with write access (see D3D11\_CPU\_ACCESS\_WRITE). Cannot be used on a resource created with the D3D11\_BIND\_CONSTANT\_BUFFER flag.
>
> A common use of these two flags involves filling dynamic index/vertex buffers with geometry that can be seen from the camera's current position. The first time that data is entered into the buffer on a given frame, Map is called with D3D11\_MAP\_WRITE\_DISCARD; doing so invalidates the previous contents of the buffer. The buffer is then filled with all available data.
>
> Subsequent writes to the buffer within the same frame should use D3D11\_MAP\_WRITE\_NO\_OVERWRITE. This will enable the CPU to access a resource that is potentially being used by the GPU as long as the restrictions described previously are respected.

My understanding is that you only use D3D11\_MAP\_WRITE\_NO\_OVERWRITE if you plan on writing to the buffer more than once per frame and I have never found a use for that so I just use D3D11\_MAP\_WRITE\_DISCARD.

---
Tags: directx11, sharpdx
---


title: Voxel river flow simulation

text:
# Question
Title: Voxel river flow simulation
I am making a Voxel game and I'd like to add rivers that can be redirected. So I thought that if a player replaces a river block or digs up a block next to a river block the river would repath itself to the sea. The rivers path would have a direction and a speed in that direction.

The rivers path would be determined by these rules: If the river can go down in its direction it will and then pick up speed. or if it has a speed under 2 and it can go sideways and down it will and keep its direction. Otherwise it will keep going in its direction until blocked, where it will pick a new direction. If the river can't go anywhere it will fill up the layer its on like a bathtub and go up. Repeat until it reaches the ocean.

However I can't figure out how you can know what to fill. The data would be stored in some sort of height map. 1 = same level, 0 = down a level, 2 = up a level

For example:

```
222222
211112
211112
211112
211112
222222

```

I can tell that the 2s completely surround the 1s meaning that all the 1s should get filled with water if the river goes up. But how can a computer tell?

# Answer
A fairly straightforward algorithm for this can be established, if you can assume some fixed 2D grid of cells, each of which contains a value for the level of the water in them. Imagine an infinitely tall grid of perspex dividers, at the bottom of which are holes/tubes to facilitate flow between adjacent cells. What's key is to not think about the cells themselves, but the connections between cells. E.g. in the simplest grid:

`A` `B`

`C` `D`

there are 4 connections between individual cells (between A and B, between B and D, between C and D, and between A and C). You can make diagonal connections as well if you like, it doesn't make a difference to the core algorithm. You can also add solid cells, connections into which are blocked, which in your case would form the banks of your imaginary river.

Imagine that you start with some initial state. It won't necessarily be 'level' or in equilibrium, and if it isn't, you expect that the first few updates will cause flow between the cells until equilibrium is reached.

## Phase 1

For each connection, look at the cells on either side, and calculate the difference in water level between them. Say, for example, that A has a level of 3 and B has a level of 1. Then the connection from A to B has a 'pressure' of 2 (3-1) in the direction of B. If the cell on the other side of the connection is not empty (say because it's ground), then the pressure will be 0. If the cell on the other side has more water than this cell, the pressure will be some negative number.

The end result of this phase will be a numeric value for each connection as to how quickly water will flow through that connection, and in which direction. This is an 'instantaneous' value, in that it describes potential for flow when you next update. It is not trying to describe how much water will flow, just how much water **wants** to flow.

## Phase 2

For each cell, look at the pressure of all of the connections that touch that cell. Use the information on those pressures to decide how much fluid to transfer from this cell to the cells on the other side of the connections. For example, say A (with its level of 3) has an outward pressure of 2 towards B (with level 1), and an outward pressure of 1 towards C (which has level 2). So in the next update, you'd transfer twice as much fluid to cell B as you do towards C.

Exactly how much fluid to transfer between cells is something you decide is sensible. Limiting that rate of transfer will cause your fluid to flow more slowly (like treacle instead of water), and you want to have a damping value of some sort to stop oscillation (e.g. water flowing from A to B, then B to A, then A to B, but never settling). It's also crucial to distribute the outwards flow between all connections (e.g. not just send all water out along the first connection you process)

What's key is that you only transfer in one direction. Because when you come to process cell B, you don't want to 'pull' fluid from A, because you may have already 'pushed' fluid from A to B.

The reason why you do it in two phases is so that you can make the decision on how fast the flows will be between cells, before you start changing the values of the individual cells. Otherwise fluid moving from A to B would affect the decision of how much fluid wants to move from B to D.
> 3 votes

---
Tags: path-finding, voxels, water
---


title: OpenGL typedefs

text:
# Question
Title: OpenGL typedefs
How far up do I have to push openGLs typedefs?

If I have GLfloat everywhere in my code, I have to include openGL libraries pretty much everywhere. Should I use glm:tmat4x4 or will regular glm::mat4x4 be fine? When coding transformations, can I use regular float to define position vector in transformation and then construct glm:tmat4x4 with it and be sure that openGL won't get surprised?

These are just some of many questions.

Does the compilers float get cast the properly to GLfloat when passing it to a function that injects the data into openGL?

**This applies to any openGL typedef.**

The main question is, is there a way to make a clean cut between float and GLfloat (or any other compiler-openGL type pair) and safely use the regular type in my code and then cast it into openGL type right before it gets introduced to openGL?

How can I use regular one in most of my code and the openGL one in the core parts that personally deal with openGL, while having the guarantee that behavior will be consistent on different platforms, regardless of their float implementation (or any other type)?

# Answer
> 1 votes
The reason why the GL types exist is for portability across different hardware architectures; table 2.2 of the GL 4.5 core profile specification (it's likely the same table number in other versions) describes the data types, their names and their sizes (in bits). The gl.h that comes with your platform(s) contains the actual typedefs.

> GL types are not C types. Thus, for example, GL type int is referred to as GLint outside this document, and is not necessarily equivalent to the C type int. An implementation must use exactly the number of bits indicated in the table to represent a GL type.

In this way, wherever you see for example GLint you know that the data type being used is a 32-bit "Signed two’s complement binary integer"; likewise for other types.

What this means for your code is that so long as you use the correct equivalent data type, you don't need to worry about percolating the OpenGL types further up your code.

For the GLint example, if you know that you're only going to run on platforms where int is equivalent, then you can use int. Otherwise you should use a more explicit type, such as int32\_t.

---
Tags: opengl
---


# Question
Title: how to spawn object at tip of rotating object
Engine: Gamemaker Studio

I'm learning to code in GML and I am having difficulty in having my bullets be created in the desired position, the front of the object firing them. Here's how it presently looks. I made the "player object" transparent to see the bullets traveling "under" it for demonstration purpose.

Here's the code of the bullet creation:

# Answer
> 2 votes
By "tip of rotating object", you meant the front? If that so.

You could do it easily if you have the rotation angle. Just add an offset to the bullet's spawn location/position. Speaking generally it would be something like:

```
x += offset * cos(angleInRadians);
y += offset * sin(angleInRadians);

```

This should be the basic idea. On your game, you probably want `offset` to be half the player's height (assuming your bullet is spawning from the middle of the player). And `angleInRadians` is of course the angle of your bullet (which i suppose is the player's angle + 90 degrees) in radians.

Oh, and when doing this step do it without the randomized angle. Because with the randomized angle, it means that your bullet are going to be translated not exactly in front of the player.

---

TL;DR: Move the bullet some step ahead without the randomized angle at the start.

# Answer
> 2 votes
Probably VERY late response, but you can do this:

```
instance_create( x+lengthdir_x(sprite_get_width( sprite_index)/2,image_angle),
                 y+lengthdir_y(sprite_get_height(sprite_index)/2,image_angle),
                 obj_bullet);

```

and the bullet will spawn at the tip of the object, no matter what image\_angle it has.

# Answer
> 1 votes
Thanks everyone for the replies, it's very appreciated. Origins are in center of objects for the record. For reasons that don't really exist, I ended up using the solution given focusing on the angle of my object in radians, played with the numbers a bit and got a solution of code that looks like this:

I do plan to attempt the solution from Liggiorgio as well just for the sake of learning.

# Answer
> 0 votes
Your issue can be easily solved. But first, I'd like to premise there's a tiny optimization you can do in your game.

### Enhance

Since the `direction` variable is pointing leftwards when its value is 0, those sprites which are supposed to rotate (by changing the `image_angle` of the instance) of the same angle as `direction` may be loaded in GM:S facing the left side.

This way, if you set the `sprite_index` of your "player object" to such a sprite, in the *Step Event* you can simply write:

```
image_angle = direction;

```

instead of:

```
image_angle = direction + 90;

```

The same applies for your bullet sprite: make it so that it's facing to the left.

### Make it work

Now, let's make the player object fire the bullets properly. From now on, **I'm assuming your sprites both have their respective origin at the center of the sprite itself**. In the *Space Press Event* of your `obj_player_press`, change the source code as follow:

```
/// Fire bullet
var angle = random_range(-20,20);
var inst = instance_create(x,y,obj_bullet);
inst.image_angle = image_angle;
inst.direction = direction;
//inst.speed = some_value;

```

This way, your bullet object will be created at the same position where your "player object" is placed. The difference with your code is the usage of the local variable `inst` to change the value of the bullet variables instead of using the `with` statement. In this case, there's no need to use the `with` statement, as you're referring to one instance in particular only, and it's much cleaner, clearer, and faster referring to the instance by using its `id` on the go, instead of using the `with` statement, which will tell GM:S to look up for the instance whose `id` is the one taken as argument. The `with` statement is more effective when using `object_index`es, whilst working with `id`s can be easier.

### The final touch

We want the bullet to be created at the tip of our rotating object. We can achieve this by using the built-in functions `lengthdir_x` and `lengthdir_y`. What they do is computing the offset distances along the *x* and *y* axes for us. Let's edit our code as follows:

```
/// Fire bullet
var angle = random_range(-20,20);
var len = 32;
var inst = instance_create(x+lengthdir_x(len,direction),y+lengthdir_y(len,direction),obj_bullet);
inst.image_angle = image_angle;
inst.direction = direction;
//inst.speed = some_value;

```

They are as useful as easy to use. Check this out, and see your bullets being shot from the tip of your player object!

---
Tags: game-maker
---


# Question
Title: Unity 5 Deleting Large Quantities of GameObjects (around 10000 or more) from Hierarchy
I've screwed up on this one. I used a script to randomly generate trees in my scene. The reason I did this instead of using the Mass Place Trees function in the terrain editor is because the trees all had a script attached to them, and Mass Place Trees does not keep the script attached.

It works, but instead of making my wanted 500 trees, I accidentally made gigantic amount of 10000 trees. I've tried to delete them, but after selected every tree (or more than 50 or so, didn't really count, sorry) it freezes Unity so I can't delete them.

I really don't want to delete 50 trees at a time for the entire quantity of 10000 trees, it'll just take way too long. Is there a way to delete all of these trees at once so I can try my tree generation script again? Because the bright side is, the script did actually work.

Also, I can't play the game either, it takes minutes to actually boot up and it lags heavily. I really need to figure out how to fix this, but I'm not sure what to do, so I put my question on here for help.

Thank you.

P.S. If you ever, for some reason, want to take a look at my Mass Tree Generation script, here's the code:

```
public class MassPlaceObjects : MonoBehaviour
{
    public GameObject tree;

    void Start()
    {
        for (int i = 0; i < 10001; i++)
        {
            RaycastHit hit = new RaycastHit();
            gameObject.transform.position = new Vector3(Random.Range(0, 10000), 500, Random.Range(0, 10000));
            Physics.Raycast(gameObject.transform.position, Vector3.down, out hit);
            Instantiate(tree, hit.point, Quaternion.identity);
        }
    }
}

```

# Answer
> 0 votes
I managed to fix it on my own by selecting everything in the current world scene except for most of the trees and copy/pasting them into a new world scene. I guess it was that simple \>.\<

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


# Question
Title: How do I implement GPU-based dynamic geometry LOD in OpenGL?
I'm trying to implement LOD to boost my game's performance. I found a very nice tutorial.

The basic concept that I think I understand is: Get the distance from the camera to the object, check for the right LOD-level and then render the object with the "right amount of instances".

How do I implement that? The provided example code is a mystery to me...

Some questions:

1. Is this a good method to implement LOD?
2. Can someone please explain me detailed, how I have to implement it, with the queries and so on...
3. I'm rendering all of my objects with

```
GL11.glDrawElements(GL11.GL_TRIANGLES, model.getRawModel().getVertexCount(),
                    GL11.GL_UNSIGNED_INT, 0);

```

The example code uses `GL_POINTS`. Can I implement it also with `GL_TRIANGLES`?

# Answer
I guess it depends how you have set up your rendering already, assuming you're using an indicie array to draw your vertices in your terrain then you can simply create more indicie arrays to draw with, stepping along more verts with each array.
> 0 votes

---
Tags: opengl, java
---


# Question
Title: LibGDX Box2d - How to only setLinearVelocity on X axis - problem while jumping
```
 public void update(float dt){
    float currentYVelocity = body.getLinearVelocity().y;

    switch(currentMoveState){
        case moveLEFT: body.setLinearVelocity(-walkSpeed * ppm, currentYVelocity);
            break;
        case moveRIGHT: body.setLinearVelocity(walkSpeed * ppm, currentYVelocity);
            break;
        case moveSTANDING: body.setLinearVelocity(0,currentYVelocity);
    }

    //handle input...
    if (Gdx.input.isKeyPressed(Input.Keys.A) && body.getLinearVelocity().x >= -2
            && body.getPosition().x >= 0.08f){
        currentMoveState = moveState.moveLEFT;
        //body.applyLinearImpulse(new Vector2(-walkSpeed * ppm,0), body.getWorldCenter(), true);
    }
    else if (Gdx.input.isKeyPressed(Input.Keys.D) && body.getLinearVelocity().x <= 2 ){
        currentMoveState = moveState.moveRIGHT;
        //body.applyLinearImpulse(new Vector2(walkSpeed * ppm, 0), body.getWorldCenter(), true);
    }
    else
        currentMoveState = moveState.moveSTANDING;
    if (Gdx.input.isKeyJustPressed(Input.Keys.SPACE)){
        body.applyLinearImpulse(new Vector2(0, jumpSpeed * ppm), body.getWorldCenter(), true);
    }

    // sets the players texture sprite to be same position as the box2d circle body...
    this.setBounds(body.getPosition().x - 8, body.getPosition().y - 8, 16, 16);
}

```

I have the above code in place. I'm using LibGDX and Box2d. Im trying to make a single screen platformer similar to old-style Donkey Kong.

My issue is that when I move and jump at the same time, the Y velocity is being heavily affected. When jumping without moving left/right it is fine, but if you hold left whilst jumping the character stays almost suspended in mid air and you can acheive all kinds of irregularities with trying to jump and move.

I tried adding the variable 'currentYvelocity' and passing that into the Y value each time i alter 'setLinearVelocity(x,y)' but I can see that this is the issue because somehow it must be removing the new calulation from Y velocity and replacing it with the previous frame perhaps..?!?

I've wracked my brains and now everything I try makes it worse.

Can anyone tell me of a proper solution to this please? (Or perhaps I'm almost right and just need a helping hint :) )

Anyways, thanks in advance for any help!

EDIT: By the way, I have now changed the currentYVelocity by removing that variable and just calling getLineaarVelocity.y in all the movement methods. But this had no effect unfortunately on my jumping whilst walking problem.

# Answer
```
      //body.applyLinearImpulse(new Vector2(walkSpeed * ppm, 0), body.getWorldCenter(), true);
}
else if (!Gdx.input.isKeyPressed(Input.Keys.A) && !Gdx.input.isKeyPressed(Input.Keys.D))
    currentMoveState = moveState.moveSTANDING;

```

Maybe the problem was that if the player exceeds the speed limit currentMoveStates changes to moveSTANDING.
> 1 votes

---
Tags: java, 2d, libgdx, box2d, platformer
---


# Question
Title: Aggregation of value in GLSL loop results in 0
I'm banging my head against a wall trying to understand why this code is giving me some reasonable results with some visible colors on parts of the screen...

```
#version 130

in vec2 vTex; // must match name in vertex shader
flat in int iLayer; // must match name in fragment shader

out vec4 fragColor; // first out variable is automatically written to the screen

uniform sampler2DArray tex;
uniform sampler2DArray norm;

#define MAX_LIGHTS 4

struct Light {
    vec3 position;
    vec4 color;
    vec3 falloff;
    vec3 aim;
    float aperture;
    float aperturehardness;
};

uniform Light lights[MAX_LIGHTS];

void main()
{
    vec4 DiffuseColor = texture(tex, vec3(vTex.x, vTex.y, iLayer));
    if (DiffuseColor.a == 0)
        discard;
    vec3 NormalMap = texture(norm, vec3(vTex.x, vTex.y, iLayer)).rgb;
    NormalMap.g = 1.0 - NormalMap.g;
    vec3 FinalColor = vec3(0,0,0);

    for (int i=0; i<MAX_LIGHTS; i++)
    {
        vec3 LightDir = vec3((lights[i].position.xy - gl_FragCoord.xy) / vec2(320.0, 200.0).xy, lights[i].position.z);
        float D = length(LightDir);
        vec3 N = normalize(NormalMap * 2.0 - 1.0);
        vec3 L = normalize(LightDir);
        vec3 Diffuse = (lights[i].color.rgb * lights[i].color.a) * max(dot(N, L), 0.0);
        vec3 sd = normalize(vec3(gl_FragCoord.xy, -1.0) - lights[i].position);
        float Attenuation = smoothstep(lights[i].aperture * lights[i].aperturehardness, lights[i].aperture, dot(sd,lights[i].aim))
            / (lights[i].falloff.x + (lights[i].falloff.y*D) + (lights[i].falloff.z*D*D) ) ;
        vec3 Intensity = Diffuse * Attenuation;
        FinalColor = max(FinalColor, DiffuseColor.rgb * Intensity);
    }
    fragColor = vec4(FinalColor, DiffuseColor.a);
}

```

... but when I change `FinalColor = max(FinalColor, DiffuseColor.rgb * Intensity);` to `FinalColor = clamp(FinalColor + DiffuseColor.rgb * Intensity, vec3(0,0,0), vec3(1,1,1));` everything goes black. Is there something I don't understand about aggregation of variables in loops in GLSL, or about the `+` operator operating on vectors? By my logic, the changed code should return *more* brightness than the original code because the changed code would be adding all the values whereas the old code would just be taking the highest one.

# Answer
Gotta remember vectors can be negative, so the assumption that `+` would always yield a larger result than max in aggregation is wrong. Changing the code to:

```
FinalColor = clamp(FinalColor + max(vec3(0,0,0), DiffuseColor.rgb * Intensity), vec3(0,0,0), vec3(1,1,1));

```

Yields a result similar to max;
> 0 votes

---
Tags: opengl, glsl
---


title: OpenGL diffuse texture mapping

text:
# Question
Title: OpenGL diffuse texture mapping
I am working on a small game engine and having some troubles when figuring out how to properly map more complex textures to their meshes. I am loading models using the .OBJ format and as far as I can tell, my loader is properly loading all the data into a Vertex list, as the model properly renders, and diffuse shading is applied properly with the normals from the file.

However, when I bind the following texture to its mesh, I get following results.

To bind this texture, I simply did this code:

```
int width, height;
unsigned char * data = SOIL_load_image("Medieval_House_Diff.png", &width, &height, 0, 0);
GLuint textureID;
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glGenerateMipmap(GL_TEXTURE_2D);

```

Here is my code for reading the OBJ file

```
while ((line = reader.getLine()) != 0)
    {
        if (line[0] == 'f' && line[1] == ' ')
        {
            bool quad = false;
            objFP f1 = { 0 };
            objFP f2 = { 0 };
            objFP f3 = { 0 };
            objFP f4 = { 0 };
            strtok_s(line, " ", &context);
            token = strtok_s(0, " ", &context);
            if (sscanf_s(token, "%u/%u/%u", &f1.vPos, &f1.tPos, &f1.nPos) == 3)
            {
                token = strtok_s(0, " ", &context);
                sscanf_s(token, "%u/%u/%u", &f2.vPos, &f2.tPos, &f2.nPos);
                token = strtok_s(0, " ", &context);
                sscanf_s(token, "%u/%u/%u", &f3.vPos, &f3.tPos, &f3.nPos);
                token = strtok_s(0, " ", &context);
                if (token)
                {
                    quad = true;
                    sscanf_s(token, "%u/%u/%u", &f4.vPos, &f4.tPos, &f4.nPos);
                }
            }
            else if (sscanf_s(token, "%u//%u", &f1.vPos, &f1.nPos) == 2)
            {
                token = strtok_s(0, " ", &context);
                sscanf_s(token, "%u//%u", &f2.vPos, &f2.nPos);
                token = strtok_s(0, " ", &context);
                sscanf_s(token, "%u//%u", &f3.vPos, &f3.nPos);
                token = strtok_s(0, " ", &context);
                if (token)
                {
                    quad = true;
                    sscanf_s(token, "%u//%u", &f4.vPos, &f4.nPos);
                }
            }
            else if (sscanf_s(token, "%u/%u", &f1.vPos, &f1.tPos) == 2)
            {
                token = strtok_s(0, " ", &context);
                sscanf_s(token, "%u/%u", &f2.vPos, &f2.tPos);
                token = strtok_s(0, " ", &context);
                sscanf_s(token, "%u/%u", &f3.vPos, &f3.tPos);
                token = strtok_s(0, " ", &context);
                if (token)
                {
                    quad = true;
                    sscanf_s(token, "%u/%u", &f4.vPos, &f4.tPos);
                }
            }
            else
            {
                f1.vPos = (GLuint)atoi(token);
                token = strtok_s(0, " ", &context);
                f2.vPos = (GLuint)atoi(token);
                token = strtok_s(0, " ", &context);
                f3.vPos = (GLuint)atoi(token);
                token = strtok_s(0, " ", &context);
                if (token)
                {
                    quad = true;
                    f4.vPos = (GLuint)atoi(token);
                }
            }

            faces[fCount++] = f1;
            faces[fCount++] = f2;
            faces[fCount++] = f3;
            //inds.push_back(f1.vPos - 1);
            //inds.push_back(f2.vPos - 1);
            //inds.push_back(f3.vPos - 1);
            if (quad)
            {
                faces[fCount++] = f1;
                faces[fCount++] = f3;
                faces[fCount++] = f4;
                //inds.push_back(f1.vPos - 1);
                //inds.push_back(f3.vPos - 1);
                //inds.push_back(f4.vPos - 1);
            }
            continue;
        }
        else if (line[0] == 'v' && line[1] == ' ')
        {
            strtok_s(line, " ", &context);
            vertices[pCount].position.x = strtof(strtok_s(0, " ", &context), 0) * modelScale;
            vertices[pCount].position.y = strtof(strtok_s(0, " ", &context), 0) * modelScale;
            vertices[pCount++].position.z = strtof(strtok_s(0, " ", &context), 0) * modelScale;
        }
        else if (line[0] == 'v' && line[1] == 't')
        {
            strtok_s(line, " ", &context);
            tempTextures[tCount].x = strtof(strtok_s(0, " ", &context), 0);
            tempTextures[tCount++].y = 1  - strtof(strtok_s(0, " ", &context), 0);
        }
        else if (line[0] == 'v' && line[1] == 'n')
        {
            strtok_s(line, " ", &context);
            tempNormals[nCount].x = strtof(strtok_s(0, " ", &context), 0);
            tempNormals[nCount].y = strtof(strtok_s(0, " ", &context), 0);
            tempNormals[nCount++].z = strtof(strtok_s(0, " ", &context), 0);
        }
    }
    reader.release();

    bool hasTextures = tCount > 0;
    bool hasNormals = nCount > 0;

    GLuint * indices = new GLuint[fCount];
    for (GLuint i = 0; i < fCount; i++)
    {

        GLuint index = faces[i].vPos - 1;
        indices[i] = index;
            if (hasTextures)
                vertices[faces[i].vPos - 1].texture = tempTextures[faces[i].tPos - 1];
            if (hasNormals)
                vertices[index].normal = tempNormals[faces[i].nPos - 1];
    }

```

I have not been able to find a resource online that deals with properly loading a texture such as this, so it would be appreciated if someone with knowledge on such topics could tell me what steps I might be missing to properly map this texture to its mesh.

# Answer
> 0 votes
My first guess is that you have incorrect UV coordinates, or you're not properly loading them. Here is my WavefrontModel class from my game engine, maybe you can compare your code to mine(which works).

```
using System;
using System.IO;
using GrimoireEngine.Framework.Maths;
using GrimoireEngine.Framework.OpenGL.Texturing;
using OpenTK;
using OpenTK.Graphics.OpenGL;

namespace GrimoireEngine.Framework.OpenGL.Modeling
{
    public class WavefrontModel
    {
        /// <summary>
        /// The Vertices of this Model
        /// </summary>
        public Vector3[] Vertices;
        /// <summary>
        /// The TexCoords of this Model
        /// </summary>
        public Vector2[] TexCoords;
        /// <summary>
        /// The Normals of this Model
        /// </summary>
        public Vector3[] Normals;
        /// <summary>
        /// The Faces of this Model
        /// </summary>
        public Face[] Faces;
        /// <summary>
        /// The Original File Source
        /// </summary>
        public string ModelSource { get; set; }
        /// <summary>
        /// The Name of this Model
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// The Material of this Model
        /// </summary>
        public Material Material { get; set; }

        /// <summary>
        /// The Triangle Count of this model.
        /// </summary>
        public int TriCount
        {
            get
            {
                return Faces.Length;
            }
        }

        public WavefrontModel()
        {

        }

        public WavefrontModel(string modelPath, Material material)
        {
            this.ModelSource = modelPath;
            this.Material = material;
        }

        public WavefrontModel(string modelPath)
        {
            this.ModelSource = modelPath;
            this.Material = null;
        }

        public WavefrontModel(string[] data)
        {
            this.ModelSource = String.Empty;
            this.Material = null;
            Load(data);
        }

        public WavefrontModel(string[] data, Material material)
        {
            this.ModelSource = String.Empty;
            this.Material = material;
            Load(data);
        }

        /// <summary>
        /// Loads a model from the desired Wavefront.obj source given
        /// at constructor initialization.
        /// </summary>
        public void Load()
        {
            Load(this.ModelSource);
        }

        /// <summary>
        /// Loads a model from a Wavefront.obj located on disk.
        /// </summary>
        /// <param name="file"></param>
        public void Load(string file)
        {
            Parse(File.ReadAllLines(file));
        }

        /// <summary>
        /// Loads a model from a Wavefront.obj located on disk.
        /// </summary>
        /// <param name="data"></param>
        public void Load(string[] data)
        {
            Parse(data);
        }

        /// <summary>
        /// Clears all Model-Buffer Data
        /// </summary>
        public void Clear()
        {
            Array.Clear(Vertices, 0, Vertices.Length);
            Array.Clear(TexCoords, 0, TexCoords.Length);
            Array.Clear(Normals, 0, Normals.Length);
            Array.Clear(Faces, 0, Faces.Length);
        }

        /// <summary>
        /// Parses Wavefront data from desired array.
        /// </summary>
        /// <param name="data"></param>
        public void Parse(string[] data)
        {
            // Create File Manifest
            int totalVertices = 0;
            int totalNormals = 0;
            int totalTextureCoordinates = 0;
            int totalFaces = 0;
            for (int i = 0; i < data.Length; i++)
            {
                char firstChar = data[i][0];
                switch (firstChar)
                {
                    case 'v':
                        char secondChar = data[i][1];
                        switch (secondChar)
                        {
                            case ' ':
                                totalVertices++;
                                break;
                            case 't':
                                totalTextureCoordinates++;
                                break;
                            case 'n':
                                totalNormals++;
                                break;
                        }
                        break;
                    case 'f':
                        totalFaces++;
                        break;
                }
            }
            // Create the Buffers
            Vertices = new Vector3[totalVertices];
            Normals = new Vector3[totalNormals];
            TexCoords = new Vector2[totalTextureCoordinates];
            Faces = new Face[totalFaces];
            // Create File Reading Buffers
            string[] fileBuffer = new string[20];
            string[] indiceBuffer = new string[3];
            Vertex[] vertexBuffer = new Vertex[3];
            // Iterators
            int verticesIterator = 0;
            int normalsIterator = 0;
            int textureCoordinatesIterator = 0;
            int facesIterator = 0;
            for (int line = 0; line < data.Length; line++)
            {
                SplitStringFast(data[line], ' ', fileBuffer);
                char firstChar = data[line][0];
                switch (firstChar)
                {
                    case 'v':
                        char secondChar = data[line][1];
                        switch (secondChar)
                        {
                            case ' ':
                                Vector3 vertex = new Vector3
                                {
                                    X = GrimoireMath.ParseFloatFast(fileBuffer[1]),
                                    Y = GrimoireMath.ParseFloatFast(fileBuffer[2]),
                                    Z = GrimoireMath.ParseFloatFast(fileBuffer[3])
                                };
                                Vertices[verticesIterator] = vertex;
                                verticesIterator++;
                                break;
                            case 't':
                                Vector2 textureCoordinate = new Vector2
                                {
                                    X = GrimoireMath.ParseFloatFast(fileBuffer[1]), // U
                                    Y = -GrimoireMath.ParseFloatFast(fileBuffer[2]) // V (Inverted)
                                };
                                TexCoords[textureCoordinatesIterator] = textureCoordinate;
                                textureCoordinatesIterator++;
                                break;
                            case 'n':
                                Vector3 normal = new Vector3
                                {
                                    X = GrimoireMath.ParseFloatFast(fileBuffer[1]),
                                    Y = GrimoireMath.ParseFloatFast(fileBuffer[2]),
                                    Z = GrimoireMath.ParseFloatFast(fileBuffer[3])
                                };
                                Normals[normalsIterator] = normal;
                                normalsIterator++;
                                break;
                        }
                        break;
                    case 'f':
                        for (int i = 0; i < 3; i++)
                        {
                            SplitStringFast(fileBuffer[i + 1], '/', indiceBuffer);
                            Vertex indices = new Vertex
                            {
                                VertexIndice = GrimoireMath.ParsePositiveInt32Fast(indiceBuffer[0]) - 1,
                                TextureIndice = GrimoireMath.ParsePositiveInt32Fast(indiceBuffer[1]) - 1,
                                NormalIndice = GrimoireMath.ParsePositiveInt32Fast(indiceBuffer[2]) - 1
                            };
                            vertexBuffer[i] = indices;
                        }
                        Faces[facesIterator] = new Face(vertexBuffer);
                        facesIterator++;
                        break;
                }
            }
        }

        /// <summary>
        /// A custom implementation of String.Split(). Realistically, this
        /// function is not much faster than what .NET offers; it gains speed
        /// more from a preset buffer mechanism. There is no bounds checking done
        /// for the buffer, which is done by design to assure optimal performance.
        /// </summary>
        /// <param name="value"></param>
        /// <param name="delimiter"></param>
        /// <param name="buffer"></param>
        /// <returns></returns>
        private static void SplitStringFast(string value, char delimiter, string[] buffer)
        {
            int resultIndex = 0;
            int startIndex = 0;
            for (int i = 0; i < value.Length; i++)
            {
                if (value[i] == delimiter)
                {
                    buffer[resultIndex] = value.Substring(startIndex, i - startIndex);
                    resultIndex++;
                    startIndex = i + 1;
                }
            }
            buffer[resultIndex] = value.Substring(startIndex, value.Length - startIndex);
        }

        /// <summary>
        /// Renders the Model using deprecated immediate mode. This
        /// function exists only for testing purposes.
        /// </summary>
        public void Render()
        {
            GL.Enable(EnableCap.Texture2D);
            GL.Color3(Material.AmbientColor);
            GL.BindTexture(TextureTarget.Texture2D, Material.Diffuse);
            GL.Begin(PrimitiveType.Triangles);
            for (int i = 0; i < Faces.Length; i++)
            {
                /**
                 * One
                 */
                GL.Normal3(Normals[Faces[i].One.NormalIndice]);
                GL.TexCoord2(TexCoords[Faces[i].One.TextureIndice]);
                GL.Vertex3(Vertices[Faces[i].One.VertexIndice]);
                /**
                 * Two
                 */
                GL.Normal3(Normals[Faces[i].Two.NormalIndice]);
                GL.TexCoord2(TexCoords[Faces[i].Two.TextureIndice]);
                GL.Vertex3(Vertices[Faces[i].Two.VertexIndice]);
                /**
                 * Three
                 */
                GL.Normal3(Normals[Faces[i].Three.NormalIndice]);
                GL.TexCoord2(TexCoords[Faces[i].Three.TextureIndice]);
                GL.Vertex3(Vertices[Faces[i].Three.VertexIndice]);
            }
            GL.End();
        }
    }
}

```

You will also need:

```
using System;

namespace GrimoireEngine.Framework.OpenGL.Modeling
{
    public struct Vertex : IEquatable<Vertex>
    {

        public int VertexIndice;
        public int TextureIndice;
        public int NormalIndice;

        public static Vertex Empty
        {
            get
            {
                return new Vertex();
            }
        }

        public Vertex(int[] indices)
        {
            this.VertexIndice = indices[0];
            this.NormalIndice = indices[1];
            this.TextureIndice = indices[2];
        }

        public Vertex(int vertexIndice, int normalIndice, int textureIndice)
        {
            this.VertexIndice = vertexIndice;
            this.TextureIndice = textureIndice;
            this.NormalIndice = normalIndice;
        }

        public bool Equals(Vertex other)
        {
            return VertexIndice == other.VertexIndice &&
                   TextureIndice == other.TextureIndice &&
                   NormalIndice == other.NormalIndice;
        }

        public override bool Equals(object obj)
        {
            return obj is Vertex && Equals((Vertex)obj);
        }

        public static bool operator ==(Vertex v1, Vertex v2)
        {
            return v1.Equals(v2);
        }

        public static bool operator !=(Vertex v1, Vertex v2)
        {
            return !(v1 == v2);
        }

        /// <summary>
        /// Order = VertexIndice, TextureIndice, NormalIndice
        /// </summary>
        /// <returns></returns>
        public int[] ToArray()
        {
            return new[] { VertexIndice, TextureIndice, NormalIndice };
        }

        public override int GetHashCode()
        {
            unchecked
            {
                int hashCode = VertexIndice;
                hashCode = (hashCode * 31) ^ TextureIndice;
                hashCode = (hashCode * 31) ^ NormalIndice;
                return hashCode;
            }
        }
    }
}

```

And

```
using System;

namespace GrimoireEngine.Framework.OpenGL.Modeling
{
    public struct Face : IEquatable<Face>
    {
        public Vertex One;
        public Vertex Two;
        public Vertex Three;

        public static Face Empty
        {
            get
            {
                return new Face();
            }
        }

        public Face(Vertex[] vertexIndices)
        {
            this.One = vertexIndices[0];
            this.Two = vertexIndices[1];
            this.Three = vertexIndices[2];
        }

        public Face(Vertex one, Vertex two, Vertex three)
        {
            this.One = one;
            this.Two = two;
            this.Three = three;
        }

        public bool Equals(Face other)
        {
            return One == other.One && Two == other.Two && Three == other.Three;
        }

        public override bool Equals(object obj)
        {
            return obj is Face && Equals((Face)obj);
        }

        public static bool operator ==(Face f1, Face f2)
        {
            return f1.Equals(f2);
        }

        public static bool operator !=(Face f1, Face f2)
        {
            return !(f1.Equals(f2));
        }

        public Vertex[] ToArray()
        {
            return new[] { One, Two, Three };
        }

        public override int GetHashCode()
        {
            unchecked
            {
                int hashCode = One.GetHashCode();
                hashCode = (hashCode * 31) ^ Two.GetHashCode();
                hashCode = (hashCode * 31) ^ Three.GetHashCode();
                return hashCode;
            }
        }
    }
}

```

And my Material class (Current work in progress because I just created my own accelerated Bitmap class and it is not using it yet):

```
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using OpenTK.Graphics.OpenGL;

namespace GrimoireEngine.Framework.OpenGL.Texturing
{
    public enum MaterialComponent
    {
        /// <summary>
        /// Represents a Diffuse Texture Component
        /// </summary>
        Diffuse
    }

    public class Material
    {
        /// <summary>
        /// The name of the Material
        /// </summary>
        public string Name;
        /// <summary>
        /// The Diffuse Material Component
        /// </summary>
        public int Diffuse;
        /// <summary>
        /// The Ambient Color for the Material
        /// </summary>
        public Color AmbientColor;

        public bool HasDiffuseComponent
        {
            get
            {
                return Diffuse != 0;
            }
        }

        public Material()
        {
            this.AmbientColor = Color.White;
            this.Diffuse = 0;
        }

        public Material(string diffuse, TextureMinFilter minFilter = TextureMinFilter.Nearest, TextureMagFilter magFilter = TextureMagFilter.Nearest)
        {
            this.AmbientColor = Color.White;
            if (diffuse != null)
            {
                if (File.Exists(diffuse))
                {
                    Bitmap diffuseImage = new Bitmap(diffuse);
                    LoadDiffuseComponent(diffuseImage, minFilter, magFilter);
                }
                else
                {
                    throw new FileNotFoundException("Could not locate: " + diffuse);
                }
            }
        }

        /// <summary>
        /// Loads a Bitmap as the Diffuse Component for this Material.
        /// </summary>
        /// <param name="diffuseImage"></param>
        public void LoadDiffuseComponent(Bitmap diffuseImage)
        {
            this.Diffuse = UploadBitmap(diffuseImage, TextureMinFilter.Nearest, TextureMagFilter.Nearest);
        }

        /// <summary>
        /// Loads a Bitmap as the Diffuse Component for this Material.
        /// </summary>
        /// <param name="diffuseImage"></param>
        /// <param name="minFilter"></param>
        /// <param name="magFilter"></param>
        public void LoadDiffuseComponent(Bitmap diffuseImage, TextureMinFilter minFilter, TextureMagFilter magFilter)
        {
            this.Diffuse = UploadBitmap(diffuseImage, minFilter, magFilter);
        }

        /// <summary>
        /// Loads a Bitmap as a Diffuse texture with full control.
        /// </summary>
        /// <param name="bitmap">The bitmap.</param>
        /// <param name="minFilter"></param>
        /// <param name="magFilter"></param>
        public static int UploadBitmap(Bitmap bitmap, TextureMinFilter minFilter, TextureMagFilter magFilter)
        {
            int bind;
            GL.Enable(EnableCap.Texture2D);
            GL.GenTextures(1, out bind);
            GL.BindTexture(TextureTarget.Texture2D, bind);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)minFilter);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)magFilter);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge);
            BitmapData data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly,
                System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, data.Width, data.Height, 0,
                OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);
            bitmap.UnlockBits(data);
            GL.BindTexture(TextureTarget.Texture2D, 0);
            GL.Disable(EnableCap.Texture2D);
            return bind;
        }

        /// <summary>
        /// Binds this texture instance to OpenGL.
        /// </summary>
        public void Bind()
        {
            GL.BindTexture(TextureTarget.Texture2D, this.Diffuse);
        }

        /// <summary>
        /// Binds a texture to the OpenGL instance.
        /// </summary>
        /// <param name="textureBind">The texture bind.</param>
        public static void Bind(int textureBind)
        {
            GL.BindTexture(TextureTarget.Texture2D, 0);
        }

        /// <summary>
        /// Unbinds the texture for this material instance.
        /// </summary>
        public void Unbind()
        {
            GL.BindTexture(TextureTarget.Texture2D, 0);
        }
    }
}

```

I also invert my Texture coordinates, because OpenGL is defaulted to bottom left-hand origin. DirectX is upper left as origin. This may or may not be an issue for you, but it's useful information nonetheless.

And general Texture Coordinate information:

https://en.wikipedia.org/wiki/Texture\_mapping

---
Tags: opengl, c++, textures, obj
---


# Question
Title: How to implement the missile trajectories in the classic missile command game - pygame
I am doing a clone of the classic arcade game missile command, i am curious about how to implement the trajectories of the missiles. I have a solution that looks pretty similar to the original game, but it have some problems that i don't know how to avoid.

Here is the relevant code i have right know:

```
missiles_attack = []

class Missile(object):

    def __init__(self, pos_src, pos_dst, color, speed):

        # direction of the missile
        direction = (pos_dst - pos_src).normalize()

        # total distance that missile must travel to reach his target
        self.__distance = pos_dst.distance_to(pos_src)

        # the current distance traveled
        self.__distance_traveled = 0

        # how many the head should move each frame
        self.__step = speed * direction

        # the length of a step
        self.__step_length = self.__step.length()

        self.pos_head = Vector2(pos_src)
        self.points = [(self.pos_head.x, self.pos_head.y)]

        self.color = color

    def update(self):
        self.__distance_traveled += self.__step_length
        if self.__distance_traveled < self.__distance:
            self.pos_head += self.__step
            self.points.append((self.pos_head.x, self.pos_head.y))
        else:
            self.destroy()

    def destroy(self):
        missiles_attack.remove(self)

def draw_missiles():
    for missile in missiles_attack:
        pygame.draw.lines(screen, missile.color, False, missile.points, 2)

def update_missiles():
    for missile in missiles_attack:
        missile.update()

```

So when i want to create a missile, i pass the src and dst position of the missile and then add it to the list of attack missiles, both the `draw_missiles` and `update_missiles` functions are called for each frame inside the game loop.

The idea behind the trajectory is to work out a new point in the line defined by the src and dst position each frame, i have three problems with this approach:

**problem 1**

I don't know how to draw the missile heads, in the video you can see that the heads are like a white pixel, i tried to take the last two points of the `missile.points` list and draw a new line with those points to represent the head, the problem is that the line length changes when the speed of the missile changes so it not works.

**problem 2**

Seems silly to store all the points of the trajectory in a list, seems like is too much waste of memory, i can't think in another more efficient solution with the same 'graphical results'.

**problem 3**

Another thing i tried is instead of use the `pygame.draw.lines` function use the `pygame.draw.line` one, the `draw_missiles` function will be something like this:

```
def draw_missiles():
    for missile in missiles_attack:
        pygame.draw.line(
          screen,
          missile.color,
          (missile.pos_src.x, missile.pos_src.y),
          (missile.pos_head.x, missile.pos_head.y),
          2
        )

```

Well, now i don't have to store all the points, which is a good thing i think, the problem is that when the line is draw, the results are different than the 'points approach', seems like the line algorithm that pygame uses under the hood not draws the same pixels for a line going from the point A to the point B, that for a line going from the point A to the point C, where C is a point in the line between A and B.

So how i can deal with this problems, what is the most reasonable approach to implement this kind of behavior?

# Answer
So a few things here. Whats most evident to me is that you seem to be looking at the problem in terms of lines. I know missile command has a lot of these and pygame offers ways to draw them in a few ways but if you can abstract the moving point ( missile ) from how it is visualised ( lines ) then it may be easier.

And so taking the above into account and your problem 3. Calculate a start position and direction for a missile, and then give it a lifespan. So given it can travel at a certain speed you can figure out a kind of 'explode timer' So it will go in a direction for so long and then explode. Every gameloop you update this and calculate a new missile position. So there are no lines here. Just a new position every game frame. so the missile is a simple object. Direction, speed and lifespan. Fire and forget :)

And so now you come to visualising the position. With missile command I seem to remember a line is drawn from current missile position to the base it was fired from. And so you can just do that every game loop. Draw a line from missile current pos to the base. This is the render part ( or visualisation ). Its separate from the update

Visualising the head is the same ( problem 1 ) . Take the current position of the missile and just draw a square. Forget how far it has traveled, the head will always be the same size no matter how fast it moves.
> 1 votes

# Answer
Have you tried using the speed as an offset for the position of the missile head? Consider this image, which uses Pythagoras Theorem:

Esentially, you would track the delta(distance moved) and use that to find your hypotenuse(speed). You can then use the speed as an offset for the missle head.

Here is an example of the formula:

```
        /// <summary>
        /// https://en.wikipedia.org/wiki/Pythagorean_theorem
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        public static float Pythagorean(float a, float b)
        {
            return (float)Math.Sqrt((a * a) + (b * b));
        }

```
> 1 votes

---
Tags: pygame, trajectory
---


# Question
Title: Certain lines in C# script not running on certain GameObjects in Unity
Sorry for the long question, but I'm being specific in order to avoid answers I've already considered. This is the weirdest problem I've encountered in Unity thus far. What's happening is that the last instantiated GameObject of all GamObjects instantiated via code, is the only one that behaves ENTIRELY correctly in its attached InteractibleWorldObject script. I didn't realise they weren't behaving correctly until I added a feature that changes the reticule icon depending on the type of interaction selected for the GameObject with which the player is currently interacting.

Consider this code in the InteractibleWorldObject script:

```
Debug.Log("Interaction triggered");
this.imgReticule.sprite = Resources.Load<Sprite>("gui/img_interaction_icon/img_interaction_icon_"
        + this.interactionOptions[this.selectedInteractionOption].imageFileName) as Sprite;
Debug.Log("changed reticule");
this.playerControl.defaultReticule = false;

this.txtReticuleTitle.text = this.interactionOptions[this.selectedInteractionOption].prompt;
this.txtReticuleBody.text = this.objectName;
Debug.Log("updated reticule text");

```

THIS CODE IS ALL IN THE SAME BLOCK. THERE IS ALSO NOTHING WRONG WITH THIS CODE.

However, the last instantiated GameObject is the only one that ever executes the first few lines, which change the reticule icon. The reticule text changes as expected when interacting with ANY instantiated GameObject with the InteractibleWorldObject script attached. When I comment out the part that changes the reticule text, the text never appears when activating any of the instantiated GameObjects, so I know two things:

1. It's nothing to do with Unity using a different version of the .cs file.
2. This code block is not out of reach.

Originally I had a bunch of duplicate GameObjects in the scene but I learnt the hard way that it doesn't really work like that. Instead, because I still want to build the scene manually in the editor, I placed the objects as I wanted them and then re-instantiate them in code by looking for them and replacing them with prefabs using the properties of the manually placed transforms.

Here is the code that does that (I suspect it may be part of the problem):

```
Transform obj;
Vector3 position;
Quaternion rotation;
for (int i = 0; i < 10; i++)
{
    // get info from gameObject placed in scene manually
    obj = gameObject.transform.GetChild(i);
    Debug.Log(obj.name);
    position = obj.localPosition;
    rotation = obj.localRotation;

    if (this.prefabs.Contains(obj.gameObject.name))
    {
        obj.gameObject.SetActive(false);
        UnityEngine.Object.Instantiate(Resources.Load<GameObject>("prefabs/"
                + obj.gameObject.name) as GameObject, position, rotation, gameObject.transform);
        Destroy(obj.gameObject);
    }
}

```

This code also functions with the desired result, or at least I thought so until now. It still might not be a problem because everything else except those few lines executes just as expected.

What could possibly be the problem here? If any more code is needed to diagnose the problem I will provide it.

# Answer
> -1 votes
OK, never mind. It wasn't what I thought it was! It was alternating between reticule icons every frame which has now been fixed.

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


# Question
Title: How can I move my box collider temporarily?
I'm very new to game development, I mostly program other things. I'm trying to write a basic whack-a-mole type of game. I've gone ahead and created a hammer with a swinging animatio in the FBX. I've also attatched a box collider to the head of the hammer.

The issue is that when I play the hammer swing animation (and the hammer moves down), the box collider does not follow. I understand that this is because the animation is only for the object, but in this case it presents a problem since I need the collider to be at the hammer's lowest point once the animation gets there.

**What is the right way to approach this problem? I've thought of a couple solutions on my own, are any of these valid?**

1) Move the Collider with the animation. I've got no clue on how to do this.

2) Store the time when I start the animation, check if enough time has ellapsed for completed animation. Then manually move collider to the contact point. Wait a few milliseconds, then move it back. I tried this, the issue with this is that it moves the entire object with the collider.

```
void Update() {
   if (Input.GetMouseButtonDown(0)) {

       animator.SetTrigger("hammer");
       animationStartTime = Time.time;
       toAnimate = true;
   }
   if(Time.time-animationStartTime > 0.38 && toAnimate == true) {
       toAnimate = false;
       //bc = attatched box collider
       bc.transform.position = new Vector3(0, 0, 0); //move to target point (won't be 0,0,0 for real, just a test point)

    }
    if(Time.time- animationStartTime > 0.50)
    {
           bc.transform.position = transform.position + bcOffset; //reset to original position
     }
}

```

3) Do what I did in step 2, but create a collider not attatched to a parent object so that the parent object isn't moved. I don't know how to create a collider on its own however.

```
BoxCollider bc = new BoxCollider();
//I then use bc.size and bc.position and set them but it does not show up
//on my scene view so I don't think this works.

```

NOTES:

This script is attatched to hammer object.

The hammer is moved with this code:

```
hPos = Input.GetAxis("Mouse X") * -0.7f;
fPos = Input.GetAxis("Mouse Y") * 0.7f;
transform.position += new Vector3(fPos, transform.position.y, hPos);

```

Edit: is it possible for me to apply the animation to the collider? This would probably be the easiest way.

# Answer
I'm not exactly proficient with FBX but it should have some sort of bone mechanic (attaching bones to limbs etc.). Just put a bone inside the hammer (preferably in the center or two with one in the head one in the body) and attach the collider you made to that bone in Unity instead of the hammer object.
> 1 votes

---
Tags: unity, collision-detection
---


# Question
Title: Unity solution not compatible with Visual Studio
Since updating to the most recent version of Unity 5.4.0f3 Personal Edition, whenever I double click on a script, it launches Visual Studio, but I get an error saying that this version of Visual Studio (Community Studio 2015) is unable to open my project. Please see the screenshots attached for the actual error message. Monodevelop also launches with it's own error message.

I am still able to open the individual script manually using the menu in VS but it's a little frustrating that it doesn't open automatically, and more annoying is that the intellisense/code completion features no longer work. Anyone know how to fix this? I have Visual Studio Tools for Unity installed and have tried running the installer to repair this tool also.

# Answer
Turns out it was an issue with my existing install of Visual Studio Tools for Unity (VSTU).

I found a thread where users had experienced similar problems due to an unsupported version of VSTU running on Unity5.2 and beyond. Unity 5.2+ requires VSTU 2.1 or later for VS to work correctly with Unity, more information for anyone interested is available in the documentation here.

I had VSTU 2.3 installed, but removing and reinstalling VSTU resolved the issue, so there must have been a problem with my install. If anyone else has this or a similar issue you can download the latest installer for VSTU here.
> 3 votes

# Answer
This looks to me like when you installed Visual Studio, you did not check the boxes needed to install C# support. You might try reinstalling Visual Studio and making you go down the "customized" installation path where you can enable and disable various features, ensuring all the C#-related stuff is installed.
> 2 votes

---
Tags: unity, visual-studio
---


# Question
Title: Loading next scene when counter is down to 0
I am trying to let my Unity project load next scene when the counter I have is down to 0. However I am unable to do that for some reason. The way I am trying to do it by :

```
    int i = SceneManager.GetActiveScene().buildIndex;

    void Update () {
     if (GameObject.FindGameObjectsWithTag("Birds") == null)
        {
            SceneManager.LoadScene(i + 1);
        }
    }

```

In the editor I have created a folder where I have made 3 scenes. Have called them Level 1, Level 2 etc.

What am I doing wrong?

# Answer
You can see here in the build settings that there are numbers next to each scene you have. After you have dragged your scenes into the build settings here you will be able to specify which scene to load by using that number next to the scene. Using `SceneManager.LoadScene(i + 1);` will work if the next scene in line in the build settings is the scene you are wanting to move from your current scene.

So for example, say I am in the title scene and I have a button that is used to move on to the game scene. When that button is pressed I would use `SceneManager.LoadScene(i + 1);` to move to the game scene since it is the next in line in build settings.
> 1 votes

# Answer
Drag and drop the scene from assets into the hierarchy bar, then unload the scene to proceed in editor.

Now, when you're in the first scene (AR2) and you call the next scene (AR1) then you'll get that scene. Don't forget that you need to keep these scenes alive if you want to go back and forth between them as the editor will unload scenes if they call another scene load.
> 0 votes

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


# Question
Title: How to interop between DirectX11 in C++ with XAML&C# or should I turn to SharpXD
I'm writing a UWP program and I want to write the general UI in C#. But there would be some graphic demonstrations using DirectX on some SwapChainPanels in the app.
I have found less than enough documents of how I can interop between these two parts in two languages. And problem occurs such as how I should instance a C++ class from another project from C#.
I might need a frequent calling between the two part for the demonstration(It's actually a scatter plot). And some suggested that this could cause a great performance damage.
So should I turn to SharpXD? And what should I do if I don't.
Thank you.

# Answer
> 1 votes
My answer is, don't. Because it is too complicated, and if the interop is frequent, it may cause performance problems. Use SharpDX instead. I found managed DirectX is much more clear and simpler, though currently the archives are not very complete.

# Answer
> 0 votes
For XAML you have a choice of using C# or C++ code-behind. The base platform only supports C++ access to DirectX APIs, so the DirectX+XAML template is provided for C++, but not C#.

You can certainly use SharpDX or other C# wrappers to get C# assemblies DirectX, but you might also want to consider using Win2D for something like a scatter plot.

---
Tags: c#, c++, directx11, windows
---


title: JavaScript 2D liquid flow

text:
# Question
Title: JavaScript 2D liquid flow
Brand new to games/graphics and I'm attempting to find a method to create a 2D liquid effect with JavaScript. Ideally I could adjust the viscosity and flow from a gas/fog effect to oil and between.

As an example, the effects in the PixelJunk Shooter trailer have stuck with me for years and I haven't ever seen another implementation with this style.

There is another question, as well, but no real implementation.

I also found a nice synopsis of ideas on gamedev so maybe that's the extent of my answer?

I'm currently using createjs but suspect I'd need another library so I'm not against using multiples.

I've looked at threejs and craftyjs but they don't seem to fit the criteria.
In order to keep with easeljs maybe I'll just check out a tutorial on how to create a particle system.

The heart of my question is really about a simple implementation rather than reading complicated mathematical presentations on the subject. While interesting it's pretty far above my head. Am I simply finding it's impossible to create a nice effect without some heavy lifting?

Thanks for any ideas on how this might be accomplished.

# Answer
> 3 votes
I've found that fluid simulation in 2d games is usually visual trick involving simple physics bodies and a shader or other rendering treatment to make them appear liquid-like. There's a good example here built with JavaScript and Phaser: http://gamemechanicexplorer.com/#fluid-1

Another purely canvas implementation, similar idea, particles + 'metaball' style renderer: https://github.com/asadm/SPHjs/tree/master/js

There's other JS implementations out there for sure, these are just the ones I remembered seeing when I was looking for the same. Both have similar visual feel to the liquid effects in Pixeljunk Shooter you're after.

# Answer
> -2 votes
Sorry, but modelling water really does require you to read a lot of mathematical papers. The libraries you mentioned either have no or just very small to do with physical simulation. ThreeJS? 3D graphics engine. EaselJS? 2D graphics library.

Try to search for a moree advanced physics library (I doubt there's one for javascript though).

---
Tags: javascript, animation, graphic-effects, easeljs
---


# Question
Title: Xna c# picking model with Ray mouse cursor select the wrong model
i made a small 3D game and i just try to apply a basic sample from here : http://rbwhitaker.wikidot.com/picking for picking model by the mouse cursor. For that i use the Ray object and check if some model intersect my Ray. But i don't know why, the model object target by my cursor is always offset to the left.there is a shift difference.

**Here is the code i use.**

// Update Ray cursor each frame in the Update loop function

```
public void UpdateRayCursor()
        {
            Vector3 nearPoint = new Vector3(Globals.mouseState.Position.ToVector2(), 0);
            Vector3 farPoint = new Vector3(Globals.mouseState.Position.ToVector2(), 1);

            nearPoint = graphic.GraphicsDevice.Viewport.Unproject(nearPoint, CameraNode.Camera.Projection, (Matrix)CameraNode.View, Matrix.Identity);
            farPoint = graphic.GraphicsDevice.Viewport.Unproject(farPoint, CameraNode.Camera.Projection, (Matrix)CameraNode.View, Matrix.Identity);

            Vector3 direction = farPoint - nearPoint;
            direction.Normalize();

            Ray = new Microsoft.Xna.Framework.Ray(
                nearPoint
                ,
                direction
                );
        }

```

// **check if a model is target by the Ray**

```
public void UpdateIntersectSceneRay()
    {
        float? nearestDistance = 0f;
        bool findModelTarget = false;
        foreach (var bdgToCheck in ListBlocksSelectable)
        {
            //Check if the boundingBox intersect with the ray
            var checkIntersectDistance = _mainPlayer.Ray.Intersects(bdgToCheck);
            if (checkIntersectDistance != null)
            {
                if ((float)checkIntersectDistance < (float)nearestDistance || nearestDistance == 0)
                {
                    nearestDistance = checkIntersectDistance;
                    _mainPlayer.ItemFocusByReticle = item;
                    findModelTarget = true;
                }
            }
        }
        if(!findModelTarget)
        {
            _mainPlayer.ItemFocusByReticle = null;
        }

    }

```

**Some people have some idea why ? i use monogame library with XNA. Thank you in advance**

# Answer
It's ok , i finally find the solution by myself. Is because when i try to get the mouse position. It's not exactly the center of the screen which must match the player cursor. I must use like this :

```
Vector2 posCursor = new Vector2(
            graphic.GraphicsDevice.Viewport.Width/2,
            graphic.GraphicsDevice.Viewport.Height/2
            );
        Vector3 nearPoint = new Vector3(posCursor, 0.0f);
        Vector3 farPoint = new Vector3(posCursor, 1.0f);

```
> 0 votes

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


title: Calculating next speed of a ball

text:
# Question
Title: Calculating next speed of a ball
Is it possible to calculate the next speed of a ball knowing only dx and dy of the ball? For example if x = 120, y = 0, dx = -10, dx = 10, gravity = 0.05. So the next position of a ball (next update) is x = 110, y = 10. But a ball will be fall faster and faster under the influence of gravity. So is it possible to calculate next speed based on current x, y, dx and dy? My equation on next update of a ball x position should be x = x + dx * speed * gravity, but I haven't information about current speed, so I must calculate it every update.

# Answer
Consider this image, which uses Pythagoras Theorem:

Here is an example of the formula:

```
/// <summary>
/// https://en.wikipedia.org/wiki/Pythagorean_theorem
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
public static float Pythagorean(float a, float b)
{
    return (float)Math.Sqrt((a * a) + (b * b));
}

```
> 0 votes

# Answer
First, sorry for my bad English...

If the speed or velocity is changing over time then yes, you have to update the speed or velocity vector each time step.

I suggest to brake down the problem into peaces that lie on the physics. You have a Display object that has a Position in the world and that object has a current speed applied in a Velocity vector. And then you have Force(s) that changes the speed in the Velocity vector during time. Gravity is a Force but there can also be others forces applied to the object. Think of jumping, this will just be another force to the object that overcomes Gravity for a amount of time, getting smaller in time.

The classes below should give you an idea how to brake the problem in to peaces in an object oriented way.

```
// Position point
public class Position {
    float x;
    float y;
}

// Velocity vector
public class Velocity {
    float dx;
    float dy;
}

// Force vector with update to change the force over time
public class Force {

    float fx;
    float fy;

    public void update( long timeStep, Velocity velocity ) {
        // first remove the previous force vector form Velocity to reset
        velocity.dx -= fx;
        velocity.dy -= fy;

        // calculate the new force vector with a specific equation of your need
        if ( fy > -6f ) {
            fy = fy - 1.0f;
        }

        // add the new force vector to the Velocity
        velocity.dx += fx;
        velocity.dy += fy;
    }

}

// This is a display object that has a position, a velocity vector and List of forces that applies to the object
// forces can change and also the list of forces can change
public class SomeDisplayObject {

    Position position;
    Velocity velocity;
    List<Force> forces;

    public void update( long timeStep ) {
        // update the velocity on all forces that act on the object
        for ( Force force : forces ) {
            force.update( timeStep, velocity );
        }

        // apply the velocity to the position
        position.x += velocity.dx;
        position.y += velocity.dy;
    }

    public void addForce( Force force ) {
        forces.add( force );
        velocity.dx += force.fx;
        velocity.dy += force.fy;
    }

    public void removeForce( Force force ) {
        forces.remove( force );
        velocity.dx -= force.fx;
        velocity.dy -= force.fy;
    }
}

```
> 1 votes

---
Tags: 2d
---


title: Procedural Hatching

text:
# Question
Title: Procedural Hatching
I know that it is possible to make a shader that uses procedural hatching instead of pre-designed tonal art maps. But is it possible to make that procedural hatching in the fragment shader? I would like to know some algorithm to achieve that, it doesn't need to be in GLSL, some pseudo-code would be nice

# Answer
Yes, in fact I'm not sure of any other way you'd do it other than in the fragment shader. Here's some examples I found:

* This ShaderToy uses a noise texture and another function to generate the hatching. It's not exactly like artistic gradiential hatching but I think it's definitely a start. You'd specifically want to look at the `texh()` function, the rest is how he generates the scene, lighting, objects, etc...

.

```
//Excerpt from https://www.shadertoy.com/view/4lfXDM
//By nmz, https://www.shadertoy.com/user/nmz
//texh is the function that generates the Hatching TEXture
//p seems to be the uv for hatching, str seems to be the strength
float texh(in vec2 p, in float str)
{
    p*= .7; //Scale p
    float rz= 1.;
    for (int i=0;i<10;i++)
    {
        float g = texture2D(iChannel0,vec2(0.025,.5)*p).x;
        g = smoothstep(0.-str*0.1,2.3-str*0.1,g);
        rz = min(1.-g,rz);
        p.xy = p.yx;
        p += .07;
        p *= 1.2;
        if (float(i) > str)break;
    }
    return rz*1.05;
}

```
* This GLSL example seems more inline with artistic hatching but is only demonstrated on a 2D image. The relevant code can be found below...

.

```
/*
    Straight port of code from
    http://learningwebgl.com/blog/?p=2858
*/

uniform sampler2D Texture;

void main()
{
    float lum = length(texture2D(Texture, gl_TexCoord[0].xy).rgb);

    gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);

    if (lum < 1.00) {
        if (mod(gl_FragCoord.x + gl_FragCoord.y, 10.0) == 0.0) {
            gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);
        }
    }

    if (lum < 0.75) {
        if (mod(gl_FragCoord.x - gl_FragCoord.y, 10.0) == 0.0) {
            gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);
        }
    }

    if (lum < 0.50) {
        if (mod(gl_FragCoord.x + gl_FragCoord.y - 5.0, 10.0) == 0.0) {
            gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);
        }
    }

    if (lum < 0.3) {
        if (mod(gl_FragCoord.x - gl_FragCoord.y - 5.0, 10.0) == 0.0) {
            gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);
        }
    }
}

```
> 3 votes

---
Tags: opengl, shaders, glsl, procedural-generation, fragment-shader
---


# Question
Title: MonoGame rendering text with black boxes?
I have a UI manager that renders a background image and some images and buttons using `BlendState.AlphaBlend`. This works as intended. However, when I try and draw some text on top of it with the same BlendState, each character is encased in a black box and it looks awful. I played around a bit and found that `BlendState.Additive` was the only one that didn't render the black boxes. However, the text is now slightly transparent, which looks weird. I then decided to mess around with custom BlendStates, but after around 10 minutes I found that there could be over 67 million different BlendStates. Hmm. My last thought is that it could be the font that is breaking it, because I tried rendering with the Arial font and AlphaBlend worked fine. Is there a way round this using BlendStates without finding a new font?

tl;dr I can only render text either with black boxes or half transparent.

Text rendering code:

```
sb.Begin(samplerState: SamplerState.PointClamp, blendState: BlendState.AlphaBlend, transformMatrix: Game.Camera.GetViewMatrix());

sb.DrawString(Game.Font, text, position, color);

sb.End();

```

SpriteFont File (using the free Minecraftia font):

```
<?xml version="1.0" encoding="utf-8"?>
<XnaContent xmlns:Graphics="Microsoft.Xna.Framework.Content.Pipeline.Graphics">
  <Asset Type="Graphics:FontDescription">
    <FontName>Minecraftia</FontName>
    <Size>6</Size>
    <Spacing>0</Spacing>
    <UseKerning>true</UseKerning>
    <Style>Regular</Style>
    <DefaultCharacter>?</DefaultCharacter>
    <CharacterRegions>
      <CharacterRegion>
        <Start> </Start>
        <End>~</End>
      </CharacterRegion>
    </CharacterRegions>
  </Asset>
</XnaContent>

```

It's a pixelly game (so I need a blocky font to avoid weird antialiasing) and I *think* the font is a bitmap font. Just in case that makes a difference.

Edit: I found that setting the text size (in the SpriteFont file) to anything other than it's native size fixes the problem (but also renders with antialiasing, which I don't want). Also, this problem seems to happen with other bitmap fonts (tested 'Minecraftia' and '04b03').

# Answer
I submitted this as an issue to the MonoGame report and they gave me this workaround: In the Pipeline tool, select your SpriteFont and in the properties pane change the Compression mode or something (bottom option) to 'Color'. This will fix the problem but in turn it will also make the resulting XNB file considerably larger.
> 0 votes

# Answer
I've seen that there is a bit of a common problem people are having with anti-aliasing and spritefonts for MonoGame, but so far the only thing I've seen as a workaround is to use BMFonts and the MonoGame.Extended library:

How do I draw non-smoothed fonts in MonoGame 3.5?

http://dylanwilson.net/bmfont-rendering-with-monogame-extended
> 0 votes

---
Tags: rendering, monogame, text
---


# Question
Title: Regarding BGE (Blender Game Engine), is it possible to generate a single .exe file from multiple files linked together?
Would any of you guys or gals know the answer, please?

I know one can generate a .exe (windows executable) file from a single blend file. My question is very simple: Can anyone generate a single .exe file from multiple blender files of a same project?

For instance, say I have a project folder with several subfolders and files from my project game. Each folder has specific elements like scenes, models, textures, etc. They are all linked together to form the final game. Now I want to generate a single .exe file for my game. Is this possible?

Or, rather, should I make an entire game inside a single .blend file? (It seems like a very unlikely arrangement, maybe even impossible, but I rather ask). Or maybe even create a master .blend file from where to link all data and when project is finished pack everything before generating the executable (.exe)?

# Answer
> 1 votes
I recommend appending all of your assets to one blend file, and export it as a standalone. Some blender games either crash or fail to load because the operating system prevented another blend file from being used.

---
Tags: blender, blender-game-engine
---


title: Incorrect values fron Input.GetAxis

text:
# Question
Title: Incorrect values fron Input.GetAxis
I need the gamepad Input on my game, and I'm trying the Input.getAxis("Horizontal") function and the documentation says that returns a value from -1 to 1, 0 is the central value, when I not move the stick left or right. Well, I'm on linux-editor on mint 17.3 and all is ok, the joystick configuration on mint is correct, but in Unity I having a 0 to maximum stick move to left and 1 to maximum stick moved to right on my gamepad (logitech rumblepad2). Center is 0.56.

What is the problem?? Is a linux editor problem, is a bad Unity configuration...

# Answer
> 0 votes
This is probably caused by the drivers in your connected gamepad. It seems that the values are on the right side of the Cartesian plane, which is different to how Unity processes input.

---
Tags: unity
---