# Question
Title: Making a game using libgdx and when running the program immediately closes
When I run the program the window immediately closes and gives some errors.

GameMapImpl.java :

```
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapTile;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.mygdx.game.entities.Entity;
import com.mygdx.game.entities.Player;

import java.util.ArrayList;

public class GameMapImpl extends GameMap {

protected ArrayList<Entity> entities;

TiledMap tiledMap;
OrthogonalTiledMapRenderer tiledMapRenderer;

public GameMapImpl() {
    tiledMap = new TmxMapLoader().load("map.tmx");
    tiledMapRenderer = new OrthogonalTiledMapRenderer(tiledMap);
    entities = new ArrayList<Entity>();
    entities.add(new Player(40,300,this));

}
@Override
public void render(OrthographicCamera camera, SpriteBatch batch) {
    tiledMapRenderer.setView(camera);
    tiledMapRenderer.render();

    batch.setProjectionMatrix(camera.combined);
    batch.begin();
    batch.end();
    super.render(camera,batch);
    for(Entity entity : entities){
        entity.render(batch);
    }
}

@Override
public void render(OrthographicCamera camera) {

}

@Override
public void update(float delta) {
    for(Entity entity:entities){
        entity.update(delta,-9.8f);
    }
}

@Override
public void dispose() {
tiledMap.dispose();
}

@Override
public TileType getTileTypeByCoordinate (int layer, int col, int row) {
    TiledMapTileLayer.Cell cell = ((TiledMapTileLayer) tiledMap.getLayers().get(layer)).getCell(col, row);

    if (cell != null) {
        TiledMapTile tile = cell.getTile();

        if (tile != null) {
            int id = tile.getId();
            return TileType.getTileTypeById(id);
        }
    }
    return null;
}

@Override
public int getWidth() {
    return ((TiledMapTileLayer)tiledMap.getLayers().get(0)).getWidth();
}

@Override
public int getHeight() {
    return ((TiledMapTileLayer)tiledMap.getLayers().get(0)).getHeight();
}

@Override
public int getLayers() {
    return tiledMap.getLayers().getCount();
}
}

```

GameMap.java:

```
package com.mygdx.game.world;

import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

import static com.mygdx.game.world.TileType.TILE_SIZE;

public abstract class GameMap {

public  void render(OrthographicCamera camera, SpriteBatch batch){

}

public abstract void render(OrthographicCamera camera);

public  void update(float delta){

}

    public abstract void dispose();

/**
 * gets a tile by pixel position within the game world at a specific layer
 * @param layer
 * @param y
 * @param x
 * @return
 */
    public TileType getTileTypeByLocation(int layer, float y, float x){
        return this.getTileTypeByCoordinate(layer,(int)(x/ TILE_SIZE),(int)(y/ TILE_SIZE));
    }

/**
 * gets a tile at its coords wwithin the map at a specific layer
 * @param layer
 * @param col
 * @param row
 * @return
 */
    public abstract  TileType getTileTypeByCoordinate(int layer, int col,int row);

    public boolean doesRectCollideWithMap(float x,float y, int width, int height){
        if(x<0|| y<0|| x+width >getPixelWidth()|| y+height>getPixelHeight())
             return true;

        for (int row = (int) (y / TileType.TILE_SIZE); row < Math.ceil((y + height) / TileType.TILE_SIZE); row++) {
            for (int col = (int) (x / TileType.TILE_SIZE); col < Math.ceil((x + width) / TileType.TILE_SIZE); col++) {
                for (int layer = 0; layer < getLayers(); layer++) {
                    TileType type = getTileTypeByCoordinate(layer, col, row);
                    if (type != null && type.isCollidable()) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public abstract int getWidth();
    public abstract int getHeight();
    public abstract int getLayers();

    public int getPixelWidth(){
        return this.getWidth()* TILE_SIZE;
    }
     public int getPixelHeight(){
        return this.getHeight()* TILE_SIZE;
    }

}

```

Entity.java :

```
package com.mygdx.game.entities;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector2;
import com.mygdx.game.world.GameMap;

public abstract class Entity {

protected Vector2 pos;
protected EntityType type;
protected  float velocityY=0;
protected GameMap map;
protected boolean grounded=false;

public Entity(float x, float y, EntityType type, GameMap map) {
    this.pos = new Vector2(x,y);
    this.type=type;
    this.map=map;

}
public void update(float deltaTime,float gravity){
    float newY=pos.y;
    this.velocityY+=gravity*deltaTime*getWeight();
    newY +=this.velocityY*deltaTime;

    if(map.doesRectCollideWithMap(pos.x,newY,getWidth(),getHeight())){
        if (velocityY<0){
            this.pos.y=(float) Math.floor(pos.y);
            grounded=true;
        }
        this.velocityY=0;
    }else{
    this.pos.y= newY;
    grounded=false;
    }
}
public abstract void render(SpriteBatch batch);
protected void moveX (float amount){
    float newX= this.pos.x+amount;
    if (!map.doesRectCollideWithMap(newX,pos.y,getWidth(),getHeight()))
        this.pos.x=newX;
}
public Vector2 getPos() {
    return pos;
}

public EntityType getType() {
    return type;
}

public float getX(){
    return pos.x;
}

public float getY(){
    return pos.y;
}

public GameMap getMap() {
    return map;
}

public boolean isGrounded() {
    return grounded;
}

public int getWidth(){
    return type.getWidth();
}

public int getHeight(){
    return type.getHeight();
}
public float getWeight(){
    return type.getWeight();
}
}

```

Player.java:

```
package com.mygdx.game.entities;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.mygdx.game.world.GameMap;

public class Player extends Entity {

private  static final int SPEED=80;
private static final  int JUMP_VELOCITY=5;

Texture image;

public Player(float x, float y, GameMap map) {
    super(x, y, EntityType.PLAYER, map);
    image =  new Texture("PlayerCharacter.png.png");
}

@Override
public void update(float deltaTime, float gravity) {
   if (Gdx.input.isKeyJustPressed(Input.Keys.SPACE)&& grounded)
   this.velocityY +=JUMP_VELOCITY*getWeight();
    super.update(deltaTime, gravity);

    if(Gdx.input.isKeyPressed(Input.Keys.A))
        moveX(-SPEED*deltaTime);
    if(Gdx.input.isKeyPressed(Input.Keys.D))
        moveX(SPEED*deltaTime);
}

@Override
public void render(SpriteBatch batch) {

    batch.draw(image,pos.x,pos.y,getWidth(),getHeight());
}
}

```

MyGdxGame.java:

```
package com.mygdx.game;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.mygdx.game.world.GameMap;
import com.mygdx.game.world.GameMapImpl;

public class MyGdxGame extends ApplicationAdapter {

OrthographicCamera cam;
SpriteBatch batch;
Texture img;

GameMap gameMap;

@Override
public void create () {
    batch = new SpriteBatch();

    cam = new OrthographicCamera();
    cam.setToOrtho(false,Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
    cam.update();

    gameMap = new GameMapImpl();
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
}

@Override
public void render () {
    Gdx.gl.glClearColor(1, 0, 0, 1);

    cam.update();
    gameMap.update(Gdx.graphics.getDeltaTime());
    gameMap.render(cam,batch);

}

@Override
public void dispose () {
    batch.dispose();

}
}

```

TileType.java:

```
package com.mygdx.game.world;

import java.util.HashMap;

public enum TileType{

SHADEDTILE(1,true,"ShadedTile"),
BLACKTILE(2,true,"BlackTile"),
WHITETILE(3,false,"WhiteTile"),
GRIDTILE(4,false,"GridTile"),
SPIKE(5,true,"Spike"),
CLOSEDDOOR(6,true,"ClosedDoor"),
OPENDOOR(7,true,"OpenDoor");

public static final int TILE_SIZE = 32 ;
private int id;
public boolean collideable;
private String name;
public float damage;
private TileType(int id,boolean collidieable, String name){

}
public boolean isCollidable() {
    return collideable;
}
private TileType(int id, boolean collideable, String name,float damage){
    this.id=id;
    this.collideable=collideable;
    this.name=name;
    this.damage=damage;
}

public int getId(){
    return id;
}
public boolean isCollideable(){
    return  collideable;
}
public String getName(){
    return  name;
}
public float getDamage(){
    return  damage;
}
public static HashMap<Integer,TileType>tileMap;
static {
    for (TileType tileType : TileType.values()){
        tileMap.put(tileType.getId(),tileType);
    }
}
public static TileType getTileTypeById(int id) {
    return tileMap.get(id);
}

}

```

Here are the errors I'm getting :

```
Exception in thread "LWJGL Application"
com.badlogic.gdx.utils.GdxRuntimeException:
java.lang.ExceptionInInitializerError
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:133)
Caused by: java.lang.ExceptionInInitializerError
at com.mygdx.game.world.GameMapImpl.getTileTypeByCoordinate(GameMapImpl.java:74)
at com.mygdx.game.world.GameMap.doesRectCollideWithMap(GameMap.java:49)
at com.mygdx.game.entities.Entity.update(Entity.java:26)
at com.mygdx.game.entities.Player.update(Player.java:25)
at com.mygdx.game.world.GameMapImpl.update(GameMapImpl.java:56)
at com.mygdx.game.MyGdxGame.render(MyGdxGame.java:40)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:225)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:126)
Caused by: java.lang.NullPointerException
at com.mygdx.game.world.TileType.<clinit>(TileType.java:50)
... 8 more

```

Sorry if this isn't the optimal way to show the code, but I'm not sure how else to show whats going wrong.

# Answer
The error tells you exactly what's wrong:

```
Caused by: java.lang.NullPointerException

```

This means that something wasn't initialized

```
at com.mygdx.game.world.TileType.<clinit>(TileType.java:50)

```

This means that it happened on line 50 on TileType.

You forgot to initialize the tileMap hashmap
> 1 votes

---
Tags: java, libgdx
---


# Question
Title: When making a game using libgdx the program immediately closes when being run
The problem is similar to my last question, but some of the errors are fixed.

The file:

```
public class MyGdxGame extends ApplicationAdapter {

OrthographicCamera cam;
SpriteBatch batch;
Texture img;

GameMap gameMap;

@Override
public void create () {
    batch = new SpriteBatch();

    cam = new OrthographicCamera();
    cam.setToOrtho(false,Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
    cam.update();

    gameMap = new GameMapImpl();
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
}

@Override
public void render () {
    Gdx.gl.glClearColor(255, 255, 255, 1);
    batch.begin();
    batch.end();
    cam.update();
    gameMap.update(Gdx.graphics.getDeltaTime());
    gameMap.render(cam,batch);
}

@Override
public void dispose () {
    batch.dispose();

}
}

```

Errors:

```
Exception in thread "LWJGL Application" java.lang.IllegalStateException: SpriteBatch.end must be called before begin.
at com.badlogic.gdx.graphics.g2d.SpriteBatch.begin(SpriteBatch.java:169)
at com.mygdx.game.MyGdxGame.render(MyGdxGame.java:38)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:225)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:126)

```

# Answer
> 1 votes
This error is telling you exactly what the problem is...

`SpriteBatch.end` must be called before begin.

The `render()` method code you have shared calls `batch.begin()` then `batch.end()`. But at some point before you are calling `render()`, you are probably calling `batch.begin()`. So then render is calling `batch.begin()` a second time and giving you that error.

In other words, you are probably calling `batch.begin()` twice in a row.

So find out where you are calling `batch.begin()` previously, and call `batch.end()` to close it.

---
Tags: java, libgdx
---


# Question
Title: Unity3d: Find which gameObject is in front
I have two `gameObjects` `A` and `B`. They are `rotated` at `90 degrees`, which makes its `local y axis` face forward.

**1st Case**

In this case, the `local y position of B` is ahead of `local y position of A`

**2nd Case**

Even though their global position is same as the 1st case, we can observe here that `local y position of A` is ahead of `local y position of B`.

I tried using `A.transform.localPosition.y` and `B.transform.localPosition.y` to find which is greater but it doesnt work. What can I do to find which is front in these two different cases?

# Answer
> 5 votes
You can check simple ahead/behind relationships using the dot product:

```
Vector3 displacement = B.transform.position - A.transform.position;

float dot = Vector3.Dot(displacement, A.transform.forward);

```

If `dot` is greater than zero, then B is ahead of A along A's forward vector. (The arrow from A to B has a component in the same direction as A's forward)

If `dot` is less than zero, then B is behind A along A's forward vector. (The arrow from A to B has a component in the opposite direction as A's forward)

If `dot` is zero, then B is somewhere directly to the side of A, neither in front nor behind. The A→B arrow points perpendicular to A's forward axis.

---
Tags: unity, mathematics, rotation, vector, direction
---


# Question
Title: Raise/Lower Object Height Based on Distance, with Easing
I'm trying to make an indicator object appear higher up in the sky the farther away a player is, up to a certain distance.

Basically, if the player is \< 5 distance away, the object's height should be 1. If the player is \> 60 distance away, the object's height should be 50. If the player's distance is between 5 and 60, the height of the object should be calculated based on the given scale, with an easing function applied so that it moves gradually to it's top and bottom locations.

This can be best illustrated with the attached graph that I created. The graph may not be perfect, but it should be close enough to get the general idea of what I'm hoping to achieve.

That said, I'd assume you'd need at least 5 variables... `groundHeight`, `maxHeight`, `minHeight`, `maxDistance`, and `minDistance`, but how would I use this information to calculate the expected height for a given distance?

This isn't related to a specific game engine and language isn't important. I happen to be working with Lua on my current project, but JavaScript, C#, or even pseudo-code solutions would help me understand how this is achieved.

# Answer
> 3 votes
First, we want to get out position between our min & max, normalized/clamped into a value between 0 (at/below the minimum) and 1 (at/above the maximum). That can look like this:

```
float t = Clamp(
          (distance - minDistance)
          / (maxDistance - minDistance),
          0, 1);

```

Then we can use a cubic SmoothStep function to bend this 0-1 value to have that signature sigmoid shape, easing in and out at the ends:

```
float sigmoid = 3*t*t - 2*t*t*t;

```

Lastly, we can use this sigmoid shape to blend between our outputs:

```
float height = minHeight + sigmoid * (maxHeight - minHeight);

```

Depending on your environment, you may have a built-in SmoothStep function that can do two or more of these steps in one fell swoop. Check the docs for your particular version for guidance, as I've seen some versions that take the distances and produce sigmoid (ie. the first two steps), and others that take the height min/max and t to produce the output (ie. the last two steps).

---
Tags: mathematics, easing
---


title: var=time() vs time()=var pico8/lua

text:
# Question
Title: var=time() vs time()=var pico8/lua
time() is a preset function in pico8 gameengine.

I don't understand whatsoever why I get an error when I write: time() = var

But it's fine if I write (where var is any variable) var = time()

What are the rules dictating order? This makes no sense to me.

For some context consider a time function:

```
time_diff=0

function time_change()
if time() - time_diff > 1 then
time_diff=time()
end
end

```

if You change to time()=time\_diff.....it generates an error.

# Answer
In math, the = sign represents the **equality comparison operator**, an assertion that "the thing on the left has the same value as the thing on the right."

This operator is **commutative**: you can exchange the left & right sides without changing anything (the statement that the left & right sides have the same value remains as true or as false as it was before. Reading them in a different order doesn't change its truth value)

In programming languages like Lua, the equality comparison operator is written `==`, with *two* equals signs.

In these languages, when you write just one `=`, you're not doing an equality comparison at all. **This is a completely different operation: an assignment operator.**

The assignment operator `=` says "take the value of the thing on the right, and assign it to the variable on the left"

It's the difference between "check *whether* these things are equal" (`==`) versus "*make* these two things equal" (`=`)

But of course there are two ways we could make the things equal by changing the value of one side: the left or the right. So, we say that the assignment operator always changes the left side. That means that **assignment is *not* commutative**. Observe:

```
local a = 1
local b = 2

if aFirstThenBSecond then
    a = b
else
    b = a
end

```
* If we take the first branch, we're saying "take the value of `b` and store it in variable `a`," so both variables hold the value 2 when this code finishes executing.
* If we take the second branch, we're saying "take the value of `a` and store it in variable `b`," so both variables hold the value 1 when this code finishes executing.

In both cases, `a` and `b` are equal to one another at the end, so the meaning of `=` as "make these things equal" holds both ways.

We get a different resulting value in the variables depending on the order of our assignment, because we're asking the computer to take a meaningfully different action each way.

That's why...

* `myVar = time()` is valid: it says "take the current time value and store it in the variable `myVar`
* `time() = myVar` is not valid: it says "take the value of `myVar` and store it into the current time" which doesn't make sense.

You could argue that programming language authors should have chosen a different symbol/syntax for assignment, like `destination <-- source`, but it turns out we need to write assignment operations *a lot* when we create programs, so having it be short and accessible without a shift key is very useful.

Some languages will let you type just a single `=` for both equality comparison and assignment, and the compiler/interpreter will try to figure out which one you wanted based on the surrounding context. This can lead to bugs though if the programmer thought they were comparing but the compiler read it as an assignment, which is why Lua and C-like languages use different operators for them. Some will also warn or error if you write something like this:

```
if myVar = 5 then...

```

Which *looks* like a comparison ("take this branch if and only if `myVar` has a value of 5") but is *actually* an assignment ("set `myVar` to 5 and then take this branch"). So some programmers will program defensively by using the fact that flipping an assignment with a constant/function call is an error, to make a what's called a "Yoda Condition":

```
if 5 == myVar then...

```

If we remember to use the `==` then this comparison works right in either order. If we accidentally forget one `=` and end up writing an assignment, it's an error "you can't assign a new value to the number 5!" which helps us find and fix our typo instead of letting the bug linger unfound. ;)
> 6 votes

# Answer
I'm not familiar with the languge.

`time()` being a function and returning a *value*, it's generally not possible (in most languages) to assing a value to such returned values (and I really wonder what would be the intention).

If you find it possible to do the same with other language native functions (I have not been able to find anything about `io.read()`), it is most likely because the function returns a *reference*, and it is to that that you are assinging a new value (something that tells where the actual value is).

I don't know any language where you can interchange the order of operands and you get the same effect, it's generally `destination = source`.
> 0 votes

---
Tags: lua, pico-8
---


# Question
Title: Confuddled with learning C++ / UE4 . Why can't I access this AActors properties?
Hello all I decided to punish myself further by now adding C++ to my list of things i know a little bit about.

Some of it looks familiar having dealt with C# quite a bit, but i am getting caught out on many occasions.

Here I am trying to open a door when the Actor enters a trigger in the level.

```
void UOpenDoor::Open_Door()
{
// Find the owning actor:
AActor* Owner = GetOwner();

// Create a rotator:
FString oldAngle = "old angle = " + Owner->GetActorRotation().Roll.ToString();
UE_LOG(LogTemp, Warning, TEXT(oldAngle));
FRotator NewRotation = FRotator(0.0f, Owner->GetActorRotation().Roll + OpenAngle, 0.0f);

// Set the door rotation:
Owner->SetActorRotation(NewRotation);
}

```

This is likely a very obvious and silly error to anyone with any experience writing in C++. But heres my questions:

Why is the Owner underlined in red? And can anyone help me out with what exactly the pictured error means? (I tried making the FString and FString\* pointer , I also tried \<\< instead of + in the string definition. And I also tried without the literal "old angle" string part. ---no dice!)

I've also tried this, now I seem to have accessed the Roll property, but how do I display it in a log output for example?

```
    // Find the owning actor:
AActor* Owner = GetOwner();

// Create a rotator:
int test = (int)Owner->GetActorRotation().Roll;
UE_LOG(LogTemp, Warning, TEXT("TEST = " << test.ToString()));
FRotator NewRotation = FRotator(0.0f, Owner->GetActorRotation().Roll + OpenAngle, 0.0f);

```

This code gave me error red-line under UE\_LOG saying "expression must have class type"

# Answer
I see a few things to note in your code. The first thing, however, is that in general calling `GetActorRotation` on an `AActor` pointer is fine.

The red underline in your screenshot is either due to the fact that you're trying to add (`operator+`) a string literal and an `FString` (which isn't supported; see below), or simply because the Visual Studio's Intellisense parser is occasionally confused by the complexity of the macro-and-generated-code-heavy Unreal codebase and malfunctions.

That said:

* In Unreal, you should use `TEXT()` for *string literals*, that is, `"stuff like this in double quotes"`); the macro ensures that the literal will be of the correct type (`TCHAR*`). Don't use `TEXT()` around variables. Your `TEXT(oldAngle)` expression is invalid.
    + To get the underlying `TCHAR*` from an `FString`, dereference it (`*oldString`).
* `FString` doesn't have any overload for `operator<<`, so you can't use that to concatenate strings. It doesn't overload `operator+` either, in fact, and only supports `operator+=`. To concatenate an `FString` and something else, you must thus do: `FString s(TEXT("Hello,")); s += TEXT(" world!");` or similar.
* The elements of a rotator (roll, pitch, yaw) are floats, not integers.

In other words, you probably want to write something like:

```
AActor* Owner = GetOwner();
float Roll = Owner->GetActorRotation().Roll;
UE_LOG(LogTemp, Warning, TEXT("Roll is %f"), Roll);

FRotator NewRotation(0.0f, Roll + OpenAngle, 0.0f);
...

```
> 1 votes

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


# Question
Title: Unity: 'Quaternion.RotateTowards' animation is too fast (instantaneous)
I have a 'block-on-a-hinge' scenario where I just want it to smoothly rotate into the position of a stair step. I messed with this for a day and finally verified that my start and end angles are correct. The problem now is that the rotation animation is instantaneous instead of smooth over time. How can I adjust this so the rotation takes about 2 seconds? Plugging this into the 'maxDegreesDelta' argument felt intuitive but didn't do anything at all:

```
endAngle * Time.deltaTime / 2.0f

```

See the Documentation

video footage

**The block itself is parented to this empty (hinge location):**

**The parent of all the hinges is just 10 blocks in a row rotated by \\$-\arctan{\left(\frac{4}{3}\right)}\\$ (so that is the angle to be undone):**

Here is the script:

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

public class SpinningStep : MonoBehaviour
{
    [SerializeField]
    GameObject triggerObj;
    bool disabled = false;
    Quaternion startAngle;
    Quaternion endAngle;
    // Start is called before the first frame update
    void Start()
    {
        startAngle = transform.localRotation; // correct
        Debug.Log(startAngle.eulerAngles);
        endAngle = startAngle * Quaternion.Euler(Mathf.Rad2Deg * Mathf.Atan(4.0f / 3.0f),0,0);
        Debug.Log(endAngle.eulerAngles); // FINALLY correct!
    }

    // Update is called once per frame
    void Update()
    {
        disabled = GameObject.Find(triggerObj.name).GetComponentInChildren<ItemBox>().disabled;

        if (disabled)
        {
            gameObject.transform.rotation = Quaternion.RotateTowards(startAngle, endAngle, Time.deltaTime);
        }
    }
}

```

**EPILOGUE - Corrections:**

This script, based off of feedback and answer from DMGregory, eliminates initialization errors for the triggerObj and gives smooth time animation:

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

public class SpinningStep : MonoBehaviour
{
    [SerializeField]
    ItemBox triggerObj;
    bool disabled = false;
    Quaternion startAngle;
    Quaternion endAngle;
    // Start is called before the first frame update

    float rotationSpeed;

    void Start()
    {
        float travelDegrees = Mathf.Rad2Deg * Mathf.Atan(4.0f / 3.0f);
        startAngle = transform.rotation;
        endAngle = startAngle * Quaternion.Euler(travelDegrees, 0, 0);

        // Speed in degrees per second.
        rotationSpeed = travelDegrees / 2.0f;
    }

    void Update()
    {
        if (triggerObj.disabled)
        {
            transform.rotation = Quaternion.RotateTowards(
                  transform.rotation,
                  endAngle,
                  rotationSpeed * Time.deltaTime  // Our third argument is a degree limit.
            );
        }
    }

```

I knew that how I was getting the trigger was garbage and wanted to ask, because I had trouble making it work, but I wanted to keep this question focused. Very silly oversight not using the name of the script as the type. Thanks!

# Answer
It looks like you're mixing up & combining two different ways to rotate an object: Slerp and RotateTowards. Your code has elements of each, but uses neither correctly.

We could implement this with a Slerp, or Spherical Linear Interpolation (where you blend from a start orientation to an end orientation using a progress variable):

```
float rotationProgress = 0f;
float rotationDuration = 2f;

// These aren't angles, they're orientations, so let's name them to match their real role.
Quaternion startOrientation;
Quaternion endOrientation;

// Don't search for this by name every frame, just cache it.
ItemBox itemBox;

// ... (Skipping Start() for now)

void Update() {
    if (itemBox.disabled)
    {
        rotationProgress = Mathf.Clamp01(rotationProgress + Time.deltaTime/rotationDuration);
        gameObject.transform.rotation = Quaternion.Slerp(
                    startOrientation, // Out first argument is the start orientation.
                    endOrientation,
                    rotationProgress  // Our third argument is a progress fraction.
        );
    }
}

```

Or we could use RotateTowards (where you rotate from wherever you happen to be, using your current orientation, an end orientation, and a max rotation increment):

```
float rotationSpeed;

void Start() {
    float travelDegrees = Mathf.Rad2Deg *  * Mathf.Atan(4.0f / 3.0f);
    startOrientation = transform.rotation;
    endOrientation = startOrientation * Quaternion.Euler(travelDegrees, 0, 0);

    // Speed in degrees per second.
    rotationSpeed = travelDegrees / rotationDuration;

    // Try to replace this GameObject.Find with a different way to get your target object.
    // Searching for objects by name is error-prone and scales poorly.
    itemBox =  GameObject.Find(triggerObj.name).GetComponentInChildren<ItemBox>();
}

void Update() {
    if (itemBox.disabled) {
        transform.rotation = Quaternion.RotateTowards(
              transform.rotation,             // We don't use startOrientation in this version.
              endOrientation,
              rotationSpeed * Time.deltaTime  // Our third argument is a degree limit.
        );
    }
}

```
> 2 votes

---
Tags: unity, c#, animation, rotation, lerp
---


# Question
Title: How do I draw a context menu next to my object?
I want to show a menu next to an item in an inventory. This is what I try to rebuild:

I do this by placing a canvas in 3D world space next to the inventory:

As I don't want the menu to be rotated, I rotated the menu the opposite X value as the camera. The camera has an X rotation of -11, so I rotate the menu by 11 to make it look straight:

Since I don't want the menu to get stuck in the case, I move it closer to the camera:

One can see that the menu is now offset to the left and to the top because of the camera perspective.

How could I offset the menu in such a way that it still aligns with the right top corner of the item?

Thank you!

# Answer
Don't put a UI element in perspective only to fight and counter that perspective. You're just making your life more complicated that way.

Instead you can use a canvas in "Screen Space - Overlay" mode like you'd asked about previously.

Then place the position of your menu to match the on-screen position of the object you want it to follow, something like this:

```
void PlaceMenuAtWorldPosition(Vector3 wordPosition, RectTransform menu, Camera camera) {
    Vector2 screenPoint = camera.WorldToScreenPoint(worldPosition);

    Vector2 uiPoint;
    RectTransformUtility.ScreenPointToLocalPointInRectangle(
        (RectTransform)menu.parent, // Local space to place the point into.
        screenPoint,
        null,         // We're in screen space overlay, no need for camera perspective.
        out uiPoint   // The resulting point in the container's space.
    );

    menu.anchoredPosition = uiPoint;
}

```
> 2 votes

---
Tags: unity
---


title: Downscaling texture via mipmap

text:
# Question
Title: Downscaling texture via mipmap
Copied from Computer Graphics SE.

---

I am implementing a post-processing effect in my DirectX 11 pet renderer. The post-processing pass is implemented by rendering a full-screen quad covered with texture containing original rendered image, which works as it should, but I have problems with downscaling the texture.

The non-processed testing scene looks like this (three very bright emmissive spheres):

I see no problem at this stage, but when I run the first post-processing pass, which just down-scales the image by the factor of 8 using the texture sampler, the result is very flickery (up-scaled for clarity):

I expected a mipmap would solve or at least reduce the flickering, but it didn't change a thing. What am I doing wrong?

# RenderDoc Update

After investigating the issue using RenderDoc I found that the mipmap is being generated successfully and it's third level looks like this:

However, the output of the down-scaling pass looks like this:

As if the sampler didn't use the mipmap at all. Don't get distracted by coloured object instead almost white ones. I lowered the sphere brightness a bit while investigating the bug.

Even if I choose the mipmap level explicitly

```
float4 vColor = s0.SampleLevel(LinearSampler, Input.Tex, 3);

```

it changes nothing :-/

RenderDoc also says "LOD Clamp 0-0" for the used sampler. What is it? Couldn't this be the problem?

# DirectX details

### Samplers

```
D3D11_SAMPLER_DESC descSampler;
ZeroMemory(&descSampler, sizeof(descSampler));
descSampler.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
descSampler.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
descSampler.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;

descSampler.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
mDevice->CreateSamplerState(&descSampler, &mSamplerStateLinear);

descSampler.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
hr = mDevice->CreateSamplerState(&descSampler, &mSamplerStatePoint);

```

...are set right before rendering the screen quad

```
ID3D11SamplerState* aSamplers[] = { mSamplerStatePoint, mSamplerStateLinear };
mImmediateContext->PSSetSamplers(0, 2, aSamplers);

```

...and used within the down-scaling PS shader

```
SamplerState PointSampler  : register (s0);
SamplerState LinearSampler : register (s1);

Texture2D s0 : register(t0);

float4 Pass1PS(QUAD_VS_OUTPUT Input) : SV_TARGET
{
    return s0.Sample(LinearSampler, Input.Tex);
}

```

### Texture

```
D3D11_TEXTURE2D_DESC descTex;
ZeroMemory(&descTex, sizeof(D3D11_TEXTURE2D_DESC));
descTex.ArraySize = 1;
descTex.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
descTex.MiscFlags = D3D11_RESOURCE_MISC_GENERATE_MIPS;
descTex.Usage = D3D11_USAGE_DEFAULT;
descTex.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
descTex.Width  = width;
descTex.Height = height;
descTex.MipLevels = 0;
descTex.SampleDesc.Count = 1;
device->CreateTexture2D(&descTex, nullptr, &tex);

```

...it's render target view

```
D3D11_RENDER_TARGET_VIEW_DESC descRTV;
descRTV.Format = descTex.Format;
descRTV.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
descRTV.Texture2D.MipSlice = 0;
device->CreateRenderTargetView(tex, &descRTV, &rtv);

```

...it's shader resource view

```
D3D11_SHADER_RESOURCE_VIEW_DESC descSRV;
ZeroMemory(&descSRV, sizeof(D3D11_SHADER_RESOURCE_VIEW_DESC));
descSRV.Format = descTex.Format;
descSRV.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
descSRV.Texture2D.MipLevels = (UINT)-1;
descSRV.Texture2D.MostDetailedMip = 0;
device->CreateShaderResourceView(tex, &descSRV, &srv);

```

Explicit generation of mipmap is called after the scene was rendered into the texture and another texture was set as a render target.

```
ID3D11RenderTargetView* aRTViews[1] = { mPass1Buff.GetRTV() };
mImmediateContext->OMSetRenderTargets(1, aRTViews, nullptr);

mImmediateContext->GenerateMips(mPass0Buff.GetSRV());

ID3D11ShaderResourceView* aSRViews[1] = { mPass0Buff.GetSRV() };
mImmediateContext->PSSetShaderResources(0, 1, aSRViews);

```

The code is compiled in debug and the D3D device was created with `D3D11_CREATE_DEVICE_DEBUG` flag and I get no runtime errors on the console.

# Answer
Your problem is that you initialize your sampler description by setting all of it's members to 0, via ZeroMemory. See this related question and answer: How to fill/initialize D3D11\_SAMPLER\_DESC properly?

Also the documentation for D3D11\_SAMPLER\_DESC which explains the values you should use: https://docs.microsoft.com/en-us/windows/win32/api/d3d11/ns-d3d11-d3d11\_sampler\_desc

You shouldn't be surprised that your min and max LOD are both 0 (which will result in miplevel 0 always being selected irrespective of other options) because that is what you have explicitly asked for, via your ZeroMemory call. Again, refer to the documentation, linked above, for the values you should be using.
> 2 votes

---
Tags: directx11, post-processing, image-processing, sampler-state
---


# Question
Title: Why is the Enemy not changing direction when entering the collider?
I'm really new to Unity, and I'm trying to make a 2.5D platform game. I want to make my enemies walk on a platform and turn when they reach the end of the platform so I placed two triggers at the beginning and at the end of it to change the direction of the enemy.

```
public class BanditScript : EnemyScript{
    // Start is called before the first frame update
    private Rigidbody rb;
    private Vector3 moveDir;
    private bool left;
    void Start(){
        left = true;
        speed = 1;
        player = GameObject.FindWithTag("Player");
        animator = GetComponent<Animator>();
        minDistance = 1;
        rb = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update(){
        IsNear();
        if (near) {
            //attack
            animator.SetBool("isAttacking", true);
            animator.SetBool("isMoving", false);
        }
        else {
            MoveOnPlat();
            animator.SetBool("isAttacking", false);
            animator.SetBool("isMoving", true);
        }
    }
    void MoveOnPlat() {
        animator.SetBool("isMoving", true);
        if (left)
            moveDir = transform.forward;
        else {
            moveDir = -transform.forward;
        }
        rb.velocity = moveDir * speed;
    }
    private void OnTriggerEnter(Collider other) {
        if (other.tag == "platEndL") {
            left = false;
            transform.rotation = Quaternion.Euler(0, 90, 0);
        }
        if (other.tag == "platEndR") {
            left = true;
            transform.rotation = Quaternion.Euler(0, -90, 0);
        }
    }
}

```

This is my class, the issue is that the enemy keeps moving in the same direction despite everything. Can you help me?

# Answer
> 2 votes
The issue you're having comes from the fact that you change the direction of your enemy twice, effectively canceling the effect you're after.

```
void MoveOnPlat() {
    animator.SetBool("isMoving", true);
    if (left)
        moveDir = transform.forward;
    else {
        moveDir = -transform.forward;
    }
    rb.velocity = moveDir * speed;
}
private void OnTriggerEnter(Collider other) {
    if (other.tag == "platEndL") {
        left = false;
        transform.rotation = Quaternion.Euler(0, 90, 0);
    }
    if (other.tag == "platEndR") {
        left = true;
        transform.rotation = Quaternion.Euler(0, -90, 0);
    }
}

```

Here,

```
    if (left)
        moveDir = transform.forward;
    else {
        moveDir = -transform.forward;
    }
    rb.velocity = moveDir * speed;

```

changes the direction in which is going, while

```
    if (other.tag == "platEndL") {
        left = false;
        transform.rotation = Quaternion.Euler(0, 90, 0);
    }
    if (other.tag == "platEndR") {
        left = true;
        transform.rotation = Quaternion.Euler(0, -90, 0);
    }

```

changes the orientation.

Assuming the enemy walks "forward", it's as if you asked it to "turn around" and then "walk in reverse".

To fix this, you need to drop one of the other.

I suggest you keep the `transform.rotation =` and drop the `moveDir` part, making it as if your object would always go forward:

```
void MoveOnPlat() {
    animator.SetBool("isMoving", true);
    rb.velocity = transform.forward * speed;
}

```

# Answer
> 0 votes
If your making this in 2D your "OnTriggerEnter" needs to be "OnTriggerEnter2D, otherwise it won't work. This could be your problem.

Hope this helps

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


# Question
Title: Problem making shooting follows an actor/object
At first I created an actor to be a projectile, he acts with a simple projectile. When generated it goes straight, anyway...

To do this, I added the **Projectile Movement** component.

It turns out that I wish this projectile did not go straight ahead simply, I would like it to be generated when it came to a minion.

Then my problems began, because being simply an actor, it seems that he can not move with the **Simple Move to Actor/Location** function.

**I created 3 sockets:**

One for each shot/projectile I was going to test.

**Shooter Blueprint:**

The **Event Atirar** causes the 3 shots/projectiles I created to be generated (TiroActor, TiroCharacter and TiroPawn).

**TiroActor Blueprint:**

**TiroCharacter Blueprint:**

**TiroPawn Blueprint:**

**I wish that when they were generated, they would go towards the only existing minion in the game, but this does not happen:**

The **Tiro Actor** goes straight, and nothing makes it stop (I activated the "call in editor" option for the **Event Andar**, but it does not match).

**The Tiro Character falls to the ground and does nothing, but corresponds when I call the Event Andar manually:**

The **Tiro Pawn** is not even generated...

I modified the "Auto Posses AI" option of **Tiro Character** and **Tiro Pawn** to **Placed in World or Spawned**.

I removed the gravity of all the components of the **Tiro Character**, but even so when generated it falls to the ground.

I would like to know how to make an object (be it actor, pawn or character) when it is generated follow the target (in this case a minion) until it collides with it.

---

**EDIT 1 (complement)**

If it was difficult to understand, I'd like to know how to do something like an AA from a Clash of Clans archer, even a champion AA that attacks from a distance, whether from Dota or LOL.

The projectile of the Dota/LOL tower would be a good example. A guided missile too...

# Answer
The chosen code was **TiroActor**. This is because it is the simplest (cause less impact on performance) and supplies all needs.

I took out the other two shots (TiroPawn and TiroCharacter).

**Event Shoot (Shooter Blueprint):**

As I suspected, it did not make sense to use the **Simple Move to Location** function on actors that does not have support to execute it.

So you must set the target and also set the projectile to be **HOMING**.

So you set the **Homing Target** and the **Homing Acceleration Magnetude**.

**Event to target setting and to defining aspects of the projectile (Projectile Blueprint):**

This last part is optional, as it sets the rotation of the projectile so that it points to the target. If your projectile is a sphere, there is no need to put it.

**Event to set the rotation of the projectile (Projectile Blueprint):**

**Links that helped me:**

https://www.youtube.com/watch?v=oyNzsbTpGqg

https://forums.unrealengine.com/community/community-content-tools-and-tutorials/48896-homing-missile?77586-Homing-missile=

https://answers.unrealengine.com/questions/239188/rinterp-to-doesnt-slowly-change-character-rotation.html

https://www.youtube.com/watch?v=TCkFqSOdw6M&
> 0 votes

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


title: Problem with action mapping

text:
# Question
Title: Problem with action mapping
Summarizing my problem well, I need a single button (right mouse button) to do two things.

In my project (TopDown) I defined that instead of the *left mouse button*, the character moves with the *right mouse button*.

I happen to like that when I click the right mouse button on a particular actor, a simple event is called (print hello).

**I tried doing this with the Event On Clicked, but it only works with the left mouse button:**

**With the help of these links:**

https://www.unrealengine.com/en-US/blog/input-action-and-axis-mappings-in-ue4

https://answers.unrealengine.com/questions/134349/right-click-on-an-actor.html

https://answers.unrealengine.com/questions/17729/how-to-create-a-right-mouse-click-event-with-bluep.html

I figured out how to do an action/event call with the right mouse button, but even then I did not succeed.

**Soon I discovered that the reason was that there was already an action that was executed with the right mouse button (walk/set destination):**

I would like my character to continue to move with the right click of the mouse, but how do I also call an event when I click the right mouse button?

---

**EDIT 1**

**If the mapping is done with two different keys, it works perfectly:**

**In this case the character jumps and walks (instead of jumping it could be anything else):**

**I want this to happen by right-clicking (walking and jumping):**

This action I want to perform is when clicking on the mesh of any actor, but I can only do this with the left button.

# Answer
To solve my problem I would have to know how to modify the **Input Action Set Destination**, or simply reproduce what the **Input Action Set Destination** does.

**With the help of this question (which I was able to answer, it was a simple mistake) I was able to figure out how to make the character walk based on the mouse click:**

https://answers.unrealengine.com/questions/260158/making-a-top-down-mouse-following-character.html?childToView=910918#answer-910918

**Just create an Action Mapping:**

**Using the code below you can get the character to go to the mouse click (ignore the pink circles, I re-used the image):**

**Based on the previous code, it was only me that added a condition based on the actor that was clicked:**

*In the future this condition will be something involving the floor of the level, but for the answer I used the tower and inverted logic.*
> 0 votes

# Answer
If you only want the RMB to trigger the event, then use the "Button Pressed" pin from the OnClicked method to check if it's a right-click or not before continuing.

You can also use GetEffectingButton and do a check to see if its RMB as illustrated here.

EDIT:

So you want two different possible actions to occur with the exact same input?

Then you won't be able to have two different action mappings, because as far as Unreal is concerned, its the same input, unless you have a modifier like Alt, Shift, etc. You'll have to do the check on your end.

I would suggest tagging the possible static meshes that can be clicked and then checking the tag of the touched object. For example, tag the terrain they can walk on with 'terrain' and the characters/items they can access a context menu with 'context'. Then call custom functions depending on which tag you find when they click.

(From a design standpoint, I do not recommend having movement and context menu on same input. Look at League & DOTA, the most popular top-down games. Movement is RMB, inspect & interact is LMB. Otherwise you can have accidental movement when a player is just trying to look.)
> 1 votes

---
Tags: input, unreal-4, mouse, blueprints
---


# Question
Title: How do I properly scale a Screen Space Overlay with its children?
I have a Canvas on which 3 Text objects are hosted.

These text objects are anchored so that they move and scale with the canvas if the canvas has "World Space" render mode.

Now I need to set the Canvas to Screen Space overlay. This causes the canvas to fill the entire screen.

I can resize / scale it user either the Panel's RectTransform's width / height or its Scale x / y.

Neither option scales or positions the Text objects as previously when the RenderMode was "World Space".

How is this properly achieve?

Here is a screenshot of what it looks like for me:

# Answer
> 2 votes
It looks like your text objects aren't children of the panel...

---
Tags: unity
---


# Question
Title: Why do i get this error in VS2017 but game compiles and works as expected?
I have this error, yet the game works and that variable ActorThatOpens get assigned correctly.

In my header the includes are:

```
#include "CoreMinimal.h"
#include "Components/ActorComponent.h"
#include "Engine/TriggerVolume.h"
#include "OpenDoor.generated.h"

```

As far as I can tell from the docs Components/ActorComponent.h contains the function GetWorld().

I have to go work now, but been scratching my head over this for an hour or so, and will continue to when i get home later. If anyone can see what I am doing wrong and can help I will be so grateful.

(As you can probably tell I am completely new to C++) THANKS!

# Answer
This is another instance of Visual Studio’s Intellisense failing to properly parse Unreal code because it doesn’t have all the information.

If your code is actually compiling when you hit “Build,” you can safely ignore these sorts of “errors” from Intellisense. You can also disable the “red squiggly” feature entirely to stop it from distracting you.

---

Unreal projects in Visual Studio don't actually build through the usual Visual Studio mechanism. They are configured to tell VS to invoke an external build tool specific to Unreal called "UnrealBuildTool." This tool is responsible for supplying a lot of command-line arguments to the actual compiler (`cl.exe`) that the IDE itself doesn't know about. This occasionally leads the IDE to thinking that you've got code that can't compile, even though it will eventually compile fine once UnrealBuildTool sets the right options.

Sometimes you can fix this by deleting the `.vs` folder next to your `.sln` file. Note that this will delete some other customizations you've made to your solution file.
> 4 votes

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


# Question
Title: Unity3d: Position a gameobject such that its forms a right angled triangle with other two gameobjects
How do I position `C gameObject` such that it forms a right angled triangle with `A and B`. I tried to use `(B.transform.position.x,A.transform.position.z)` but it still gives me something which is close to `A` (it takes it globally). I want the `C` to be along the `local red axis of A` and `local green axis of B` as seen in the picture. What do I do?

# Answer
Taking these two constraints:

* "position C gameObject such that it forms a right angled triangle with A and B"
* "I want the C to be along the local red axis of A"

We can solve this relatively easily using A's transformation:

```
// Transform point B into A's local space.
Vector3 bInAsSpace = a.transform.InverseTransformPoint(b.transform.position);

// Find a position along A's x-axis (y = z = 0 in A's local coordinates)
// that matches B's x-coordinate when viewed from A's frame of reference.
Vector3 cInAsSpace = new Vector3(bInAsSpace.x, 0, 0);

// Transform this position from A's local space back to world space.
Vector3 cInWordSpace = a.transform.TransformPoint(cInAsSpace);

```

This is guaranteed to be along A's x-axis (the red axis), since its y & z position in A's local space are both zero.

It's guaranteed to form a right-angled triangle with A & B because it forms a right triangle in A's local space (its separation from A is purely along the x-axis, and its separation from B has an x component of zero), and Unity transforms don't include shear.
> 1 votes

---
Tags: unity, mathematics, transformation, angles, direction
---


title: Why does my game crash on startup?

text:
# Question
Title: Why does my game crash on startup?
I'm very new to networking, so I've been trying to develop my own server and client to use with Unity. I did some copy and pasting to learn the basics, but now I'm trying to get a real grasp of how to accomplish what I am looking for. As for now, I just want to connect a client to a server (UDP), and get a confirmation that it is working before I continue.

**My current issue is this:** Unity crashes immediately upon running the game.

**Server:**

```
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class Server
{
    private const int port = 8080;

    public static int Main()
    {
        //bool done = false;
        UdpClient listener = new UdpClient(port);
        IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, port);
        string receivedData;
        byte[] receivedBytes;

        try
        {
                Console.WriteLine("Waiting for broadcast...");
                receivedBytes = listener.Receive(ref groupEP);

                Console.WriteLine("Receiving broadcast from: {0}", groupEP.ToString());

                receivedData = Encoding.ASCII.GetString(receivedBytes, 0, receivedBytes.Length);
                Console.WriteLine("Data follow\n{0}\n\n", receivedData);
        }

        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
        listener.Close();
        return 0;
    }
}

```

**Client:**

```
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class Client
{
    public static void Main()
    {
        //Boolean done = false;
        Boolean exception_Thrown = false;

        Socket sending = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

        IPAddress sendTo = IPAddress.Parse("192.168.1.127");

        IPEndPoint sendEndPoint = new IPEndPoint(sendTo, 8080);

        Console.WriteLine("Enter text to broadcast");
        Console.WriteLine("Enter a blank line to exit the program");

        string sendText = "Success!";
        /*
        if (sendText.Length == 0)
        {
            done = true;
        }

        else
        {
        */
            byte[] sendBuffer = Encoding.ASCII.GetBytes(sendText);
            Console.WriteLine("Send to address: {0}, port: {1}", sendEndPoint, sendEndPoint.Port);

            try
            {
                sending.SendTo(sendBuffer, sendEndPoint);
            }

            catch (Exception send_Exception)
            {
                exception_Thrown = true;
                Console.WriteLine("Exception {0}", send_Exception);
            }

            if (!(exception_Thrown))
            {
                Console.WriteLine("Message has been sent to the broadcast address");
            }

            else
            {
                exception_Thrown = false;
                Console.WriteLine("The exception indicates the message was not sent");
            }
        //}
    }
}

```

**The script I'm going to use to call the other scripts without MonoBehaviour:**

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

public class ServerManager : MonoBehaviour
{
    private GameObject netGameObject;
    private Server serverScript;
    private Client clientScript;
    //private float timer = 0.0f;
    //private float nextServerUpdate = 2.0f;
    //private bool runUpdate = true;
    //private bool s = false;

    // Start is called before the first frame update
    void Start()
    {
        netGameObject = this.gameObject;
        serverScript = new Server();
        clientScript = new Client();
        StartCoroutine(ServerUpdate(2f));
        //Server.Main();
        //Client.Main();
    }
    /*
    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.Y))
        {
            s = true;
        }
    }
    */
    private IEnumerator ServerUpdate(float waitTime)
    {
        while (true)
        {
            Server.Main();
            Debug.Log("Working");
            yield return new WaitForSeconds(waitTime);
        }
    }
}

```

I've been toying with various things for a while now, and I really need some help.

**Things I've tested:**

1. The coroutine freezes as soon as it hits `Server.Main()`.
2. DIY timers react the same as coroutine.
3. `while(true)` loop in coroutine doesn't appear to make a difference.
4. `Server.Main()` freezes even from start or awake, with all loops that I can find removed.
5. `Client.Main()` gives me the exact same problems.

Just a note: I have been avoiding Unity's built in systems (UNET and the like) because networking is something I would really like to learn to manage for myself, where I could use it outside of Unity as well.

# Answer
> 1 votes
Checking the docs on `UdpClient.Receive`:

> The Receive method blocks execution until it receives a message.

From what we can see in this sample, you don't have any code here that sends a message. So `Receive` will wait forever, halting your game from updating, processing input, rendering - a hard freeze.

You likely want to either:

* put this on its own thread so your game can continue to update while waiting for the next message (coroutines are not threads: they execute synchronously on the main thread, taking turns with the rest of your code)

See how not to freeze the main thread in Unity
* use `UdpClient.BeginReceive` to listen for messages asynchronously, getting an `AsyncCallback` call when the next message arrives

There are other issues with this code that I'd recommend reconsidering as you refactor to solve this lock:

* your Server & Client `Main` methods construct new listeners / sockets for every message, then immediately discard them, instead of keeping a channel open and reusing it
* you seem to be missing a call to dispose of your `Socket` once you're done with it.
* you construct instances of both `Server` and `Client`, but both have only static members

---
Tags: unity, networking
---


title: Why is the button's code not running?

text:
# Question
Title: Why is the button's code not running?
My script for a slot machine isn't working. When the button in the Bilboard GUI is clicked, the below dosen't run. I am new to scripting and this is mostly based on wiki/stack exchange/ Dev page info.

```
local player = game.Players.LocalPlayer
local textLabel = script.Parent
local toggled = false
local button = script.Parent

textLabel.Text = "Click to Play for 5 Cash!"
slot1Combos = {"Bar", "Seven", "Seven", "Seven", "Cherry", "Cherry", "Cherry", "Cherry", "Orange", "Orange", "Orange", "Orange", "Orange", "Lemon", "Lemon", "Lemon", "Lemon", "Lemon", "Banana", "Banana", "Banana", "Banana", "Banana"}
slot2Combos = {"Bar", "Seven", "Cherry", "Cherry", "Cherry", "Orange", "Orange", "Orange", "Orange", "Orange","Orange","Lemon", "Lemon", "Lemon", "Lemon", "Lemon", "Lemon", "Banana", "Banana", "Banana", "Banana", "Banana", "Banana"}
slot3Combos = {"Bar", "Seven", "Cherry", "Cherry", "Cherry", "Orange", "Orange", "Orange", "Orange", "Orange","Orange","Lemon", "Lemon", "Lemon", "Lemon", "Lemon", "Lemon", "Banana", "Banana", "Banana", "Banana", "Banana", "Banana"}

local function onButtonActivated()
    if toggled == false then
        toggled = true

        x = math.random(1,23)
        y = math.random(1,23)
        z = math.random(1,23)
        g = false
        player.leaderstats[currencyName].Value = player.leaderstats[currencyName].Value - 5
        if slot1Combos[math.floor(x)] == "Bar" and slot2Combos[math.floor(y)] == "Bar" and slot3Combos[math.floor(z)] == "Bar" then
            player.leaderstats[currencyName].Value = player.leaderstats[currencyName].Value + 60
            textLabel.Text = "You Got 3 Bars. You won 60 cash"
            wait(5)
            textLabel.Text = "Click to Play for 5 Cash!"
        elseif slot1Combos[math.floor(x)] == "Seven" and slot2Combos[math.floor(y)] == "Seven" and slot3Combos[math.floor(z)] == slot2Combos[math.floor(y)] then
            player.leaderstats[currencyName].Value = player.leaderstats[currencyName].Value + 40
            textLabel.Text = "You Got 3 Sevens. You won 40 cash"
            wait(5)
            textLabel.Text = "Click to Play for 5 Cash!"
        elseif slot1Combos[math.floor(x)] == slot2Combos[math.floor(y)] and slot3Combos[math.floor(z)] == slot2Combos[math.floor(y)] then
            player.leaderstats[currencyName].Value = player.leaderstats[currencyName].Value + 10
            textLabel.Text = "You Got 3 of a Kind. You won 10 cash"
            wait(5)
            textLabel.Text = "Click to Play for 5 Cash!"

        elseif slot1Combos[math.floor(x)] == "Cherry" and slot2Combos[math.floor(y)] == "Cherry" and slot3Combos[math.floor(z)] == "Cherry" then
            player.leaderstats[currencyName].Value = player.leaderstats[currencyName].Value + 20
            textLabel.Text = "You Got 3 Cherries. You won 20 cash"
            wait(5)
            textLabel.Text = "Click to Play for 5 Cash!"
        elseif slot1Combos[math.floor(x)] == "Cherry" and slot2Combos[math.floor(y)] == "Cherry" or slot3Combos[math.floor(z)] == "Cherry" and slot1Combos[math.floor(x)] == "Cherry" or slot2Combos[math.floor(y)] == "Cherry" then
            player.leaderstats[currencyName].Value = player.leaderstats[currencyName].Value + 3
            textLabel.Text = "You Got 2 Cherries. You won 3 cash"
            wait(5)
            textLabel.Text = "Click to Play for 5 Cash!"
        elseif slot1Combos[math.floor(x)] == "Cherry" or  slot2Combos[math.floor(y)] == "Cherry" or  slot3Combos[math.floor(y)] == "Cherry" then
            player.leaderstats[currencyName].Value = player.leaderstats[currencyName].Value + 3
            textLabel.Text = "You Got 1 Cherry. You won 3 cash"
        else
            textLabel.Text = "Sorry, you didn't win"
            wait (5)
            textLabel.Text = "Click to Play for 5 Cash!"

        end
    end
button.Activated:Connect(onButtonActivated)
end)

```

This is the explorer tree with the script highlighted

# Answer
> 1 votes
Taking a look at your script, we see that there is a little hick-up at the bottom of your function.

```
local function onButtonActivated()
    if toggled == false then
        toggled = true

        x = math.random(1,23)
        y = math.random(1,23)
        z = math.random(1,23)
        g = false
        player.leaderstats[currencyName].Value = player.leaderstats[currencyName].Value - 5
        if slot1Combos[math.floor(x)] == "Bar" and slot2Combos[math.floor(y)] == "Bar" and slot3Combos[math.floor(z)] == "Bar" then
            player.leaderstats[currencyName].Value = player.leaderstats[currencyName].Value + 60
            textLabel.Text = "You Got 3 Bars. You won 60 cash"
            wait(5)
            textLabel.Text = "Click to Play for 5 Cash!"
        elseif slot1Combos[math.floor(x)] == "Seven" and slot2Combos[math.floor(y)] == "Seven" and slot3Combos[math.floor(z)] == slot2Combos[math.floor(y)] then
            [...]
        else
            textLabel.Text = "Sorry, you didn't win"
            wait (5)
            textLabel.Text = "Click to Play for 5 Cash!"

        end
    end
button.Activated:Connect(onButtonActivated) -- <- !!!This here!!!
end)

```

Lua code does not have to be indented, it is indented to ease the reading of the code. Your code being cleanly indented, we can assume that the last `end` is the one that ends your function `onButtonActivated`.

From that, we can infer that the part `button.Activated:Connect(onButtonActivated)`, which links your button to the function, is being part of your `onButtonActivated` function.

Essentially, you're trying to link the function to your button from within the function, which would happen only if you would call the function in the first place.

What you most likely want here is to link the button to the function from the outside of the function, after the function has been declared:

```
local function onButtonActivated()
    if toggled == false then
        toggled = true

        x = math.random(1,23)
        y = math.random(1,23)
        z = math.random(1,23)
        g = false
        player.leaderstats[currencyName].Value = player.leaderstats[currencyName].Value - 5
        if slot1Combos[math.floor(x)] == "Bar" and slot2Combos[math.floor(y)] == "Bar" and slot3Combos[math.floor(z)] == "Bar" then
            player.leaderstats[currencyName].Value = player.leaderstats[currencyName].Value + 60
            textLabel.Text = "You Got 3 Bars. You won 60 cash"
            wait(5)
            textLabel.Text = "Click to Play for 5 Cash!"
        elseif slot1Combos[math.floor(x)] == "Seven" and slot2Combos[math.floor(y)] == "Seven" and slot3Combos[math.floor(z)] == slot2Combos[math.floor(y)] then
            [...]
        else
            textLabel.Text = "Sorry, you didn't win"
            wait (5)
            textLabel.Text = "Click to Play for 5 Cash!"
        end
    end
end

button.Activated:Connect(onButtonActivated) -- <- !!!Moved outside of the function!!!

```

---

The closing parenthesis sicked to the `end` at the end of your code snippet above could be causing a syntax error (unexpected symbol). Chances are you have that reported somewhere. Just remove it, you'll be fine :)

---
Tags: lua, roblox
---


# Question
Title: Why does WorldToScreenPoint return "strange" results?
I would like to show a menu to the right side and at the same y coordinate as a certain gameobject (shown as a green cube in the screenshot).

Therefore I'm trying to get the screen coordinates of the object in my scene using WorldToScreenPoint.

The code I'm using is this:

```
Vector3 nPos = new Vector3(GlowCube.position.x + GlowCube.localScale.x, GlowCube.position.y, GlowCube.position.z);
Vector3 nOff = Camera.main.WorldToScreenPoint(nPos);

```

The resulting values however don't look right to me. I have created a red rectangle in order to demonstrate where the coordinates "nOff" would actually be in the screen:

At first I thought I get these strange results because the GlowCube is parented to the case, but since I use GlowCube's world coordinates (GlowCube.postion...) and not its local coordinates (GlowCube.localPosition...), I thought that this wouldn't matter.

What am I forgetting here?

Thank you!

# Answer
I forgot to take into account that the object's origin is in its center and not at top / left.

The correct formula (if top / left is required) would therefore be:

```
Vector3 nPos = new Vector3(GlowCube.position.x + GlowCube.localScale.x - (GlowCube.localScale.x / 2), GlowCube.position.y + (GlowCube.localScale.y / 2), GlowCube.position.z);

```
> 0 votes

---
Tags: unity
---


title: Detect walls in geometry

text:
# Question
Title: Detect walls in geometry
Is it possible to automatically detect walls in polygon soup?

Of course it's hard to strictly define what a wall is, my slightly vague definition would be:

A wall is a largest possible box (not necessarily axis-aligned) with its entire volume covered by subset of geometry in that polygon set.

Provided set of polygons may contain multiple walls, walls under specific low volume should be ignored, walls may overlap if it's easier for the algorithm, subset of geometry used to construct a wall may have larger volume than the wall itself, but opposite is not allowed.

# Answer
I'd try:

* Generate a BSP from the complete set of polygons.
* Clip each polygon from the original set against the BSP. If the entire polygon is "inside" the tree, then it is completely covered and meets your definition of "wall."

BSP generation can be a bit taxing depending on the size and complexity of your input dataset. If you're not doing this real time, or if the data set is small-ish (a relative term on modern hardware), that shouldn't really be an issue.

You may be able to speed things up by checking each poly as its added to the tree. If the whole poly is clipped, mark it as a wall and leave it out of the tree.

Now, this assumes that the walls are already part of the input dataset. If that's not the case, and you need to generate a set of walls from the input data, that could also be handled via a BSP, but it'll be a bit more involved.
> 0 votes

# Answer
Is the mesh created by hand or computer-generated or scanned (i.e. contains noise)?

I was thinking that 3D scanning systems like http://structure.io and Microsoft HoloLense probably have to solve a similar problem when the scanned mesh is used in a 3D engine and allow "physical" interaction.

In Unity there is a Spatial Mapping Collider, but they don't really mention the concepts behind the collision detection.
> 0 votes

---
Tags: algorithm, geometry, computational-geometry
---


# Question
Title: Google play services not working in unity
I've done everything as specified- Linked my app to play services in the developer console. Added the SHA1 from Applications -\> Release Management -\> App signing -\> Upload certificate. Downloaded the latest 'play services' unity package from GitHub. Added the required 'resource' to the play services setup in unity editor. Added the following script to the 'Canvas' object:

```
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using GooglePlayGames;
 using GooglePlayGames.BasicApi;
 using UnityEngine.SocialPlatforms;

 public class PlayGamesServices : MonoBehaviour
 {
     // Start is called before the first frame update
     void Start()
     {
         PlayGamesClientConfiguration clientConig = new
         PlayGamesClientConfiguration.Builder().Build();
         PlayGamesPlatform.InitializeInstance(clientConig);
         PlayGamesPlatform.Activate();
         Social.localUser.Authenticate((bool success) =>
         {
             if (success)
                 Debug.Log("Logged In");
             else
                 Debug.Log("Failed to Log In");
         });
     }

     public static void PostToLederboard(long newHighScore)
     {

   Social.ReportScore(newHighScore,GPGSIds.leaderboard_global_high_score, (bool success) =>
         {
             if (success)
                 Debug.Log("New High Score posted");
             else
                 Debug.Log("Unable to post New High Score");
         });
     }

     public void ShowLeaderboard()
     {
    PlayGamesPlatform.Instance.ShowLeaderboardUI(GPGSIds.leaderboard_global_high_ score);
     }
 }

```

I've already published my game to alpha testing and then implemented play services. I'm wondering if that's the problem.

I've run the adb logcat and this error popped up:

> \[Play Games Plugin DLL\] 07/21/19 12:06:19 +05:30 ERROR: UnityEngine.AndroidJavaException: java.lang.ClassNotFoundException: com.google.games.bridge.TokenFragment 07-21 12:06:19.325 23287 23314 W Unity :
>
> at UnityEngine.AndroidJNISafe.CheckException () \[0x00000\] in \<00000000000000000000000000000000\>:0 07-21 12:06:19.325 23287 23314 W Unity :
>
> at UnityEngine.AndroidJNISafe.CallStaticObjectMethod (System.IntPtr clazz, System.IntPtr methodID, UnityEngine.jvalue\[\] args) \[0x00000\] in \<00000000000000000000000000000000\>:0 07-21 12:06:19.325 23287 23314 W Unity :
>
> at UnityEngine.AndroidJavaObject.\_CallStatic\[ReturnType\] (System.String methodName, System.Object\[\] args) \[0x00000\] in \<00000000000000000000000000000000\>:0 07-21 12:06:19.325 23287 23314 W Unity :
>
> at UnityEngine.AndroidJavaClass.\_AndroidJavaClass (System.String className) \[0x00000\] in \<00000000000000000000000000000000\>:0 07-21 12:06:19.325 23287 23314 W Unity :
>
> at GooglePlayGames.Android.AndroidTokenClient.DoFetchToken (System.Boolean silent, System.Action\`1\[T\] callback) \[0x00000\] in \<00000000000000000000000000000000\>:0 07-21 12:06:19.325 23287 23314 W Unity :
>
> at System.Action.Invoke () \[0x00000\] in \<00000000000000000000000000000000\>:0 07-21 12:06:19.325 23287 23314 W Unity :
>
> at GooglePlayGames.OurUtils.PlayGamesHelpe

I've tried reproducing the error by re-doing the exact same steps in an empty project and ended up with the same error.

> Update: When i change Player Settings -\> Publishing -\> Minify -\> Release to None and Debug to None the error is gone and play services sign-in was successful. This worked for the empty project, however when i make the same change in my original game project the build fails with errors. How do I build my game without errors when Minify is set to None?

# Answer
> 1 votes
I managed to solve the problem. Had to remove Advertisements package from Window -\> Package Manager and then set Minify -\> Release and Debug to None, then build the game and installed it on device and the play games login showed up.

---
Tags: unity, google-play-services
---


# Question
Title: Improving an O(N^2) function (all entities iterating over all other entities)
A little bit of background, I'm coding an evolution *game* with a friend in C++, using ENTT for the entity system. Creatures walk around in a 2D map, eat greens or other creatures, reproduce and their traits mutate.

Additionally, performance is fine (60fps no problem) when the game is run in real time, but I want to be able to speed it up significantly to not have to wait 4h to see any significant changes. So I want to get it as fast as possible.

I'm struggling to find an efficient method for creatures to find their food. Each creature is supposed to look for the best food that is close enough to them.

If it wants to eat, the creature pictured in the center is supposed to look around itself in a 149.64 radius (its view distance) and judge which food it should pursue, which is based on nutrition, distance, and type (meat or plant).

The function responsible for finding every creature their food is eating up around 70% of the run-time. Simplifying how its written currently, it goes something like this:

```
for (creature : all_creatures)
{
  for (food : all_entities_with_food_value)
  {
    // if the food is within the creatures view and it's
    // the best food found yet, it becomes the best food
  }
  // set the best food as the target for creature
  // make the creature chase it (change its state)
}

```

This function is run every tick for every creature looking for food, until the creature finds food and changes state. It's also run every time new food spawns for creatures already chasing a certain food, to make sure everyone goes after the best food available to them.

I'm open to ideas on how to make this process more efficient. I'd love to reduce the complexity from \\$O(N^2)\\$, but I don't know if that's even possible.

One way I already improve it is by sorting the `all_entities_with_food_value` group so that when a creature iterates over food too big for it to eat, it stops there. Any other improvements are more than welcome!

EDIT: Thank you all for the replies! I implemented various things from various answers:

I firstly and simply made it so the guilty function only runs once every five ticks, this made the game around 4x faster, while not visibly changing anything about game.

After that I stored in the food searching system an array with the food spawned in the same tick it runs as. This way I only need to compare the food the creature is chasing with the new foods that appeared.

Lastly, after research into space partitioning and considering BVH and quadtree, I went with the latter, as I feel like it's much simpler and better suited to my case. I implement it pretty quickly and it greatly improved performance, the food search barely takes any time at all!

Now rendering is what's slowing my down, but that's a problem for another day. Thank you all!

# Answer
> 34 votes
I know you do not conceptualize this as collisions, however what you are doing is colliding a circle centered at the creature, with all food.

You really do not want to check food that you know is distant, only what is nearby. That is the general advice for collision optimization. *I would like to encourage to search for techniques to optimize collisions, and do not limit yourself to C++ when searching.*

---

**Creature finding food**

For your scenario, I would suggest to put the world on a grid. Make the cells at least the radius of the circles you want to collide. Then you can pick the one cell on which the creature is located and its up to eight neighbors and search only those up to nine cells.

**Note**: you could make smaller cells, which would mean that the circle you are searching would extend beyond the immidiate neighbors, requiring you to iterate there. However, if the problem is that there is too much food, smaller cells could mean iterating over less food entities in total, which at some point turns in your favor. If you suspect this is the case, test.

If food does not move, you can add the food entities to the grid on creation, so that you do not need to be searching what entities are in the cell. Instead you query the cell and it has the list.

If you make the size of the cells a power of two, you can find the cell on which the creature is located simply by truncating its coordinates.

You can work with squared distance (a.k.a. do not do sqrt) while comparing to find the closest one. Less sqrt operations means faster execution.

---

**New food added**

When new food is added, only nearby creatures need to be awaken. It is the same idea, except now you need to get the list of creatures in the cells instead.

Much more interestingly, if you annotate in the creature how far is it from the food it is chasing... you can directly check against that distance.

Another thing that will help you is to have the food aware of what creatures are chasing it. That will allow you to run the code for finding food for all the creatures that are chasing a piece of food that was just eaten.

In fact, start the simulation with no food and any creatures have an annotated distance of infinity. Then start adding food. Update the distances as the creatures move... When food is eaten, take the list of creatures were chasing it, and have then find a new target. Besides that case, all other updates are handled when food is added.

---

**Skipping simulation**

Knowing the speed of a creature, you know how much it is until it reaches its target. If all creatures have the same speed, the one that will reach first is the one with smallest annotated distance.

If you also know the time until you add more food... *And hopefully you have similar predictability for reproduction and death,* then you know the time to next event (either added food or a creature eating).

Skip to that moment. You do not need to simulate creatures moving around.

# Answer
> 16 votes
You should adopt a space partitioning algorithm like BVH to reduce complexity. To be specific to your case, you need to make a tree that consists of axis-aligned bounding boxes that contain food pieces.

To create a hierarchy, put food pieces close to each other in AABBs, then put those AABBs in bigger AABBs, again, by distance between them. Do this until you have a root node.

To make use of the tree, first perform a circle-AABB intersection test against a root node, then if collision happens, test against children of the each consecutive node. In the end you should have a group of food pieces.

You can also make use of AABB.cc library.

# Answer
> 3 votes
While the space partition methods described indeed can reduce the time your main problem is not just the lookup. Its the sheer volume of lookups you make that makes your task slow. So your optimizing the inner loop, but you can also optimize the outer loop.

Your problem is that you keep polling data. Its a bit like having kids in the back seat asking for a thousandth time "are we there yet", theres no need to do that the driver will inform when you are there.

Instead you should strive, if possible, to solve each action to its completion put it into a queue and let those bubble events out, this may make changes to the queue but that is ok. This is called discrete event simulation. If you can implement your simulation this way then you are looking fora sizable speedup that far outweighs the speedup you can get from the better space partition lookup.

To underline the point in a previous career i made factory simulators. We simulated weeks of big factories/airports entire material flow at each item level with this method in less than a hour. While the timestep based simulation could only simulate 4-5 times faster than real time.

Also as a really low hanging fruit consider decoupling your drawing routines from your simulation. Even though your simulation is simple there is still some overhead of drawing things. Worse the display driver may be limitting you to x updates per second while in reality your processors could do things 100's of times faster. This uderlines the need for profiling.

# Answer
> 1 votes
You can use a sweep-line algorithm to reduce the complexity to Nlog(N). The theory is that of Voronoi diagrams, which makes a partitioning of the area surrounding a creature into regions consisting of all points closer to to that creature than any other.

The so-called Fortune's algorithm does that for you in Nlog(N), and the wiki page on that contains pseudo code to implement it. I am sure that there are library implementations out there as well. https://en.wikipedia.org/wiki/Fortune%27s\_algorithm

# Answer
> -1 votes
The easiest solution would be integrating a physics engine and using only the collision detection algorithm. Just build a circle/sphere around each entity, and let the physics engine compute the collisions. For 2D i would suggest Box2D or Chipmunk, and Bullet for 3D.

If you feel that integrating a whole physics engine is too much, I would suggest looking into the specific collision algorithms. Most collision detection libraries work in two steps:

* Broad phase detection: the goal of this stage is to get the list of candidate pairs of objects that may collide, as fast as possible. Two common options are:
    + Sweep and prune: sort the bounding boxes along the X axis, and mark those pair of objects that intersect. Repeat for every other axis. If a candidate pair passes all the tests, it goes to the next stage. This algorithm is very good at exploiting temporal coherence: you can keep the lists of sorted entities and update them every frame, but as they are almost sorted, it will be very fast. It also exploits spatial coherence: because entities are sorted in ascending spatial order, when you are checking for collisions, you can stop as soon as an entity doesn't collide, because all the next ones will be further away.
    + Spatial partitioning data structures, like quadtrees, octrees, and grids. Grids are easy to implement, but can be very wasteful if the entity density is low, and very difficult to implement for unbounded space. Static spatial trees are easy to implement too, but difficult to balance or update in place, so you would have to rebuild it each frame.
* Narrow phase: candidate pairs found on the broad phase are further tested with more precise algorithms.

---
Tags: c++, performance, entity-system
---


title: Passive skills and items

text:
# Question
Title: Passive skills and items
I'm making a small text browser RPG game using PHP, MySQL and Java Script (and jQuery). All the items are saved in the MySQL database.

Every now and then a character have to make a skill roll (Talk, Climb, Sneak, etc. ), but I have the following problem - some of the items give passive bonuses to some skills. Let's say we have **Official Suit** item, it gives *+1 to Talk rolls* and *One time use only - automatic success on a Talk roll*.

My problem is the following - how can I implement a function for every item, that gives the bonuses or other options when the appropriate roll is made. I want when the player click the **Talk** option, a function to be run that makes the Talk roll and searches character's inventory for items that give him bonuses to that roll. If it sees that the player have such an item, let's say it's the Official Suit, it runs the item's function which gives the *+1 Talk bonus* and if the roll fails, the function gives an option to use the special ability of the item for automatic success.

So what is the best way to do this? Keywords to each item or some other way? I can't think of a scalable solution.

# Answer
> 2 votes
Here is one way to do it:

**CalculateCharacterStatEvent**

Define a CalculateCharacterStatEvent with properties sender (the Character object that raised the event), stat (the name of the stat that is to be calculated), bonusAbsolute and bonusPercentageBased and some setter functions to manipulate the bonus properties, like increaseBonusAbsolute().

**Items and event listeners**

Add the item's bonuses in the item's reactToCalculateCharacterStatEvent() method. For example:

```
public function reactToCalculateCharacterStatEvent($event) {
    // The event listener only reacts if the talk skill is calculated
    if($event->getStat() == "talk") {
        // Increase the item bonus depending on the Character's intelligence
        if($event->sender->intelligence < 6) {
            $event->increaseBonusAbsolute(1);
        } else {
            $event->increaseBonusAbsolute(2);
        }
    }
}

```

**Event listener registration**

When you load the items, register the item's event handler reactToCalculateCharacterStatEvent at the Character object, so that it is called whenever the Character object raises a CalculateCharacterStatEvent.

**Character class and event raisers**

In the Character class, define functions that return character stats, like getAttribute() or getSkillLevel(). At the beginning of your getStat() functions, raise a CalculateCharacterStatEvent. This will give the item's event listeners a chance to respond to the event by changing its bonusAbsolute and bonusPercentage values. Use these values to modify the result of your getStat() methods. For example:

```
getSkillTalking() {
    $event = new CalculateCharacterStatEvent($this, "talking");
    $this->raiseEvent($event);
    $base = 5; // or some logic to determine the base stats
    return $base * $event->getBonusPercentage + $event->getBonusAbsolute();
}

```

**Option to automatically succeed**

In order to add functionalities to items, you can just add new event classes, event raisers in the Character class, and new event listeners in the item classes.

For example: you could add an event called FailedSkillCheckEvent and an event listener reactToFailedSkillCheckEvent() in the item classes. When a skill check fails, the Character class raises a FailedSkillCheckEvent. The items's event listeners then have an opportunity to react by adding recovery options to the event object. After raising the FailedSkillCheckEvent, the skill check method continues depending on whether or not there are recovery options listed in the FailedSkillcheckEvent.

**Further enhancements**

**Decorators.** This basic pattern can be made more flexible by turning the item's reactTo-methods into a decorator class (Decorator pattern), which can then also be used by other game elements like status effects, passive skills, etc.

**Link with data.** reactToCalculateCharacterStatEvent() and other event listeners can also be linked to the item's properties so that you can edit the bonuses in a database without having to change any code for bonus assignments. (You can still code unique item behavior if you want to.)

**More complex events.** In the examples above, the item's event listeners have access to the sender of the event, i.e. the Character object for whom some stat is to be calculated. You could define more complex events that can pass more information to the items's event listeners. For example, you pass an object that represents the enemy of the Character object in a battle context. Your items's bonuses could then depend on the enemy's stats:

```
// in Character class
getSkillMelee($battle) {
    $event = new CalculateCharacterBattleStatEvent($this, $battle->enemy, "melee");
    $this->raiseEvent($event);
    $base = 5; // or some logic to determine the base stats
    return $base * $event->getBonusPercentage + $event->getBonusAbsolute();
}

// in Item class
public function reactToCalculateCharacterBattleStatEvent($event) {
    if($event->getStat() == "melee") {
        // Increase the item bonus depending on the Character's enemy's intelligence
        if($event->enemy->intelligence < 6) {
            $event->increaseBonusAbsolute(1);
        } else {
            $event->increaseBonusAbsolute(2);
        }
    }
}

```

# Answer
> 1 votes
> how can I implement a function for every item, that gives the bonuses or other options when the appropriate roll is made

First, there are two approaches to managing passive bonuses and such:

1. Calculate resulting value whenever you need it.
2. Calculate resulting value whenever circumstances change.

But there is also a third way: keep a list of effects and update it whenever circumstances change, and calculate a resulting value whenever you need it.

> using PHP, MySQL

I would create an `effects` table with fields

* `character` \- character (PC/NPC) id/ref
* `attribute` \- target attribute id/ref
* `method` \- modification method `enum('add'|'mult')`
* `value` \- effect value

You can have a library of possible effects stored in some other table, so you can fetch `attribute`, `method`, `value` fields whenever you need to add an effect. You can reference to effects in this library from your items or spells/buffs.

Now, regarding your question, whenever you equip/unequip an item (or apply/remove a buff) you simply

1. lookup for an effect on the library and
2. add (insert `character`, `...effect`) or remove (delete where `character`, `...effect`) a record to the `effects` table.

And don't worry if you added two identical effects - it doesn't matter in which order are you going to remove them, as long as you remove both of them.

And whenever you need to get resulting value you can run a simple `SELECT method, SUM(value) FROM effects WHERE character=$id AND attribute=$attr GROUP BY method`. This will return sums of all +X effects and all of +X% effects. Then you can apply them in `$attr = $attr * (1 + $mult / 100) + $add` fashion.

DBFiddle example

And if you are comfortable with a bit more complicated DB queries (selecting), you can use library reference in the `effects` table instead of copying values.

# Answer
> 0 votes
What kind of effects do +you want to use? The answer may constrain the solution. For example if all bonuses are like "+2 skill X" or "-1 skill X", then it does not matter *in what order* they are applied. If the bonuses are like "+2 skill X" or "+50% skill X", suddenly it becomes important whether you apply the +50% bonus before the +2 bonus, giving 10 × 1.5 + 2 = 17, or after the +2 bonus, giving (10 + 2) × 1.5 = 18. And that was a very simple example! More complex example could increase skill X by 20% of skill Y, or give a bonus only at night, or only against some kinds of monsters/attacks, possibly with an area effect but only for members of the same guild, or one-time use with a timeout. And it could burn your mana or health while it is active. So it is probably good to specify in advance what the effects can and cannot do.

If you want to treat each object as a *black box*, and you want to avoid having the difference between "+2, +50%" and "+50%, +2" depending on the order of objects in inventory, you could do this:

For each object, make a function `getEffects()` which returns a set of `Effect` objects. When something important is happening, collect all the effects. Each effect has a priority and a function.

Sort all those effects by priority. A priority is a number you have specified for each effect. For example if you want to process all the additive effects (+2 to skill X) first, and all the multiplicative effects (+50% to skill X) later, assign them priorities 1 and 2. For other effects use other priority numbers depending on when you want them to apply.

Then put the character data (their base skills, and everything that could be relevant to the effects) into a variable, and gradually apply all the effects on this variable: `$data = $effect->applyTo($data)`.

If you want some skills used only in some context, make it `$data = $effect->applyTo($data, $context)`. So the item may activate only when `$context` is `TALK_ROLL`. If you want an automatic success on talk rolls, you could put a variable "automatic success" to the `$data`, and the item would set it on true (only if it was false previously, so you wouldn't waste *two* one-time bonuses on the same roll).

---
Tags: rpg, browser-based-games, databases, php, text-based
---


title: How to stop an animation from looping

text:
# Question
Title: How to stop an animation from looping
I want to make Unity play a squish animation when the player hits the ground, but only once, until the player jumps and hits the ground again, although Unity its constantly detecting that the player is on the ground and keeps playing the squish animation over and over again, only jumping stops it cause the condition to play the animation is if the player is on the ground. (loop already disabled) How I can possibly solve this?

```
 if (isGrounded == true)
        anim.SetTrigger("EnterGround");

```

# Answer
You need to store previous value of `isGrounded`. Change your code to this:

```
if (isGrounded && !wasGrounded) OnLanding ();
wasGrounded = isGrounded;

```

where `wasGrounded` is a boolean field and `OnLanding` is a method where you for example trigger animation.
> 2 votes

---
Tags: unity, animation
---


# Question
Title: Color of Image changes to white between 2 positions using Color.Lerp - Unity
Hi I have an empty object `barHolder` that I move between `10` and `98` on x-axis. It has 2 child images `roundBar` and `bar`. I am trying to change the color of `roundBar` and `bar` when the object is moving. On `x=10` the the color will be red and on `x=98` it will be green. Here is what I have done so far:

```
    public GameObject meterBarHolder;

    public GameObject barRoundHead;
    public GameObject bar;

    public Text meterSpeedText;
    int currentSpeed;

    Color maxColor = new Color(21, 193, 25, 255);
    Color minColor = new Color(229, 85, 85, 255);

    float totalSpeed;

    float speedPercentage;

    float pos;
    //--------------//

    private void Start()
    {
        totalSpeed = (float)PlayerPrefs.GetInt("speed");
    }

    // Update is called once per frame
    void Update()
    {
        currentSpeed = int.Parse(meterSpeedText.text);

        speedPercentage = (float)currentSpeed / totalSpeed;

        pos = 88 * speedPercentage;

        if(pos < 10)
        {
            meterBarHolder.gameObject.GetComponent<RectTransform>().localPosition = new Vector3(10f, 0f, 0f);
            changeColor(0);
        }
        else if(pos > 98)
        {
            meterBarHolder.gameObject.GetComponent<RectTransform>().localPosition = new Vector3(98f, 0f, 0f);
            changeColor(1);
        }
        else
        {
            meterBarHolder.gameObject.GetComponent<RectTransform>().localPosition = new Vector3(pos, 0f, 0f);
            changeColor(speedPercentage);
        }

    }

    void changeColor(float x)
    {
        bar.GetComponent<Image>().color = Color.Lerp(minColor, maxColor, x);
        barRoundHead.GetComponent<Image>().color = Color.Lerp(minColor, maxColor, x);
    }

```

The problem is that when ever I click play the color changes to white.

For reproducing the problem `totalSpeed=120` and `meterSpeedText` changes between `0` and `120`. The rest are calculated in the code.

Here is a gif to give an idea what I am trying to do:

# Answer
This is because you are using Color as if it was a Color32.

* Color uses (float) values between 0 and 1
* Color32 uses (byte) values between 0 and 255.

So a value greater then one is clamped to 1 for the shader, new Color(21, 193, 25, 255) is therefore to the shader the same color as new Color(1, 1, 1, 1) a.k.a. white.

So to fix this problem, you should either use Color32 instead of Color or change your input to float values ranging between 0 and 1.

Color32 can also be implicitly casted to a Color, so this would be the simplest solution:

```
Color maxColor = new Color32(21, 193, 25, 255);
Color minColor = new Color32(229, 85, 85, 255);

```
> 3 votes

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


# Question
Title: Synchronizing with monitor refreshes without vsync
What is the preferred way of synchronizing with monitor refreshes, when vsync is not an option? We enable vsync, however, some users disable it in driver settings, and those override app preferences. We need reliable predictable frame lengths to simulate the world correctly, do some visual effects, and synchronize audio (more precisely, we need to estimate how long a frame is going to be on screen, and when it will be on screen).

Is there any way to force drivers to enable vsync despite what the user set in the driver? Or to wait for a swap manually? We have issues with manual sleeping when our frame boundaries line up closely to buffer swaps. It causes occasional missed frames, and up to 1 extra frame of input latency.

We mainly use OpenGL, but Direct3D advice is also appreciated.

# Answer
> 3 votes
In OpenGL you can control the swap interval of your application, which will limit the frame swap to the refresh rate of the monitor (v-sync). However, the user can override this by disallowing applications to control vertical sync within the Nvidia preferences application. In such as case, you have to make a choice:

1. live with the issue, and inform your users that to fix any A/V de-sync they have to allow the application to control v-sync.
2. Cap the refresh rate in your software: have a timer event, triggered every 60th of a second (16.667ms), which will trigger a redraw. Additionally/Alternatively, after every frame draw call `glFinish()` which will force every queued API call to be executed, and will prevent further queuing until complete. This means that more CPU/GPU sync is performed, thus reducing frame draws, however, on it's own is limited only by hardware performance, and thus, is unpredictable as a frame limiter.

Generally, if you cap your frame draws in the same way you would limit solver cycles for your physics engine, then you should get a controlled frame-rate unaffected by vertical sync/driver settings.

example:

```
void engine::run()
{
    float dt = 0f;
    time_t last = 0;
    time_t now = 0;
    float gfx_timer = 1.0f/60;
    float gfx_accumulator = 0f;
    while (m_running == true)
    {
         now = time::now();
         dt = (now - last)/(float)CLOCKS_PER_SECOND;
         updateGame(dt); // update gamestate
         if (dt >= gfx_timer) // ensures the renderer will only call once per 16.667ms at most
         {
             gfx_accumulator = 0.0f;
             m_renderer.renderScene();
         {
         else
             gfx_accumulator += dt;
         last = now;
    }
}

```

In general frame capping is a good idea, to not melt people's gpus, but be warned, gamers with an expensive graphics card will not thank you for capping them at 60fps.

---
Tags: opengl, directx, windows
---


title: How move camera where i look?

text:
# Question
Title: How move camera where i look?
I am try make simple flying camera. Without character. But than I press forward camera moving to another direction.

```
    void Update()
{
    horizontalInput = Input.GetAxisRaw("Horizontal");
    verticalInput   = Input.GetAxisRaw("Vertical");

    var mouseX = Input.GetAxis("Mouse X");
    var mouseY = Input.GetAxis("Mouse Y");

    var trm = Camera.main.transform;

    if (horizontalInput != 0 || verticalInput != 0)
    {
        trm.position += moveSpeed * new Vector3(horizontalInput, 0, verticalInput);
    }

    var rotateValue = new Vector3(mouseY * 2, mouseX * -2, 0);

    trm.eulerAngles -= rotateValue;

    //trm.rotation = Quaternion.Euler(rotateValue);
}

```

Than I press 'W' camera moving to left... I understand that it is necessary to coordinate the motion vectors and camera rotation. How best to do it?

# Answer
> 0 votes
Use Transform.transformDirection().

```
if (horizontalInput != 0 || verticalInput != 0)
{
    Vector3 vec = moveSpeed * new Vector3(horizontalInput, 0, verticalInput);
    trm.position += trm.transformDirection(vec);
}

```

It basically converts a vector direction from the transform's local space into world space. So that transform's rotation is going to affect that vector.

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