# Question
Title: How to model chess knight movement in GameMaker?
I am making a chess game in GameMaker, and I have the basic movement down for all of the other pieces except for the knight. I am using a system where I have an if statement that checks if the mouse is in a location that it can move too, then if it moves the piece there. For example, the rook code is `(mouse_y div 64) *64 == y || (mouse_x div 64) * 64 == x`. What would be an expression that would work for knights? Would this strategy even work for knights?

# Answer
> 2 votes
**I imagine you have to do 8 expressions. All expressions using the x and y axes:**

```
if (mouse_x div 64) * 64 == x+64 && (mouse_y div 64) * 64 == y-128 ||
(mouse_x div 64) * 64 == x+128 && (mouse_y div 64) * 64 == y-64 ||
(mouse_x div 64) * 64 == x+128 && (mouse_y div 64) * 64 == y+64 ||
(mouse_x div 64) * 64 == x+64 && (mouse_y div 64) * 64 == y+128 ||

(mouse_x div 64) * 64 == x-64 && (mouse_y div 64) * 64 == y+128 ||
(mouse_x div 64) * 64 == x-128 && (mouse_y div 64) * 64 == y+64 ||
(mouse_x div 64) * 64 == x-128 && (mouse_y div 64) * 64 == y-64 ||
(mouse_x div 64) * 64 == x-64 && (mouse_y div 64) * 64 == y-128 {

```

This way you check every possible point.

# Answer
> 4 votes
Borrowing the diagram from disc\_code22's answer, let's overlay it with some numbers. For each square, we're going to count how many squares it is left or right from the knight, and square it; then do the same for up/down; then add the two numbers together:

You might recognize this as Pythagorean theorem, just without the square root (we don't need it if we just want to tell the squares apart).

Knight moves that travel 2 out and 1 over are the only moves on the chess board with squared length exactly 5.

So, we can do something like this:

```
travelX = (mouse_x div 64) - (x div 64)

travelY = (mouse_y div 64) - (y div 64)

```

With these variables in hand, now we can write a variety of piece moves as one-liners:

* Knight: `travelX * travelX + travelY * travelY == 5`
* Rook: `travelX == 0 || travelY == 0`
* Bishop: `travelX == travelY || travelX == -travelY`
* King: `travelX * travelX + travelY * travelY < 3`

# Answer
> 2 votes
There are quite a few approaches you could take to validating this kind of movement, so you should choose whatever is cohesive with the style of your movement validation so far, but I'll suggest a simple approach and perhaps you and other answerers can build on it.

If your knight is at a position, lets say (x,y) on the chess board/grid, lets also imagine a second version of this grid that is relative to the knights position. To tie this in with the example image, if we drew these relative grid labels on the example image, the knight's position would be labeled (0,0), and the grid would range through (+/-2, +/-2).

Using these relative positions can make it a lot simpler to determine which knight moves are valid. Lets consider the movement where the knight heads north and then east. In the example image's grid this is the move that ends up on (3,0), but in our imaginary relative grid this would end up at (1, 2).

Since there are only 8 valid moves maximum for a knight, the simplest approach is likely to hard code these valid relative moves, then check the players attempted move against the list of valid relative positions representing knight's possible moves. The valid positions could most concisely be stated as (+/-1, +/-2) and (+/-2, +/-1)

So in conclusion, this approach simplifies stating which moves are valid for the knight, but adds in some trickiness about transforming between the absolute and relative grid so you can compare the players absolute grid mouse clicks with the relative grid moveset of the knight.

There are certainly other approaches to this problem but I hope this one is enough to get you started on tackling the issue.

If you are looking for more reading including some different approaches to this issue as well as some code samples, check out this Geeks4Geeks article on coding chess knight movement

---
Tags: movement, game-maker
---


# Question
Title: How to replace texture maps on models in a packaged game?
I'm trying to do an experiment. I'd like to do some object masking to the assets inside of a game, so during run time, when you are playing, they're texture maps are replaced by the masks.

The masks will literally be just color maps. They are supposed to be labels for a machine learning program.

Preferably if one could replace the texture maps with color masks during runtime that would be better.

# Answer
Typically this is done via DLL injection.

You insert a piece of custom software that poses as the graphics driver while you're running the game. Each frame, when the game tries to ask the graphics driver:

> please **set the texture sampler to use the tree texture** and then draw this batch of triangles

...your software receives that message, records it, then passes it on to the *real* graphics driver to do the work.

In a second pass, you can take those recorded rendering instructions and play them back, to reproduce each drawn frame. Or you can modify them to alter the frame: for instance, you can recognize the ID of the tree texture, and and substitutes a modified instruction when passing the message along to the *real* graphics driver for playback:

> please **set the mask shader to draw pure-green** and then draw this batch of triangles

This is the general idea behind how the work behind papers like "Playing for Data: Ground Truth from Computer Games" was done. You can read the paper for more details, and examine the code they used for their particular injection.

As Romen says, techniques like this can also be used to exploit games in ways that their creators might object to, so I won't go further into a step-by-step walkthrough in a public forum like this, but you can find more information on your own by following those keywords.
> 4 votes

---
Tags: software-engineering, models, masking
---


title: MMO Chat system methods

text:
# Question
Title: MMO Chat system methods
I'm working on a little MMO game as a learning experience, the server coded in Python.

When a player logs in it pulls their character data from a SQL db and into server memory. It then uses memory for just about all things in the game and only uses the database again to back up the states at periodic save intervals, or when that player leaves/disconnects.

My question though is about the chat system. I've made chat systems before for websites where it just pulls from mySQL databases. But as I've learned accessing databases can be expensive for MMOs.

Currently in my build, chat is just sent to and stored locally by the player as and when it happens, but if an important guild message is sent while the player is loading between zones/channels then they don't receive it.

Is my current way the 'common' one? (just needing tweaks) Or should I be pulling chat from a SQL database? Or should chat be saved in server memory? Maybe its a mix...

Some pointers in the right direction would be great!

# Answer
Databases are supposed to be used for persisting long-lived data, not for ephemeral data. Using a database for storing short-lived chat messages just to delete them seconds later is quite an anti-pattern. It was common in the early years of PHP where databases were pretty much the only way to exchange data between sessions. But more modern web application frameworks have ways to communicate between sessions using in-memory techniques without having to abuse a database.

However, when your architecture supports offline messes which get delivered as soon as the player goes back online, then you are not dealing with ephemeral data. It's data which can last for days, probably forever. That means it belongs into a database so it doesn't hog RAM and doesn't get lost in case of a server reboot.

So my recommendation would be to conceptually separate *chat messages* from *offline notifications*. The first are ephemeral. They just get sent to all receivers and then the server forgets about them. The latter are stored in the database until the recipient connects to the server. Deciding what's a chat message and what's an offline notification would be up to the server. If the recipient is online, it's always a chat message. If the recipient is offline, the server should decide whether it's important enough to turn into an offline notification or if it should just be discarded.

On the other hand, there is one argument for storing all chat messages permanently in the database: You want to log them. That can be useful if you want to investigate reports of abusive behavior. But the question is if it is worth the cost. Large communities can generate a lot of pointless chatter. Is it really worth it to store all of that forever? And then there is the legal problem of data protection. Are you actually *allowed* to permanently store all that communication, probably some of which players consider confidential? Or maybe you are even *required* to log communication in case law enforcement wants access? That's a question for your local lawyer.
> 1 votes

---
Tags: python, mmo, sql
---


# Question
Title: How to change the up vector of something in Unreal
---

I'm creating a grapple hook mechanic.

The elements of this particular situation are a Player and a grapple point.

---

I would like the top of the player to always be pointing towards this grapple point. (the up vector of the player is pointing along the vector to the point).

The default Unreal CharacterMovementComponent is in the falling movement mode right now, and the player's rotation around the Z axis is determined by the movement input. The X and Y rotations are unchanged.

Because the player's position around this grapple point could be anywhere on the sphere of influence of the rope, I never have a definite axis to rotate around to point the up vector towards the grapple point.

---

How do I achieve something like this?

# Answer
"How to change the up vector of something in Unreal ?" The answer is simple - to change the `upvector` you simply need to change the object's rotation.

To make your `upvector` to point to something - you can use innate function of FMath especially take a look at: `MakeRotFromXZ` family of functions. docs
> 1 votes

---
Tags: mathematics, vector, unreal-4
---


# Question
Title: What is the most efficient way to trigger an action based on proximity?
I am developing a 3rd person platformer that entails a grapple hook system.

This grapple hook system relies on a series of 'grapple-able' points.

I would like these points to shine every so often.

These points will shine when:

* Within the player's view cone AND
* Within a certain distance of the player.

This `Grapple` object class will contain the method `Shine()` to trigger the effect.

---

**Initial research**

My initial research was based upon using a cone trace from the player for these `Grapple` objects, then in each one found, calling the `Shine` method.

I could then tweak the cone's angle and height to better represent the view cone.

---

**Problems**

Unreal by default does not have a cone trace, and I'm not sure if using a multibox trace followed by an angle check is the most efficient solution.

# Answer
> 1 votes
You actually have 2 ways of doing the frustum check:

1) Every scene component (or most fo them) has a property `WasRecentyRendered()` -- so if it was recently rendered - they are 99% in the camera frustum.

2) You can manually check the frustum with something like described here: UE4\_AnswersHub\_Link

To make it all performant you can trigger some object-sphere-trace to get a subset of close enough points - and then sieve them through the frustum/WasRecentyRendered queries.

# Answer
> 0 votes
Instead of a cone check you can use a frustum check.

If there is no built-in method for that you can do this by multiplying the vec4 position you want to check with the MVP matrix as you would in the vertex shader and then checking that the point is within the \[-w,w\] cube (you may need to take \[0,w\] for z if you use have a 0 to 1 depth).

You can move the virtual camera backwards a bit to allow objects on the edge of the screen to also shine when the control point is just off screen but the shine would still be on screen. And the far parameter of the perspective matrix can be adjusted to implement the range check.

---
Tags: c++, unreal-4, platformer, unreal, raytracing
---


# Question
Title: Godot _on_Area2D_area_entered not detecting
In my Scene I have a Node2D. I then Instanced the Player and Area2D nodes. The Area2D has a signal pointing to itself that prints test when run.

Here is the Code For the Area2D. Nothing happens when an object enters the Area2D.

```
extends Area2D

# Declare member variables here. Examples:
# var a = 2
# var b = "text"

# Called when the node enters the scene tree for the first time.
func _ready():
    pass # Replace with function body.

# Called every frame. 'delta' is the elapsed time since the previous frame.
#func _process(delta):
#   pass

func _on_Area2D_area_entered(area):
    print('test')

```

Level Scene

Player

Area 2D

Google Drive Link to Project: https://drive.google.com/drive/folders/1OG3BBqKJzC3Je\_r5eQdqiFUp7PzzBmt1?usp=sharing

# Answer
The question isn't entirely clear on *what* you want to trigger the signal, but I assume you want it to fire when the player enters the area. The docs for `area_entered` say:

> Emitted when another area enters.

The player is a `PhysicsBody`, not an `Area`. Use `body_entered` instead:

> Emitted when a physics body enters.
>
> The body argument can either be a PhysicsBody2D or a TileMap instance (while TileMaps are not physics body themselves, they register their tiles with collision shapes as a virtual physics body).
> 2 votes

---
Tags: godot
---


# Question
Title: The camera does not capture movements in z-axis
I want to make a simple drag and drop card in Unity, where the card pops up a bit towards the screen when the drag begins (lifting effect), and then drops down back on the table when the drag ends.

My script looks like this:

```
public class Draggable : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    void IBeginDragHandler.OnBeginDrag(PointerEventData eventData)
    {
        this.transform.position = new Vector3(this.transform.position.x, this.transform.position.y, this.transform.position.z - 10);
    }

    public void OnDrag(PointerEventData eventData)
    {
        this.transform.position = new Vector3(Input.mousePosition.x, Input.mousePosition.y, -10);

    }

    public void OnEndDrag(PointerEventData eventData)
    {
        this.transform.position = new Vector3(this.transform.position.x, this.transform.position.y, this.transform.position.z + 10);

    }

}

```

The card is an image, and it is child of the canvas. The render mode for the canvas is `Screen Space - Overlay`.

The drag works correctly, but I cannot capture the movements in the z-axis.
It does capture the movements in the z-axis when I change the render mode. However, then the card is too far away in the z-axis, and it moves with an offset with respect to the mouse pointer.

As far as I understood, I need to do something about realtive distances, but I how can I force the mouse pointer to be on z=0 plane.

# Answer
> 1 votes
When the canvas is set to screen space overlay, the z isn't going to do anything as 'Screen space overlay' uses an orthographic camera which renders everything between z -1000 and z 1000 the same. It is not going to look like it is closer to the camera. That is just how an orthographic projection works..

I think you'd either want to set it to Screen space Camera and let a perspective camera render it, or edit the scale instead of the z position to fake it getting closer to the camera...

If you change the render mode however, your current drag code won't work as you already realized. This is because in 'screen space overlay' the canvas is scaled to this huge thing where the width and height of the canvas in world coordinates is equal to the width/height in pixels of the screen. Allowing you to set an items world position to a screen position without having to convert to world position first.

To convert to world space, I'd advise using RectTransformUtility.ScreenPointToLocalPointInRectangle. As this method is intended for usage in the UI system. I also use local instead of world position, to make it easier to edit the z without having to worry about the current rotation of the camera or position of the canvas. Result would look something like this:

```
public void OnDrag(PointerEventData eventData)
{
    Vector2 localPos;
    if (RectTransformUtility.ScreenPointToLocalPointInRectangle(transform.parent as RectTransform, eventData.position, eventData.pressEventCamera, out localPos))
    {
        transform.localPosition = new Vector3(localPos.x, localPos.y, -10);
    }
}

```

Where the -10 is replaced by a 0 in the end drag event.

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


title: Unpack the pak file - Unreal Engine

text:
# Question
Title: Unpack the pak file - Unreal Engine
So I have the encryption key. This is stressed so much to have it. Well, I have it. Where do I use it? Unrealpak does not seems to offer an option to supply the encryption key, if your pak is encypted - the unpackaging simply fails.

# Answer
> 0 votes
Found that keys can be supplied with a json

---
Tags: unreal-4, unreal
---


# Question
Title: Why are assets (images) in Unity build reported as 28 times larger
I'm trying to reduce a Unity WebGL build size which, for the data asset, is currently at 30 Mb. I installed the Build report inspector. On clicking the "Source assets" tab and choosing "Size" it showed the top entries were images. Fine. But all the sizes reported were between 4 and almost 30 times the size of the file on disk. Is this just a bug / artifact of the build reporter or a genuine problem which I need to address to reduce the build sizes?

\** Edit \**

Two of the files are text files. Their size in unity build report is the same as that on disk. Why?

\** Edit 2 - after Ed Marty's answer \**

Using low quality with crunch compression at 70 results in slightly lower image quality but it went from 10 Mb to 300 kb, i.e. 30 times smaller size (and about 10x smaller than actual file size on disk).

# Answer
Unity projects don’t include the source file in the project when building. Instead, every image is converted during import to a format useful to the GPU, as set by you in the import settings for that image. These tend to be larger, especially if an uncompressed format is chosen, and especially if the source image is in a compressed format (eg. jpeg, or png if many neighboring pixels are identical). For example, a 1024x1024 image stored in RBG-24 format uses 3 bytes per pixel, times 1024\*1024 pixels, equals 3 MB. A 2048x2048 image in the same format uses 12 MB. It also likely includes mipmaps, which increases the size. A 2048x2048 image in the same format with mipmaps would be about 16 MB.

If a compressed output format is chosen instead, this can significantly reduce the file size, at the expense of image quality. Depending on platform, there are several formats and compression levels to choose from with varying trade offs between quality and size.

See here for more details about specific formats per platform. https://docs.unity3d.com/Manual/class-TextureImporterOverride.html

Compare all this with the png format for example, which has lossless compression built in. Even a gigantic 4096x4096 png image can be as small as a few kB if it’s mostly empty.

Of course none of this applies to text files, which don’t need to be modified for GPU optimization.

So to decrease app size, your best bet is to change compression settings, decrease image size, and potentially turn off mipmaps for a bit more savings, *if you don’t need them*, otherwise that could decrease performance.

An alternative I would not recommend would be to store the source images in the streaming assets folder, and load them manually at runtime. An option, but not a good one.
> 7 votes

---
Tags: unity, build-process
---


# Question
Title: Collision detection / physics for simple game
I am currently working on a mini game for class (first time doing something like this) and I don't really know how to start with collision detection at all. The game I'm creating is a top down sumo fighting game on a icy circular arena where you move around gaining momentum and velocity and try to knock each other off to gain points.

So far I have the movement acceleration/friction pretty much down and I also have a system to detect when a collision occurs, I just don't know how to actually push the characters away when they collide. I think I will base the knock back amount/ damage on the velocity the attacker has against their velocity alongside the character's resistance stat that I will be adding. I also assume that I will have to do some intense math with like tangents and stuff to get the direction correct but I'm not sure how to do that at all.

I would greatly appreciate any help and I am open to future help if you want to assist me on this project later via Discord or something. Thanks for everything.

import pygame, sys, time
from pygame.locals import *
import random
import math

#Colors
colorRed=pygame.Color(241,59,62)
colorPurple=pygame.Color(200,254,249)
colorBlue=pygame.Color(52, 207, 235)
colorGreen=pygame.Color(100,182,100)
colorWhite=pygame.Color(255,250,250)
colorBlack=pygame.Color(0,0,0)
colorOrange=pygame.Color(242,164,0)
colorBrown=pygame.Color(148,103,58)

#Dimensions
w=800
h=600
pygame.init()
fpsClock=pygame.time.Clock()
screen=pygame.display.set_mode((w,h))
pygame.display.set_caption ('SUMO')
centerX=w//2
centerY=h//2

#Stage
stageR=250
def stage (centerX,centerY):
    """stage (centerX,centerY) - creates a stage with given centerpoint"""
    pygame.draw.circle(screen, colorBlue, (centerX,centerY),stageR)

#Character 1
xR=int((stageR//10))
x1=int(centerX-(stageR*0.8))
y1=centerY
x1_dir=0
y1_dir=0
def char1 (x1,y1):
    """char1 (x1,y1) - creates char1 at given coordinates"""
    pygame.draw.circle(screen, colorRed, (x1,y1),xR)
print (x1)
print (centerX)

#Character 2
x2=int(centerX+(stageR*0.8))
y2=centerY
x2_dir=0
y2_dir=0
def char2 (x2,y2):
    """char2 (x2,y2) - creates char1 at given coordinates"""
    pygame.draw.circle(screen, colorGreen, (x2,y2),xR)

while True:
    screen.fill(colorBlack)
    for event in pygame.event.get():
        #Game Exit
        if event.type== QUIT:
            pygame.quit()
            sys.exit()

    distance=math.hypot(x1-x2,y1-y2)
    if distance <= 2*xR:
        print ("HIT")

    keys = pygame.key.get_pressed()

    if keys[K_d] or keys[K_a]:
        x1_dir += 0.1 if keys[K_d] else -0.1
    else:
        x1_dir *= 0.98

    if keys[K_w] or keys[K_s]:
        y1_dir += 0.1 if keys[K_s] else -0.1
    else:
        y1_dir *= 0.98

# -------------------- CHAR2 MOVEMENT --------------------

    if keys[K_RIGHT] or keys[K_LEFT]:
        x2_dir += 0.1 if keys[K_RIGHT] else -0.1
    else:
        x2_dir *= 0.98

    if keys[K_UP] or keys[K_DOWN]:
        y2_dir += 0.1 if keys[K_DOWN] else -0.1
    else:
        y2_dir *= 0.98

    stage (centerX,centerY)
    char1 (round(x1),round(y1))
    char2 (round(x2),round(y2))
    x1+=x1_dir
    y1+=y1_dir
    x2+=x2_dir
    y2+=y2_dir
    pygame.display.update()
    fpsClock.tick(60)
    ```
</code></pre>

# Answer
> 0 votes
Your goal is to prevent them from going into each other, which means once you detect a collision they shouldn't go toward each other. I assume the sumos are circles.

I wrote some pseudo code to show how to do it:

```
# We compute how much one moves relative to the other.
velocity = velocity_B - velocity_A;

# If the sumos are circles the normal is the direction from one center to the other.
normal = Normalize(position_B - position_A);

# We find the proportion of the relative velocity that is in the direction of the normal.
# Basically we want to find out how fast they are moving toward each other.
vel_normal = Dot(velocity, normal);

if vel_normal < 0:
    # if vel_normal is positive that means they are already moving away from each other
    # now we modify their velocity so that vel_normal becomes 0
    impulse = normal * vel_normal

    # we modify their velocity depending on their mass. The bigger one is the less it will move.
    sum_inv_mass = 1/mass_A + 1/mass_B
    velocity_A += impulse  * (1/mass_A) / sum_inv_mass
    velocity_B -= impulse  * (1/mass_B) / sum_inv_mass

```

This is the basics, if you want them to bounce you can multiply `vel_normal` by something bigger than one.

Because of small errors in the calculations it's possible they will be able to go into each other very slowly. There are ways to fix that but it's probably better as its own question.

---
Tags: collision-detection, physics, python, pygame, collision-resolution
---


# Question
Title: Making a box character in UE4, not a capsule
I want to make a character for a Breakout game that is a kind of cube.

From the instructions from Unreal it appears I need to create a 'Character' blueprint. But when i do this, it comes with CapsuleComponent (Inherited) and I can't change the shape/mesh.

I could perhaps turn off collision on the capsule, but is that really the way it has to be. The capsule is annoying and not needed in this case. I just want a block that I can move left to right with A and D key.

Am I approaching this wrong completely? Do I need a 'Character' blueprint in order to make such a controllable Paddle for Breakout game?

# Answer
In C++ you can just destroy the `CapsuleCompoennt`, however the `ACharacter` class is intended to use the `CapsuleComponent` many of its underlying functions are relying on a `CapsuleComponent`.

With that said you probably better to use APawn - and add all the bells and whistles manually. - Yes it will lose all the `ACharacter's` bells and whistles.

Leaving the `CapsuleComponent` without collisions is probably an option.

If you are planning to use `UCharacterMovementComponent` of some kind - it will assume a proper capsule - it is possible to fix/override everything, but it is up to you to answer if it is worth the effort.
> 5 votes

---
Tags: c++, unreal-4, blueprints
---


# Question
Title: How to control multiple characters simultaneously in Unreal Engine 4?
How do I make two or more characters response to a single user input, in this case a mouse click?

Ideally, I'd like something similar to Baldur's Gate style party control. The only example of multiple character party control I have seen implemented is the BioWare style system.

# Answer
> 2 votes
Generally speaking if you want to control multiple characters in UE4 with a free Camera (like IIRC was in BG).

You make a "GOD" player controller - that will have its own `Pawn` let's say some sphere with an arm and camera attached to it.

Then Process the input inside your player controller - and delegate the commands to your characters.

**EDIT per DMGregory's request**

I will not get in to too much code here - as it will take quite a lot but I will try to expand on UE4's specific and a general controls:

1) A "GOD" PlayerController (PC for short): In this scenario a PC will not be possessing any `ACharacter` directly, it will have it's free `APawn` let's call it a CP (for camera pawn). The CP will be anything than just a simple setup for a free RTS like camera lets try to describe it and its functionalities.

`ACameraPawn
--SceneRoot
---SpringArm
----Camera`

We will use the `SpringArmComponent` to handle Zoom in/out if needed. `ACameraPawn` will be the PlayerPawn a pawn that is possessed by the PC And the PC will move it around as a whole `AActor` for the in SceneCamera navigation.

`ABaseCharacter`

Now we will build a base class for our characters that we will be controlling them from our PC - we will define some basic functionality:

```
//Remark the code to be threated more like a pseudo code I am no where around UE4 and have no any compilers handy here.
class ABaseCharacter public ACharacter, IAttackable //... whatever interfaces are needed...
{
    public:
    //... C'tor ... D'tor omitted...
    bool MoveToWorldLocation(FVector worldLocation);
    bool AttackTarget(IAttackable* target);

};

```

These are more or less a minimal needed methods for our `ABaseCharacter` So we will be able to send it some basic orders.

Now the PC itself (I will not go into code details here, but will describe a general approach) Note: the player pawn is set in the UE4s settings so no code needed for the setup.

Our PC will consume all Player inputs Keyboard (WSAD) and mouse (left right clicks, scroll whatever else).

So the WSAD will be processed inside the PC itself and all it will do is just set its controlled pawn's world location and rotations - Scroll-wheel will set the length of pawns `SpringArmComponent` etc.

The PC will hold your `ABaseCharacter`s references `TArray` (not really matters if they were placed in world all spawned dynamically.

Now on mouse input (for instance Goto World Location) it will iterate the `ABaseCharacters` `TArray` and dispatch its `MoveToWorldLocation` method - of-course then the `ABaseCharacters`'s own `AAIController` will execute the `MoveTo` task or whatever implementation based there.

So this is how we defined a "GOD" PC in RTS like style that can control multiple characters.

---
Tags: unreal-4
---


title: How to create video from camera?

text:
# Question
Title: How to create video from camera?
I have a 3d scene and a camera; I want to create video file from camera pre-set movements. If it is possible, running application by command line (without needed to "show" at video, my camera) .

Is it possible in Unity ?

If yes what's the best approach ?

Thanks

# Answer
You can use the official Unity Recorder asset. The latest Unity Recorder is available in Preview via the Package Manager from Unity 2018.3+, the asset store version is no longer being updated actively I believe.
> 4 votes

---
Tags: unity, camera
---


# Question
Title: How do I get the size of a Plane in pixels and set it multiplied by some factor to be the size of a Sphere?
I am doing an attempt to make a 3D snake game, as an experiment but I am still a beginner. I have a `Sphere` that I wish to dynamically resize to be, let's say, the 20th part of the width of this `Plane`. How can I do this? I thought to find the size of the `Plane` first. I also thought to use `Screen.width` and `Screen.height` because in my actual project the `Plane` is almost the size of the screen, but from what I found the `Transform` class does not have a way to resize it to a specific dimension in pixels.

Using the code below I do not get this work, but I also see that the `Sphere` becomes a black circle because of the only instruction in the `Start` method.

# Existing code

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

// Attached to the Plane
public class SphereResizer : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        // what should I put here?
        GameObject.Find("Sphere").transform.localScale = new Vector3(1f, 1f);
    }

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

```

# Screenshots

# Download the example

Here is the GitHub repository.

Thank you.

# Answer
As this question is kinda 2 questions in one, I'm going to answer the one that I think is the root of your problem (scale sphere relative to plane). Because if I read this correctly, the pixel part sounds like you only want to do that because you couldn't find the solution to your original problem.

In Unity, a position is based on 'units'. a 'unit' doesn't have a set real world scale, it is just a number. As in, if you want a unit to be a mm, you pretend it is a mm. If you want it to be an inch, you pretend it to be an inch. (if you have UI with rendermode set to screen space overlay, it pretends 1 unit is 1 pixel). Note however that the physics engine is by default configured so that 1 unit == 1 meter in the real world. The grid that is drawn in the scene view is 1x1 unit, 10x10 units or 100x100 units (depending on zoom level).

How much pixels this one unit actually is depends on the camera used to render it, and there could even be 2 cameras rendering the same 3D object, resulting in the same object to be 2 different sizes in pixels on 2 different cameras.

The default cube and sphere, with a scale of \[1,1,1\] take up 1 unit in each axis.

The default plane, with a scale of \[1,1,1\] and not rotated takes up 10 units in x and z. And well, its a plane, so basically nothing in y...

So by default 10 spheres fit on a plane, so if you want to fit 20 spheres on a plane, you'd need to set the sphere scale to \[0.5, 0.5, 0.5\].

Also note, that you are giving the Vector3 constructor 2 parameters instead of 3. Meaning the z defaults to 0, resulting in your black sphere. So if you'd set the z aswell like this:

```
GameObject.Find("Sphere").transform.localScale = new Vector3(0.5f, 0.5f, 0.5f);

```

it should work better.

Also, you'd might want to consider using a quad instead of a plane... As that one by default takes up 1 unit in x/y. Which might just make it more intuitive for you...
> 1 votes

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


# Question
Title: Setting vertex colors for a marching cubes mesh
I am making a voxel based terrain system (Yes, I know, very original...), anyway...

Each voxel should have it's own color so the player can distinguish which type of material it is. For example: dirt would be brown; grass, green and stone would be gray.

I don't really understand marching cubes, so I come to you guys with my issue. I want to be able to color each vertex based on which voxel it would visually make sense to belong to. **Edit**: To clear things up a little. The voxel contains the color data, I do not wish to generate the colors (like how some systems automatically apply a stone texture based on the height/slope of the face)

How would I go about doing this?

---

## Edit: Marching Cubes Code

Here is the code I am using for marching cubes, as I have said. I don't understand marching cubes so this code wasn't written by me.

Original Source of the Code Here

(Some of the data structures (like the lookup tables) have been omitted from the code)

Also note that the code below has been edited to pass in the color data for each Voxel.

```
        public virtual void Generate(IList<float> voxels, IList<Voxel> voxelData, int width, int height, int depth, IList<Vector3> verts, IList<int> indices)
        {

            if (Surface > 0.0f)
            {
                WindingOrder[0] = 0;
                WindingOrder[1] = 1;
                WindingOrder[2] = 2;
            }
            else
            {
                WindingOrder[0] = 2;
                WindingOrder[1] = 1;
                WindingOrder[2] = 0;
            }

            int x, y, z, i;
            int ix, iy, iz;
            for (x = 0; x < width - 1; x++)
            {
                for (y = 0; y < height - 1; y++)
                {
                    for (z = 0; z < depth - 1; z++)
                    {
                        //Get the values in the 8 neighbours which make up a cube
                        for (i = 0; i < 8; i++)
                        {
                            ix = x + VertexOffset[i, 0];
                            iy = y + VertexOffset[i, 1];
                            iz = z + VertexOffset[i, 2];

                            Cube[i] = voxels[ix + iy * width + iz * width * height];
                        }

                        //Perform algorithm
                        March(x, y, z, Cube, verts, indices);
                    }
                }
            }

        }

        protected virtual float GetOffset(float v1, float v2)
        {
            float delta = v2 - v1;
            return (delta == 0.0f) ? Surface : (Surface - v1) / delta;
        }
        protected override void March(float x, float y, float z, float[] cube, IList<Vector3> vertList, IList<int> indexList)
        {
            int i, j, vert, idx;
            int flagIndex = 0;
            float offset = 0.0f;

            //Find which vertices are inside of the surface and which are outside
            for (i = 0; i < 8; i++) if (cube[i] <= Surface) flagIndex |= 1 << i;

            //Find which edges are intersected by the surface
            int edgeFlags = CubeEdgeFlags[flagIndex];

            //If the cube is entirely inside or outside of the surface, then there will be no intersections
            if (edgeFlags == 0) return;

            //Find the point of intersection of the surface with each edge
            for (i = 0; i < 12; i++)
            {
                //if there is an intersection on this edge
                if ((edgeFlags & (1 << i)) != 0)
                {
                    offset = GetOffset(cube[EdgeConnection[i, 0]], cube[EdgeConnection[i, 1]]);

                    EdgeVertex[i].x = x + (VertexOffset[EdgeConnection[i, 0], 0] + offset * EdgeDirection[i, 0]);
                    EdgeVertex[i].y = y + (VertexOffset[EdgeConnection[i, 0], 1] + offset * EdgeDirection[i, 1]);
                    EdgeVertex[i].z = z + (VertexOffset[EdgeConnection[i, 0], 2] + offset * EdgeDirection[i, 2]);
                }
            }

            //Save the triangles that were found. There can be up to five per cube
            for (i = 0; i < 5; i++)
            {
                if (TriangleConnectionTable[flagIndex, 3 * i] < 0) break;

                idx = vertList.Count;

                for (j = 0; j < 3; j++)
                {
                    vert = TriangleConnectionTable[flagIndex, 3 * i + j];
                    indexList.Add(idx + WindingOrder[j]);
                    vertList.Add(EdgeVertex[vert]);
                }
            }
        }

```

```
/// VoxelData
[Serializable]
public struct Voxel
{
    public Color32 color;
    public long materialId;
}

```

---

## Example of what I tried

I have already tried assigning the color based on the current cube being processed, it did not give the result I wanted, take a look at the image below, notice that the corner of some voxels are white instead of gray, this is because of the way I implemented colors the first time, those vertices are technically generated from an air block but should visually belong to a stone block.

(Ignore the weird glitches in the terrain, that is something I have already fixed, it was with the way I was generating the terrain)

---

# After a few hours of searching:

I found what seems promising in an answer here

```
private static final byte[] BLOCK_PICK_BITS_BY_VERT_INDEX = new byte[]{
    (byte)0x67,
    (byte)0x26,
    (byte)0x23,
    (byte)0x37,
    (byte)0x45,
    (byte)0x04,
    (byte)0x01,
    (byte)0x15,
    (byte)0x57,
    (byte)0x46,
    (byte)0x02,
    (byte)0x13
};

private static final int pickBlockIdForVertex(long blockIds, int vertIndex)
{
    int bits = BLOCK_PICK_BITS_BY_VERT_INDEX[vertIndex];
    int blockIndexA = bits >> 4;
    int blockIndexB = bits & 0xf;
    int blockIdA = (int)(blockIds >> 8 * blockIndexA) & 0xff;
    int blockIdB = (int)(blockIds >> 8 * blockIndexB) & 0xff;

    //assert (blockIdA == airBlockId) != (blockIdB == airBlockId);
    //return blockIdA - nonZeroAirBlockId + blockIdB;
    return blockIdA + blockIdB;
}

```

However the answer doesn't explain how `blockIds` work or how to get `vertIndex`.

I am really at a lost on how to solve this problem, I'd really like *someones* help. I'm sure there are probably other people with the same questions as me, I am honestly surprised there is absolutely no direct documentation on this (at least, to my knowledge there isn't).

I will be reading up on marching cubes and trying to figure out how to maybe implement colors.

---

## I think I'm almost there!

So the answer I linked to in the previous edit, where I said it looked promising, I finally was able to understand *some* of it. And from what I understood I made the code below:

```
    // Because the Marching Cubes implementation I use has some of the least to greatest significant vertex indices swapped, I modified this below to account for that.
    /// Mainly any 7s in the array below were swapped with 6s and the same for 4s and 5s.
    private static byte[] MAT_CHOOSE_BITS = new byte[]{
        0x76,
        0x27,
        0x23,
        0x36,
        0x54,
        0x05,
        0x01,
        0x14,
        0x46,
        0x57,
        0x02,
        0x13
    };

    public Color32 GetMaterialColor(int[] mats, int vert)
    {
        int bits = MAT_CHOOSE_BITS[vert];

        // Because I am indexing an array and not bit-shifting a long I must use `7 - bits`
        int indexA = 7 - (bits >> 4);
        int indexB = 7 - (bits & 0xf);

        return Material.materials[(mats[indexA] + mats[indexB]) - 1].color;
    }

```

The code above ***ALMOST*** works, it's very frustrating. When I run the code, it runs through the loop about 8 times before it encounters an Argument Out Of Bounds Exception, I debugged it and apparently in one of the situations the "mats" array doesn't contain any zeros, which from what I understand shouldn't be possible. The theory behind the code above is that one of the indices (either `indexA` or `indexB`) should point to a zero in the `mats` array, because in theory one side of the equation is *always* zero (or air).

I don't understand what I did wrong... I know at this point it has to be the way I am generating the voxels, it might also still be that code but I need to first solve the issue where none of the ints passed into the mats array is 0.

Here is the code I am using to generate the terrain:

```
        for (int i = 0; i < 16; i++)
        {
            for(int j = 0; j < 256; j++)
            {
                for (int k = 0; k < 16; k++)
                {
                    Voxel v;
                    float d = terrain.noise.Value.GetSimplex(i, j, k);

                    if (d > 0 || Mathf.Approximately(d, 0f)) v.materialId = UnityEngine.Random.Range(1, 3);
                    else v.materialId = 0;

                    v.density = d;

                    data.voxels[i + j * 16 + k * 16 * 256] = v;
                }
            }
        }

```

---

# FAILURE

So I wasn't able to fix this issue, and it seems nobody else on this forum is going to as well. So I decided to go with a much simpler solution, basically, I dropped smoothing the terrain to just binary smoothing. Either a cube is off, or on and there are sharp slopes between that. it makes the terrain look blocky but it's the best solution for how I fixed the vertex colors. I fixed the vertex colors by first checking if the current cube is air, if it is it chooses the material of the first neighbor that isn't air.

If anyone has an answer to this question in the future, I am all ears.

# Answer
# I gave this issue another shot, and I found a solution!

I figure that this will probably be helpful to someone in the future, so I will describe exactly how I did it, I will provide minimal code though, because my solutions code is a tiny bit implementation specific.

---

### Credit Where it is Due

This answer was made possible by this answer here. In fact, my answer is basically just going to explain the stuff I was confused about in the that answer and what I did to fix it for my implementation.

### The code I ended up using

```
    Color SeletColor(Color[] options, int vertIndex)
    {
        int bits = ColorSelectBits[vertIndex];
        int indexA = 7 - (bits >> 4);
        int indexB = 7 - (bits & 0xF);

        Color a = options[indexA], b = options[indexB];

        Color c = new Color
        {
            r = a.r + b.r,
            g = a.g + b.g,
            b = a.b + b.b,
            a = a.a + b.a
        };

        return c;
    }

    private static readonly int[] ColorSelectBits = new int[]
    {
        0x67,
        0x74,
        0x45,
        0x56,
        0x23,
        0x30,
        0x01,
        0x12,
        0x62,
        0x73,
        0x40,
        0x51
    };

```

### An explanation of how I fixed it

So in the answer I linked to, his least to most significant vertex order was different than the Marching Cubes implementation I used.

I was able to fix this thanks to the presence of 2 arrays.

```
    protected static readonly int[,] VertexOffset = new int[,]
    {
        {0, 0, 0},{1, 0, 0},{1, 1, 0},{0, 1, 0},
        {0, 0, 1},{1, 0, 1},{1, 1, 1},{0, 1, 1}
    };

    /// <summary>
    /// EdgeConnection lists the index of the endpoint vertices for each
    /// of the 12 edges of the cube.
    /// edgeConnection[12][2]
    /// </summary>
    private static readonly int[,] EdgeConnection = new int[,]
    {
            {0,1}, {1,2}, {2,3}, {3,0},
            {4,5}, {5,6}, {6,7}, {7,4},
            {0,4}, {1,5}, {2,6}, {3,7}
    };

```

I used `EdgeConnection` to get an index to `VertexOffset`, I then found an index to the opposite of whatever "Vector" (The three floats in the second dimension) that `EdgeConnection` pointed me to, and the index to the opposite is what the first/last 4 bits of an entry of `ColorSelectBits` are.

Here is an example:

`EdgeConnection[0]` is `{0, 1}`

`VertexOffset[0]` is `{0, 0, 0}` the opposite of that is `{1, 1, 1}` so the index I needed was `6`

`VertexOffset[1]` is `{1, 0, 0}` the opposite of that is `{0, 1, 1}` so the index I needed was `7`

That means the value I needed for `ColorSelectBits[0]` is `0x67`
> 1 votes

---
Tags: unity, terrain, voxels, marching-cubes
---


title: Designing mouse-aimed aircraft controls

text:
# Question
Title: Designing mouse-aimed aircraft controls
I am attempting to design mouse-aimed turning to control an aircraft in a 3D environment. To cut it short, you aim where you want to go, and the aircraft turns to face that direction (similar to *War Thunder*).

When turning an aircraft, it makes sense to use your elevator instead of your rudder (especially in long turns). If you need to turn 90 degrees left, it makes sense to roll 90 degrees left first, then use the elevator to turn, finally leveling out the aircraft once the target heading is reached.

Now, I want the user to be able to control the roll, but I also want the game to do it automatically when the player is not controlling it. My problem is conceptualizing what operations I need to do to get the target roll angle.

I managed to figure out that to align myself correctly, I need to align the plane that bisects the aircraft (the **V plane**) with the direction I want to move to (the **D vector**). The **R angle** is how much I would need to turn (in local angles) to achieve the derired orientation.

So, if I the player looks at the blue circle, the plane will roll right and hold that roll until it's almost aligned with the desired direction. At that point, it will unroll and level out.

Just figuring out the roll I need would be a big help. Preferably I'd like to get it done with dot and cross products, as these operations are already established and I have easy access to the up, right and forward vectors of the plane, as well as the direction vector.

# Answer
> 2 votes
While Philipp's suggestion works quite well, it wasn't quite enough for me, so after giving it some thought I found a definitive solution.

Finding the roll angle is actually not that difficult: I start by removing the forward component from the direction vector (**red**). I can then compute the dot product between this vector (**green**) and the world up vector (**purple**) (0,0,1) or (0,1,0), depending on your convention.

The roll angle is the inverse cosine of the result (assuming all vectors are normalized) times the sign of the dot product between the right vector **if the roll were 0** (**purple** vector below) and the **green** vector from the drawing above. This last part defines which side the plane is actually turning to.

In my experience this works flawlessly! The plane aligns itself perfectly with where you want to go.

# Answer
> 2 votes
I once solved the problem in a way that sounds fake but feels surprisingly good:

Mouse controls pitch and yaw, relative to the horizon. Roll is just a visual effect determined automatically by the current angular velocity. In other words, flying a curve makes the plane bank, not the other way around.

---
Tags: game-design, control
---


# Question
Title: How can I load an asset from a file after I exported the build?
I am seeking possibility to switch character textures for game, even after I have compiled and built the binary.

For example I have a troll with a Sprite from "/assets/texture1.png"

Now after the game has been released, I can change this sprite.

Currently I have found this method

```
func _ready():
    var texture = load("res://textures/troll1.png")
    sprite.texture = texture

```

But after the export, when I change the `troll1.png`, the texture in the game remains the same.

# Answer
I have found an answer to my question.

First mistake i did, was that i did not copy my assets folder to my game export folder, so the game never found the assets, pretty dumb...

Also, i will put some methods how to load images without using Godot automatic importer.

The simplest is this method

```
var texture = ImageTexture.new()
    texture.load("textures/troll1.png");
    $Sprite.texture = texture

```

And 2 methods that was posted on reddit

https://www.reddit.com/r/godot/comments/eojih/how\_to\_load\_images\_without\_importer/

```
var file = File.new()
var image = Image.new()

file.open("/path/to/image.png", File.READ)
image.load_png_from_buffer(file.get_buffer(file.get_len()))

file.close()
image.lock()

```

```
var path = "/path/to/image.png"

var file = File.new()
var image = Image.new()

file.open(path, File.READ)
var buffer = file.get_buffer(file.get_len())

match path.get_extension():
    "png":
        image.load_png_from_buffer(buffer)
    "jpg":
        image.load_jpg_from_buffer(buffer)

file.close()
image.lock()

var texture = ImageTexture.new()
    texture.create_from_image(image);
    $Sprite.texture = texture

```
> 1 votes

---
Tags: assets, godot
---


# Question
Title: Unity BoxCollider2D causes motion to be exponentially multiplied
I have a player and an enemy square for my 2D game (technically it's a cube, but it's rendered as a 2D character). I have a RigidBody2D attached to the player and the enemy each, along with a BoxCollider2D, with trigger ticked on both of them. However, when I untick trigger the motion gets multiplied drastically. It appears to be that the trigger being ticked is causing the entire thing to be updated more quickly but I'm not sure. Can someone help?

**FIX** I needed to turn off Auto Mass in the Rigidbody2D. Thanks @DMGregory

Enemy Code:

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

public class enemyController : MonoBehaviour
{

    [Header("Refrences")]
    public GameObject player;
    public GameObject graphicsGameobject;

    [Header("Speeds")]
    public int movementSpeed;
    public float fireRate;

    // Private Refrences
    new private Rigidbody2D rigidbody;

    // Start is called once
    void Start() {
        rigidbody = GetComponent<Rigidbody2D>();
    }

    ////////////
    // MOTION //
    ////////////

    // Return position to face player
    Vector2 getMouseVector()
    {
        // Get mouse pixel position, convert it to world position, subtract
        // from current position vector to get angle, and return as negative Vector2
        // Why negative?  Only way I could get it to work.
        Vector2 myPosition = transform.position; // V3 converted to V2, that's why this line exsists
        return -(myPosition - new Vector2(
            player.transform.position.x,
            player.transform.position.y
        ));
    }

    // Move the player's RigidBody to chase player
    void moveEnemy() {
        Transform ptrans = player.transform;
        if (ptrans.position.y > transform.position.y) // Up
            { rigidbody.AddForce(transform.up * movementSpeed * Time.deltaTime); }
        if (ptrans.position.x > transform.position.x) // Left
            { rigidbody.AddForce(transform.right* movementSpeed * Time.deltaTime); }
        if (ptrans.position.y < transform.position.y) // Down
            { rigidbody.AddForce(transform.up * -movementSpeed * Time.deltaTime); }
        if (ptrans.position.x < transform.position.x ) // Right
            { rigidbody.AddForce(transform.right * -movementSpeed * Time.deltaTime); }
    }

    ////////////
    // UPDATE //
    ////////////

    void Update() {
        graphicsGameobject.transform.up = getMouseVector();
        moveEnemy();
    }

}

```

# Answer
What I’m describing was caused by the Rigidbody2D auto-calculate mass. Just uncheck that box and it should work fine!
> 1 votes

---
Tags: unity, c#, 2d
---


title: Correct way to handle A* no pathing?

text:
# Question
Title: Correct way to handle A* no pathing?
I'm developing a little game for fun and I wrote a pathfinding system based on the A\* algorithm. What is the best or correct way to deal with unavailable paths?

A\* by default will go through every node on the grid until it either finds the target node or it has exhausted all of them. This can become problematic if certain areas are cut off into "islands" and A\* tries to find a path there.

The obvious solution might be to flood fill regions and check in advance, but the problem is that I plan for my world to be a bit dynamic - new areas might appear, some areas which are accessable at one point might not be later, etc.

Another solution I've read about is that I can limit the amount of nodes it's allowed to search before it gives up, but this sounds a bit hacky and something I'd like to avoid if possible if there are better ways, because it means that there could be a very long and complex path to the target but it'll still not find it just because of this limit.

So how should I do it? I appreciate any help here, fellow devs!

# Answer
Normally, if it is possible for there to be isolated sections of your graph, you would want to have an extra parameter for what "set" each node belongs to. All nodes that are connected in the graph have the same set value. Nodes which are not connected in the graph have a different set value. That lets you perform an immediate out by checking if start set != end set.

To add a dynamic connection, you could store a data structure that defines what two sets a particular node connects and its location, as well as if it is active or not. If start set != end set, then you can search for a dynamic connection in your list that connects the two sets and is active.
> 2 votes

# Answer
Having a node limit for your pathfinding is actually a very common thing to have.

If a\* is not good enough for your game, then there are some more advanced solutions you can try, like hierarchical pathfinding or precalculated navigation meshes.
> 1 votes

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


# Question
Title: How can I reference classes from my scripts in my unit tests?
Bit of a noob question, but I'm having trouble getting unit testing working in Unity. I created a PlayMode test assembly, I toggled "Enable playmode tests for all assemblies" as directed in the manual, but when I try to edit the test script, Visual Studio still isn't recognizing references to the classes I've written. There's also no option to manually add a reference within Visual Studio. Am I doing something wrong, or is this some kind of bug? It's hard to imagine what kind of unit testing you could even do without references to your main project.

# Answer
Figured out how to do it. I had to create a new assembly definition in my Scripts folder. (I also moved my Tests folder out of the Scripts folder to be on the safe side.) Then, looking at the Tests assembly definition in the Inspector, I added a new item to the Assembly Definition References list, which I made point to my MainAssembly.
> 1 votes

---
Tags: unity, unit-testing
---


title: Force new players to play tutorial?

text:
# Question
Title: Force new players to play tutorial?
We have released our new game to a closed alpha group. It's a browser-based MMO RTS, however some aspects of the game are slightly different from the "standards" you'd expect to see in traditional RTS' due to it being persistent, browser-based etc. For this reason, we have a new player tutorial which helps players through some aspects of the game that differ from the "norm", such as the way you acquire territory and the way you move large groups of units.

I think that every game I've played has had a "skip tutorial" option during the tutorial, so we put that option in as well. However, this has now caused us a dilemma: looking at the player stats in our database, there is an almost perfect correlation between those players who have played through the tutorial and have progressed through the game, and those who haven't. Basically, if you don't play the tutorial, you pretty much don't know what to do next and stop playing the game after not doing anything meaningful for a few minutes.

I'm really torn here between "best practice" / user experience (which probably dictates that players should have an option to ***not*** play the tutorial), and clear evidence which shows that if players don't play the tutorial, they likely will quit the game early.

Is it reasonable in this situation to "force" players to play the tutorial? I.e., don't give them a "skip tutorial" option? Could we dress it up as "missions", where the first 10 or so missions are compulsory to progress, but actually those "missions" are simply the current tutorial steps?

# Answer
I feel like you should force players to take the tutorial, especially if it isn't a long one. It's better to make people stay longer with the game (by making them understand how to play it) than acually making it daunting for them to play it (by adding that skip button). Also I would advice **against** making the tutorials into missions, as they would be simple. (because they are tutorials) Talking from a player perspective I wouldn't like the first few levels/missions to be basic moves. They should be interesting and entertaining beacause the first few levels/missions are always the ones that will captivate the user or make them hate your game.

Hope this helps:)
> 2 votes

# Answer
A good tutorial is one where the player doesn't realize it's one.

Work on your new user experience to introduce the complexity of the game gradually. After giving the player access to a new game element, give them a trivial and intuitive problem based in that new mechanic. Only let them progress to the next layer of complexity when they solved that problem.
> 13 votes

# Answer
Although I think @Philipp's answer is the way to go, a "quick fix" for your situation could be to still give your player the option to skip the tutorial, or keep on following the tutorial for a *reward*. As they progress through it, make the reward bigger.

And it has to be a meaningful reward, like something that could usually only be obtained through the cash shop, or make it an achievement. Or a hat for their avatar.
> 2 votes

# Answer
For players who replay your game, being forced to go through the tutorial again can be frustrating.

You could find a smart way to propose the tutorial again for users who skipped and don't manage to accomplish anything in the game.
> 0 votes

# Answer
The problem I see by forcing the player to go through the tutorial is:

> how do you actually know you‘re dealing with a new player?

In singleplayer games it is basicly impossible to tell if someone someone is starting a new game or already played through the entire thing before. In Multiplayer/MMO games someone with a fresh account is very likely to be a new player but it‘s not guaranteed. People start new accounts for various reasons. And you need to ask yourself, when you confront a player with a skip option, how likely is it he‘s going to use it if he has no clue about the game yet?

There should always be a skip button for tutorials that just explain the core mechanics of the game.

The best way is to allow skipping and offer a "repeat the tutorial" option for the players that decided to skip it and noticed that it would have been a good idea to play through the tutorial afterwards.
> 0 votes

---
Tags: rts, tutorials, mmorts
---


# Question
Title: Collision with walls in a completely tile based game
I am making a tile based game, in which also the player movement is completely snapped to the grid. Imagine sokoban.

I basically have a 2d array for the layout of the level (walls / not walls), and the player can check is there's a wall where he is going.

My question is, when the player is trying to move into a wall, should I:

1. Let it move into the wall, then later check if it's in a wall and if needed revert it's movement?
2. Check whether it is going to move into a wall and prevent it beforehand?

I understand the answer may heavily depend on the structure of my code, but I'd still like to hear some opinions about how it was done in the past. What do you think? which of the two is better? (or is there a third option)

# Answer
It doesn't matter that much for collisions with static objects. It gets more relevant when you have collisions between moving entities.

Personally I prefer to check first and move when the destination is valid, because it prevents two problems:

1. You don't have to remember where the entity moved from
2. You never have an entity in an illegal position
> 1 votes

---
Tags: collision-detection, tiles
---


# Question
Title: How to create a new civilization mod for Age of Empires 1 Definitive Edition?
I want to make a mod for Age of Empires 1 Definitive Edition, in which I split an existing civilization (Phoenicians) into two civilizations:

* **Eastern Phoenicians:** Primarily representing Canaanites
* **Western Phoenicians:** Primarily representing Carthaginians

I want to do so to fix an historical mistake in the development of AOE1 in which the Phoenician tech tree includes war elephants:
As far as I know --- none of the Eastern Phoenicians regularly used war Elephants in their armies:

**Eastern Phoenicians from north to south and west to east:**

```
Kingdom of Ugarit | Mittani polities
Kingdom of Tyre   | Kingdom of Aram-Damascus
Kingdom of Israel | Kingdom of Ammon
Kingdom of Judah  | Kingdom of Moab
Kingdom of Edom   | Nabataean polities

```

## My problem

As a webmaster coding primarily in *Bash-HTML-CSS-JavaScript-Wiki-Markdown* stack who never wrote a GUI program with languages common for the task (such as XML, C++, C# and others) I have no idea where to start.

## My question

How to create a new civilization mod for Age of Empires 1 Definitive Edition?

# Answer
> 3 votes
*I do not have this game, cannot test if it works correctly.*

I suggest the open source tool Advanced Genie Editor 2019. (github repository).

On the linked website it says:

> **Advanced Genie Editor**
>
> for Age of Empires, Rise of Rome, Age of Kings, The Conquerors (including HD), Star Wars Galactic Battlegrounds and Clone Campaigns.
>
> This is a program for editing data of genie (DAT and DLL) files. It can edit properties of units, civilizations, technologies, graphics, terrains, sounds, player colors and some other things.

---

## Definitive Edition

It should work with the 2018 *Definitive Edition* if you select this version on the Genie version drop down list when opening files, as pictured below:

*Advanced Genie Editor "Open files..." dialog*

The application has support for editing tech trees among other things:

*Advanced Genie Editor main window, Tech Trees tab, no file open.*

That should allow you to remove access to particular units for given civilizations. Remember to backup your dat files.

I found this tool linked from aoe.heavengames.com. *I did not see any real alternatives while searching.*

---

### Update

I tried the tool on a friend's copy of the game. I had to put the path to the dat file manually. There is no language.dll file, so untick that when opening. There is an option to copy a civilization (on the "Civilizations" tab), and to disable units to particular civilizations (on the "Units" tab). However, editing the tech tree for a particular civilization was not available (there was no "Tech trees" tab).

---
Tags: modding, steam
---


# Question
Title: Godot 3.1.2: Black lines / borders around Sprite
In Godot 3.1.2 using OpenGL ES2, black borders/ lines seem to form around some sprites I have imported. Usually they appear on top of the sprite but can also "border" around it.

Being new to Godot development but coming from Unity I expect I did something wrong in the import or that the texture settings aren't set correctly. But so far I haven't been able to find any setting that resolves this issue.

So my question is: where can I find texture/image settings that can resolve this issue? Or if the issue stems from another source, how can I make sure that the images are being displayed without the black lines? (Bonus question: Is there also a way/ setting to display tiles in the Y-Axis non-blurry?)

(I'm pretty new to Stack Exchange/ GameDev so if my question is missing some details please let me know :) )

# Answer
> 3 votes
**Edit:** To remove the border around the sprite turns out there is an option in the Import Menu for the asset. In this menu change the ***Repeat*** Flag Setting to *Disabled*. Make sure to Reimport the asset after setting this the lines are no longer displayed around the image.

(Import menu Viewable by selecting the image file and then checking the import tab, located at the left dock next to the scene tab)

**Original:** Turns out you need to put some empty (transparent) space around your assets, to make sure no lines appear. Putting around 10 pixels of empty space around every side of the image will do the trick.

---
Tags: sprites, opengl-es2, assets, godot
---


# Question
Title: What does it mean to "release" a game in a country?
I would like to understand what is the meaning of releasing (or not) a game in a particular country.

See for instance the case of Halo 2. According to this source the game was released in a set of countries (e.g., USA, Germany). I wonder about countries where the game was not 'officially' released. Does it mean that Mexico's market will receive a Halo 2 version that is not localized?

What happens when a game is not officially released in a specific country?

# Answer
It’s a bit simpler than that. If you have not released a game in a certain country, it is not available to purchase in that country. These days, you can always import it, through eg. Amazon, but you won’t find it in any retail or digital store. Before the prevalence of online retailers like Amazon, importing was a much more difficult prospect.

Note that imported copies of console games from another country may be region locked, meaning they only run on a console manufactured for that region, so you would also need to import a whole console just to play that game. These days region locking is artificial, mostly for business reasons, but in ye olden days, it was (also?) for technical reasons, due to the differences between NTSC and PAL televisions. You might have needed to import a custom television set while you were at it.

In the case of Halo 2 specifically, however, the information you linked to is incomplete. The date listed for release in the US is actually its release date for all of North America, including Mexico. See here:

https://en.m.wikipedia.org/wiki/Halo\_2

Whether it has localization is up to the developer/publisher, and is not necessarily related to releasing it in a certain country/region.
> 3 votes

# Answer
Nowadays, in the era of digital distribution, it is more work to limit the regional availability of a title than to release it internationally. Sometimes there can be business or legal reasons to make a title unavailable in certain regions, but that's rather the exception than the norm. There are very few countries you can not reach by simply putting your game on a digital distribution platform like Steam or Google Play. (One exception is China, for example. You need to get government-approval to publish there, and they don't give that to everyone).

But back in the age of physical distribution, that was different. It used to be quite a lot of work to establish the logistics to get the copies of a game to a country and to convince the local retail chains to stock it. It also involved a lot of economic risk. Manufacturing physical copies and not selling them caused a considerable financial loss. So when publishers weren't expecting to sell a lot of copies in a country, they just wouldn't go through the trouble to release there.

Halo 2 was released in the age where physical distribution was the major way to buy games, especially in the console market.
> 1 votes

---
Tags: game-industry, release
---


# Question
Title: OpenGL concatenate vertex data into one big VBO
I successfully can render two triangles (with a texture) that looks like the side of a crate and also "walk" around it. Also, a small .obj file parser is available which gives me a float array of the vertices, texture coords and an unsigned int array of the indices (of a simple cube).

The vertices and texture coords look like the following:

```
float vertices[] =
{
     // positions         // texture coords
     0.5f,  0.5f, 0.0f,   1.0f, 1.0f,
     0.5f, -0.5f, 0.0f,   1.0f, 0.0f,
    -0.5f, -0.5f, 0.0f,   0.0f, 0.0f,
    -0.5f,  0.5f, 0.0f,   0.0f, 1.0f
};

```

And the indices:

```
unsigned int indices[] =
{
    0, 1, 3, // first triangle
    1, 2, 3  // second triangle
};

```

To assign the vertices and tex coords I use the following:

```
unsigned int VBO;
glGenBuffers( 1, &VBO );
glBindBuffer( GL_ARRAY_BUFFER, VBO );
glBufferData( GL_ARRAY_BUFFER, 5 * 4 * sizeof( float ), vertices, GL_STATIC_DRAW );

```

Creating an IBO

call `glEnableVertexAttribArray()`
`glVertexAttribPointer()`

Creating a shader, a texture etc.. and draw it with `glDrawElements()`.

This works all very well, I just can't wrap my head around how to use just a single VBO with the "split" data that my .obj parser gives back.
I now (when using the .obj parser) have the vertices and texture coords separated; how do I put that two arrays into one VBO?

The picture I have in mind is to have fewer draw calls and also prevent redundant code if I, for example, use the same model for 100 times.

# Answer
As I'm now a bit more advanced with OpenGL, I can tell that I couldn't express what I was looking for. What I was really looking for was a way to draw multiple objects in a performance saving way, i.e. batch rendering or instancing.

I solved my problem in choosing instanced rendering. It roughly boils down to:

* Set up everything as usual
* Specify a mat4 attribute for the position of each object in your shader
* Submit the data to the shader (make sure to specify `GL_STREAM_DRAW` in the `glBufferData()` function
* Here's how I do it, but this should be put into a separate class to make it more flexible to use for other attributes:

```
// Set transform attribute
p_int modelMatrixLocation_0 = MeshCollection->m_UsedShaders[m_ShaderName]->GetAttribLocation( "a_ModelMatrix" );
p_int modelMatrixLocation_1 = modelMatrixLocation_0 + 1;
p_int modelMatrixLocation_2 = modelMatrixLocation_0 + 2;
p_int modelMatrixLocation_3 = modelMatrixLocation_0 + 3;

if ( modelMatrixLocation_0 != -1 )
{
    Platf::glBindBuffer( GL_ARRAY_BUFFER, m_ModelMatrixID );
    Platf::glBufferData( GL_ARRAY_BUFFER, m_ModelMatrix.size() * sizeof( Maths::mat4 ), &m_ModelMatrix[0][0], GL_STREAM_DRAW );

    Platf::glEnableVertexAttribArray( modelMatrixLocation_0 ) ;
    Platf::glVertexAttribPointer( modelMatrixLocation_0, 4, GL_FLOAT, GL_FALSE, sizeof( Maths::mat4 ), ( const void * )( 0 * sizeof( Maths::vec4 ) ) );

    Platf::glEnableVertexAttribArray( modelMatrixLocation_1 ) ;
    Platf::glVertexAttribPointer( modelMatrixLocation_1, 4, GL_FLOAT, GL_FALSE, sizeof( Maths::mat4 ), ( const void * )( 1 * sizeof( Maths::vec4 ) ) );

    Platf::glEnableVertexAttribArray( modelMatrixLocation_2 ) ;
    Platf::glVertexAttribPointer( modelMatrixLocation_2, 4, GL_FLOAT, GL_FALSE, sizeof( Maths::mat4 ), ( const void * )( 2 * sizeof( Maths::vec4 ) ) );

    Platf::glEnableVertexAttribArray( modelMatrixLocation_3 ) ;
    Platf::glVertexAttribPointer( modelMatrixLocation_3, 4, GL_FLOAT, GL_FALSE, sizeof( Maths::mat4 ), ( const void * )( 3 * sizeof( Maths::vec4 ) ) );

    Platf::glVertexAttribDivisor( modelMatrixLocation_0, 1 );
    Platf::glVertexAttribDivisor( modelMatrixLocation_1, 1 );
    Platf::glVertexAttribDivisor( modelMatrixLocation_2, 1 );
    Platf::glVertexAttribDivisor( modelMatrixLocation_3, 1 );
}

```
* Then in the shader calculate it like that gl\_Position = u\_ProjectionViewMatrix * a\_ModelMatrix * vec4( a\_InVertexPosition, 1.0f );
* And finally, call Platf::glDrawElementsInstanced( GL\_TRIANGLES, \_IndeciesCount, GL\_UNSIGNED\_INT, nullptr, \_InstancedCount )

There are some really good tutorials on this subject, for example, this one at learnopengl.com:
https://learnopengl.com/Advanced-OpenGL/Instancing

As for batch rendering, I've found these two tutorials which should give a basic knowledge of how to implement it:
http://craiggiles.wordpress.com/2009/08/03/opengl-es-batch-rendering-on-the-iphone/
https://www.youtube.com/watch?v=ImtWD\_9OAeY
> 0 votes

---
Tags: opengl, vbo
---


# Question
Title: Same noise generator for C# and Javascript
I'm writing a 2D web racing game with procedural generated maps using perlin noise(as a university project). The server is written using C# and the client using Javascript. I've developed procedural generating of maps on the server but I've realized that's so time consuming. I've thought that players can generate maps and the server can validate some key points so server doesn't have to do both. The problem is that I don't know how to generate same map on the client (in JS) and the same map on the server (in C#). I've read some about deterministic random number generators which are platform independent. But I'm not sure how to search noise generators with them. Do you know where can I find some, especially in programming languages I'm using? Do I have to write own noise generator?

# Answer
I was expecting that it was trivial to seed the javascript pseudo-random number generator. Turns out you can't, at least not in any standard portable way.

Alright, we are going to implement one. The following is `mulberry32` in JavaScript:

```
function mulberry32(a) {
    return function() {
      a |= 0; a = a + 0x6D2B79F5 | 0;
      var t = Math.imul(a ^ a >>> 15, 1 | a);
      t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
      return ((t ^ t >>> 14) >>> 0) / 4294967296;
    }
}

```

Taken from bryc/code.

It is very easy to use, just initialize with the seed. It is also very fast. I have taken the liberty to translate this to (ideomatic) C#:

```
public sealed class Mulberry32
{
    private uint _seed;

    public Mulberry32(int seed)
    {
        _seed = (uint)seed;
    }

    public double Next()
    {
        _seed += 0x6D2B79F5;
        var t = (_seed ^ (_seed >> 15)) * (1 | _seed);
        t = (t + ((t ^ (t >> 7)) * (61 | t))) ^ t;
        return (t ^ (t >> 14)) / (double)4294967296;
    }
}

```

In fact, I went back and rewrote `Mulberry32` a bit:

```
function Mulberry32(seed) {
    "use strict";
    return {
        next: function () {
            seed |= 0; seed = seed + 0x6D2B79F5 | 0;
            var t = Math.imul(seed ^ seed >>> 15, 1 | seed);
            t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
            return ((t ^ t >>> 14) >>> 0) / 4294967296;
        }
    };
}

```

---

Now, what you need to do is generate a seed on the server and send it to the client. *It could be `DateTime.Now.GetHashCode()` or something like that*. If both client and server use the same value, they should generate the same pseudo-random numbers.

I do not know how your noise code looks like... however you should be able to update it to use your new random number generator. It could be that the generator you have has it own seeding mechanism that we got to identify and replace (probably a `seed` function).

Assuming your noise generator uses generic random...

On C# replace this code:

```
var random = new Random(/*seed*/);
var x = random.NextDouble();

```

With this:

```
var random = new Mulberry32(seed);
var x = random.Next();

```

Make sure to add the seed you generated. The same that you send to the client.

On JavaScript replace this code:

```
var x = Math.random();

```

With this:

```
var random = new Mulberry32(seed);
var x = random.next();

```

Make sure to pass the seed you got from the server. Please note that `mulberry32(seed)` is initialization, and you are meant to do that only once, and continue using the function it returns as if it were `Math.random`. Similary to how in C# you initialize your `random` object and reuse it.

---

I had a look to some nice to use and easy to modify perlin noise solution for javascript... found this one: esimov/perlin.js. We have to replace `seed`.

Ern... be honest with you, I decided to port it to C#, and then back to JavaScript. *I suppose I could just have ported that javascript to C# along with its `seed` method, forget that I already had ported the pseudo-random number generator... Instead I decided to pass the pseudo-random number generator in the constructor.*

This is C#:

```
public sealed class Perlin
{
    private readonly int[][] _grad3 =
    {
        new[]{1, 1, 0}, new[]{-1, 1, 0}, new[]{1, -1, 0}, new[]{-1, -1, 0},
        new[]{1, 0, 1}, new[]{-1, 0, 1}, new[]{1, 0, -1}, new[]{-1, 0, -1},
        new[]{0, 1, 1}, new[]{0, -1, 1}, new[]{0, 1, -1}, new[]{0, -1, -1}
    };

    private readonly double _inverseMaximumPersistence;
    private readonly double[] _octaveFrequency;
    private readonly double[] _octavePersistence;
    private readonly int _octaves;
    private readonly byte[] _p = new byte[256];
    private readonly byte[] _perm = new byte[512];

    public Perlin(Func<double> random, int octaves, double persistence)
    {
        if (random == null)
        {
            throw new ArgumentNullException(nameof(random));
        }

        for (var i = 0; i < 256; i++)
        {
            _p[i] = (byte)Math.Abs(Math.Truncate(random() * 256));
        }

        // To remove the need for index wrapping, double the permutation table length
        for (var j = 0; j < 512; j++)
        {
            _perm[j] = _p[j & 255];
        }

        _octaves = octaves;
        _octaveFrequency = new double[_octaves];
        _octavePersistence = new double[_octaves];

        double maximumPersistence = 0;
        for (var octaveIndex = 0; octaveIndex < _octaves; octaveIndex++)
        {
            var addedPersistence = Math.Pow(persistence, octaveIndex);
            maximumPersistence += addedPersistence;
            _octaveFrequency[octaveIndex] = Math.Pow(2, octaveIndex);
            _octavePersistence[octaveIndex] = addedPersistence;
        }

        _inverseMaximumPersistence = 2 / maximumPersistence;
    }

    public double Noise2D(double x, double y)
    {
        var result = 0.0;
        for (var index = 0; index < _octaves; index++)
        {
            var frequency = _octaveFrequency[index];
            result += _octavePersistence[index] * SimplexNoise2D(frequency * x, frequency * y);
        }

        return ((result * _inverseMaximumPersistence) + 0.8) * 0.5;
    }

    public double Noise3D(double x, double y, double z)
    {
        var result = 0.0;
        for (var index = 0; index < _octaves; index++)
        {
            var frequency = _octaveFrequency[index];
            result += _octavePersistence[index] * SimplexNoise3D(frequency * x, frequency * y, frequency * z);
        }

        return ((result * _inverseMaximumPersistence) + 0.8) * 0.5;
    }

    // Return the dot product for 2d perlin noise
    private static double Dot2(int[] g, double x, double y)
    {
        return (g[0] * x) + (g[1] * y);
    }

    // Return the dot product for 3d perlin noise
    private static double Dot3(int[] g, double x, double y, double z)
    {
        return (g[0] * x) + (g[1] * y) + (g[2] * z);
    }

    private static double Fade(double t)
    {
        return t * t * t * ((t * ((t * 6.0) - 15.0)) + 10.0);
    }

    private static double Lerp(double a, double b, double t)
    {
        return ((1.0 - t) * a) + (t * b);
    }

    // 2D Simplex Noise
    private double SimplexNoise2D(double x, double y)
    {
        // Find unit grid cell containing point
        var cellX = (int)Math.Floor(x) & 255;
        var cellY = (int)Math.Floor(y) & 255;

        // Get relative xyz coordinates of point within that cell
        x -= Math.Floor(x);
        y -= Math.Floor(y);

        var u = Fade(x);
        var v = Fade(y);

        // Calculate a set of four hashed gradient indices
        var n00 = _perm[cellX + _perm[cellY]] % 12;
        var n01 = _perm[cellX + _perm[cellY + 1]] % 12;
        var n10 = _perm[cellX + 1 + _perm[cellY + 1]] % 12;
        var n11 = _perm[cellX + 1 + _perm[cellY + 1]] % 12;

        // Calculate noise contributions from each of the four corners
        var gi00 = Dot2(_grad3[n00], x, y);
        var gi01 = Dot2(_grad3[n01], x, y - 1);
        var gi10 = Dot2(_grad3[n10], x - 1, y);
        var gi11 = Dot2(_grad3[n11], x - 1, y - 1);

        // Interpolate the results along axises
        return Lerp
        (
            Lerp(gi00, gi10, u),
            Lerp(gi01, gi11, u),
            v
        );
    }

    // 3D Simplex Noise
    private double SimplexNoise3D(double x, double y, double z)
    {
        // Find unit grid cell containing point
        var cellX = (int)Math.Floor(x) & 255;
        var cellY = (int)Math.Floor(y) & 255;
        var cellZ = (int)Math.Floor(z) & 255;

        // Get relative xyz coordinates of point within that cell
        x -= Math.Floor(x);
        y -= Math.Floor(y);
        z -= Math.Floor(z);

        var u = Fade(x);
        var v = Fade(y);
        var w = Fade(z);

        // Calculate a set of eight hashed gradient indices
        var n000 = _perm[cellX + _perm[cellY + _perm[cellZ]]] % 12;
        var n001 = _perm[cellX + _perm[cellY + _perm[cellZ + 1]]] % 12;
        var n010 = _perm[cellX + _perm[cellY + 1 + _perm[cellZ]]] % 12;
        var n011 = _perm[cellX + _perm[cellY + 1 + _perm[cellZ + 1]]] % 12;
        var n100 = _perm[cellX + 1 + _perm[cellY + _perm[cellZ]]] % 12;
        var n101 = _perm[cellX + 1 + _perm[cellY + _perm[cellZ + 1]]] % 12;
        var n110 = _perm[cellX + 1 + _perm[cellY + 1 + _perm[cellZ]]] % 12;
        var n111 = _perm[cellX + 1 + _perm[cellY + 1 + _perm[cellZ + 1]]] % 12;

        // Calculate noise contributions from each of the eight corners
        var gi000 = Dot3(_grad3[n000], x, y, z);
        var gi001 = Dot3(_grad3[n001], x, y, z - 1);
        var gi010 = Dot3(_grad3[n010], x, y - 1, z);
        var gi011 = Dot3(_grad3[n011], x, y - 1, z - 1);
        var gi100 = Dot3(_grad3[n100], x - 1, y, z);
        var gi101 = Dot3(_grad3[n101], x - 1, y, z - 1);
        var gi110 = Dot3(_grad3[n110], x - 1, y - 1, z);
        var gi111 = Dot3(_grad3[n111], x - 1, y - 1, z - 1);

        // Interpolate the results along axises
        return Lerp
        (
            Lerp
            (
                Lerp(gi000, gi100, u),
                Lerp(gi001, gi101, u),
                w
            ),
            Lerp
            (
                Lerp(gi010, gi110, u),
                Lerp(gi011, gi111, u),
                w
            ),
            v
        );
    }
}

```

Usage in C#:

```
// seed: 5646
var random = new Mulberry32(5646);
// 3 octaves
// 0.2 persistence
var perlin = new Perlin(random.Next, 3, 0.2);
// x = 0.5, y = 0.1
Console.WriteLine(perlin.Noise2D(0.5, 0.1)); // output: 0.221234322580645

```

This is JavaScript:

```
function Perlin(random, octaves, persistence) {
    "use strict";
    if (typeof(random) !== "function") {
        throw "argument `random` should be a function";
    }

    let _grad3 = [[1, 1, 0], [-1, 1, 0], [1, -1, 0], [-1, -1, 0], [1, 0, 1], [-1, 0, 1], [1, 0, -1], [-1, 0, -1], [0, 1, 1], [0, -1, 1], [0, 1, -1], [0, -1, -1]];
    let _p = new Uint8Array(256);
    let _perm = new Uint8Array(512);

    let i = 0;
    while (i < 256) {
        _p[i] = (Math.abs((random() * 256) | 0)) | 0;
        i = ((i + 1) | 0);
    }

    let j = 0;
    while (j < 512) {
        _perm[j] = (_p[(j & 255)] | 0);
        j = ((j + 1) | 0);
    }

    let _octaves = (octaves | 0);
    let _octaveFrequency = new Float64Array(_octaves);
    let _octavePersistence = new Float64Array(_octaves);

    let maximumPersistence = 0;
    let octaveIndex = 0;
    while (octaveIndex < _octaves) {
        let addedPersistence = (Math.pow(+persistence, octaveIndex));
        maximumPersistence += addedPersistence;
        _octaveFrequency[octaveIndex] = (Math.pow(2, octaveIndex));
        _octavePersistence[octaveIndex] = addedPersistence;
        octaveIndex = ((octaveIndex + 1) | 0);
    }

    let _inverseMaximumPersistence = +(2 / maximumPersistence);

    function dot2(g, x, y) {
        return (((g[0]) * x) + ((g[1]) * y));
    }

    function dot3(g, x, y, z) {
        return ((((g[0]) * x) + ((g[1]) * y)) + ((g[2]) * z));
    }

    function fade(t) {
        return (((t * t) * t) * ((t * ((t * 6) - 15)) + 10));
    }

    function lerp(a, b, t) {
        return (((1 - t) * a) + (t * b));
    }

    function simplexNoise2D(x, y) {
        let cellX = ((Math.floor(x)) | 0) & 255;
        let cellY = ((Math.floor(y)) | 0) & 255;
        x -= (Math.floor(x));
        y -= (Math.floor(y));
        let u = fade(x);
        let v = fade(y);
        let n0 = (((_perm[((cellX + (_perm[cellY] | 0)) | 0)] | 0) % 12) & 0xFF);
        let n = (((_perm[((cellX + (_perm[((cellY + 1) | 0)] | 0)) | 0)] | 0) % 12) & 0xFF);
        let n2 = (((_perm[((((cellX + 1) | 0) + (_perm[((cellY + 1) | 0)] | 0)) | 0)] | 0) % 12) & 0xFF);
        let n3 = (((_perm[((((cellX + 1) | 0) + (_perm[((cellY + 1) | 0)] | 0)) | 0)] | 0) % 12) & 0xFF);
        let gi0 = dot2(_grad3[n0], x, y);
        let gi = dot2(_grad3[n], x, y - 1);
        let gi2 = dot2(_grad3[n2], x - 1, y);
        let gi3 = dot2(_grad3[n3], x - 1, y - 1);
        return lerp(
            lerp(gi0, gi2, u),
            lerp(gi, gi3, u),
            v
        );
    }

    function simplexNoise3D(x, y, z) {
        let cellX = ((Math.floor(x)) | 0) & 255;
        let cellY = ((Math.floor(y)) | 0) & 255;
        let cellZ = ((Math.floor(z)) | 0) & 255;
        x -= (Math.floor(x));
        y -= (Math.floor(y));
        z -= (Math.floor(z));
        let u = fade(x);
        let v = fade(y);
        let w = fade(z);
        let n0 = (((_perm[((cellX + (_perm[((cellY + (_perm[cellZ] | 0)) | 0)] | 0)) | 0)] | 0) % 12) & 0xFF);
        let n = (((_perm[((cellX + (_perm[((cellY + (_perm[((cellZ + 1) | 0)] | 0)) | 0)] | 0)) | 0)] | 0) % 12) & 0xFF);
        let n2 = (((_perm[((cellX + (_perm[((((cellY + 1) | 0) + (_perm[cellZ] | 0)) | 0)] | 0)) | 0)] | 0) % 12) & 0xFF);
        let n3 = (((_perm[((cellX + (_perm[((((cellY + 1) | 0) + (_perm[((cellZ + 1) | 0)] | 0)) | 0)] | 0)) | 0)] | 0) % 12) & 0xFF);
        let n4 = (((_perm[((((cellX + 1) | 0) + (_perm[((cellY + (_perm[cellZ] | 0)) | 0)] | 0)) | 0)] | 0) % 12) & 0xFF);
        let n5 = (((_perm[((((cellX + 1) | 0) + (_perm[((cellY + (_perm[((cellZ + 1) | 0)] | 0)) | 0)] | 0)) | 0)] | 0) % 12) & 0xFF);
        let n6 = (((_perm[((((cellX + 1) | 0) + (_perm[((((cellY + 1) | 0) + (_perm[cellZ] | 0)) | 0)] | 0)) | 0)] | 0) % 12) & 0xFF);
        let n7 = (((_perm[((((cellX + 1) | 0) + (_perm[((((cellY + 1) | 0) + (_perm[((cellZ + 1) | 0)] | 0)) | 0)] | 0)) | 0)] | 0) % 12) & 0xFF);
        let gi0 = dot3(_grad3[n0], x, y, z);
        let gi = dot3(_grad3[n], x, y, z - 1);
        let gi2 = dot3(_grad3[n2], x, y - 1, z);
        let gi3 = dot3(_grad3[n3], x, y - 1, z - 1);
        let gi4 = dot3(_grad3[n4], x - 1, y, z);
        let gi5 = dot3(_grad3[n5], x - 1, y, z - 1);
        let gi6 = dot3(_grad3[n6], x - 1, y - 1, z);
        let gi7 = dot3(_grad3[n7], x - 1, y - 1, z - 1);
        return lerp(
            lerp(
                lerp(gi0, gi4, u),
                lerp(gi, gi5, u),
                w
            ),
            lerp(
                lerp(gi2, gi6, u),
                lerp(gi3, gi7, u),
                w
            ),
            v
        );
    }

    return {
        noise2D: function (x, y) {
            let _x = +x;
            let _y = +y;
            let result = 0;

            let index = 0;
            while (index < (_octaves | 0)) {
                let frequency = _octaveFrequency[index];
                result += _octavePersistence[index] * simplexNoise2D(frequency * _x, frequency * _y);
                index = ((index + 1) | 0);
            }

            return (((result * _inverseMaximumPersistence) + 0.8) * 0.5);
        },
        noise3D: function (x, y, z) {
            let _x = +x;
            let _y = +y;
            let _z = +z;
            let result = 0;

            let index = 0;
            while (index < (_octaves | 0)) {
                let frequency = _octaveFrequency[index];
                result += _octavePersistence[index] * simplexNoise3D(frequency * _x, frequency * _y, frequency * _z);
                index = ((index + 1) | 0);
            }

            return (((result * _inverseMaximumPersistence) + 0.8) * 0.5);
        }
    };
}

```

Usage in JavaScript:

```
// seed: 5646
var random = new Mulberry32(5646);
// 3 octaves
// 0.2 persistence
var perlin = new Perlin(random.next, 3, 0.2);
// x = 0.5, y = 0.1
console.log(perlin.noise2D(0.5, 0.1)); // output: 0.22123432258064518

```

---

Hmmm... Let us compare the values:

```
C#:         0.221234322580645
JavaScript: 0.22123432258064518

```

Yeah, this is an obstacle if you want to sample the noise to compare it. I tested on a large range of numbers, and apparently they they match up to 13 places after the decimal point (some values one or two digits more).
> 1 votes

# Answer
Your first problem doing this would be with JavaScript. It doesn't really have a deterministic, seedable random number generator. (Deterministic means it produces the same array of values every time you use it given the same starting conditions, seedable means you can set those starting conditions).

C# does have this, when you create a new Random object you can pass in a seed. Try setting it to something, it will produce the same results every time you run it (e.g. `var rand = new Random(1337);`)

So the first thing you'll have to do is either to reimplement the algorithm in JS (for more info, look here) or to implement a different algorithm in both languages (they're surprisingly simple if you give them some thought).

After this you'll have to implement your noise function using this random number generator in both languages. If everything is correct, they should generate the same values.

## Alternatives

Firstly, if I were you, I would ditch C# and go with Node.js if possible. It allows you to use the exact same code (and given Chromiums very alarming growth rate, probably the exact same JavaScript engine), which basically guarantees the exact same output (almost, you'll still need a new random number generator, but there are readily available options).

Secondly, if the noise generator algorithm is your own, I would try looking for ways to speed it up. You could also use one, which has been thoroughly tested to be fast enough for modern games, such as Perlin noise (Ken Perlin still has the original source code on his university site written in Java, which is really just 3 steps from C#. It's also very compact. You'll have to shuffle the permutation array using the random number generator to randomize the output. There's a great shuffling algorithm described here)
> 0 votes

---
Tags: c#, javascript, procedural-generation, perlin-noise
---


# Question
Title: How to Bring the Scene View Camera Controls into Game View
I've got a scene with a big sphere in the centre (the Earth) and a lot of smaller spheres around (the stars).

Above is a screengrab in Scene View with the camera in the Front View position.

I really like the controls in Unity's Scene View when moving around the viewport and I was wondering whether it can be brought into the Game View.

How can I do this?

# Answer
You know what? I will be generous. Here is a a script made by unity that pretty much does this for you. Enjoy.

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

namespace UnityEngine.Rendering
{
    [HelpURL(Documentation.baseURL + Documentation.version + Documentation.subURL + "Free-Camera" + Documentation.endURL)]
    [ExecuteAlways]
    public class FreeCamera : MonoBehaviour
    {
        public float m_LookSpeedController = 120f;
        public float m_LookSpeedMouse = 10.0f;
        public float m_MoveSpeed = 10.0f;
        public float m_MoveSpeedIncrement = 2.5f;
        public float m_Turbo = 10.0f;

        private static string kMouseX = "Mouse X";
        private static string kMouseY = "Mouse Y";
        private static string kRightStickX = "Controller Right Stick X";
        private static string kRightStickY = "Controller Right Stick Y";
        private static string kVertical = "Vertical";
        private static string kHorizontal = "Horizontal";

        private static string kYAxis = "YAxis";
        private static string kSpeedAxis = "Speed Axis";

        void OnEnable()
        {
            RegisterInputs();
        }

        void RegisterInputs()
        {
#if UNITY_EDITOR
            List<InputManagerEntry> inputEntries = new List<InputManagerEntry>();

            // Add new bindings
            inputEntries.Add(new InputManagerEntry { name = kRightStickX, kind = InputManagerEntry.Kind.Axis, axis = InputManagerEntry.Axis.Fourth, sensitivity = 1.0f, gravity = 1.0f, deadZone = 0.2f });
            inputEntries.Add(new InputManagerEntry { name = kRightStickY, kind = InputManagerEntry.Kind.Axis, axis = InputManagerEntry.Axis.Fifth, sensitivity = 1.0f, gravity = 1.0f, deadZone = 0.2f, invert = true });

            inputEntries.Add(new InputManagerEntry { name = kYAxis, kind = InputManagerEntry.Kind.KeyOrButton, btnPositive = "page up", altBtnPositive = "joystick button 5", btnNegative = "page down", altBtnNegative = "joystick button 4", gravity = 1000.0f, deadZone = 0.001f, sensitivity = 1000.0f });

            inputEntries.Add(new InputManagerEntry { name = kSpeedAxis, kind = InputManagerEntry.Kind.KeyOrButton, btnPositive = "home", btnNegative = "end", gravity = 1000.0f, deadZone = 0.001f, sensitivity = 1000.0f });
            inputEntries.Add(new InputManagerEntry { name = kSpeedAxis, kind = InputManagerEntry.Kind.Axis, axis = InputManagerEntry.Axis.Seventh, gravity = 1000.0f, deadZone = 0.001f, sensitivity = 1000.0f });

            InputRegistering.RegisterInputs(inputEntries);
#endif
        }

        void Update()
        {
            // If the debug menu is running, we don't want to conflict with its inputs.
            if (DebugManager.instance.displayRuntimeUI)
                return;

            float inputRotateAxisX = 0.0f;
            float inputRotateAxisY = 0.0f;
            if (Input.GetMouseButton(1))
            {
                inputRotateAxisX = Input.GetAxis(kMouseX) * m_LookSpeedMouse;
                inputRotateAxisY = Input.GetAxis(kMouseY) * m_LookSpeedMouse;
            }
            inputRotateAxisX += (Input.GetAxis(kRightStickX) * m_LookSpeedController * Time.deltaTime);
            inputRotateAxisY += (Input.GetAxis(kRightStickY) * m_LookSpeedController * Time.deltaTime);

            float inputChangeSpeed = Input.GetAxis(kSpeedAxis);
            if (inputChangeSpeed != 0.0f)
            {
                m_MoveSpeed += inputChangeSpeed * m_MoveSpeedIncrement;
                if (m_MoveSpeed < m_MoveSpeedIncrement) m_MoveSpeed = m_MoveSpeedIncrement;
            }

            float inputVertical = Input.GetAxis(kVertical);
            float inputHorizontal = Input.GetAxis(kHorizontal);
            float inputYAxis = Input.GetAxis(kYAxis);

            bool moved = inputRotateAxisX != 0.0f || inputRotateAxisY != 0.0f || inputVertical != 0.0f || inputHorizontal != 0.0f || inputYAxis != 0.0f;
            if (moved)
            {
                float rotationX = transform.localEulerAngles.x;
                float newRotationY = transform.localEulerAngles.y + inputRotateAxisX;

                // Weird clamping code due to weird Euler angle mapping...
                float newRotationX = (rotationX - inputRotateAxisY);
                if (rotationX <= 90.0f && newRotationX >= 0.0f)
                    newRotationX = Mathf.Clamp(newRotationX, 0.0f, 90.0f);
                if (rotationX >= 270.0f)
                    newRotationX = Mathf.Clamp(newRotationX, 270.0f, 360.0f);

                transform.localRotation = Quaternion.Euler(newRotationX, newRotationY, transform.localEulerAngles.z);

                float moveSpeed = Time.deltaTime * m_MoveSpeed;
                if (Input.GetMouseButton(1))
                    moveSpeed *= Input.GetKey(KeyCode.LeftShift) ? m_Turbo : 1.0f;
                else
                    moveSpeed *= Input.GetAxis("Fire1") > 0.0f ? m_Turbo : 1.0f;
                transform.position += transform.forward * moveSpeed * inputVertical;
                transform.position += transform.right * moveSpeed * inputHorizontal;
                transform.position += Vector3.up * moveSpeed * inputYAxis;
            }
        }
    }
}

```
> 2 votes

---
Tags: unity, camera, scene, control, view
---