# Question
Title: Want some limits in Bullet firing and its stop when i press the shoot button
I want some limits or range when my player fire the bullets and when i press the shoot button my fire as been stopped. I use the GetButtonDown from this its fire continuously but its not stopped. and if i use Input.GetButton than its hold the button and fire continuously but in fire there is no gap. So, my problem is that how i stop the bullet fire when i press the shoot button and if choose this (INPUT.GETBUTTON) and its hold the shoot button and its fire continuously than i want some gap on that fire and some limits or range of fire.

```
void Update(){
        if(Input.GetButtonDown("Fire1"))
        {
            shootRoutine = StartCoroutine(PlayerShoot());

        }else if(Input.GetButtonUp("JumpButton"))
        {
            StopCoroutine(shootRoutine);
            shootRoutine = null;

        }
    }

    void JumpButton(){
        if(!transform.GetChild(0).gameObject.GetComponent<PlayerHealth>
            ().hasDied){
            if (grounded){
                grounded = false;
                myRigidBody.AddForce (new Vector2 (0,
                    jumpPower), ForceMode2D.Impulse);
                if(myRigidBody.velocity.y > jumpPower){
                    myRigidBody.velocity = new Vector2 (0,
                        jumpPower);
                }
                animator.SetBool ("isGrounded", grounded);
            }
        }
    }

```

PlayerShoot method

```
IEnumerator PlayerShoot()
    {
        while(true)
        {
            if (!transform.GetChild
                (0).gameObject.GetComponent<PlayerHealth>().hasDied)
            {
                if (energy >= 5f)
                {
                    //energy -= 5f;
                    energyLevel.value = (int)
                        energy;
                    energyText.text = (int)energy
                        + "%";

                    GameObject newProjectile =
                        Instantiate(projectile, new Vector3(transform.position.x + 1.5f, transform.position.y - 0.02f,
                            transform.position.z), Quaternion.identity) as GameObject;
                    if
                        (GameController.instance.isMusicOn)
                    {

                        AudioSource.PlayClipAtPoint(MusicController.instance.audioClips[2],
                            newProjectile.transform.position);
                    }
                }
            }

            yield return new WaitForSeconds(shootDelay);
            //Wait for 'shootDelay' seconds before starting over again.
        }
    }

```

# Answer
Try something like this. I got rid of the coroutine, tell me if it's ok for you

```
private float lastShootTime = 0 ;
private PlayerHealth health ;

public Graphic button; // Drag and drop a UI image / Raw Image
private bool buttonDown = false;

// Indicates whether the player can shoot
private bool canShoot
{
    get { !health.hasDied && energy >= 5f && Time.time >= lastShootTime + shootDelay ; }
}

void Start()
{
    // Retrieve **once** the PlayerHealth script
    health = transform.GetChild(0).gameObject.GetComponent<PlayerHealth>();

    // Add event listeners to the button to detect whether the user is holding the button
    button.raycastTarget = true;
    EventTrigger eventTrigger = button.GetComponent<EventTrigger>();
    if (eventTrigger == null)
        eventTrigger = button.gameObject.AddComponent<EventTrigger>();

    EventTrigger.Entry pointerDownEntry = new EventTrigger.Entry();
    pointerDownEntry.eventID = EventTriggerType.PointerDown;
    pointerDownEntry.callback.AddListener( (data) => { buttonDown = true; } );
    eventTrigger.triggers.Add( pointerDownEntry );

    EventTrigger.Entry pointerUpEntry = new EventTrigger.Entry();
    pointerUpEntry.eventID = EventTriggerType.PointerUp;
    pointerUpEntry.callback.AddListener( (data) => { buttonDown = false; } );
    eventTrigger.triggers.Add( pointerUpEntry );

    EventTrigger.Entry pointerExitEntry = new EventTrigger.Entry();
    pointerExitEntry.eventID = EventTriggerType.PointerExit;
    pointerExitEntry.callback.AddListener( (data) => { buttonDown = false; } );
    eventTrigger.triggers.Add( pointerExitEntry );
}

void Update()
{
    if( buttonDown && canShoot )
    {
        // No coroutine anymore
        // The "wait" between 2 bullets is handled inside the `canShoot` property
        Shoot();
    }
}

// Shoot the bullet!
private void Shoot()
{
    energyLevel.value = (int) energy;
    energyText.text = (int)energy + "%";

    Vector3 projectilePosition = new Vector3(transform.position.x + 1.5f, transform.position.y - 0.02f, transform.position.z)
    GameObject newProjectile = Instantiate(projectile, projectilePosition, Quaternion.identity) as GameObject;
    if (GameController.instance.isMusicOn)
    {
        AudioSource.PlayClipAtPoint(MusicController.instance.audioClips[2], projectilePosition);
    }
    lastShootTime = Time.time;
}

```
> 0 votes

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


# Question
Title: Dragging UI element lags behind the cursor
Have been at this for 2 days straight trying different ways to solve this, and I can't.

I'm simply dragging around a UI panel using PointerDown and Drag events. I set the transform.localPosition inside the Drag handler. It works as expected, only problem is, the UI element seems to lag behind the cursor.

I created a GIF to show the issue in a build version to rule out the Editor.

Not sure how well you can see the issue, but the faster you move the cursor the worse it is.

Any ideas of what the issue is and how can I solve it?

Thanks

# Answer
> 3 votes
Your computer is using a hardware cursor, which is extremely fast at rendering the cursor.

Unity will be rendering the frame a few milliseconds slower than the cursor. All games have input lag to some degree. It takes time for the game engine to talk to the GPU, as well as process whatever CPU computations are needed per frame.

You can reduce input lag by disabling Vertical Sync via `QualitySettings.vSyncCount = 0;` (API reference here), though this may introduce screen tearing.

In short, don't worry about slight input lag like this. Whether you're aiming a gun with your mouse, moving an object, or even typing a character to display on the screen, there will be a slight delay – this is normal for games.

---
Tags: unity
---


# Question
Title: Procedurally generating dungeons using predefined rooms
Most attempts at procedurally generating dungeons I have stumbled upon do space out areas that will be rooms and connect them will corridors and hallways but what about instances where you have a collection of possible rooms in various dimensions and want to generate a dungeon that uses some of these specific rooms without those corridors and connections? To answer this question I found this particular video on the topic of generating levels in Path of Exile (~5:20 - ~7:20 about the dungeon part I am referring to) which left questions open on how to technically implement the algorithm described.

In general I understand the idea but I am struggling to figure out how this would be translated into code (most efficiently) and therefore here are a few questions:

1. When he shows how the entire level is sliced up I could not come up with a graph that would allow to represent this structure. My naive approach would be to have the entire level consist of `1x1` rooms and arbitrarily merge nodes in the graph to form rooms of valid dimensions (valid = there is a predefined room that can be inserted there later on). What would be a suggested approach to this?
2. Coloring the rooms should be just assigning random distances (in a given interval) to edges of connected nodes and just applying Dijkstra to find the sequence of rooms from start to finish I presume?
3. When he adds branching rooms I noticed that they do not allow another alternative path to the exit (which could be random of course) but how would one implement the branching? Just a recursive traversal with diminishing chances of continuing deeper into the graph?

---

# Description of the algorithm in the video

**Step 1.** Place a start and end room arbitrarily into the level (presumably with a given minimum distance to prevent degenerate layouts):

**Step 2.** Slice the entire level into areas that have exactly the sizes of your predefined rooms:

**Step 3.** Assign each room a random weighting/distance which is depicted with colors in this example:

**Step 4.** Find a shortest path to get a nonlinear path from start to end:

**Step 5.** You have your basic layout with a single successful path in which you can place random rooms of corresponding sizes that have to be connected with appropriate doors:

**Step 6.** Finally, add some branching rooms:

# Answer
> When he shows how the entire level is sliced up I could not come up with a graph that would allow to represent this structure. My naive approach would be to have the entire level consist of 1x1 rooms and arbitrarily merge nodes in the graph to form rooms of valid dimensions (valid = there is a predefined room that can be inserted there later on). What would be a suggested approach to this?

I would say it's valid approach, but doesn't give much opportunities to apply biases or complex structures: if you want more bigger rooms, you have to create smaller firsts, in a recursive manner. That by itself may hinder medium room sizes or non-rectangle rooms.

Alternatively create a map of nxm squares, mark entrance and exit as taken. Then try to create rooms in it with random positions. This way, you can try to create more rooms with 2x2, 1x3 or L-shaped than 4x4, simply by randomly but biased selecting, what room should be created next.

> Coloring the rooms should be just assigning random distances (in a given interval) to edges of connected nodes and just applying Dijkstra to find the sequence of rooms from start to finish I presume?

If you already have rooms to those room slots assign, I wouldn't do that. If you have two pits of death one after another with low weight, this will be extremely hard. These two rooms should have higher weights, but maybe with a little difference of +/- k. But that's more game design, so yeah, Dijkstra to get the way.

On top of that, you can create side ways or alternative routes by applying new start and end rooms and leaving the already taken rooms out of the new sequence of rooms.

> When he adds branching rooms I noticed that they do not allow another alternative path to the exit (which could be random of course) but how would one implement the branching? Just a recursive traversal with diminishing chances of continuing deeper into the graph?

Basically yes. Nothing to say here.
> 1 votes

---
Tags: algorithm, procedural-generation, graph
---


title: MMO - Some NPCs controlled clientside?

text:
# Question
Title: MMO - Some NPCs controlled clientside?
I'm making an online game and considering whether to handle certain NPCs clientside. Is this common?

For example I play Elder Scrolls Online and it seems basic townspeople NPC locations aren't quite synced up with my friends. I guess it makes sense if they're only wandering around in a set area for that to be handled clientside right?

So my question is, should I go with this method, or are there any good reasons why I shouldn't? Any examples of games that do, so I can see how they handle it?.

# Answer
> 3 votes
In an MMO, every byte you send over the network literally costs you money. You can (and should) in fact calculate the impact each byte/player-second has on your monthly operating cost by looking up what you pay for bandwidth and traffic. So whenever you see a line of code which sends or receives a network message, imagine a price-tag sticking to it. Every time you can get away with *not* synchronizing something via network you are improving your profit margin.

But don't get too overzealous with moving game mechanics to the client, because everything you do on the client can be manipulated by hackers. If a cheater could get a tangible benefit by fudging it, keep it server-sided. People quitting your game because they are annoyed by cheaters is far more detrimental to your profits.

Now what does that mean for NPCs?

When the NPC is an irrelevant background detail which doesn't affect the game, then handling the NPCs client-sided is a completely reasonable approach. Most of the time, the players won't notice that they aren't synchronized. You can then even add a config option to control the density of background NPCs in cities to make the game run better on low-end hardware.

When the background NPC behaves in a predefined routine and does not react on the player's behavior at all (like a random person walking up and down the street without evading any PCs standing in the way), or that behavior is completely determined by network-synchronized player-actions (like birds flying away when someone walks past), you can in fact even keep the NPCs synchronized when they are client-sided. When each client simulates them in the same way, they will appear as if they were synchronized, even if not a single bit directly related to the NPC is sent via network.

The only situation where the players might notice that something is off is when players are able to interact with the NPCs in ways which influence their behavior. For example, a wandering NPC might stop their routine when a PC talks to them and continue walking when the dialog window is closed. When you don't synchronize this, you might get some bewildering situations when one player observes another. But that's more of a cosmetic problem with little gameplay impact. Remember your cost calculation and decide for yourself if it's worth it or not.

In other situations, Player-NPC interactions might be a relevant part of the multiplayer-experience. There might be party-quests where everyone in the party wants to see what the NPC is doing. Or players might be able to fight and kill NPCs. They would then expect other players to notice this and be affected by the NPC's demise. In that case, the NPC must be synchronized. If you can't afford it, you can not afford the whole feature.

# Answer
> 1 votes
### Quick Assumptions

Some things I'm assuming about the MMO:

* Exact NPC location is not important, just being close enough to interact
* There are a lot of NPCs (enough to make constantly updating their location cause network lag)
* Players interactions with the NPCs has little effect on the NPCs location (think escort quests, where an NPC follows a player)

With those, it may be a good idea to look at how Real Time Strategy (RTS) games handle individual unit positions.

### RTS Games

Typically in an RTS game, each client receives the commands given by the other players, and then interpolates where the units should be based on that.

So if Player A sends his units to coordinates 100,100 at time 500, and the movement of all the units is deterministic, then any client in the session can recreate the position of the units at any given time.

This requires a couple of things in order for it to be effective in an RTS:

**Players must be in sync**
So when Player A issues a comment at time 500, and Player B issues a command at time 600, they must all be working on the same clock. If you've ever encountered a "players out of sync" issue or "players catching up" in older RTS, this is likely because their clocks were no longer the same.

**Results must be Deterministic**
Given just the command specifics and time, all clients should produce the same exact result. This is actually how replays work, they are just the commands sent, replayed as if you were in the game.
*Note: Some things don't have to be. In Starcraft 2, the effects after a unit dies may be different each time you play a recording. This is just aesthetics and has no impact on the game mechanically.*

### For an MMO

Your server should still be the authority on where NPCs should be. Otherwise you'd run the risk of having a malicious client putting two NPCs near each other, and maybe taking advantage of trading with both at once, etc.

However, you can avoid updating the exact position of an NPC to every client (as if the NPC itself were a player) by providing more generalized information that the client can use to determine the NPC location.

If you have a tolerance for how close someone has to be to an NPC to interact, then you don't have to worry about **Syncing** players clocks as much as in an RTS. And when your server receives an interaction with an NPC, you can just check that the client is close enough to where the NPC should be.

---
Tags: mmo, npc
---


title: Field of view or resolution?

text:
# Question
Title: Field of view or resolution?
I'm new to CG and I'm building a ray tracer.

I don't quite understand how to set camera parameters and film(pixel plane) parameters.

Say I want to get an image of 400x300 resolution. I can set an fov, and then the distance between the film and camera can be calculated.

If that's true, a high resolution and a "reasonable" fov, e.g 80 degree, will result in a large distance. Does that makes the object small on the final image?

And I feel like people like to determine resolution at first, in order to get an expected image size. To avoid distortion of objects(fish eye), the fov cannot be too large.

So how do I get close look of an object on a high resolution image?

I think the rasterization way is different from ray tracing one since I can project an object into NDC(normalized device coordinate) to make it big, but what about ray tracers?

# Answer
When you read "FOV", think "zoom". Decreasing the field of view is like zooming into the center of an image. When you decrease the FOV-angle, anything still in the field of view will appear larger and more detailed.
> 1 votes

---
Tags: camera, coordinates
---


# Question
Title: How to pass the correct data into a continuous world
I'm having a hard time implementing the player moving around my world of 2048x2048 tiles that is generated using a noise function. I'm in it for weeks, and I can not, I mess around with the coordinates, and there's always a bug. I was trying like this:

1 - I paint the map around the player (I'm using a tilemap) I paint a 64x64 area, with the player positioned in the center

2 - create a rectangle and center it in the player, the rectangle has an equivalent size of 32x32, and each frame creates another rectangle that is compared with the old one, so I take the area that has not yet been painted, so I can paint.

The problem is that when I reach the extremes of the map, when x = 0 or x = 2048 for example, I need that "x" equals 2048, and equals 0, respectively, as if the world had "turned" and I'm not sure how to deal with the world's data and the coordinates of the tilemap, because when I start by painting the map around the player, it will be in a position that would be 32.32, and the rectangle 16.16, I can not understand what I have to do it, I mess up everything with the coordinates, in this question, it helped me, I'm using the mod:

Make a 2d top down game with round map

it works, but what I am not able to do is pass the x and y correct, there are always bugs of this type, where I struggle with the numbers, but no use, if I fix the floor to one side the bug appears on the other:

*here was to be water, and it has a land line for example.*

I'm using Godot 3.

> **Up 1:**

I'm not sure, but it seems everything is going very well, what I was wrong was forgetting that, for example, a 64x64 array starts from 0 to 63, I was really dumb. The image below shows what it would look like in a 64x64 world:

As I solved it was just doing this "map\_size - 1" and decreasing and adding values to the left or right, 0, +31, respectively, since the rectangle starts at position 16, 16.

but when I do this now, there is another problem when this happens:

which occurs because of the "map\_size - 1", but without it it is still more messy.

> \** Up 2: \**

I was able to fix the up 1 error, I was calling the wrong mod function, without adding the + x and + y, so it arrived at 33 and it is no more than the verification "map\_size - 1", now it is working in the horizontal and vertical movements, however I'm still wrong to move diagonally.

or

> **Up 3:**

I think I got it, the problem if I was not mistaken was in the "stairs", so it works:

```
# LEFT-UP

# RIGHT-UP

# DOWN-LEFT

# DOWN-RIGHT

```

But I still have to hit the pieces of map that are behind, but I think it's in the "turn them off" function. I confess that I do not quite understand why this works, I would like to understand.

**Note 1:** Still the rare cases that the map generates wrong, but actually abusing the keys, quickly clicking for all meaningless directions, such as varying up and down, pressing low, a very strange movement, but the failure happens.

# Answer
in the function

```
func gen_data(var _posWorld=Vector2(0, 0), var _posTileMap=Vector2(0, 0), var size=Vector2(16, 16)):

_posWorld.x = mod(_posWorld.x, map_size)
_posWorld.y = mod(_posWorld.y, map_size)

var x = 0
var y = 0
while x < size.x:
    var elevation_column = {}
    elevation_array[_posWorld.x + x] = elevation_column
    y = 0
    while y < size.y:
        #elevation_column[_posWorld.y + y] = MY NOISE FUNCTION + OCTAVES...

        if (_posWorld.x + x >= 0 && _posWorld.y + y >= 0) && (_posWorld.x + x <= map_size && _posWorld.y + y <= map_size):
            if tile_map.get_cell(_posTileMap.x + x, _posTileMap.y + y) == -1:
                tile_map.set_cell(_posTileMap.x + x, _posTileMap.y + y, solos(elevation_array[_posWorld.x + x][_posWorld.y + y]))
        y += 1
    x += 1

```

you are using mode for every chunk while you shoud be using for every tile like:

```
func gen_data(var _posWorld=Vector2(0, 0), var _posTileMap=Vector2(0, 0), var size=Vector2(16, 16)):

var x = 0
var y = 0
while x < size.x:
    var elevation_column = {}
    rx=mod(_posWorld.x + x ,map_size)
    elevation_array[rx] = elevation_column
    y = 0
    while y < size.y:
        ry=mod(_posWorld.y + y ,map_size)
        #elevation_column[ry] = MY NOISE FUNCTION + OCTAVES...

        if (rx >= 0 && ry>= 0) && (rx <= map_size && ry <= map_size):
            if tile_map.get_cell(_posTileMap.x + x, _posTileMap.y + y) == -1:
                tile_map.set_cell(_posTileMap.x + x, _posTileMap.y + y, solos(elevation_array[rx][ry]))
        y += 1
    x += 1

```
> 3 votes

# Answer
> **RESOLVED**

I solved my problem, I made the system based not on the keys but on the position of the player. Now this situation does not happen anymore. How I did it:

1 - I created a central rectangle.

2 - Instance the map around the player

3 - Instead of checking with two rectangles, I check if the position of the player has moved from the position of the rectangle, which makes it much easier, therefore I do not even have to worry about the diagonal movements, I just leave the ifs of the 4 directions, and everything works.

4 - Example:

```
if posPlayer.x> = center_rect2.end.x:
     #generate here

```

5 - I change the position of the rectangle to the new place, always walking with it exactly, if it will not go wrong, thinking of the world as a grid of these rectangles.

It was a much simpler and clean system, but the fps has fallen, because it is necessary to generate more in this way, however I have already thought about how to solve this, I will decrease the size of the chunks, and increase the distance that is generated, and generate a larger initial map.

***I was able to solve the problem of the diagonal movement in a better way, here in this question I read with it:* https://stackoverflow.com/questions/46454993/diagonal-movement-causing-tilemap-painting-flaws**
> 3 votes

---
Tags: procedural-generation, tilemap, maps, godot
---


# Question
Title: Transforming quaternion between coordinate systems
Working in DirectX (with DirectXMath objects): If I have the rotation of an object relative to some coordinate space as quaternion Q, and I have a transformation matrix tx from that coordinate space to world space, how do I find the rotation of my object in world space?

My thinking, which has proven inaccurate, was: Use XMMatrixDecompose on tx to get the orientation that is the rotation difference between world space and my local coordinate space (qLocalToWorld), invert it to get the rotation of the local coordinate system relative to the world (qWorldToLocal) and combine it with my local rotation Q.

```
XMVECTOR scale, qLocalToWorld, translation;
XMMatrixDecompose(&scale, &qLocalToWorld, &translation, tx);
auto qWorldToLocal = XMQuaternionInverse(qLocalToWorld);
auto worldOrientation = q * qWorldToLocal;

```

I figured for e.g. that if the local coordinate system was rotated 90 degrees with respect to the world, and my object was 5 degrees with respect to local, this would yield the 90 + 5 = 95 in world space. But I was wrong :(

I'd appreciate help in understanding the right way to do this. Thanks in advance!

# Answer
> 0 votes
> If I have the rotation of an object relative to some coordinate space as quaternion Q, and I have a transformation matrix tx from that coordinate space to world space, how do I find the rotation of my object in world space?

Consider what you're doing.

You have a transformation `Q`, which transforms from object to "local" space. You have a transformation `tm` which transforms from "local" to "world" space.

What you want is a transformation from object to world space. The transform from object to world space is `tm * Q`. Admittedly, this is under OpenGL/GLM conventions and ordering, so the order might need to be reversed for the math library you're using.

You will of course need to extract a quaternion from the 3x3 transformation matrix.

---
Tags: c++, directx, directxmath
---


# Question
Title: How to generate multiple particles at once?
I am tying to create a cartoony balloon-pop animation. I want there to be particles that come from all sides of a sphere. However they should all come at once, in a single burst.

What I've done is this. I generated a particle system as a child of the sphere. I set the shape to sphere, reduced the duration, and increased the rate. However it doesn't seem like any particles are being generated at the same time still, only one is created at once.

How can I make all of the particles come at the same time?

# Answer
This is called a "Burst" and it's part of the particle system's emission properties: Burst (scripting reference).

> A burst is a particle emission event, where a number of particles are all emitted at the same time.

You can get some help from the Unity documentation with this explosion example, and this page on the EmissionModule.
> 3 votes

---
Tags: unity, particles
---


# Question
Title: Parallelism in GPU's rasterization process
Based on this article I understood the base principle inside the Rasterization algorithm:

```
For every triangle
Compute Projection, color at vertices
Setup line equations
Compute bbox, clip bbox to screen limits
For all pixels in bbox
Increment line equations
Compute curentZ
Compute currentColor
If all line equations>0 //pixel [x,y] in triangle
If currentZ<zBuffer[x,y] //pixel is visible
 Framebuffer[x,y]=currentColor
zBuffer[x,y]=currentZ

```

What I don't understand is how it is implemented in parallel inside the GPU.

**I consider 2 possible implementations of the algorithm inside the GPU:**

1. The first way is drawing every triangle one after the other(in 1 thread) as all of the pixels inside of them are ran in parallel. What bothers me about this way is that it's really slow for a large amount of triangles.
2. The second way is drawing every triangle in parallel as for every triangle all the pixels inside of it are ran in parallel too. This looks efficient to me, but I see a problem in the way **zBuffer** and **Framebuffer** data are synced as if 2 pixels try to occupy 1 spot there will be 2 threads trying to write on same data at same time. Considering that there are 2 buffers that need to be updated I don't see a way it could happen atomicly.

Another observation I have is that when I draw 2 triangles at same coordinates it's always the last that gets drawn. This stops me from thinking that there's some atomic way of doing pixel calculations as if there were the output pixels of the triangle would be random based of the 2 input triangle colors.

The thing that I guess is that the implementation is something in the middle of my 2 guesses, but it's there were I give up and ask here.

# Answer
Different GPUs use different tricks and techniques so this answer will intentionally be very generic and some detail may not apply to some GPUs, past, present (2017), and future.

This mostly applies to personal computer GPUs. Mobile (phones, tablets) GPUs try to be smarter, less wasteful, and save on memory bandwidth but still follow a similar process. Covering all GPUs in details would make for a very long answer.

The stages of rendering are intentionally not in order.

In bold are the parts covering **parallelism**

The stages can run in a **pipeline where the next draw call starts being processed before the previous finishes, and while other GPU cores are drawing.**

---

## Drawing Pixels

Modern GPUs don't draw one triangle then the next one anymore. It's much more complicated to maximize parallelism:

GPUs split the drawing into WxH tiles (this depends on the GPU but let's go with 8x8 for our example).

**Each tile can be drawn in parallel** by the GPU regardless of the drawing mode.

GPU cores are (usually) arranged in groups of WxH (eg: 8x8 = 64 cores) that matches the tile, **one group can render to one tile while the other renders another tile**.

The entire group execute the same shader at the same time; **Rendering to all the tile's pixels at the same time**. If some pixels are not to be drawn (ie: the triangle covers only part of the tile) those cores still execute but in a disabled mode that ignores the result and writes nothing. Mobile GPUs often work with smaller core groups to be less wasteful but still render multiple pixels in the tile at the same time.

* On some GPUs two or more non-overlapping **triangles** using the same shader rendered in the same draw call covering the same tile **will be combined and rendered at the same time in that tile**.
* Other GPUs will have to make one pass for each triangle.

This means worst case if you have a triangle of 1 pixel in size you will have 1 core in the group drawing something useful and the other 63 cores in the tile in "ignore-result" mode doing "nothing".

---

## Transforming Vertices

The same core groups (unified GPU) also process incoming vertices (vertex shader).

Incoming vertex batches are processed **N vertices at a time** (eg: 64 or a multiple of it at a time in our above 8x8 core arrangement) and dumped into a transformed temporary buffer.

The GPU can start transforming vertices of the next draw call before the first is done transforming so **vertex work on different draw calls can be done in parallel**.

---

## Clipping & Geometry Shaders

The temporary outputs from the vertex transform are culled and clipped into more triangles, optionally running a geometry shader before clipping, and written to yet another temporary buffer.

**Each buffer processing from the vertex transform can run in parallel.**

GPU drivers might combine vertex, geometry, and/or clipping stages together into one shader-program execution stage internally.

---

## Tile Triangle Buckets

The transformed and clipped triangles are put into "buckets" (lists, arrays, circular buffer, or other methods), of every tile they cover. One bucket for each render tile, or more (could be one per shader in a queue, depends on GPU & Driver).

When a tile is ready to draw a GPU core group "grabs" it from the queue and starts drawing that tile, **the next GPU core group can grab the next tile**, and so on...

There's essentially two ways:

* As triangles come in, they're shoved into the tile buckets and GPU core groups "grab" the tile as they come and draw the triangles in the list.
* All the triangles are sorted into tile buckets first and then the GPU cores start to draw.

The above often depends if it is a cellphone (mobile) GPU or a desktop/laptop GPU but not necessarily.

* On some GPUs this bucketing work is done by one or more master-coordinator CPUs that are inside the GPU which coordinate all the "dumber" (but better at drawing pixels) GPU core groups and tell them what to do when.
* On other GPUs the cores are more generic and capable enough to do this themselves or at least part of this coordination work.
* On some machines this coordination work is done by the main computer CPU itself.
* And on yet other (older or integrated GPU) machines the vertex, geometry, and clipping work is done by the CPU itself and the GPU cores only do pixel-shader work.

---

All the work is cut into small workload batches and as many stages as possible (and practical) to maximize parallelism and striking a balance between parallelism and coordination overhead costs.
> 6 votes

---
Tags: opengl, synchronization, rasterization
---


# Question
Title: Monogame smoothing out tile to tile movement
What I want to achieve is a 'smooth' movement from tile to tile. I'd like for the movement to not be instant.

My map has 32x32px tiles and my player is also 32x32.

This is what I already have so far:

*Player class:*

```
       public Player()
       {
          state = State.Idle;
          destination = Sprite.Hitbox;
       }

       ...

       public void UpdatePosition(GameTime gameTime, Input input)
       {
        switch (state)
        {
            case State.Idle:
                if (input.IsKeyDown(Keys.Up) || input.IsKeyDown(Keys.Z))
                {
                    Sprite.Direction = Direction.UP;
                    Sprite.AnimationTimer += (int)gameTime.ElapsedGameTime.TotalMilliseconds;
                    if (Sprite.Hitbox.Y > 0)
                    {
                        destination.Y -= 32;
                        state = State.MovingUp;
                    }
                }
                else if (input.IsKeyDown(Keys.Down) || input.IsKeyDown(Keys.S))
                {
                    Sprite.Direction = Direction.DOWN;
                    Sprite.AnimationTimer += (int)gameTime.ElapsedGameTime.TotalMilliseconds;
                    if (Sprite.Hitbox.Y < (Globals.SCREEN_HEIGHT - Sprite.Hitbox.Height))
                    {
                        Sprite.AnimationTimer += (int)gameTime.ElapsedGameTime.TotalMilliseconds;
                        destination.Y += 32;
                        state = State.MovingDown;
                    }
                }
                else if (input.IsKeyDown(Keys.Left) || input.IsKeyDown(Keys.Q))
                {
                    Sprite.Direction = Direction.LEFT;
                    Sprite.AnimationTimer += (int)gameTime.ElapsedGameTime.TotalMilliseconds;
                    if (Sprite.Hitbox.X > 0)
                    {
                        destination.X -= 32;
                        state = State.MovingLeft;
                    }
                }
                else if (input.IsKeyDown(Keys.Right) || input.IsKeyDown(Keys.D))
                {
                    Sprite.Direction = Direction.RIGHT;
                    Sprite.AnimationTimer += (int)gameTime.ElapsedGameTime.TotalMilliseconds;
                    if (Sprite.Hitbox.X < (Globals.SCREEN_WIDTH - Sprite.Hitbox.Width))
                    {
                        destination.X += 32;
                        state = State.MovingRight;
                    }
                }
                break;

            case State.MovingUp:
                if (Sprite.Hitbox.Y - (Globals.Speed * gameTime.ElapsedGameTime.TotalMilliseconds) < destination.Y)
                {
                    Sprite._hitbox.Y = destination.Y;
                    state = State.Idle;
                }
                else
                    Sprite._hitbox.Y -= (int)(Globals.Speed * gameTime.ElapsedGameTime.TotalMilliseconds);
                break;

            case State.MovingDown:
                if (Sprite.Hitbox.Y + (Globals.Speed * gameTime.ElapsedGameTime.TotalMilliseconds) > destination.Y)
                {
                    Sprite._hitbox.Y = destination.Y;
                    state = State.Idle;
                }
                else
                    Sprite._hitbox.Y += (int)(Globals.Speed * gameTime.ElapsedGameTime.TotalMilliseconds);
                break;

            case State.MovingLeft:
                if (Sprite.Hitbox.X - (int)(Globals.Speed * gameTime.ElapsedGameTime.TotalMilliseconds) < destination.X)
                {
                    Sprite._hitbox.X = destination.X;
                    state = State.Idle;
                }
                else
                    Sprite._hitbox.X -= (int)(Globals.Speed * gameTime.ElapsedGameTime.TotalMilliseconds);
                break;

            case State.MovingRight:
                if (Sprite.Hitbox.X + (int)(Globals.Speed * gameTime.ElapsedGameTime.TotalMilliseconds) > destination.X)
                {
                    Sprite._hitbox.X = destination.X;
                    state = State.Idle;
                }
                else
                    Sprite._hitbox.X += (int)(Globals.Speed * gameTime.ElapsedGameTime.TotalMilliseconds);
                break;
        }
    }

       public void Update(GameTime gameTime, Input input)
       {
          UpdatePosition(gameTime, input);
          base.Update(gameTime);
       }

```

# Answer
The same deltaTime you use in the conditions of your if statements must be used also while assigning the new position.

```
newPos = pos + (speed * deltaTime);
if (newPos < targetPos) {
    pos = newPos;
}

```

Currently, you are assigning `pos = targetPos`, that's why it's moving instantly.
> 1 votes

---
Tags: monogame
---


# Question
Title: Particles emit even though emission is disabled
I have created a basic particle system which is a single burst around a sphere.

I have a script that disables this emission upon `Start`.

If I don't disable the emission, then the particles continuously emit in bursts.

However when I disable the emission, it does not completely prevent particles from being emitted. There is still a single burst at the beginning.

Here is how it looks with emission disabled:

Here is the script which is setting `emission.enabled = false`. This is attached to the sphere and the particle system is a child of the sphere.

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

public class BalloonPop : MonoBehaviour
{
    public new Renderer renderer;
    public ParticleSystem emitter;
    public float explosionTime = 0.5f;

    private ParticleSystem.EmissionModule emission;

    void Start() {
        if (!renderer) { renderer = GetComponentInChildren<Renderer>(); };
        if (!emitter) { emitter = GetComponentInChildren<ParticleSystem>(); }
        emission = emitter.emission;
        renderer.enabled = true;
        emission.enabled = false; // <===================================== this
    }
}

```

All I want to do right now is to make it not emit any particles at all.Then I'll add an event to re-enable the emission, but that's not the issue I'm asking about here. I also tried `emitter.enableEmission = false`, which is deprecated, and it didn't work.

Here is the particle system in the inspector:

# Answer
The answer is that I needed to disable Play On Awake in the ParticleSettings settings.
> 2 votes

---
Tags: unity, particles
---


# Question
Title: When the player collides with an entity, the player can no longer move
Here is my collision code, any ideas on how I can improve it to fix the problem?

```
    public void collide(Entity entity){
    if(x + width >= entity.x && x <= entity.x + entity.width && y + height >= entity.y && y <= entity.y + entity.height){
        setShouldCollide(true);
    }else{
        setShouldCollide(false);
    }
}

```

# Answer
You are most likely running into problems with **object interpenetration**.

It is quite likely that you are implementing your movement code like this:

```
x += speed*Math.cos(theta)*deltaTime
y += .5 * gravity * Math.pow(delaTime,2) + speed*Math.sin(theta)*deltaTime

```

The problem with grid coordinates is that they are integers, so they can only round to the nearest integer pixel. The other problem is that points are essentially teleport-ing to their next position.

What can happen is that the next `(x,y)` position that the object "teleports" to could be inside an object in which case your physics engine stops the character. **You need to have additional logic that can deal with interpenetration cases**.

---

## What do you mean by "dealing with interpenetration cases"?

Dealing with interpenetration means that you need to teleport the object outside of the collider object. You are currently implementing an Axis Aligned Bounding Box collision algorithm (using squares to check for collision). All you have to do is to modify your collision algorithm a bit.

```
public void collide(Entity entity){
    if(x + width >= entity.x && x <= entity.x + entity.width && y + height >= entity.y && y <= entity.y + entity.height){
        //we know the object is interpenetrating at some point within our entity

        //set x,y coordinate of moving object to the nearest point outside of the box.
        //you will have to decide what is "acceptable visual behavior"
        //closer approximations will cause greater performance hits
        //
        //iex. use distance formula to teleport the object outside the entity
        //relative to the closest corner
        //
        //or
        //
        //Draw an imaginary line that represents the vector that the object came
        //into the object and follow that line backwards until you are no longer colliding with the object.

    }else{
        //object did not collide
    }
}

```

---

## Additional note on AABB

You may want to consider using the built in Rectangle Class and leverage it's built in `.intersects(Rectangle r)` which implements a AABB algorithm.
> 1 votes

# Answer
Just have bools like "canMoveForward" or "canMoveBackwards" or have one global bool that controls movement. However you want to implement it, when you detect collision, simply stop the player from moving forward. Good luck!
> 0 votes

# Answer
I am not sure how you coded your player, however since it is 2D perhaps you can make collision checks for left and right and maybe even top and bottom if needed.

If the collision on the left side is checken then the player can only move towards the right and not the left. If for example left and right have a collision then the player can only move up or down.

I think it is a simple yet effective solution. The checks would need to be placed at your movement codes, for example the player can only move left when the left collision boolean is false.
> 0 votes

---
Tags: collision-detection
---


# Question
Title: Player movement vs world movement in infinite runner game?
Well I'm developing a Temple Run or Subway Surfer style infinite runner game. Which is more good? -Moving the player and make the Main Camera follow, or keep the player in one position and move the generated worlds? And the generated paths or worlds will have many animations in it. So which choice ouuld be good and why?

# Answer
Keep the camera stationary and move the world. The moving-camera setup has a lot of disadvantages for games of this genre.

When the player plays for a long time, the player-character moves further and further away from the scene origin. The further you move away, the less accurate do floating point numbers become. That can cause some very weird glitches to appear after a while. Depending on how fast the character is moving and how long the average playsession takes, there is a chance that this problem will never actually become relevant in practice. But you never know.

Then you will have a lot of game-objects which will always keep their position relative to the camera. Among these are the obstacle-spawner(s) at the far edge of the screen and the despawn collider just behind the player which removes the obstacles when they leave the screen. With a stationary-camera setup, these objects won't move either. That means you can set these objects as static, which will improve the performance of the collision detection system.

The moving-player setup also has a practical disadvantage for your development workflow. When you testplay your game in the Unity editor, the camera on the game-window will follow the player-character but the camera in the editor-window will not. If you want to know whats happening, you need to pause the game, switch to the editor and try to find the position of the player. In the stationary-player setup, you can just orient the camera in your editor to always keep the playfield in view while you testplay.

The only disadvantage of a stationary-camera setup I could think of is that rigidbody physics might not behave as expected in that setup. But very few games of that genre make use of that. Still, if you want to have rigidbody physics in your infinite runner, then a moving-camera setup might give you better results.
> 1 votes

---
Tags: unity, android, 3d
---


# Question
Title: How to deal with texture coordinates without range?
I have a set of given texture coordinates(u,v coordinates), but they are ranging from (-inf, inf), contradicting the \[0,1\] convention.

I tried to do a rescaling by `value = (value - min) / (mac - min)`. But if I have a rectangle which composed of two triangles, four vertices. Suppose the u,v coordinates are `-0.260944 0.490887
 3.619507 0.490887
 3.619507 -3.043434
 -0.260944 -3.043434`

After scaling, the coordinates would be mapped to exact -1 and 1, resulting in wrong texture.

So how should I deal with this kind of texture coordinates?

# Answer
> 1 votes
Texture coordinates that go greater than abs(1) generally are used to specify tiling. So if you have a coordinate (such as in your example) that goes from 3.619507 to -0.260944, then that means that the texture is repeated a bit more than 3.5 times in that distance. Sometimes, certain art packages will give UV coordinates without tiling that are greater than 1. Those would be UV coordinates such as 1.45-1.68. A UV coordinate from 1.45 to 1.68 can be renormalized to 0.45 to 0.68, which is equivalent in most cases.

Going back to your example, you could, in theory, rescale your UV coordinates to be be within the range of -1,1 to by doing the modulus. For example, 3.619507 would become 0.619507, and -3.043434 becomes -0.043434. At each vertex, you would be referencing the same texture coordinate as before, but as the GPU renders the texture across the face of your triangle, it would not repeat, so it would still look different.

//START TLDR
There isn't a great solution for you, your rendering engine either needs to support tiling, or you would have to subdivide your triangle such that you don't have any tiling in the UV coordinates. This subdivision is basically to linearly interpolate your UV coordinates across each edge, and create new vertices with new UV coordinates that don't tile. This can get very complex very quickly. Let's imagine you have a triangle (so it only consists of 3 points). For the purposes of this example, let's assume the U and V coordinates are always the same, that way we'll only talk about a single value for each point. If one point has the UV 3.0, and the other 2 points have the UV 0.0, then we will have to subdivide each edge that has UV coordinates 3.0 and 0.0. So the edge in question would end up being 4 edges instead, one that goes from 0.0 to 1.0, a new one that goes from 1.0 to 2.0, and a final one that goes from 2.0 to 3.0. Each of those would end up getting re-normalized into values from 0-1, so the edge that goes from 1.0 to 2.0 gets normalized into 0.0 to 1.0 again, and the same for the edge that goes from 2.0 to 3.0. Here comes the second problem. While that is only 3 edges, you have 3 edges that are back to back that go from 0.0 to 1.0. The 1.0 point on one edge is the point on the next edge that is 0.0, which means you can't share vertices between the edges. That means that your 0.0 to 3.0 point becomes 6 new vertices (0.0 stays at 0, 1.0 turns into 1.0 and 0.0, 2.0 turns into 1.0 and 0.0, and 3.0 becomes 1.0). Since you were dividing a triangle, you end up with a number of different polygons (think about a line through a triangle. You can end up with either 2 triangles, or you can end up with a triangle and a quad), some of which won't have 3 edges. Those again need to be decomposed into triangles (so your quad becomes 2 triangles). As you can see, the subdivision method is complex.
//END TLDR

In the end, you are trying to render a model that your renderer doesn't natively support, and anything you try to "fix" it is going to result in an approximation. I find it unlikely that your renderer doesn't support tiling, it may just be disabled. If the renderer is set to CLAMP instead of TILE (which is often the case), then any value greater than 1.0 will be clamped to 1.0. Instead, set the renderer to TILE, and you can leave your UV coordinates alone, and everything should work correctly.

---
Tags: textures, uv-mapping
---


# Question
Title: Get GameObject which instantiated me in Unity
How can I get a GameObject from another GameObject? If I know, that the GameObject I want to get instantiated(using function Instantite()) the GameObject from which I want to get it.

If there is no solution, how can I get the direction in which should move the instantiated bullet? I mean should it be 1 or -1.

# Answer
You must attach a script to the prefab you instantiate and "inject" a reference of the gameobject which has instantiated the prefab as follow :

```
public class Bullet : MonoBehaviour
{
    public GameObject Gun ;
    public Vector3 direction ;

    public void Awake()
    {
       // You can't use Gun yet
    }

    public void Start()
    {
        if( Gun != null )
            Debug.Log("I've been instiated by " + Gun.name ) ;
    }

    public void Update()
    {
        transform.Translate( direction ) ;
    }
}

public class Gun : MonoBehaviour
{
    public void Shoot()
    {
        GameObject instance = Instantiate( bulletPrefab ) ;
        Bullet bullet = instance.GetComponent<Bullet>();
        if( bullet != null )
        {
            bullet.Gun = gameObject;
            bullet.Direction = transform.forward;
        }
    }
}

```
> 1 votes

---
Tags: unity, bullet-physics, instancing, direction
---


# Question
Title: Unity: Smart approach needed: Enemy AI detection of firearm discharge
If the player fires his firearm within a certain hearing range of an Enemy Bot, the Enemy AI should be alerted to his position. My initial solution to the problem was the following: Everytime the player fires a shot, find all Enemy AI Game Objects and trigger a function that checks wether the player is within hearing range or not.

The problem is some weapons have a firerate of up to 20 shots per second. And if there are 25 enemies in the scene it means that, while shooting, I will be asking for `GameObject.FindGameObjectsWithTag(Enemy);` and accessing a function within 500 times every second. This is not very performance friendly.

I cannot think of a better way to do this. Is there?

# Answer
This assumes that you're not worried about audio occlusion (sound muffling around obstacles like walls etc.).

I would have a circular/spherical trigger collider (`SoundCollider`) attached to your gun/weapon that is the size / radius of how far you want the sound to travel. When you shoot: it that turns on this `SoundCollider`. Enemies can have an appropriate `Rigidbody` (`Listener`) to collide with the trigger and a handler in a component that handles what to do if they are triggered if they are in range of your `SoundCollider`.

Couple of Pros I can see to this approach:

* You can have an easy to edit variable that changes the radius of the `SoundCollider`, making some weapons quieter than others.
* You can let Unity handle the events between your Gun sound and the enemies in hearing range.
* Effects can be applied to the collider if necessary so when it is active a radar on the mini-map (if you need one) can show the area that sound will travel to.
* As you only need to turn the `SoundCollider` on or off instead of sending multiple events, it will work regardless of firerate on your weapons as you simply turn it on when you start firing and have a small delay to turn it off once you've stopped.
* You only need `Listener`s on appropriate enemies and you don't need to use Tags to filter through them. Disabling a `Listener` can make a unit "deaf" quite easily if you need them to not hear anything under certain conditions (interactive cut-scene).

It's a concept but can work well, I used something similar to make an AOE damage ability on a unit but the concept is essentially the same - Unit in certain proximity triggers code when ability is active (gun is firing).
> 4 votes

# Answer
1. Does every shot need to be heard individually, or just the first in a volley / every 50th in a sustained spray?
2. Do your enemies change so drastically frame to frame that you need to search every gameobject in the whole scene to see if it now has an enemy tag?

* Instead, could your enemies register themselves to a master list on spawn, and un-register themselves when killed/despawned? Then you only need to search the enemy list.

    (This is effectively how an Event solution as Zebraman suggests works under the hood - enemies subscribe to the noise event on spawn, adding themselves to a master list of event subscribers)
    * Better yet, could this master list be a spatial partition your enemies update when they move? Then you only need to search the portions of the partition within hearing range. (Probably only helpful if you have hundreds of enemies — for dozens, a linear scan through the list is reasonable and much simpler)
3. If all or most of your range queries are centered on the player, could you use a physics trigger collider surrounding your player to capture and maintain a list of only those enemies within perception range, then process only that list?
> 2 votes

# Answer
This is a good place for events. Both c# and unity have an event system, so use whichever you're more comfortable with.

With events, you don't have to "find" the game objects. The event can pass whatever necessary information, and each AI determines if they can hear it.

Because events work as a "subscription" system, it's fairly easy to "deafen" an ai based on scripted events, distance from player, loading areas, etc.

docs for unityEvent: https://docs.unity3d.com/ScriptReference/Events.UnityEvent.html

docs for c# event: https://msdn.microsoft.com/en-us/library/aa645739(v=vs.71).aspx
> 2 votes

# Answer
Perhaps you could make use of influence maps?

Every time you shoot you can propagate values trough the influence map and make AI aware.

Obviously it adds more complexity.
> 1 votes

# Answer
I simplified things even more than the other answers suggest so I thought I'd contribute:

1. A sphere collider representing sound travel distance around the player updates once a second: If the weapon has been fired in that second it turns itself on for one second and it is disabled by default.
2. Everytime an enemy bot collides with that Sound collider a timer is set to 30s and the bot is set to alert and does his thing.
3. If that timer runs out and the bot hasn't heard or seen anything it will go back to doing whatever it did before.
> 0 votes

---
Tags: unity, ai
---


# Question
Title: How can I implement simple object orbits in Game Maker?
I've seen a lot of tutorials for things like "fixed circular orbit" and "elliptical orbits" which end up never been what I actually want.

I have two objects: `oPlayer`, and `oPlanet`.

I am trying to allow the player to move around freely, but be able to be caught by the gravity of `oPlanet`, causing the player to go around in circles/elliptical orbit. I also need the player to be able to escape thate orbit, and end up on a trajectory. In fact, I want it to work for **any** `oPlanet`.

What I am looking for is something similar to the orbital gravity in Kerbal Space Program.

Is there any way I should go about this? If anyone can be of help, I would rather answers be in GML rather than the Drag and Drop, but any help is great!

# Answer
I use Game Maker 8.1 all the time, and I've done orbital sims in them too. More good news: Game Maker has **a built-in function that does vector addition** for you:

`motion_add(direction, acceleration)` this will automatically change an object's hspeed and vspeed with the correct vector addition.

Remember that Game Maker treats 0 degree angle pointing right, 90 degree pointing up (which is the negative y direction), 180 deg pointing left, 270 deg pointing down. However, with motion add, you don't even need to know that.

**Here's what I would do.** In oPlayer, use the built-in variables x, y, hspeed, vspeed so that GM automatically does motion based on speed. Now you just need to do the acceleration from gravity, using motion\_add. In the step event of oPlayer, write this:

```
var g, gdir; // it's necessary to make these temp vars because GM code remembers them in the scope even if you go into "with" for other objects. THIS ALSO ASSUMES YOU HAVE NO OTHER VARIABLES NAMED g OR gdir IN EITHER oPlayer OR oPlanet

with (oPlanet)
{
   // this assumes each planet has a mass variable, I used 1000
   g = mass/sqr(point_distance(x, y, oPlayer.x, oPlayer.y)); // handy built-in distance function
   gdir = point_direction(oPlayer.x, oPlayer.y, x, y); // VERY HANDY built-in get direction function from point 1 to point 2

   with (oPlayer)
     motion_add(gdir, g);
}

```

Now in the key down events for oPlayer, for all 4 arrow buttons, put this

```
hspeed += 0.2; // for right arrow
hspeed -= 0.2; // for left arrow
vspeed -= 0.2; // for up arrow
vspeed += 0.2; // for down arrow

```

So if you hold down the right arrow, each step will add 0.2 to your hspeed. Softcode this with whatever variable name you want.

I tested this exact code myself in a GM example. The room speed was 60, oPlanet mass was 1000, and things seemed to flow at a normal pace. One orbit took 1 or 2 seconds and I could easily break or re-enter orbit by pressing the arrows.

**There is 1 caveat:** If the player goes too close to the planet, such as sinking beneath its surface, it will get SO close to the center that gravity becomes extremely strong, which tends to make the ship go flying off in a random direction and never coming back. To avoid this, you should make a destruction event so that the ship just crashes when it hits or goes below a planet's surface, then restart the game. Use point\_distance() to test if the distance is less than or equal to the planet's radius.

Finally, like I said, I use GM 8.1. I have never used GM 9, also known as GM Studio because it looks very bloated and way, way different than the nice interface of GMs 5, 6, and 8 that I am used to.
> 1 votes

# Answer
The first thing to do when you want to model space as it is is to understand Newtons laws of motion. An object keeps moving with a constant speed and direction unless a force acts on it.

That means you need to get away from the methodology of moving an object by changing its position. Give an object a speed in x- and y-direction and then change its position by its current speed every frame. When you want to change the motion of the object, change the speed through acceleration and deceleration.

Now you can add a gravity source by adding another constant acceleration to it every frame in addition to the acceleration from the player input.

When you want to simulate a point gravity source (like a planet), you first need to make the acceleration directed into the direction of the planet. You can do that by calculating the distance between gravity source and object with the Pythagorean law:

```
dist_x = object_x - source_x;
dist_y = object_y - source_y;
dist = Square_root(dist_x * dist_x + dist_y * dist_y);

```

Then you can calculate the horizontal and vertical portion of the acceleration vector by dividing each axis distance by the total distance:

```
acceleration_x = dist_x / dist;
acceleration_y = dist_y / dist;

```

You now have a constant acceleration *away* from the gravity source. But you want attraction, not repelling, so you need to invert it:

```
acceleration_x = -acceleration_x;
acceleration_y = -acceleration_y;

```

But keep in mind that in astrophysics, the magnitude of gravity is reduced by the distance squared. Also, different objects have different mass which means they are stronger gravity sources:

```
 gravity_power = source_mass / (dist * dist);
 acceleration_x = acceleration_x / gravity_power;
 acceleration_y = acceleration_y / gravity_power;

```

You should now have a proper simulation of orbital mechanics.
> 2 votes

# Answer
I've found that `motion_add` behaves weirdly for simple orbital mechanics. There's the precession problem and acceleration is much faster when approaching the object you're using as the gravitational source.

This code gets rid of the precession and the velocity of the orbiting object is more manageable when approaching the planet:

```
object = obj_player;
source = obj_planet;
ddist = point_distance(object.x, object.y, source.x, source.y)
dsquare = ddist * ddist
grav_power = source.mass / dsquare;
ad = point_direction(object.x, object.y, source.x, source.y)
cx = cos(pi / 180 * ad)
cy = sin(pi / 180 * ad)
hspeed += grav_power*cx
vspeed -= grav_power*cy

```

Just copy it into a script file in GameMaker and drag it into the step event of your orbiting object.
> 0 votes

---
Tags: game-maker, orbit
---


# Question
Title: Board-Games Design: Physical vs Digital?
Is there any difference when learning the designing of a physical board-game and digital board game, meaning if I watch a tutorial about a physical board-game design is it applicable on a digital one?

Note: I'm focusing only on design process, **not the art-design**, only on the gameplay-design (rules, levels, obstacles, etc).

# Answer
One big difference between physical board games and digital ones is how they deal with complexity. If players forget about rules in a physical board game, then they're playing a different game. So you have to work hard to make each rule count, to make it both intuitive and easy to use. If there is a conflict, inconsistency, or just confusion the rule system, then that can bring the game to a screeching halt as the players argue about which way it works.

Digital board games have a final arbiter for rules: the game itself. Videogames do not forget rules. You're not allowed to make illegal moves. And so forth. This allows you to have lots more rules in a videogame than you could in a physical one. If there is a conflict, then you either code a solution or the game works itself out (or crashes).

But complexity goes farther than that.

In a physical board game, players are often required to keep track of certain things. Some board games give units stats, for example. But players have to keep track of such stats as they change throughout the game. That's hard; it requires upkeep and effort.

For a videogame, it's trivial. Oh sure, you need to present this information to the player in a digestible form. But the player's focus is not on remembering to track the HP of all of their units; they don't have to do math and subtract numbers during combat. They just have to know what the current value is.

By some measurements, Civilization and its ilk are "digital board games". You *could* make a physical board game equivalent. But it would be pretty much unplayable due to the sheer amount of stuff you have to keep track of. Harvesting your food and leveling up cities. Counting up how much production each city made and finishing any construction projects that it completed. And so forth.

What a computer does instantly when you press "End Turn" would require minutes or hours of mindless grunt-work by each player.

So there are entire design spaces that physical board games would never enter which digital ones can. While needless complexity is generally bad design for any kind of game, videogames can handle greater levels of mechanical and rules complexity without breaking down than physical board games.
> 7 votes

# Answer
The principles of design are the same, but there is one crucial difference for digital versions of board games: the lack of physical pieces.

As Quintin Smith argues in this Kotaku article from 2013: (emphasis added)

> **The game as physical object is a pleasing thing**. Working with your friends to set up a game brings a happy psychological bookending, like opening a brand new book.
>
> ...
>
> The appeal of table games' physical presence isn't to do with the luxury of the objects themselves. Play is how we form emotional connections. The purpose of the game-as-object is to make it easiest to foster those connections, allowing everybody to invest in what's on the table, right down to building it up and breaking it down, and in doing so, it gives you the path of least resistance to connect to each other. Put another way, **that tiny plastic man isn't a toy. He's an emotional power adaptor**.

Think about the feel of a cool glass token in your hand, the way it sparkles in the light, the feeling of running your fingers through a pile of them in front of you.

Those small physical interactions mean a lot, and have a huge impact on how the game feels to play. In the absence of real physicality, you'll have to pay extra attention to game feel and juice to ensure your game retains that emotional resonance and doesn't feel "flat" on the screen.

Also watch out for things that you get automatically with physical games, but are easy to overlook for digital versions:

* Take care to show the transitions between game states, pieces moving from *here* to *there*. This is impossible to miss when the player has to literally haul them through space, but can vanish invisibly in a digital state transition, especially if you automate any of the book-keeping-type mechanics.
* Showing other players' pieces - even if I can't see the fronts of an opponent's cards / the contents of their resource pile in detail, just knowing how many items they have in front of them or the way they've arranged them can be an important tell. Combined with the point above, you need to carefully message how the remote players are taking their actions on the shared game state, otherwise it can feel like playing against a mysterious phantom presence instead of another human being. ;)
* Messaging *why* a particular game action is taking place. In person, I can tell you, "My basilisk attacks you for three damage, but since I have the orb of serpents it actually does five." Your interface design has to be able to communicate that story instead.
> 1 votes

---
Tags: game-design, board-game
---


# Question
Title: How can I design loot to be enjoyable to acquire and neither a chore nor frustrating?
I am currently working on an ARPG and I am trying to figure out which elements of the game influence each other and one example is that endgame activities inherently influence loot drops/handling and the other way round. The more classical loot systems we usually get in touch with are following:

* **Classic MMORPG loot** where enemy bodies have to be clicked which open up a window which displays the loot that can be clicked one item at a time. Sometimes it is possible to enable auto-loot in order to skip the clicking of each item.
* **ARPG loot** where slain enemies die in a explosion of loot which can occasionally get extreme up to a point where loot filters are necessary otherwise the screen will be cluttered. In this case players usually pick up uncapped currency like gold automatically while everything else from gear to crafting parts has to be looted manually if the player so desires. Diablo, Path of Exile and the likes to handle it with cliackable labels on-screen while Borderlands for example spreads the loot all around the place and has visual light beams indicating rarities that allows players to filter quickly and go grab the items they might be interested in.
* **"Loot chests"** is what I call the system of Destiny. During a strike or adventure players do participate in combat and are not distracted by random loot on the ground which would require consideration as to whether picking it up is a good choice. After the event has ended, typically after defeating the final boss a chest appears that contains loot.
* **"Vacuum loot"** which was used for Guild Wars 2 and Wildstar where the loot physically drops on the ground and players can loot everything from currencies to gear with one click of a button. In an ARPG this would never work out since inventory space is even more restricted than anything else.

My naive first thoughts are based on how the endgame of Diablo 3 is designed. In classic endgame rifts players can slay enemies and are usually busy picking up materials and some "useless" items that may be used to disassemble them for even more materials. Furthermore they are looking for chests and hoping for some random drops. In contrast to that game mode there are greater rifts which, similiar to Destiny, drop no loot at all except when you kill the final boss that appears after progressing far enough.

In greater rifts there are no distractions just the challenge to finish those at higher difficulties and farming them with specific speed builds while on the other hand the classic rift slow down gameplay when you have to stop every few meters just to click and pick up those items.

I have reached an impasse since I understand players might want to blaze through content and I don't want to make them slow down constantly (with a system like classic rifts in Diablo or Path of Exile in general) but when I stick to "loot chests" at the end of an activity it might happen that less loot drops in general and that there is less gratification when collecting things since the is nothing on the way. Take a long dungeon for example, a "loot chest" system might incentivize just skipping all enemies and do the bare minimum to tackle the final boss. **In such a scenario I basically invalidated almost the entire content I am presenting!**

Comparing this to (current) legendary items in WoW: if one legendary drops I might be relieved to finally get one (and be angry about it since it's a shitty one...) but I missed the reward stimulus up to the drop itself. Applied to my scenario, the player sees a dungeon as an annoying chore to finally get the chance of acquiring something. If the drops are not satisfying it could possibly be more demotivating thinking that that only chance to get something after such a chore was a waste of time.

So my question is the following: Even though loot explosions may be enojoyable at first they can degenerate into an annoyance (e.g. clicking a bazillion items on the floor). When thinking about making them less boring I end up with something that can be as frustrating in the end. How can I balance this?

# Answer
> 1 votes
I would say it depends on the loot your game provides and what your target is. A looting system is a tool to loot the items your game provides.

* **MMOs** tend to have certain 'Must-have'-items for different classes. Lower levels have to grind stuff for quests or crafting/job's, killing hundreds of monsters of the same type, only rarely dropping something else than this crafting stuff. And if so, then its something you can use for some levels. Money is mostly made by selling stuff, big amounts are rarely dropped.

For this type of loot, you want only to check rarely: only dead bodies with loot won't despawn, maybe even with a glow around them, showing worthwhile loot. More mundane grindable items get often auto collected and/or stored in an infinite bag of craftable components.

* **ARPGs** have more random loot, several tiers of item qualities, some crafting stuff like runes or gems. Unique items are more common, in theory can be dropped by any monster, but can be replaced by items of a lower tier, if it simply has better stats for your char. That's until it has a real unique effect you want. Mostly money has no use for higher level chars, but early you might need it to kick-start your champ with better items from the shop. But you also have consumables like potion, that are instant to drink (unlike most MMOs I know).

Games like **Diablo** and \**Torchlight \** do this by just dropping stuff on the ground, like you said, but still convey information about those items: colored names, dropping sounds, particle effects. Torchlight implemented the auto money pickup and the companion for selling items. This system is intended to let you fight, then let's you loot for a short time, maybe longer if you found something worthwhile, maybe new equip or a gem to plug in your inventory. Out of potions or space, take a town portal. Torchlight tried to reduce the down time in the city with the company, Diablo 3 had their health orbs against the potions and smaller Items/bigger inventory to stay longer in the field.

* **Loot chest** are an oddball and hard to balance. They are somewhat like raids, need time to do, and if you fail you get nothing. And even if you succeed you might get nothing you want.

**Destiny** (never played it) is basically an MMO with more speed. Standing still while in the battle field gets you killed. **Vermintide** has a similar concept, while you get better items based on the difficulty and how good you were. Still it doesn't guarantee you get items you want.

* **Vacuum loot** is a combination of the MMO and ARPGs system. You get many different items, but also a lot space.

That said, you want a loot system that fits to your item content. If you have many tiers of item quality, stick to the ARPG system. If not, pick the MMO approach. If you want to encourage exploration, add smaller dungeons with lesser bosses for more opportunities to drop better stuff.

Now you can modify your system. For example in an ARPG:

* have a companion gather everything and/or auto-sell / disassemble everything below a certain quality. So the player can look at the rest at any time he wants.
* this companion could be either attackable (Torchlight), needs orders (auto-gather like) and then some time, or can be send to buy consumables (Torchlight 2)
* this would enable to give the companion traits for himself (walking speed, gather speed, better prices for selling, more components from disassembling,...) or for the player (healing aura, damage or armor buff, more items to find,...)

This is just one example but already so potent in its possibilities.

# Answer
> 1 votes
Which kind of looting system is least annoying will depend largely on the size of a player's inventory and how often looting happens. If the inventory is large or uncapped and looting happens frequently, automate as much as possible. If the inventory is small and looting happens infrequently, interrupting the game for looting might be more clear to the player.

**Why not do both?**

An RPG typically has frequent looting and a large inventory. I recently was playing Stardew Valley, which has a fairly small inventory (12-36 kinds of things, 999 max of each kind), and its automatic looting still works well, so the inventory may not need to be huge. Be sure to give some feedback about what the player is collecting, but seeing it briefly on the ground, getting some sound feedback, and then seeing the name and quantity of each item in the corner of the screen would suffice. There's no need to click on loot, since you can assume the only reason a player would not want to pick up loot is because of time, since it is more enjoyable getting lots of stuff and sorting through it later than having to choose every few seconds whether to keep another thing.

Many RPGs have additional kinds of inventories and more rare items. For example, equipment. A player usually can only wear a few items, and these items are usually more rare, perhaps only appearing after a boss battle. You can show the player these items are more significant by having a less automated way to loot, such as loot chests. The player will want to make a decision whether to equip it immediately. Keeping the chests limited to rare items keeps a player excited every time a chest appears but does not discredit the advantage of slaying smaller enemies.

# Answer
> 1 votes
Personally I think that the system used in **Runescape** is a good option as well, where the player's inventory is small (exactly 28 slots), very few items are stackable, and players aren't encouraged to carry everything they own around with them all the time.

The benefit of this system is that players are required to manage their inventory, manage their bank, and think about inventory management as part of the game. It's a minigame, a game-within-the-game. Do you bury the bones of enemies immediately so you can take 28 Dragonhides back to your bank, or do you take back 14 Dragonhides and 14 Dragon Bones and sell both? If you bury them, you get Prayer XP, but if you don't, you have to run back to the bank and deposit your things more often. These sorts of decisions are interesting to me, personally. There are also decisions like what sorts of items do you take with you? You can't go to a dungeon and take three sets of armour *and* a ton of food *and* a whole lot of potions *and* etc. etc. etc. You have to made tradeoffs.

It also opens up the possibility of the 'hardcore ironman mode' where you can't use a bank and you have to keep everything you ever own in your inventory. It definitely is a challenge to play an entire MMORPG with only 28 inventory slots. Thankfully you can drop items to the ground and they'll stay there for a couple of minutes before disappearing into the aether.

The game doesn't really have the 'useless items' or 'grey items'. I've never really understood why a game would have those items, they just make everything seem so cluttered. There are items that aren't useful to your character because they're very low level, for example, but not items that are just useless to everyone. Even then, if you kill a chicken and get 15 feathers (a 50/50 chance, if I remember correctly) then those are as useful to a level 100 as a level 1, because feathers can always be used to make arrows of any level.

The items drop to the ground in a stack. Like everything else in the game, the top item in the stack on a particular grid tile is visible in the game world. You can click to pick it up, or you can right-click to see a list of all the items in the pile and pick up any particular one of them. If you want to pick everything up, it's a spam-click, alas.

Recently I think the game has started highlighting particularly rare and powerful items that drop. I dislike it because personally I don't want the game to tell me when I should get excited about things, as it feels like going to a studio to watch a TV show being made and being shown a sign that tells me when to laugh. But if you want to ensure that rare and powerful items aren't lost in the clutter, you could try that. I think that rare and powerful items should actually be *rare* enough that people have heard of them and will recognise them when they see them without giant sparkly words and special music playing when you get them.

Everything in RPGs seems to sparkle like crazy if it's interactable now, it definitely is unimmersive.

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


title: Client not executing commands in Unet

text:
# Question
Title: Client not executing commands in Unet
## **Edit**

Okay, so I partially solved the problem by adding a rigid body component to the capsule. I read somewhere that apparently you have to have one in order to move on the server.

**Problem 2**

The next problem I have is that I can now move a capsule that is spawned by the client fine and the host can move it as well as many times as they like. The problem I am getting now is that when the host spawns a capsule the client cannot move it at all and I get a sort of glitch effect on the client side and the capsule still doesn't move on the host side. Is there a reason why it would only work one way and not the other way around? I thought at first it might have to do with Spawn vs SpawnWithClientAuthority but that doesn't seem to make a difference.

---

**Project Summary**

I have a pretty simple multiplayer project, all I want to do is have one player host and the other join as a client. Once they are joined together the two players can spawn a capsule and then when the user clicks on a capsule. They should be able to pick it up and move it around the scene and the other player should be able to see this action. I can get both players to connect to the server and spawn their own capsule and both players can see this. The movement script is done as well. However, it is only transmitted on the host side. When the client picks up the object it does not update on the server.

**Problem**

I have done a bit of debugging and have found that when I call the command on the client it is not being executed at all through line breaks and simple debug statements.

**Code**

```
public void OnInputClicked(InputClickedEventData eventData)
    {
        Debug.Log("clicked");
        if (isLocalPlayer)
        {
            if (Physics.Raycast(transform.position, direction: transform.forward, hitInfo: out hit, maxDistance: range))
            {
                Debug.Log("Hit capsule");

                objectID = GameObject.Find(hit.transform.name);
                objNetId = objectID.GetComponent<NetworkIdentity>();
                playerIDThatClicked = player.GetComponent<NetworkIdentity>();

                CmdAssignAuthority(objNetId, playerIDThatClicked);
                Debug.Log("grabbed");

            }
            else
            {
                //if we are releasing the object we want to unassign our authority
                if (objNetId != null)
                {
                    CmdAssignAuthority(objNetId, playerIDThatClicked);

                    objNetId = null;
                    Debug.Log("released");
                }
            }
        }

    }

[Command]
    void CmdAssignAuthority(NetworkIdentity target, NetworkIdentity player)
    {
        Debug.Log("inside cmd");
        current = target.clientAuthorityOwner;
        playerconn = player.connectionToClient;

        if (current != null && current != playerconn)
        {
            Debug.Log("Had authority now removing and replacing");
            target.RemoveClientAuthority(current);

            target.AssignClientAuthority(playerconn);

        }
        else if (current != null)
        {
            Debug.Log("removing authority");
            target.RemoveClientAuthority(current);

        }
        else if (current == null)

        {
            Debug.Log("No authority, adding one now");
            target.AssignClientAuthority(playerconn);

        }
        else {
            Debug.Log("CmdAuthority error");
            target.RemoveClientAuthority(playerconn);

        }
    }

```

**Question**

Am I calling this command correctly? The script is attached to a player prefab and the capsule prefab contains a network id and a network transform. I am pretty new to Unet and this feels like a noob mistake.

# Answer
EDIT:

If your objects have the same name I could see `GameObject.find(hit.transform.name)` giving you issues (use `hit.transform.gameObject` instead)

---

Original answer:

If I'm reading your logic right, `CmdAssignAuthority` written another way works as follows:

* `if (current != null && current != connectionToClient)` set authority to `connectionToClient`
* `else if ( current == connectionToClient )` set to `null` (b/c current != null means it must be connection to client due to the first if statement)
* `else if ( current == null )` set to `connectionToClient`

I'm not entirely sure how often your `OnInputClicked` due to differences between AR devices but I'm going to assume something like this video. The logic in `OnInputClicked` can be psuedo-coded as:

* `if ( click and raycast hit )` it will do the above routine for that object
* `if ( click and miss and cached hit object )` it will do the same routine

This logic has a few potential errors:

* Clicking twice with the same raycast outcome (hit or miss) is going to put the authority out of sync with who's actually clicking (a hit would be a release and a miss would set authority).
* Because it only ever assigns authority with `connectionToClient`, the host client, when clicking, will assign authority to `connectionToClient` as well which is probably why you can never move it on the host.
* The third case in your `CmdAssignAuthority` which your first `if` catches should never happen and makes it harder to read what's going on.

It looks like your logic is tangled up in `CmdSetAuthority` and potentially can break down in `OnInputClicked` if the clicker is not the `connectionToClient`. I suggest rewriting your logic so that it sends some sort of ID for the clicking player to the `CmdSetAuthority` instead of just toggling between `null` and `connectionToClient`
> 0 votes

---
Tags: unity, unity-networking, unet
---


# Question
Title: How do game designers create vibration patterns?
I am curious about creating and implementing vibration patterns for console controllers (for the PS4 controller, if it makes a difference).

There is a delay and motor speed parameter right? But also we can fade from left motor to right, or make them work together....

Is there a standardized way to create those patterns?

For example I thought about creating them with stereo wav audio in an audio editor and reading the wav file in my code to convert them to delays and speeds.

How is this done in the gaming industry?

# Answer
The PS4 dualshock controller has 1 byte values for the left and right rumble packs, so this basically works like 8 bit music.

Most of these are behind an NDA, so it's very hard to get any information about this (even the information above was hard to get, I only figured it out from a third party SDK for node.js). These are the informations I pieced together:

The process is literally like making 1 byte stereo music (and it's supposedly made by a music artist). It involves connecting a PS4 controller to the computer and using a program to create the rumble patterns. They make one based on guessing, then run it, then tweak it and repeat these steps until the pattern feels good.

Some of the rumbles are generated programatically (like when a car goes off the road), but these are usually either a simple function (like sinus) or a constant value similar to how phones do it. Even the most complex effects consist of multiplying a normalized rumble pattern by the strength you want.

The PS4 SDK also comes with some predefined patterns. Some examples are: a sawtooth pattern (constantly increasing, then going from 255 to 0), a sinus wave and triangles (it increases to 255 linearly, then back down to 0 linearly).

I couldn't find any details about other controllers (especially Switch's HD rumble, not even the patent describes how that works). But they're probably using a similar approach with more precise rumble packs.

### Sources:
> 10 votes

# Answer
There's no standardised way.

Different devices have different rumble capabilities and limitations.

The vast majority of devices don't support actual "force feedback" (eg: A steering wheel that when hitting a curb/pothole would allow the programmer to push back to a specific angle) but just rumble in some uncontrolled/arbitrary direction.

So most of the Force Feedback features mentioned on MSDN/DirectX and other APIs have never really materialised in practice on the user market or have such poor and/or **non-portable** implementations of the "smart" controls (envelope, repeat, etc) as to be so unusable that **in practice developers are often forced to just use the ON/OFF controls directly with their own effect implementation.**

More advanced devices that allow servo-controlled force feedback need custom APIs as generic input APIs don't support the necessary parameters (exact angles, exact forces, limits, etc).

Adding emerging technologies like VR feeling-gloves into the mix make those generic APIs are even more lacking.

---

The most common implementation is with two DC motors with an unbalanced load each, one being weighted heavier than the other and with no precise speed control.

At the minimum you have on/off control over them and can do some limited PWM power control but not exact speed control. You don't know what the speed and the resulting vibration will actually be. Different controllers have different motors and weights that will run at different speeds for the same setting.

The motors have to spin up first and require full power for a bit of time then can be PWM to a lower setting. The spin up delay greatly limits the responsiveness.

The controllers are often updated once per frame giving you roughly 20Hz to 100Hz update frequency. This limits the resolution of your PWM control as you don't want the motors to stall at the lowest setting. And you don't know how low the end user controller's motors can go before stalling (stopping) so you need a good safety margin.

Some system requirements put further limit on what you can do with them.

Mobile devices usually only have 1 vibration motor and PWM may not be possible due to the low inertia from the size of the weight and slow update rate. The system may filter it further to prevent abuse or maybe even damage (power driver transistor limits and induction spikes) or just a really slow GPIO subsystem.

On mobile you may be limited or want to limit yourself to "vibrate for roughly X\*50 milliseconds" without PWM.

Some newer devices and controllers have a solenoid driven like a speaker by a low sample rate audio wave. These give you more control but are completely different from the more common controllers.

---

Because of all these differences you may want to abstract the vibration system to play a limited number of high-level macro-effects by name in a shoot-and-forget fashion: `PlayVibration(player, "Got Loot");`, `PlayVibration(player, "Heavy Fall");`, `StopAllVibrationFor(player);`, ...

Then you will have to create low-level vibration effects and vibration control code **adapted to each platforms individually**.

Even for a music game calling one-shot `PlayVibration` for every beat is easier to manage and control when factoring in **pausing the game** and the issues of re-syncing a would-be-smart periodic effect generator.

While devices with an actual solenoid-driven rumble can be treated like an audio device and use audio APIs due to battery concerns **this may run afoul of the system's regulations if the solenoid is constantly powered/active**. "Power Level 0" may not be the same as "Solenoid Off" so even then special care is needed.
> 5 votes

# Answer
From André LaMothe in Tricks of the Windows Game Programming Gurus:

> Programming these devices is very complex. Not only is a good understanding of force, spring, and motion needed, but the devices and the forces events, or effects, have a very close relationship to musical notes. That is, they can have an envelope that modulates the forces as they are applied to the various motors and actuators on the joystick. Thus, values like rate, frequency, timing, and so on all play a role in using and programming force feedback.

While that text is rather old, a quick search through the MSDN for force feedback shows the concepts mentioned haven't changed much; here's a summary of topics covered in their Basic Concepts of Force Feedback:

* Constant force: A steady force in a single direction
* Ramp force: A force that steadily increases or decreases in magnitude.
* Periodic effect: A force that pulsates according to a defined wave pattern.
* Condition: A reaction to motion or position along an axis.
* Envelope: An envelope defines an attack value and a fade value, which modify the beginning and ending magnitude of the effect.
* Offset: Defines the amount by which the waveform is shifted up or down from the base level.
* Scale: A single gain value can be applied to all effects for a device.

In terms of the PS4, the only thing I turned up was some Unreal Engine 4 documentation, which states:

> These (identifiers) will be mapped according to the platform specific implementation. For example, the PS4 only listens to the XXX\_LARGE channels and ignores the rest, while the XBox One could map the XXX\_LARGE to the handle motors and XXX\_SMALL to the trigger motors. And iOS can map LEFT\_SMALL to its single motor.

As Stephane Hockenhull's answer indicates, each platform is different. And as suggested in the GDSE chat it's possible the details for PS4 force feedback API are NDA restricted.
> 4 votes

---
Tags: playstation4, force-feedback
---