# Question
Title: Adding Animation to Object—Unexpected Behavior
I've been following the Unity 2D roguelike tutorial and I'm a bit confused about something. When he drags a series of sprites to his player object, a dialog box appears that prompts him to name and choose a location for his animation. I have seen this behavior in a couple video tutorials now.

When I do this, it simply creates the animation and animation controller in the sprite folder and nothing more. This becomes a bit tedious after a while and I'm not sure these animations are being associated with the object correctly.

What am I doing wrong?

# Answer
You can Create a Animation folder and put them in it for Organization purposes. The animations you create will be associated with the animated controller you use while creating them. After you point it to the Animation Folder the next time you go to create one the directory should be showing the same as in the tutorial. When dragging multiple sprites at once it will automatically create the controller and name it the first sprite of the bunch then will prompt you to name the animation.
> 0 votes

---
Tags: unity
---


# Question
Title: What is next to interpolate camera position with smooth speed changes?
I am working on a path camera to be used in demo playback. (3d game) The spline math used is catmull rom. I am on my second attempt to get constant position speed :( (someone else is doing rotation). The path cam keyframes are position@time.

I have a step now when the path is recalculated, it also generates the arc distance/time lookup table which I have normalized. I have the duration of each segment(k through k+1)as well as each segments linear velocity calculated from that data.

I am not very good at reading anything except basic equations. I could use an explanation or psuedo code of what is needed next in order to get the camera to smoothly accelerate or decelerate depending on the velocity of the next segment. Right now it's instant changes and no good. I tried googling for hours and was going in circles.

# Answer
> 1 votes
Well, a very basic linear interpolation pattern goes like this (pseudocode):

```
currentVelocity = currentVelocity + (interpolationRate * (targetVelocity - currentVelocity ))

```

Calling this on update instead of directly setting the current velocity will do what you requested, the transition speed is adjustable by adjusting the interpolationRate value (between 0.0 and 1.0, 1.0 being an instant change).

---
Tags: animation, camera, splines
---


# Question
Title: How to detect collision position and that position's texture color in Unity?
I have a prefab and I use Circlecollider2D for physics operations. I want to detect the color of the contact position of the collided objects ? Is is possible by using Unity's collider classes ?

# Answer
Take a Look at Texture2D.GetPixel

You can find the contact point on the collider and then map that to the specific point on the texture.
> 1 votes

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


# Question
Title: Why does editing the client's memory in some MMOs allow them to cheat?
Why editing the memory of the game client works? Why so many "Hack protection" tools coming with the clients?

If I were to design a client-server game, everything would happen at the server (the simulation of the game world) and clients would be only passive consumers receiving status updates of the part of the world near their characters, sending only some information like keystrokes or move/action commands. Maybe I missing something here, but with that design, any hack like raising my STR by 200 in the client memory (if the value is present at all), just won't have any effect.

The only explanation I can think is that games in which memory editing works let parts of the simulation run in the client and the server then just synchronize all the clients periodically. I can understand that design for Real Time Strategy games with a fixed number of players once a match is configured, but, why in MMORPGs? Is it a strategy to reduce server load?

# Answer
> 21 votes
While ideal, it is practically improbable to validate *every single input* against the server, both in terms of computational load and latency in input confirmation for the client.

Consequently there are usually a handful of things that *aren't* validated on the server in many MMOs. In some cases this includes certain classes of character movement, which is why teleportation and speed hacks exist. Client-side protections help provide an extra barrier to those hacks, although of course with sufficient time they can be bypassed. To combat this, many such games would employ a strategy of logging and after-the-fact verification and rotation of the actual protections employed.

There's also the issue of screen other simple memory-scraping hacks that can collate information and transmit keypress and other input back through the client faster than a human can normally react. Or they can look for information that may be transmitted to the client but not necessarily visible yet (such as the positions of creatures that are close by but not displayed anywhere yet, as was common in early Diablo map hacks).

# Answer
> 10 votes
One of the reasons why there are protections is that reading the game state could allow bots to know the state of the game and act accordingly.

For instance, grinding in a MMO: if the "bot" knows what mob is around, it can send commands to the game clients to select the mob, hit it until its life is 0, pick up the loot, rinse and repeat. With this, even if all the changes to the simulation are made/confirmed server side, some players may cheat. The commands could be sent via fake mouse-clicks or key-downs, or via memory writing.

This is one of the reasons why MMOs use memory protection.

# Answer
> 6 votes
Many MMO's are designed with client-side hit prediction. So if there is a hit on the client, it sends that result to the server that there was a hit. In this case the server is not truly authoritative, and thus cheating is possible.

To be honest, if I were designing an MMO, I would make the server fully authoritative, with the client only sending clamped input values to the server, and the server resolving the result.

As to why this isn't done yet by many MMO's, I can only think of additional server load and 'response lag' that comes with having a fully authoritative server, as it just breaks the feel and responsiveness of the game.

---
Tags: mmo, client-server, online, anti-cheat, hacks
---


# Question
Title: Designing AI in a 1 on 1 battle similar to Pokemon
I am designing a game where the battle system is similar to Pokemon. That is, a 1 on 1 battle with only a few (4-6) moves to choose from. As the game is taking shape, I'm starting to think about some of the more difficult coding areas such as enemy AI and I have a few questions. I have already thought about some possibilities for designing the AI and wanted also to hear your feedback.

I am thinking of trying a universal AI for my game where all monsters will utilize the same logic for determining what move they will use. It will be based around equations/values assigned to each move and determining which is the best to make. For example, if the monsters move will be resisted (1/2 damage) by the opponent then it receives a lower effective value than the others and moves that do extra damage due to vulnerability will receive higher effective value. Also, I was thinking of adding a variable that reduces the value if the move has been used repeatedly to avoid the computer always using the same move. I feel that this is currently limited just to making the computer use the highest damage move. Any suggestions?

SO for my questions.

1. How does designing AI logic for each monster/Pokemon vs having a general set of rules for all effect the size of my game in terms of code and effectiveness of the AI?
2. Are there any resources that discuss designing AI in this manner? I found very little on the AI in Pokemon games and I'm unsure what other games might be similar in mechanics.

Thanks for your time!

# Answer
> 12 votes
Generalized AI with modular components will probably result in smaller code, and will be easier to expand for a larger number of characters. Here are some example considerations, assuming you construct a generic weighting system for all characters.

-You could assign each character a 'personality' or 'attitude' from a set list (e.g. 'Aggressive', 'Defensive', 'Random'). Then, have your weighting formula take that into account. So, say, an Aggressive character would give more weight to damaging moves, while a Defensive character would give more weight to healing himself. Then, you only have to assign the personality to each character rather than writing unique scripts for each.

-Instead of always choosing the 'best' option, your AI can weight each option, then randomly decide between them. So, given 4 moves, if their calculated values come out to 60, 35, 25, and 20 in this turn, that adds up to 140. Pick a random number in the range 1 to 140, and check against the weights to decide which move is used. This will make the AI *usually* use the best move, but often surprise you with an alternate choice.

-You can give each AI character a numeric "skill" rating that is used to scale the chances that they will pick the best move.

-Remember that Pokemon has a LOT of moves that do not do damage directly, but instead apply status effects, buffs, or debuffs. You can give each character a numeric preference for damaging versus non-damaging moves. You could also give them a set number or possible range of non-damaging moves that they will use before starting to attack directly. Current self and opponent HP values could also be a factor in the formula to weight attacking versus using strategic moves - when you're both at full health, you've got time to set up, but when it's down to a sliver of HP each, it's time to use an attack (hopefully one that hits first!).

-Also, Pokemon has attacks with secondary effects. Consider how you want to weight an attack that does more damage versus a weaker attack with a chance to stun or that always goes first.

# Answer
> 5 votes
So your biggest concerns are code and AI effectiveness. Since your question has 44 views an no suggestions, I thought you wouldn't mind ideas from a basic gamer - esp one that has played Pokemon games. I do not have an AI background an only a small programming background however I think:

If you have unique AI per Poke (Pokemon), your code may be huge. Thus you need Poke classes, and AI (a strategy set) per class. The problem is that for classes=n, you have "The sum from i=n to i=0 of i" strategy sets (SS) to make.

```
Example:
Classes A, B, C have match-ups AA, AB, AC, BB, BC, CC. n=3 SS=6=3+2+1
Classes ABCD; match-ups AA AB AC AD BB BC BD CC CD DD. n=4 SS=10=4+3+2+1

```

If you design your classes the typical way, there is a rock-paper-scissor way to everything. Like fire beats water beats earth bears fire (cycles around). Thus, each Poke can have an identifier for the Class of Poke. Also you have say a maximum of 5 moves.

```
Example:
Pikachu's "growl" has the same effect as Raticates "squeal" to "Lower defense"

```

Your Poke object would contain the following

1. It's class (A,B,C, etc)
2. class# of ordered lists that prioritize which move to use against other classes

Example: Pikachu: Class A. StrategySet A;12345, B;34512 C;51234 Chrmndr: Class B. StrategySet A;21543, B;12345 C;34512 Squirtl: Class C. StrategySet A;43215, B;21543 C;12345

When they fight, (Say Pikachu vs Charmander) if the CPU is Pikachu, the Charmander object passes Class B to Pikachu, and the CPU-Pikachu selects strategy set B;34512, which is the pre-prioritized way to fight a Class B opponent. Those five moves fall into general categories (attack, defense, self-speedup, enemy-speeddown, enemy-attackdown) or what have you, and thus the computer knows what to use first. Using other items in the list can be up to parameters like opponent's health frequency, or even something crazy like the sim of priority values going over a maximum.

# Answer
> 0 votes
I have done some work on the pixelmon battle code, as has been mentioned it works on weighted options for the moves, but also there are the statuses to worry about, then the speed attribute is used + buffs/debuffs/items to determine the move order for that turn then recalc next turn.

But remember there are limited moves and items for anyone to use in a pokemon style game as they all are pre-determined at the start of the battle.

---
Tags: game-mechanics
---


# Question
Title: Gravity not being applied to character, using character controller
So I just copy and pasted the unity example class to use with my character controller.

```
public float speed = 6.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
void Update() {
    CharacterController controller = GetComponent<CharacterController>();
    if (controller.isGrounded) {
        moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
        moveDirection = transform.TransformDirection(moveDirection);
        moveDirection *= speed;
        if (Input.GetButton("Jump"))
            moveDirection.y = jumpSpeed;

    }
    moveDirection.y -= gravity * Time.deltaTime;
    controller.Move(moveDirection * Time.deltaTime);
}

```

The code seems to work okay if I comment out the isGrounded check statement (which means that gravity isn't being applied). So what could be the reason that the gravity is not being applied to my character controller?

# Answer
It looks like time scaling could be an issue here: you scale gravity by Time.deltaTime and apply that to the y axis of the movement vector. You then take that vector and scale it by Time.deltaTime.

This means that the y axis has been scaled twice. Given that there is usually very little time between Updates, you'll probably find that this means moveDirection.y is an infinismall number which gets rounded out to 0.
> 1 votes

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


# Question
Title: A* Implementation Produces zig-zag in positive directions
I have an implementation of A\* in Java. I followed this guide.

But I noticed that the paths generated where the goal is in the positive X and Y direction, I get this zig-zag phenomenon.

Let me demonstrate with these two images (top left area is the origin \[0,0\]):

Here I generate a path where the goal is farther away from the origin than the start: And here I generate a path where the goal is **closer** to the origin than the start: I have tried to manipulate the heuristic algorithm I use, to no avail.

Here's the code:

```
public List<Vector3f> find(Vector3f startLocation, Vector3f goalLocation, NodeValidator validator) {
    start = nodes.get(grid.getNode(startLocation).index);
    goal = nodes.get(grid.getNode(goalLocation).index);

    if ( ! validator.validate(goal.node)) return null;

    open.clear();
    closed.clear();

    open.add(start);

    start.movementCost = 0;
    start.heuristic = 0;

    while(open.isEmpty() == false) {
        NodeProxy q = null;

        for(NodeProxy node : open) {
            if (q == null || node.getCost() < q.getCost()) {
                q = node;
            }
        }

        //did we get the goal?
        if (q == goal) {
            List<Vector3f> path = new ArrayList<Vector3f>();

            //get goal node
            NodeProxy nodeProxy = goal;
            while(nodeProxy != start && nodeProxy != null) {
                if (nodeProxy != null) {
                    path.add(nodeProxy.node.center);
                }

                if (nodeProxy.parent == null) {
                    break;
                }
                nodeProxy = nodeProxy.parent;
            }

            Collections.reverse(path);
            return path;
        }

        open.remove(q);
        closed.add(q);

        float g;
        for(Compass direction : Compass.values()) {
            Node n = q.node.neighbours.get(direction);
            if (n == null) continue;

            NodeProxy successor = nodes.get(n.index);

            g = direction.cost;

            if (validator.validate(successor.node) && closed.contains(successor) == false) {
                if ( ! open.contains(successor)) {
                    open.add(successor);
                    successor.movementCost = q.movementCost + g;
                    successor.heuristic = getHeuristic(successor.node, goal.node);
                    successor.parent = q;
                }else if (q.movementCost < successor.movementCost + g) {
                    successor.movementCost = q.movementCost + g;
                    successor.heuristic = getHeuristic(successor.node, goal.node);
                    successor.parent = q;
                }
            }

            closed.add(q);
        }
    }

    return null;
}

```

Some notes regarding the code: The validator object is simply an object tasked with checking if a node is "walkable".

# Answer
this line:

```
if (q.movementCost < successor.movementCost + g)

```

should look like:

```
if (q.movementCost + g < succesor.movementCost)

```

also remember that function getCost() should return heuristic + movementCost.
> 1 votes

# Answer
The issue was that, the way I computed the neighbours was based on a normalized direction vector. But of course, those don't work for diagonals.

Except, that they kinda did, in my case, but only in the positive directions.

Because when I ask the A\* grid to "getNode(Vector3f location)", it does this to the input vector:

```
location.x -= location.x % nodeSize
location.z -= location.z % nodeSize;

```

So, basically: Use a grid location for each node, where nodes have a size of 1. Just multiply or divide by node size whenever you translate from grid space to world space etc.
> 0 votes

---
Tags: java, path-finding
---


title: Black Rectangle instead of texture

text:
# Question
Title: Black Rectangle instead of texture
I am trying to draw a textured ractangle like in this example. But instead of a texture the rectangle is just black.

Draw method:

```
protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.CornflowerBlue);

    effect.EnableDefaultLighting();
    effect.World = world;
    effect.Projection = camera.Projection;
    effect.View = camera.View;
    effect.TextureEnabled = true;
    effect.Texture = grass;
    effect.LightingEnabled = true;

    foreach (var pass in effect.CurrentTechnique.Passes)
    {
        pass.Apply();

        GraphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, quad[0].Vertices, 0, 4, AlignedQuad.Indexes, 0, 2);
    }

    base.Draw(gameTime);
}

```

The `effect` is like a in the example a `BasicEffect`. The texture is existing and is not a black rectangle.

What am I missing or doing wrong? Thank you for your help.

# Answer
Try adding `effect.Alpha = 1f;` The alpha channel was probably premultiplied (check the texture properties in your content section).
> 1 votes

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


title: Do I need TCP socket?

text:
# Question
Title: Do I need TCP socket?
My game uses UDP sockets to stream updates between server and client and I've also made a reliable channel that resends messages if there's no response and makes sure same message isn't processed multiple times.

But TCP is specifically designed to be reliable and the people who made it probably have more experience than me. So would it be good to use TCP to send commands such as "attack", "play animation", etc. instead of my UDP implementation?
(Of course I mean TCP sockets that don't delay sending the data (Nagle algorithm))

# Answer
> 9 votes
One of the most common misunderstandings of TCP vs UDP is that TCP's main feature is reliability.

The main feature of TCP is that it abstracts a stream of data to send from one socket to another. Reliability, as provided by TCP is a requirement for the abstraction to work, but is not the central idea behind TCP. You might want to consider basing your decisions on whether or not a stream abstraction is appropriate for your needs.

A stream abstraction means that you have a place where you put bytes, and the same bytes appear on the other end as soon as possible. That's all there is to it.

TCP has no concept of messages. As so, it is perfectly possible that you make two sends of 10 bytes each, and you get one receive of 20 bytes. Also it is possible that you get 3 receives, one of 1 byte, one of 14 bytes and one of 5 bytes. If you need to have messages on TCP, you will have to implement your own messaging abstraction over TCP.

Additionally, TCP makes no guarantees as of when the messages will arrive on the other side. It is perfectly possible for you to do one million minus one 10-byte sends, wait 1 hour and then do one final 10 byte send, and only get one 10 megabyte receive at the other end.

There are ways to get around some of these limitations, but the main idea is that TCP abstracts a stream of bytes, and should be used when you need a stream of bytes that you want to send as soon as possible to another place. File sends are an awesome example of an application that makes good use of TCP.

On the other hand, UDP offers you a messaging abstraction. You send messages, and they get immediately sent to the other side. Since messages are completely independent of each other, there is no concept of order, and as such it is perfectly possible for sent messages to arrive in disorder, or not arrive at all. If you want order, and delivery guarantees, you will have to implement those on top of UDP.

However, unlike TCP, each message on UDP is a separate entity. Each send will result in one receive at the other side (supposing the message did not get lost). Messages won't be buffered, split or reassembled anywhere. Also, UDP guarantees that each message will be sent as soon as possible.

For games, you may want to think which abstraction works best for you (stream or messages), and build your communications infrastructure on top of that. If there are additional requirements that the abstraction does not offer, you can build on top of them according to your needs.

For action-based, I would most likely use UDP, as each action can probably be converted into one message. Since UDP does not have any concept of order and reliability, I would insert a few bytes on top of each message, which state a sequence number for that message, and the last sequence number I have received from the other end.

If both hosts are constantly exchanging messages, a host that notices that the most recent messages have not been received by the other host, can assume that a particular message was lost, and could try retransmitting it. This is a very simple order/reliability system that can be easily implemented on top of UDP.

There are many other fun things you can do with UDP, like creating separate channels, each with different sequence numbers, so a message lost on one channel won't affect the rest, or a specific channel without sequence numbers.

Unfortunately, I find it way too common for people to stop at "TCP:Reliable:GOOD!, UDP:Unreliable:BAD!", without considering the more important difference between the protocols.

# Answer
> 2 votes
Panda Pajamas excellent answer has covered a lot of the topic, but if you want more detailed information I suggest taking a look at Gaffer on Games series of blogs on 'UDP vs TCP'. There Glenn Fiedler goes into more detail about the problem with using TCP for games with real-time requirements, and suggests how you can build reliability into your own UDP-based solution.

---
Tags: networking, client-server, socket
---


# Question
Title: How to understand kind of matrix/world from implemented math operations?
i'm a newbie in 3d programming, and i approach for the first time this argument. I try to make some changes to an existing 3d object viewer, to better suite my needs. This object viewer is jsc3d.

I read many different articles about 3d matrices and programming, and my scholar math allows me to understand the matrix operations. What i'm missing now is how to apply all this theory to get the desired result. What is the relationship between matrix math and the resulting projected 3d rotations in 2d space, or: "When i apply some matrix operations, what shall be the expected "visual" result"?

This is the implementation of the matrices:

```
JSC3D.Matrix3x4.prototype.identity = function() {
    this.m00 = 1; this.m01 = 0; this.m02 = 0; this.m03 = 0;
    this.m10 = 0; this.m11 = 1; this.m12 = 0; this.m13 = 0;
    this.m20 = 0; this.m21 = 0; this.m22 = 1; this.m23 = 0;
};
JSC3D.Matrix3x4.prototype.scale = function(sx, sy, sz) {
    this.m00 *= sx; this.m01 *= sx; this.m02 *= sx; this.m03 *= sx;
    this.m10 *= sy; this.m11 *= sy; this.m12 *= sy; this.m13 *= sy;
    this.m20 *= sz; this.m21 *= sz; this.m22 *= sz; this.m23 *= sz;
};
JSC3D.Matrix3x4.prototype.translate = function(tx, ty, tz) {
    this.m03 += tx;
    this.m13 += ty;
    this.m23 += tz;
};

```

For example: could please someone kindly explain me how to recognize what kind of rotation is generated from following matrix:

```
JSC3D.Matrix3x4.prototype.rotateAboutXAxis = function(angle) {
    if(angle != 0) {
        angle *= Math.PI / 180;
        var c = Math.cos(angle);
        var s = Math.sin(angle);

        var m10 = c * this.m10 - s * this.m20;
        var m11 = c * this.m11 - s * this.m21;
        var m12 = c * this.m12 - s * this.m22;
        var m13 = c * this.m13 - s * this.m23;
        var m20 = c * this.m20 + s * this.m10;
        var m21 = c * this.m21 + s * this.m11;
        var m22 = c * this.m22 + s * this.m12;
        var m23 = c * this.m23 + s * this.m13;

        this.m10 = m10; this.m11 = m11; this.m12 = m12; this.m13 = m13;
        this.m20 = m20; this.m21 = m21; this.m22 = m22; this.m23 = m23;
    }
};

JSC3D.Matrix3x4.prototype.rotateAboutYAxis = function(angle) {
        if(angle != 0) {
            angle *= Math.PI / 180;
            var c = Math.cos(angle);
            var s = Math.sin(angle);

            var m00 = c * this.m00 + s * this.m20;
            var m01 = c * this.m01 + s * this.m21;
            var m02 = c * this.m02 + s * this.m22;
            var m03 = c * this.m03 + s * this.m23;
            var m20 = c * this.m20 - s * this.m00;
            var m21 = c * this.m21 - s * this.m01;
            var m22 = c * this.m22 - s * this.m02;
            var m23 = c * this.m23 - s * this.m03;

            this.m00 = m00; this.m01 = m01; this.m02 = m02; this.m03 = m03;
            this.m20 = m20; this.m21 = m21; this.m22 = m22; this.m23 = m23;
        }
    };

JSC3D.Matrix3x4.prototype.rotateAboutZAxis = function(angle) {
    if(angle != 0) {
        angle *= Math.PI / 180;
        var c = Math.cos(angle);
        var s = Math.sin(angle);

        var m10 = c * this.m10 + s * this.m00;
        var m11 = c * this.m11 + s * this.m01;
        var m12 = c * this.m12 + s * this.m02;
        var m13 = c * this.m13 + s * this.m03;
        var m00 = c * this.m00 - s * this.m10;
        var m01 = c * this.m01 - s * this.m11;
        var m02 = c * this.m02 - s * this.m12;
        var m03 = c * this.m03 - s * this.m13;

        this.m00 = m00; this.m01 = m01; this.m02 = m02; this.m03 = m03;
        this.m10 = m10; this.m11 = m11; this.m12 = m12; this.m13 = m13;
    }
};

```

It seems to me that this matrices are rows based and follows the right-hand rule, but i'm not sure. Why is also the 4th column involved in rotation? I think i'm missing somewhat else here.

I made also a fiddle to test the results: https://jsfiddle.net/50dhpLq5/

The final transformation matrix is then translated to the origin, rotated, scaled, and finally translated as needed:

```
this.transformMatrix.identity();
this.transformMatrix.translate(...);
this.transformMatrix.multiply(this.rotMatrix);
this.transformMatrix.scale(...);
this.transformMatrix.translate(...);

```

It would be for me also a great step forward to learn how to recognize the kind of 3d space used. I'm right if i call this a "world rotation matrix"?

# Answer
> 2 votes
## Pipeline background

The spaces involved in most 3D graphics pipelines are:

* model/object space, the space in which the vertices of your geometry are specified;
* world space, a common space into which you transform your meshes;
* eye space, a space in which the observer/camera is at the origin and the axes are along their right/up/forward vectors;
* ndc/screen space, a homogeneous space in which the view frustum occupies a cube around the origin, which maps directly to your window.

You typically represent these by matrices, constructed from several basic operations chained together. These matrices take you from one space to another:

* `world` transform takes you from a model space to the world space;
* `view` transform takes you from world space to eye space;
* `projection` transform takes you from eye space to screen space.

Transformation is simply `vtx_ndc = projection * view * world * vtx_model`.

The `transformMatrix` you manipulate appears to be the `world` transform of your pipeline.

As for your operations, they are just the basic operations mentioned, they work in any regular space and you use them to construct both world and view transforms, for moving/scaling/rotating objects and placing the camera, respectively.

## Deciphering your code

Optimized code may appear unobvious to the observer if the actions inside are unknown and only the end result is seen.

Apart from the `identity` function you cite, all your functions do two things in unison, they construct a matrix for the requested operation and they multiply it with the current matrix in-place.

Wikipedia describes the matrices for rotating around the cardinal axes, here I'll cover the case of the X axis.

```
Rx(a) = [ 1     0        0    ]
        [ 0  +cos(a)  -sin(a) ]
        [ 0  +sin(a)  +cos(a) ]

```

The function to add an X rotation in an unoptimzed form would be like:

```
function makeXRotation(angle) {
    var M = new Matrix3x4();
    var c = cos(angle);
    var s = sin(angle);
    M.m00 = 1; M.m01 =  0; M.m02 =  0; M.m03 = 0;
    M.m10 = 0; M.m11 = +c; M.m12 = -s; M.m13 = 0;
    M.m20 = 0; M.m21 = +s; M.m22 = +c; M.m23 = 0;
    return M;
};

function multiplyInPlace(lhs, rhs) {
    // performs rhs = lhs*rhs
    // dot product of rows of LHS vs. cols of RHS
    // last row assumed (0,0,0,1)
    var m00 = lhs.m00*rhs.m00 + lhs.m01*rhs.m10 + lhs.m02*rhs.m20 + lhs.m03*0;
    var m01 = lhs.m00*rhs.m01 + lhs.m01*rhs.m11 + lhs.m02*rhs.m21 + lhs.m03*0;
    var m02 = lhs.m00*rhs.m02 + lhs.m01*rhs.m12 + lhs.m02*rhs.m22 + lhs.m03*0;
    var m03 = lhs.m00*rhs.m03 + lhs.m01*rhs.m13 + lhs.m02*rhs.m23 + lhs.m03*1;
    var m10 = lhs.m10*rhs.m00 + lhs.m11*rhs.m10 + lhs.m12*rhs.m20 + lhs.m13*0;
    var m11 = lhs.m10*rhs.m01 + lhs.m11*rhs.m11 + lhs.m12*rhs.m21 + lhs.m13*0;
    var m12 = lhs.m10*rhs.m02 + lhs.m11*rhs.m12 + lhs.m12*rhs.m22 + lhs.m13*0;
    var m13 = lhs.m10*rhs.m03 + lhs.m11*rhs.m13 + lhs.m12*rhs.m23 + lhs.m13*1;
    var m20 = lhs.m20*rhs.m00 + lhs.m21*rhs.m10 + lhs.m22*rhs.m20 + lhs.m23*0;
    var m21 = lhs.m20*rhs.m01 + lhs.m21*rhs.m11 + lhs.m22*rhs.m21 + lhs.m23*0;
    var m22 = lhs.m20*rhs.m02 + lhs.m21*rhs.m12 + lhs.m22*rhs.m22 + lhs.m23*0;
    var m23 = lhs.m20*rhs.m03 + lhs.m21*rhs.m13 + lhs.m22*rhs.m23 + lhs.m23*1;
    rhs.m00 = m00; rhs.m01 = m01; rhs.m02 = m02; rhs.m03 = m03;
    rhs.m10 = m10; rhs.m11 = m11; rhs.m12 = m12; rhs.m13 = m13;
    rhs.m20 = m20; rhs.m21 = m21; rhs.m22 = m22; rhs.m23 = m23;
}

```

Followed by the composition of those two functions to perform the operation:

```
function rotateAroundX(angle) {
    var R = makeXRotation(angle);
    multiplyInPlace(R, this);
}

```

That's a lot of operations, many of which are pointless as some matrix components are known to have fixed values like 0 or 1. We can mechanically substitute in the constants to see what we can statically remove:

```
var c = cos(angle);
var s = sin(angle);
var m00 = 1*rhs.m00 +  0*rhs.m10 +  0*rhs.m20 + 0*0;
var m01 = 1*rhs.m01 +  0*rhs.m11 +  0*rhs.m21 + 0*0;
var m02 = 1*rhs.m02 +  0*rhs.m12 +  0*rhs.m22 + 0*0;
var m03 = 1*rhs.m03 +  0*rhs.m13 +  0*rhs.m23 + 0*1;
var m10 = 0*rhs.m00 + +c*rhs.m10 + -s*rhs.m20 + 0*0;
var m11 = 0*rhs.m01 + +c*rhs.m11 + -s*rhs.m21 + 0*0;
var m12 = 0*rhs.m02 + +c*rhs.m12 + -s*rhs.m22 + 0*0;
var m13 = 0*rhs.m03 + +c*rhs.m13 + -s*rhs.m23 + 0*1;
var m20 = 0*rhs.m00 + +s*rhs.m10 + +c*rhs.m20 + 0*0;
var m21 = 0*rhs.m01 + +s*rhs.m11 + +c*rhs.m21 + 0*0;
var m22 = 0*rhs.m02 + +s*rhs.m12 + +c*rhs.m22 + 0*0;
var m23 = 0*rhs.m03 + +s*rhs.m13 + +c*rhs.m23 + 0*1;
rhs.m00 = m00; rhs.m01 = m01; rhs.m02 = m02; rhs.m03 = m03;
rhs.m10 = m10; rhs.m11 = m11; rhs.m12 = m12; rhs.m13 = m13;
rhs.m20 = m20; rhs.m21 = m21; rhs.m22 = m22; rhs.m23 = m23;

```

Lots of zeroes and ones, let's trim:

```
var c = cos(angle);
var s = sin(angle);
var m00 =   rhs.m00                                ;
var m01 =   rhs.m01                                ;
var m02 =   rhs.m02                                ;
var m03 =   rhs.m03                                ;
var m10 =             +c*rhs.m10 + -s*rhs.m20      ;
var m11 =             +c*rhs.m11 + -s*rhs.m21      ;
var m12 =             +c*rhs.m12 + -s*rhs.m22      ;
var m13 =             +c*rhs.m13 + -s*rhs.m23      ;
var m20 =             +s*rhs.m10 + +c*rhs.m20      ;
var m21 =             +s*rhs.m11 + +c*rhs.m21      ;
var m22 =             +s*rhs.m12 + +c*rhs.m22      ;
var m23 =             +s*rhs.m13 + +c*rhs.m23      ;
// remove writes to m0X, as they're no-ops
// rhs.m00 = m00; rhs.m01 = m01; rhs.m02 = m02; rhs.m03 = m03;
rhs.m10 = m10; rhs.m11 = m11; rhs.m12 = m12; rhs.m13 = m13;
rhs.m20 = m20; rhs.m21 = m21; rhs.m22 = m22; rhs.m23 = m23;

```

This appears to resemble your original code rather closely. It's kind of obvious if you think about it that modifications pertaining to the X axis disappears as rotating around X by definition cannot affect the X component.

By following this chain of transformations, you can track how the last column comes into play. As we are chaining transformations we need to take in account all the effects of the previous transformation, including the translation parts. Matrix multiplication is always full rows vs. full columns. As pure rotation always acts around the origin, omitting the encoded translation would result in a rotation around the wrong location.

---
Tags: 3d, matrix
---


title: Unreal Engine for 2d in c++

text:
# Question
Title: Unreal Engine for 2d in c++
I was about to start my journey on unreal engine but currently all of the tutorials we're all about blueprints in 2D games. I really want to make 2d games since I am not good at 3d (not yet). My concern is ,all their tutorials where blueprints (not really) but most of its 2d tutorials we're made in blueprint. **Is blueprint that good and powerful than C++ in 2d game developement for UE4 or this is just an advertisement for this features?** I really want more power that is why I really want to use c++ in UE4,

Main purpose is for desktop and console games only. (I don't care about the mobile industry, I prefer cocos if focusing on mobile).

# Answer
> 0 votes
Blueprints are designer-friendly, so that you can introduce code-like behaviour from a friendly interface without actually writing code. Mind you, you can use C++ to achieve the same goal. When you write your C++ code, you can add some macros (UE tutorials show how) in your code to make it "visible" as blueprints. It's not an advertisement; it's a really good and flexible system, I'm currently learning about it myself.

# Answer
> 0 votes
I read your question as can you use C++ to make 2D games in Unreal, to which the short answer is **yes**. Some key points to bear in mind:

**Everything you can do in blueprint, you can do in C++**. So if you feel more comfortable in making your game in C++, it is fairly straight forward to follow blueprint tutorials and implement them in C++. A few bits and pieces like latent actions (e.g. delay nodes) are slightly more fiddly to implement in C++ but certainly not hard.

**Some things can only be done in C++** . Not loads, and not many that you are likely to need, so if you'd prefer to use blueprint you'll mostly be fine. If you've seen BP tutorials that cover everything you want to do, then obviously this is not an issue.

Personally, if you feel comfortable with C++, I would use that. You certainly won't be limited by this choice and, as @Babis's answer points out, you can mark up your C++ which allows you to extend it in blueprint using the editor.

Crucially, whatever you choose, you are not stuck with it. Start with BP and find something you can't do without code: no problem, add some code to your project. Start with code but find recompile times tedious: mark up your code so you can access it from BP and continue. For best results you'll probably want to mix and match.

---
Tags: 2d, performance, unreal-4, development-speed
---


title: Unity 3D engine for Ubuntu?

text:
# Question
Title: Unity 3D engine for Ubuntu?
Is there any way to get Unity 3D to run on Ubuntu. I am currently running Ubuntu 12.04 64bit edition. I also have Wine installed.

# Answer
> 7 votes
According to Unity's bizarro-world SO the answer is no. The Unity3D authoring program is only available for Windows or Mac OS.

# Answer
> 4 votes
According to WineHQ AppDB Unity3D versions 3.3.0 and prior might work via wine.

Here's a link for 3.3.0: http://download.unity3d.com/download\_unity/UnitySetup-3.3.0.exe

# Answer
> 3 votes
It's been years since this question was done, but Unity has started to develop the editor for Linux.

More info on the link http://blogs.unity3d.com/2015/07/01/the-state-of-unity-on-linux/

# Answer
> 2 votes
My answer is **perhaps**.

I tried to run Unity3d 4 with the same configuration. Installs flawlessly, but when you try to run it, it fails at start when trying to checking license for activation.

I wonder if there is some manner to bypass that step. For example, I was able to run the activation part on a Windows XP running within an VirtualBox, so perhaps moving some archive from that VirtualBox install to the wine one may do the trick. Just wonder...

On the other hand it didn't work fine neither on my VirtualBox. Windows are not drawn correctly and crashes after a few seconds.

# Answer
> 1 votes
You have to use winetricks to improve several parts of WINE for compatibility sake before it will work. Fonts, DirectX, force Mono, and you have to edit the registry. More details are out there.

Video of someone doing it on 12.10

---
Tags: unity
---


# Question
Title: Unity 2D - Instantiate a GameObject and scale it every second
I want to make a bomb-like game object, that when instantiated, takes 2 seconds to charge, and then some other event triggers. The problem is I can't make it scale smoothly for 2 seconds, and then trigger some other event.

Here's what I have:

```
public GameObject bombGO;

// This method is inside a Input.GetButtonDown("Fire2") event in Update()
void ChargeBomb() {
    Vector3 offset = transform.rotation * playerOffset;
    GameObject bomb = (GameObject) Instantiate(bombGO, transform.position + offset, transform.rotation);
    bomb.transform.localScale += new Vector3(0.2f, 0.2f, 0.2f);
    // Now I want this transform to be fired continuosly for 2 seconds, while the object progressivelly and smoothly gets larger, up to 1.0f scale
    // after 2 seconds, destroy the said object
}

```

How can I do it?

# Answer
> 0 votes
manage all in the Update (I use c# and pseudo code)

```
    bool Charging=false;
    float timer = 2f;
GameObject bomb;

    void Update() {
    ...
    if (Input.GetButtonDown("Fire2") && Charging==false ){
       bomb = (GameObject) Instantiate(bombGO, transform.position + offset,transform.rotation);
        Charging=true;
    }
    ...
    if Charging {
     if (timer > 0 )
     {
     Vector3 offset = transform.rotation * playerOffset;
        bomb.transform.localScale += new Vector3(0.2f, 0.2f, 0.2f);
        // Now I want this transform to be fired continuosly for 2 seconds, while the object progressivelly and smoothly gets larger, up to 1.0f scale
       //Update timer
       timer = timer - Time.deltaTime;
     } else {
        // after 2 seconds, destroy the said object
        // ...add destroy object logic

        //reset timer and flag
        Charging=false;  //maybe it's useless if you destroy the object
        timer = 2f;     //maybe it's useless if you destroy the object
     }
    }
    ...
    }

```

# Answer
> 1 votes
I have to agree with Ben. You can do things in Update but once you start having to manage many different objects changing simultaneously it is much nicer to do it with CoRoutines.

Having said that, it took me several iterations and seeing good examples in the Unity demos to feel like I understood them properly. For now, go with what makes the most sense. But set aside some time to experiment with coroutines.

# Answer
> 0 votes
Coroutines are very useful for actions like these. When programming a game you've probably found yourself wishing each object was independent with the ability to do things over time without blocking other objects from executing. To achieve this normally, we'd need a new thread for each object that exists in the game world ( which is is impractical for several reasons. )

Coroutines allow us to program objects as if they run on a separate thread ( but they don't. ) Using "yeild return" we can tell Unity to continue the execution of this method later.

My implementation:

```
private IEnumerator ChargeBomb( GameObject bomb )
{
    // Percentage of the scale we have completed.
    var t      = 0.0f;

    // The scale we're going from and the scale we're going to.
    var start   = new Vector3( 0.2f, 0.2f, 0.2f );
    var end     = Vector3.one;

    // In other words while our scale is not equal to our "end" vector.
    while( t < 1.0f )
    {
        // Scale the bomb. 2.0 here because you specified the scale to be over 2 seconds.
        t += ( Time.deltaTime / 2.0f );
        bomb.transform.localScale = Vector3.Lerp( start, end, t );

        // Wait till the next frame.
        yield return null;
    }

    // Bomb is scaled, invoke an event here.
}

```

We start out defining what scales we'd like to lerp between, then enter a loop. Here we scale using Vector3.Lerp and we increase the lerp fraction by the delta time / 2 ( so this takes place over two seconds. ) We use yield return null to tell Unity to come back next frame so the rest of the game isn't blocked. Do this until the object is fully scaled.

I find this much nicer and easier to understand than managing a bunch of state in the update method.

http://docs.unity3d.com/Manual/Coroutines.html http://docs.unity3d.com/ScriptReference/Vector3.Lerp.html

---
Tags: unity, sprites, gameobject, scale
---


# Question
Title: Libgdx - How to rotate a single ShapeRenderer object
So, looked at a couple of questions similar to this, led me straight into dead ends. I have an object drawn out in `ShapeRenderer`, and I wish to rotate **only** that one object. I have tried `shapeRenderer.rotate(x, y, 1, 1)`, however all of my `ShapeRenderer` objects rotate. Anyone know how one would go about rotating a single `ShapeRenderer` object that is defined by an array of vertices? I've posted how I have drawn my object below.

```
    //LEFT
    shapex[0] = x - 59/2;
    shapey[0] = y + 53/2;

    shapex[1] = x - 18/2;
    shapey[1] = y + 30/2 ;

    shapex[2] = x - 6/2;
    shapey[2] = y + 53/2;

    shapex[3] = x - 16/2;
    shapey[3] = y -51/2;

    shapex[4] = x - 21/2;
    shapey[4] = y + 1/2;

```

EDIT: I have tried to use polygon, however I see no good tutorials showing how to use it.

# Answer
> 1 votes
As @drumbumLOLcatz says, there are a bunch of overloaded methods when you create your shapes, what you are looking are for those methods that involve a `degree`parameter. Something like this:

```
public void rect(float x, float y, float originX, float originY, float width,
                 float height, float scaleX, float scaleY, float degrees)

```

So everytime you call the `shapeRenderer` object, you must specify this parameters for each shape that you want to transform (in this case, rotate):

```
shapeRenderer.begin();
// more code
shapeRenderer.rect(x, y, oX, oY, w, h, sX, sY, degrees);
// more code
shapeRenderer.end();

```

As you don't say if you are using complex shapes, I don't know if this will satisfy your question (since I don't know if you are drawing simple lines, quadrilaterals, circles, arcs, etc.). If you are using the `Polygon` class, this should be easier, since this class can manage the rotation individually.

To draw a polygon, first, you construct your shape with your vertices, something like this:

```
// this are the vertices for a simple quadrilateral
float[] vertices = new float[] {
    0,   0,
    100, 0,
    100, 100,
    0,   100
};
// Create the polygon
Polygon polygon = new Polygon();
polygon.setVertices(vertices);

```

Then, if you want, you could rotate this polygon:

```
polygon.rotate(degrees);

```

And draw it:

```
shapeRenderer.begin();
// more code
shapeRenderer.polygon(polygon.getTransformedVertices());
// more code
shapeRenderer.end();

```

But, take in count that this will only draw the outline, in order to fill your shape you must consider another option like the `Mesh` class, triangulating your complex shape.

# Answer
> -1 votes
When you draw a shape, there is sometimes a degree parameter (at least when you draw a rect) http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/graphics/glutils/ShapeRenderer.html#rect-float-float-float-float-float-float-float-float-float-

EDIT: also, any libgdx Shape Class will have a rotate function. Maybe instead of keeping your shapes in arrays of x and y, make an array of Polygons.

Docs: http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/math/Polygon.html#rotate-float-

---
Tags: java, libgdx
---


# Question
Title: Libgdx - How to change GestureListener pan finger sensibility?
I implemented GestureListener in my Overlap2dStage to pan the camera when the player drags its finger over the screen. But I also have some actors that extend InputAdapter to detect when the user touches on them. Then I mix them with a InputMultiplexer.

So far it's working fine on my computer, but when I get into Android and tap an object it trigers both: `pan()` from stage and `touchDown()` from the actor.

I remember I read something about a pan box to decrease the sensibility, since in a touch screen you are touching several pixels, it detectes a pan. It's worst in smaller screens.

# Answer
> 0 votes
I guess you are looking for the constructor:

```
GestureDetector(float halfTapSquareSize, float tapCountInterval,
        float longPressDuration, float maxFlingDelay,
        GestureDetector.GestureListener listener)

```

The default constructor has this values: halfTapSquareSize=20, tapCountInterval=0.4f, longPressDuration=1.1f, maxFlingDelay=0.15f.

I don't know with which value you need to change to get what you are looking for. But you could play with them.

Another thing, you could return `false` for the `touchDown()` event, as this site says:

> If you are supporting multi touch, be sure to return false from the more atomic events such as touchDown and TouchUp, so they still get a crack at handling those events.

---
Tags: java, android, libgdx, touch
---


title: GLSL 2D Silhouette

text:
# Question
Title: GLSL 2D Silhouette
I'm trying to render a silhouette of any entity behind foreground objects to indicate their position to the player. Here's an example of what I want to achieve, from Hyper Light Drifter:

From what I've read online about GLSL and the ways I might be able to achieve this, the closest thing I can think of to achieve this would be to use the stencil buffer, which was also indicated in this question:

2D Hidden Object Silhouette Shader

I don't quite understand how I can achieve this within LibGDX. Should I be using a vertex / fragment shader, or the native Gdx methods? This is my current rendering workflow:

```
Render Lower Tiled Map Layers
Render Entities
Render Upper Tiled Map Layers

```

From what I understand, I would have to:

1. Write the top layer to the stencil buffer
2. Render the entities (silhouettes) within the stencil

Is this right? If anyone can enlighten me, it would be greatly appreciated!

# Answer
All of the drawing code is separated into their own systems responsible for rendering what is on the screen. Differentiate between Lower and Upper layers by naming the layer you want the Entities to be on. I use a custom interface designed to separate the `render` method of LibGDX into `update(delta)` and `draw(SpriteBatch, delta)`, similar to C#'s XNA as this was more familiar for me.

You need two fragment shaders and one vertex shader to get the desired result. The vertex shader is a simple passthrough shader:

```
    attribute vec4 a_color;
    attribute vec4 a_position;
    attribute vec2 a_texCoord0;

    uniform mat4 u_projTrans;

    varying vec4 v_color;
    varying vec2 v_texCoord0;

    void main() {
        v_color = a_color;
        v_color.a = v_color.a * (255.0/254.0);
        v_texCoord0 = a_texCoord0;

        gl_Position = u_projTrans * a_position;
    }

```

Then you need a fragment shader to discard any pixels from the upper layers with an alpha value of 0 from the Stencil Buffer:

```
    varying vec4 v_color;
    varying vec2 v_texCoord0;

    uniform sampler2D u_texture;

    void main() {
        gl_FragColor = v_color * texture2D(u_texture, v_texCoord0);

        if (gl_FragColor.a == 0.0) {
            discard;
        }
    }

```

And finally, another fragment shader to render entity silhouettes:

```
    varying vec4 v_color;
    varying vec2 v_texCoord0;

    uniform sampler2D u_texture;

    void main() {
        gl_FragColor = vec4(0.0, 0.75, 1.0, 0.25) * texture2D(u_texture, v_texCoord0).a;
    }

```
1. Render Lower Tiled Map Layers.

```
 public class LowerTiledMapRenderSystem extends EntitySystem implements Drawable {

     private int[] layerIndeces;

     private static final OrthogonalTiledMapRenderer renderer = LevelManager.RENDERER;

     public LowerTiledMapRenderSystem() {
         List<Integer> layers = new LinkedList<>();

         for (int i = 0; i < renderer.getMap().getLayers().getCount(); i++) {
             if (renderer.getMap().getLayers().get(i).getName().equalsIgnoreCase("entities")) {
                 layerIndeces = layers.stream().mapToInt(Integer::intValue).toArray();

                 return;
             }

             if (renderer.getMap().getLayers().get(i) instanceof TiledMapTileLayer) {
                 layers.add(i);
             }
         }
     }

     @Override
     public void draw(SpriteBatch batch, float delta) {
         batch.end();

         renderer.render(layerIndeces);

         batch.begin();
     }
 }

```
2. Render the Entities. This should be simple enough to do depending on how you have your ECS set up.
3. Render the Upper Map Layers normally, and then to the Stencil Buffer. This is almost identical to the `LowerTiledMapRenderSystem`, but specifying all layers above the Entities layer instead of below, and also constructing a new `ShaderProgram` which uses the `alphatest` shader.

```
 public class UpperTiledMapRenderSystem extends EntitySystem implements Drawable {

     ShaderProgram alpha;

     private static final OrthogonalTiledMapRenderer renderer = LevelManager.RENDERER;

     private int[] layerIndeces;

     public UpperTiledMapRenderSystem() {
         alpha = Assets.getShader("passthrough", "alphatest");

         List<Integer> layers = new LinkedList<>();

         for (int i = renderer.getMap().getLayers().getCount() - 1; i > 0; i--) {
             if (renderer.getMap().getLayers().get(i).getName().equalsIgnoreCase(Layer.ENTITIES.getName())) {
                 Collections.reverse(layers);
                 layerIndeces = layers.stream().mapToInt(Integer::intValue).toArray();

                 return;
             }

             if (renderer.getMap().getLayers().get(i) instanceof TiledMapTileLayer) {
                 layers.add(i);
             }
         }
     }

     @Override
     public void draw(SpriteBatch batch, float delta) {
         batch.end();

         // Render normally
         renderer.render(layerIndeces);

         // Enable the Stencil Buffer
         Gdx.gl20.glClear(GL20.GL_STENCIL_BUFFER_BIT);

         Gdx.gl20.glEnable(GL20.GL_STENCIL_TEST);
         Gdx.gl20.glStencilFunc(GL20.GL_ALWAYS, 0x1, 0xFF);
         Gdx.gl20.glStencilOp(GL20.GL_REPLACE, GL20.GL_REPLACE, GL20.GL_REPLACE);

         // Set the Shader of the renderer to the alpha shader
         renderer.getBatch().setShader(alpha);
         // Render the same layers again
         renderer.render(layerIndeces);
         // Disable the shader
         renderer.getBatch().setShader(null);

         batch.begin();
     }
 }

```
4. Render the Silhouettes. This is virtually identical to the `SpriteRenderSystem`, but we're enabling the `silhouette` shader.

```
 public class SilhouetteRenderSystem extends SortedIteratingSystem implements Drawable {

     private final ShaderProgram silhouetteShader;

     public SilhouetteRenderSystem() {
         super(Family.all(
                 // Specify components needed here
         ).get(), new EntityOrderComparator());

         silhouetteShader = Assets.getShader("passthrough", "silhouette");
     }

     @Override
     protected void processEntity(Entity entity, float deltaTime) {}

     @Override
     public void draw(SpriteBatch spriteBatch, float delta) {
         Gdx.gl20.glStencilFunc(GL20.GL_LEQUAL, 0x1, 0xFF);
         Gdx.gl20.glStencilOp(GL20.GL_KEEP, GL20.GL_KEEP, GL20.GL_KEEP);

         spriteBatch.setShader(silhouetteShader);

         // Render your entities here

         spriteBatch.setShader(null);

         Gdx.gl20.glDisable(GL20.GL_STENCIL_TEST);
     }
 }

```

I strongly advise looking into OpenGL Documentation to gain a better understanding of how shaders work, specifically glStencilFunc and glStencilOp.
> 2 votes

---
Tags: libgdx, shaders, glsl, graphic-effects
---


title: 2D platform collision

text:
# Question
Title: 2D platform collision
I have went over and over in my head for the past month trying to get a simple platformer together. My problem is collision. So far from every tutorial I've found this tilemap based collision needs to be done this way: Check for for tile in x+xVel / tilesize if so xVel=0 same for x axis just subtracting for when the player goes left. Check for tile in y+yVel/tilesize. if so yVel=0. No matter how many different ways I end up programming this concept. The player always ends up clipping walls, falling through, or just hanging out 2 pixels before the collision. Can anyone tell me what's up?

By the way my collision check is a two point method. eg. Check top two points of the rectangle box if going up, bottom two for down ect.

Thanks!

# Answer
https://www.youtube.com/watch?v=DOpqkaX9844

This is a great tutorial on tilemap collision, but you can also use Box2d. That is what I ended up doing because tilemap based collision only works if your character moves in increments of 1 tile at a time. If he can move fractions of a tile it doesn't really work.
> 1 votes

# Answer
Your player has two points for each direction, so 8 points in total. For each point do the following:

1. Check where the point is, where it wants to go. I use a line draw algorithm to determine the tiles the point crosses.
    2. Pick the nearest collidable tile from the tiles you found.
    3. If a collidable tile is found: stop movement to that direction.
    4. The important one: calculate the position the player would end up. This is relative easy as you know the tile that caused the collision. Example if the collision was moving left, the position would be something like: `collidedtile.x-collidedtile.width`

Note that things can be optimised to verify if the point has to be checked (example only check horizontal collisions if the character moves that direction). I also use a switch statement for each 4 directions so I can add additional checks (for example jump-through-platforms in the up direction check) or events (character has landed a jump in the down direction).
> 0 votes

---
Tags: c++
---


# Question
Title: How to create a state based traffic signal?
I want to create a traffic light for a Unity3D game. I will model it in blender.

What is the best way to control this light in a unity scene?

One way I could think of is to change texture of say red light from dull red to bright red, when it is time for red signal. But I am not sure if this is possible or a good strategy.

# Answer
You can access the material of the lamp object in the Unity-API.

```
public GameObject lampObject;
public bool isGreen;
public Color greenColor, redColor;

private void Update()
{
    lampObject.material.color = isGreen ? greenColor : redColor;
}

```

This will set the material color of the lamp to a specified value you can edit in the inspector. It is also possible to lerp to the target color with `Color.Lerp`.

```
var targetColor = isGreen ? greenColor : redColor;
lampObject.material.color = Color.Lerp(lampObject.material.color, targetColor, 0.1f);

```

The 0.1f will control how fast the color will blend to the target color.

Other possible ways would be -as you said- changing the texture of the lamp object texture by accessing `lampObject.material.mainTexture` but I dont see any reasons to change the whole texture just for a traffic lamp color.
> 1 votes

---
Tags: unity, c#, blender, state
---


# Question
Title: Naming a weapon during game development: is using the actual model name in real life against copyright?
I was planning to name each weapon at the weapon shop and I was wondering if it is safe to use the real name of each weapon and model as well before publishing it via Google Play Store for my created game app? I'm using a freemodel method with ad banner on menu on it, user friendly. I'm making a concept third-person shooter zombie survival game.

I'm checking some other sample of the games, (other than from mobile app) one from the gamer console's classic in *PlayStation 1* game *Syphon Filter*; and the other one from the PC, a popular online FPS game created by Korea called *CrossFire*. Let's take a comparison's similar of the gun (both gun model name and the model itself) used between these two:

* In *Syphon Filter*, the name of this assault rifle is PK-102. (See gameplay video **here**) It was based either a model from AK-47, AK-74, or AK-102 assault rifle in metalic like body.
* In *CrossFire*, the name of this assault rifle retained the original name AK-47 along with the model itself. (See video gameplay **here**.) It assumed they take for a permission to use the original name before using it.

I want to know more further if it is safe to use the model name only but not mentioning the corporation name who created the AK-47. Naming a gun could be striking, same thing naming the actor of the game. If not, probably if it is also okay to name close to the original but at least it's not against the copyright standards.

# Answer
> 4 votes
(I am not a lawyer, and this is definitely not legal advice.)

The kind of laws and regulations you should look into are probably trademark law, as most of the time, the design, names, shapes, and other identifiable attributes are covered by registered marks. Contact a lawyer in that field and you could probably get some up-front evaluations of your situation for a reasonable dime.

You may find some prior art in car games, where licensing costs big money and has severe restrictions on the use of the vehicles. If you've ever wondered why some games do not have any form of visible car damage, the answer is "license terms".

Note that in many areas, developers unknowingly or knowingly use the marks of others in their products. That does not give you the right to do it as well, and if you're in a market where it's easy to sue you, you should probably look forward to legal action.

A particularly fun aspect of trademark infringement is that as the holder of a mark, you're expected to actively defend it from commoditization and misuse, even if it may appear silly lest you'd lose the right to the mark.

In recent history, you've got encounters like:

* Metro AG vs. Microsoft (using the term "Metro" for their UI design),
* Zenimax vs. Mojang ("Scrolls" resembling "The Elder Scrolls"),
* Langdell suing everyone ever using the term "Edge".

In the end, if you publish anything whether it is making you money or not, you should probably have legal representation in some form. Paying for the occasional chat with your lawyer up-front beats having to find a decent one when you're subject to legal action.

---
Tags: copyright, trademark
---


# Question
Title: How to generate interresting procedural terrain
I work on a voxel-like game, and I have finally managed to create some basic terrain generation using simplex noise. Heres what it looks like:

Sure I can generate different kind of terrains (more or less hilly/aggressive), but there wont really be any variation.

At the moment I only know one way to make it more interesting, and that would be to add stone blocks under the grass (I would simply check the above block).

So my questions are: What techniques would I need to use, to generate different kind of terrains, which still kind of blended together at the edges. And how would I go about caves and rivers? And lastly how would I make a better variation of blocks?

If any could lead me in the right directions, I would appreciate it a lot.

**Ps. It's not a valid answer to say that I just need to mix a lot of noises, to generate it. How?**

# Answer
> 1 votes
It's all about adding more features and doing some processing on your output. You are currently generating a heightmap but what seems to be missing? First off there are no rivers or trees. To generate this I would sugest creating a second noise map that contains rainfall. Then maybe add a third one for fertility. The areas with high rainfall and fertilty become forests, high rainfall low fertility might become something like a swamp (it elevation is low) or might be a place to start a river and places with low fertility and low rainfall can become desert. This will automatically generate good looking biomes that make it all look more interesting.

After that you can do some proccessing cycles. A good second step is to take the rivers and forrest from step 1 and let them influence the terrain a bit. A forrest naturally puts down dirt on the ground (slighly more fertility) and a river carves a path trough the ground. By respawning the rivers several times on different randomly chosen points you can simulate the natural proces by which rivers normally form from many sources and often have a history of changing the point of origin to reflect changes in rainfall. With this as a basis you can then continue to expand the proccessing step to create natural valleys, canyons and river paths.

You should also use a different texture depening on the type of ground currently it's a solid green but it would look more interesting if slighly steeper hills (esp when facing the north) were more dirt colored and really steep cliff faces were painted grey ish for the stone walls that they probably are.

---
Tags: mathematics, procedural-generation, perlin-noise
---


# Question
Title: Can you have an embedded browser in Gamemaker:Studio
I am trying to make a sort of browser in gamemaker and I wanted to know how to embed a browser within a game. **Are there any extensions I need to download?**

# Answer
> 2 votes
For Windows projects you can use https://marketplace.yoyogames.com/assets/683/web-browser

---
Tags: browser-based-games, game-maker, browser
---


# Question
Title: Is computing depth in a pixel shader bad? Can I reduce fillrate by moving depth calc to vertex shader?
I have a DX10 game that is fillrate bound. One of the things I've been realizing may be contributing to this is that I compute depth in the pixel shader (the game uses a logarithmic depth buffer to get extreme precision from 1cm to millions of meters away).

It occurred to me that writing the depth in the pixel shader is ruining the ability to to Early Z testing.

Can this be fixed by outputting this computed depth value in the vertex shader instead?

# Answer
> 1 votes
It appears that this may not be possible, as noted in this blog post about the Outerra engine.

I successfully moved the log depth buffer calculations into the vertex shader. This solved my problem with the Early-Z testing, but it also led to deal-breaking artifacts with triangles that were too close to / crossed the camera. Apparently the only way to fix this is with a tweak in the pixel shader which will break the Early-Z again!

# Answer
> 0 votes
Not sure if you've heard about this, but many games will do a "depth only" first render to fill in the z buffer, then they do the usual, more expensive pass, only where the pixel z matches the depth buffer z. This can really help with overdraw problems and reduce wasted fill rate.

# Answer
> 0 votes
By swapping the near and far planes and inverting the depth test you may well be able to get sufficient precision out of a hardware depth buffer.

http://outerra.blogspot.co.uk/2009/12/floating-point-depth-buffer.html

You could also try rendering in multiple passes, with the far clip plane from one pass matching the near clip plane from the previous pass. You'd also want to clear the depth buffer between each pass.

---
Tags: depth-buffer, directx10
---


title: What is a game mechanic?

text:
# Question
Title: What is a game mechanic?
I am trying to understand exactly what defines a game mechanic, and whether it is the same as a gameplay mechanic. There are many different sources online that try to define this but they appear to be quite inconsistent. Two that go into quite a bit of depth are below: https://en.wikipedia.org/wiki/Game\_mechanics (game context)

https://badgeville.com/wiki/Game\_Mechanics (gamification context)

I understand the concepts of objectives, challenges and rules in a game, but exactly how do game mechanics tie into these? For example, are game mechanics simply abstract ways of motivating users (eg. points, achievements, discovery etc)? Or are they more practical aspects of a game such as a cover system, or how a character moves, jumps etc?

# Answer
In my book I summarized them this way:

One of the most central parts of game design is crafting game mechanics; these are individual actions (or systems of actions) within a game. The mechanics in a game are often set up by its rules, whereas the challenges in a game generally come from applying the mechanics to specific situations. For example, walking around the game is a mechanic, whereas a maze is a kind of challenge based on that mechanic.
> 5 votes

# Answer
In the context of video game development, game mechanics or gameplay mechanics (the words are quite synonymous in this context) are the set of rules which govern how a game works. They explain things such as:

* What entities are there in a game (the player-character, the enemies, projectiles they spawn, the environment, etc.)
* What game-relevant state do they have (position, direction, hit-points...)
* What actions can they perform and when do they perform said actions (ex. *"Enemies can spawn a projectile every 10 frames which have a position 5px in front of them and the same direction as the spawning entity"*, *"enemies only spawn a projectile when the player collides with a straight line going from the enemies current position into the direction they face"*, *"Projectiles move forward with a speed of 5px per frame in their current direction"*).
* How do these entities interact with each other (ex. *"when a projectile collides with the player-character, the projectile is removed and the player-character loses 1 hit point"*)
* What actions can the player perform to affect the behavior of entities (ex. *"the player can command the player-character to move left or right with a speed of 3px per frame."*). Often this is only one entity: the character they control. But sometimes the player can command more than one entity, like in a real-time strategy game.
* What are the win-conditions and lose-conditions (ex. *"when the player-character loses all hit points, the player loses"*. *"when all enemies are removed from the game, the player wins"*)

Points, achievements and discovery *can* be part of the game mechanics when they actually do something (ex. *when the score reaches 1,000,000 points, the player-character gains an extra life"*, *"when the player reaches level 12, the player-character gains the double-jump ability"*). But when they don't actually affect the game at all, e.g. when they would be removed the game could still be played in the same way (even though the average player might want to play it differently in that case), they are not a game mechanic. They are part of the presentation.

you might now wonder "OK, so what part of the game are not part of the game mechanics"?

1. The controls. The game mechanics explain *what* commands the player can give, but not *how* the player gives said commands. The controls heavily affect the way the player plays a game, because the player will usually prefer to give those commands which are easy to give. When the player can command their character to perform a kick by pressing `B` and a super-kick by pressing `up down left left right B`, they will usually prefer using the normal kick when sufficient because it is simpler to do.

Note that in highly competitive gaming, the controls can actually bleed into the game mechanics because they put an additional limitation on how fast certain actions can be performed. At a very high competitional level, some real-time strategy players feel like the entity they control directly are not actually their units but rather their mouse cursor.
2. The presentation. To be able to interact with the game, the player needs to be made aware of what is happening. The presentation is what the player sees on the screen and what they hear over their speakers.

The presentation can also affect how the player plays the game without actually changing the game mechanics. The player will usually pay most attention to those game events the presentation makes them most aware of and behave accordingly. For example, when you would still want the player to use the super-kick more often, have the presentation acknowledge their success at performing it correctly by accompanying it with a flashy graphic effect, a satisfying sound effect and when they do it the first time, give them an achievement "Congratulation! You did a Super Kick!" presented in big letters in the center of the screen with fireworks around them.
> 6 votes

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


# Question
Title: How to design game server to mitigate DDOS attacks
I'm in the design phase of a turn based game with low load on the server (\<1 message every 10 seconds per user, \<50'000 users at a time). The game is multi-platform.

The protocol has not been decided yet.

How can I mitigate DDoS attacks against such a server by design?

# Answer
> 2 votes
When a large scale attack reaches your machines, there's a limited amount of things that the code can do to mitigate the problem.

For low volume attacks, you could attempt to recognize bogus requests early and rate-limit/ignore sources that do not appear to do anything useful to lessen the amount of computational resources your application wastes on them. You can limit unauthorized connection attempts rather heavily, and move all your static unauthorized assets like images and CSS onto a content delivery network.

For high volume attacks, most of the traffic will not reach your application and is probably not even intended for your application. The purpose there is to completely saturate the network connection to your machine, or to spend all CPU time and memory in the kernel on buffering.

The way to combat the latter kind is to work with your hosting provider and their upstream providers to prevent traffic recognized to be part of an attack from reaching the site in the first place. This is an ongoing process and nothing you can solve up-front, except by establishing communication paths and terms of service.

You can also gain some resilience by making your service distributed and placing all core services on backend machines separate from the frontends. This ensures that if your some of your fluffy cloud frontends get hammered, a few of them will remain reasonably functional and be able to talk with the backends as normal.

---
Tags: server, security, hacks
---


# Question
Title: How can I generate a simple river surface seen from above, in a browser game?
I'm developing my first browser-based game, a very simple signup gamification where users become captains of boats, and their referred friends join the boats. The boats race to a finish line.

There is only one view, bird's eye, that shows the boats on a river. To simplify things further, I thought I would keep the boats fixed, and have the river flow from right to left. Here's the Codepen I have so far:

How can I make the river animation look more immersive? I remember after playing Chronos (video) or River Raid back in the day for a while, when I'd move my eyes off the monitor, my vision would "flow" in the other direction for a while - that's how good the effects were.

One idea I had was to use a perfectly looping background GIF, so that the eye anchors on the continuously moving background, and the boats *appear* to move the opposite way.

# Answer
I suggest Perlin noise

A 2d Perlin noise , with an appropriate color gradient, to simulate river surface:

Two 1d Perlin noise for the two river margins:
> 1 votes

# Answer
It seems that for the brain to perceive the illusion that the ships are moving in the opposite direction to the one in which the background flows, the eyes need to anchor on the background. In my first experiment, the waves were thin lines, and didn't provide much of a *unified* background; the anchor was the boats.

Below is an experiment that simply pans a water texture using CSS keyframes (very CPU-intensive on Chrome unless you force GPU rasterization). You should click "Full page" and "Redraw" after running the code snippet, or you can view it on Codepen.

Suggestions are welcome.

```
window.requestAnimationFrame = window.requestAnimationFrame || window.msRequestAnimationFrame;

var
  boatHeight = 40;
  boatBow = 80;

var canvas, context,
  sizeX, sizeY,

  boats = [],
  numBoats;
  minBoatLength = 140,  /* minimum boat length to accommodate the text */
  maxBoatLength = minBoatLength + 60 + boatBow;

var runAnimationCheckbox, numBoatsControl;

function Boat(x, y, length, text) {
  this.x = x;
  this.y = y;
  this.length = length;
  this.text = text;
  this.color = '#4F5E5B';
  return this;
}

Boat.prototype.draw = function () {
  // add a shadow to boats so they look more realistic, though in reality there wouldn't be much of a shadow
  context.shadowOffsetX = 2;
  context.shadowOffsetY = 2;
  context.shadowBlur = 5;
  context.shadowColor = 'black';

  context.beginPath();
  context.moveTo(this.x, this.y);
  context.lineTo(this.x + this.length, this.y);
  context.quadraticCurveTo(this.x + this.length + 15, this.y/* control point */, this.x + this.length + boatBow, this.y + boatHeight / 2/* bow */);
  context.quadraticCurveTo(this.x + this.length + 15, this.y + boatHeight/* control point */, this.x + this.length, this.y + boatHeight/* back from bow */);
  context.lineTo(this.x, this.y + boatHeight);
  context.fillStyle = this.color;
  context.fill();

  // add the text, without shadows
  context.font = '16pt Calibri';
  context.fillStyle = '#000';
  context.shadowOffsetX = context.shadowOffsetY = context.shadowBlur = 0;
  context.fillText(this.text, this.x + 10, this.y + 26);

};

Boat.random = function createRandomBoat(b) {
  return new Boat(
    Math.random() * (sizeX - maxBoatLength - 20),
    // 0, 0, 1, -1, 2, -2, 3, -3, 4, -4
    -boatHeight / 4 + sizeY / 2 /* center boat generation at half river width */ + (sizeY - boatHeight) / numBoats /* size of a boat channel */ * (Math.floor(b/2)*(b%2?1:-1)),
    minBoatLength + Math.random() * (maxBoatLength - minBoatLength),
    'Student from ...'
  );
}

function createBoats() {
  for (var b = 1; b <= numBoats; b++) {
    boats.push(Boat.random(b));
  }
  // Make the first boat "you"
  boats[0].text = 'You are here';
  boats[0].color = '#A7C8B2';
}

function clearCanvas() {
  context.clearRect(0, 0, sizeX, sizeY);
}

function drawBoats() {
  for (i = 0; i < boats.length; i++) {
    boats[i].draw();
  }
}

function animate(timestamp) {
  clearCanvas();
  drawBoats();
  // keep animating
  if (runAnimationCheckbox.checked)
    window.requestAnimationFrame(animate);
};

// automatically resize the canvas to fill its container
function resizeCanvas() {
  sizeX = canvas.width = canvas.scrollWidth;
  sizeY = canvas.height = canvas.scrollHeight;
  console.log('Resized to', sizeX, sizeY);
}

window.addEventListener('resize', resizeCanvas, false);

document.addEventListener('DOMContentLoaded', function () {

  runAnimationCheckbox = document.querySelector('input[type="checkbox"]');
  canvas = document.querySelector('canvas');
  context = canvas.getContext('2d');
  numBoatsControl = document.querySelector('input[type="number"]');
  numBoats = numBoatsControl.value;

  runAnimationCheckbox.onchange = function (event) {
    if (this.checked) animate();
  };

  numBoatsControl.onchange = document.querySelector('button').onclick = function (event) {
    boats = [];
    numBoats = numBoatsControl.value;
    createBoats();
    clearCanvas();
    drawBoats();
  };

  document.querySelector('#background').onchange = function (event) {
    var urlString = 'url(' + this.value + ')';
    document.querySelector('canvas').style.backgroundImage = urlString;
  };

  document.querySelector('select').onchange = function (event) {
    var urlString = 'url(' + this.value + ')';
    document.querySelector('canvas').style.backgroundImage = urlString;
  };

  setTimeout(function () {
    resizeCanvas();
    createBoats();
    drawBoats();
    animate();

  }, 100);  // give the canvas a chance to be sized, otherwise we'll get the default 300x150 dimensions

});
```

```
body {
  margin: 0;
/*  background: url('https://i.imgur.com/1iQw8zz.jpg') no-repeat center center;*/
  line-height: 1.5em;
  display: flex;
  display: -webkit-flex;
  flex-direction: column;
  -webkit-flex-direction: column;
  height: 100vh;
}

canvas#river {
  flex: 1;
  -webkit-flex: 1;
  background: url('http://4.bp.blogspot.com/-9F5e4P9JxwE/UlAYhVwdWUI/AAAAAAAACYI/1VlbEE5O0aI/s400/Water_WaveAnimation_16frames_SeamlessTest.gif') repeat;
  background-size: 400px auto;

  animation: animatedBackground 5s linear infinite;
  -webkit-animation: animatedBackground 5s linear infinite;

  -webkit-transform: translateZ(0);  /* doesn't actually force GPU rasterization */
}

@keyframes animatedBackground {
    0% { background-position: 0 0; }
    100% { background-position: -400px 0; }
}

/* for Opera, Safari */
@-webkit-keyframes animatedBackground {
    0% { background-position: 0 0; }
    100% { background-position: -400px 0; }
}
```

```
<p>
Enter background URL: <input type="text" id="background" size=100>
<br>Or try one of these:
<select>
  <option>[default]</option>
  <option value="http://subtlepatterns.com/patterns/perforated_white_leather.png">Subtle pattern: perforated white leater</option>
  <option value="http://2.bp.blogspot.com/-OtKPPI6BPm8/Uk_wRVK8rmI/AAAAAAAACUk/ZvzC-lWuB_E/s640/AnimatedWater_004.png">http://auryn-beorn.blogspot.com/2013/10/creator-resource-animated-water-texture.html #2</option>
  <option value="http://2.bp.blogspot.com/-S_9dNop-3V0/Uk_2YlzXBDI/AAAAAAAACU8/oo4F2FJpo-4/s640/AnimatedWater_005.png">http://auryn-beorn.blogspot.com/2013/10/creator-resource-animated-water-texture.html #3</option>
  <option value="http://3.bp.blogspot.com/-wR-RuA5QUwY/Uk_2eXBjxxI/AAAAAAAACVE/0dVYl1g2EuQ/s640/AnimatedWater_006.png">http://auryn-beorn.blogspot.com/2013/10/creator-resource-animated-water-texture.html #4</option>
  <option value="http://4.bp.blogspot.com/-bYhE5gQ-wqo/Uk_2jmBprsI/AAAAAAAACVM/fwFjFdZ5VyI/s640/AnimatedWater_007.png">http://auryn-beorn.blogspot.com/2013/10/creator-resource-animated-water-texture.html #5</option>
  <option value="http://4.bp.blogspot.com/-luyCsWFRkpc/Uk_2raLOg-I/AAAAAAAACVU/Sgz6k58BUco/s640/AnimatedWater_008.png">http://auryn-beorn.blogspot.com/2013/10/creator-resource-animated-water-texture.html #6</option>
  <option value="http://3.bp.blogspot.com/-IFmfJ19lZkw/Uk_6N6wNjNI/AAAAAAAACV8/OFQ1BOp1Ins/s640/AnimatedWater_012.png">http://auryn-beorn.blogspot.com/2013/10/creator-resource-animated-water-texture.html #7 - seamless</option>
  <option value="http://4.bp.blogspot.com/-5k_7_FEdMrQ/UlAXnsxGHCI/AAAAAAAACYA/UuXkei0lRDM/s400/Water_WaveAnimation_16frames_TestRippling_6_Smear.gif">http://auryn-beorn.blogspot.com/2013/10/creator-resource-animated-water-texture.html #8</option>
  <option value="http://1.bp.blogspot.com/-MwXleupp6FM/UHU5pF4jYjI/AAAAAAAADcA/OXjgoPBpy8Y/s1600/Tileable+classic+water+texture.jpg">http://1.bp.blogspot.com/-MwXleupp6FM/UHU5pF4jYjI/AAAAAAAADcA/OXjgoPBpy8Y/s1600/Tileable+classic+water+texture.jpg</option>
  <option value="http://i.imgur.com/yk2LLAg.gif">30000fps</option>
  <option value="http://media.giphy.com/media/McFOLsoTLoudi/giphy.gif">http://giphy.com/gifs/mr-gif-mrgif-patterns-McFOLsoTLoudi</option>
  <option value="http://i.imgur.com/wnbZg44.gif">http://imgur.com/gallery/BjSEE/ (Honeycomb)</option>
  <option value="http://i.imgur.com/H4JyDWw.gif">http://mr-gif.com/post/14532187128</option>
  <option value="http://i.imgur.com/CFO1StD.gif">http://30000fps.com/post/107836389508</option>
  <option value="http://i.imgur.com/V6Z7K2J.gif">http://60000fps.tumblr.com/post/114106084470</option>
  <option value="http://i.imgur.com/I0ES1Lc.gif">http://30000fps.com/post/118219650398</option>
  <option value="http://i.imgur.com/Z56ICih.gif">http://30000fps.com/post/117644318763</option>
  <option value="http://i.imgur.com/EBGBPTe.gif">http://30000fps.com/post/122047609773</option>
  <option value="http://i.imgur.com/CAm1A4X.gif">http://30000fps.com/post/108557720353</option>
  <option value="http://media.giphy.com/media/ToMjGpANd3KoRiE4ZYA/giphy.gif">http://giphy.com/gifs/sebasandclim-ToMjGpANd3KoRiE4ZYA</option>
  <option value="http://media.giphy.com/media/3o85xEIe1YKaGrSvhC/giphy.gif">http://giphy.com/gifs/gfaught-loop-colors-3o85xEIe1YKaGrSvhC</option>
  <option>http://i.imgur.com/A1nDSdr.gif</option>
  <option>http://33.media.tumblr.com/743b05ff21fde73a5a018c5506278cc3/tumblr_nj84h6W95C1s4fz4bo1_500.gif</option>
  <option>http://33.media.tumblr.com/23e95fd77d71f41d72be5ca3eb7719a7/tumblr_nof002o30r1s4fz4bo1_r6_500.gif</option>
  <option>http://38.media.tumblr.com/a66a4fd09436ee4026b0b952a185c2da/tumblr_nnw73kScuN1s4fz4bo1_500.gif</option>
  <option>http://i.imgur.com/HwfZ77H.gif</option>
  <option>http://i.imgur.com/ISheC3U.gif</option>
  <option value="http://i.imgur.com/N6miqht.gif">http://30000fps.com/post/108466273273</option>
</select> (WARNING: some may take time to load! Go back through the list after you've seen all patterns)
  <br/>Find more at <a href="http://subtlepatterns.com/">Subtle patterns</a> or <a href="http://giphy.com/search/pattern">Giphy /pattern</a>.
</p>

<canvas id="river"></canvas>
<div id="river-controls">
  <button>Redraw </button><input type="number" value="5" style="width: 2rem"> boats
  <span hidden><input type="checkbox" checked>Animate</span>
</div>
```
> 0 votes

---
Tags: animation, water, non-photorealistic
---


# Question
Title: Using Physics.Raycast inside OnCollisionEnter2D function
```
    void OnCollisionEnter2D(Collision2D collision)
    {
       foreach(ContactPoint2D contact in collision.contacts)
       {
           RaycastHit raycastInfo;
           Physics.Raycast(contact.point, Vector3.forward, out raycastInfo, 1000.0f);
           if(raycastInfo.collider)
           {
               Debug.Log("Hit!");
           }
       }
    }

```

I am using this code to raycast an abject with the contact position of collision. The collision part works fine, when collision happens this function is triggered. But when I raycast to that position, RaycastHit variable return empty.

I couldn't find what I am doing wrong.

# Answer
Looks like you're mixing 3D & 2D physics.

You're using OnCollisionEnter**2D**, which triggers when 2D colliders hit each other.

But then you're using Physics.Raycast, which casts rays against 3D colliders - so it won't be able to detect the two colliders that triggered the event, or any similar colliders in your scene. Maybe you want Physics**2D**.Raycast?
> 1 votes

---
Tags: unity, 2d, collision-detection, physics
---


title: Rectangle Collision Not Correct

text:
# Question
Title: Rectangle Collision Not Correct
As you can see on the top corner it says COL: False/True. This is if the player bounds and the tiles which are solids. The rectangles for the tiles and players are checked if they intercept each-other. Looks like its working right? Well nope. Look more closely.

The **BOTTOM RIGHT** corner needs to be inside the tiles for it to count.

Now let's get to the code I used now that hopefully you understand the problem.

**Player Bounds (Rectangle)**

```
playerBounds.Width = 32;
playerBounds.Height = 64;
playerBounds.X = (int)this.position.X;
playerBounds.Y = (int)this.position.Y;

```

**Tile Bounds (Rectangle)**

```
newTile.bounds = new Rectangle(x * TILE_SIZE, y * TILE_SIZE, TILE_SIZE, TILE_SIZE);

```

Now onto how it detects it:

```
for (int x = 0; x < Tilemap.MAP_WIDTH; x++)
        {
            for (int y = 0; y < Tilemap.MAP_HEIGHT; y++)
            {

                if (tm.tile[x, y].bounds.Intersects(playerBounds))
                {
                    if (tm.tile[x, y].getSolid())
                    {
                        Colliding = true;
                    } else
                    {
                        Colliding = false;
                    }
                }
            }

        }

```

**Move**

```
    public void Move(Vector2 pos)
    {
        for (int i = 0; i < speed; i++)
        {

            position += pos;
        }

    }

```

I have used breakpoints at the collision detection loop. And the rectangle fully covers the character and the tiles.

# Answer
```
        for (int x = 0; x < Tilemap.MAP_WIDTH; x++)
        {
            for (int y = 0; y < Tilemap.MAP_HEIGHT; y++)
            {

                if (tm.tile[x, y].bounds.Intersects(playerBounds))
                {
                    if (tm.tile[x, y].getSolid())
                    {
                        foundCols++;
                    } else
                    {

                    }
                }
            }

        }
        if (foundCols < 1)
        {
            Colliding = false;
            foundCols = 0;
        }
        else
        {
            Colliding = true;
            foundCols = 0;
        }

```

Answer by: David van brink.
> 1 votes

---
Tags: c#, xna, collision-detection
---


# Question
Title: Moving from HeroEngine to Unity/Torque 3D
Short background: small team with some financial back-up from investors, yet no multi-billion-$ enterprise, working on an MMORPG for PC.

HeroEngine looks like the perfect solution. Everything included that's needed to get started, programming languages also include C++/C#. Sounds perfect.

However, once the money's rolling in, a company might prefer work on its own, including its own server park, etc.

Does anyone have experience in using HeroEngine? Is it possible to migrate projects from it to Unity/Torque 3D or the like? Are there legal restrictions (I had a look into the license agreements yet was unable to find an answer to this)?

Should they get started with HeroEngine and the migrate later or is it wiser to choose an engine like Unity/Torque 3D from the get-go?

# Answer
> 2 votes
I wouldn't recommend planning to switch engines. You should always develop in the game engine you ultimately intend to use. The only possible exception is when prototyping, and that doesn't sound like what you're asking about.

That said, Hero Engine looks like a fine choice for the entire project. There is one obvious advantage to Unity: it's cross platform. I think Hero is Windows only. If you do want to learn about Unity, you should check out my book http://www.manning.com/hocking/

---
Tags: unity, torque
---


title: TopDown Island Generation

text:
# Question
Title: TopDown Island Generation
I am trying to generate an island using Simplex Noise. To actually make a island shape i used Amitp's answers to the following questions:

1.Fast, simple procedural 2d island generation

2.Generating random Pools or lakes

Using them i have snippet of code for generation:(width/height is 128)

```
for(int y = 0; y < HEIGHT; y++) {
        for(int x = 0; x < WIDTH; x++) {
            // amitp's solution
            Vector2 vec = new Vector2(2 * x / WIDTH - 1, 2 * y / HEIGHT - 2);
            float d = Mathf.Sqrt(vec.x * vec.x + vec.y * vec.y);
            //
            float noise = Noise.Generate((float)x / WIDTH * 10, (float)y / HEIGHT * 10);

            // amitp's solution again
            mapData[x, y] = noise > 0.3 + 0.4*d*d ? noise * 10 : 0.0f;
            //

            colors[x + y * WIDTH] = new Color(mapData[x, y], mapData[x, y], mapData[x, y]);
        }
    }

```

This gives me the following unwanted result:

How do i get fix it to generate properly?

Lastly i'm using Unity.

\***EDIT:

Fixed/Changed a couple of things and now i am getting this(still not what i want):

with this changed code:

```
for(int y = 0; y < HEIGHT; y++) {
        for(int x = 0; x < WIDTH; x++) {
            // amitp's solution
            Vector2 vec = new Vector2(((2 * x) / WIDTH) - 1, ((2 * y) / HEIGHT) - 1);
            float d = Mathf.Sqrt((vec.x * vec.x) + (vec.y * vec.y));
            //
            float noise = Noise.Generate((float)x / WIDTH, (float)y / HEIGHT);

            // amitp's solution again
            mapData[x, y] = noise > 0.3 + 0.4*d*d ? noise * 10 : 0.0f;
            //

            colors[x + y * WIDTH] = new Color(mapData[x, y], mapData[x, y], mapData[x, y]);
        }
    }

```

# Answer
I suggest this aproach. Let fs(x,y) be your simplex noise function. Let's introduce a second function : `f(x,y) = ((float)Math.Sin(((float)x/(float)WIDTH) * Math.PI) ) * ((float)Math.Sin(((float)y / (float)WIDTH) * Math.PI) )` or any function that rassemble the following and that gives values from 0 to 1:

at this point take your simplex noise fs(x,y) :

and multiply per f(x,y) you get something like this :

finaly apply a colorgradient to obtain something like :
> 5 votes

---
Tags: unity, c#, procedural-generation, terrain
---