# Question
Title: Control Two agents separately with one script?
I have two characters"agent" moving them on terrain by mouse. My script for both of them is...

```
public Vector3 point_;
public float mark;
public float mark;
public UI_Button _active_character; // butoon select script

void Update
{

  Ray mouseRay = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit mousePoint;
    if (Input.GetMouseButtonUp(0))
    {
        if (Physics.Raycast(mouseRay, out mousePoint, 100) )
        {
            point_ = mousePoint.point;
            mAgent.SetDestination(mousePoint.point);
            mark = Vector3.Distance(point_, gameObject.transform.position);
        }
    }
 }

```

Here script for character buttons. Every character has it own button.

```
public bool character1, character2;

void Start()
{
    character1 = true;

}

   void Update()
{

    if (character1 == true)
    {
        character2 = false;
    }

    if (character2 == true)
    {
        character1 = false;
    }

   if (character1 == fale && character2 == false)
    {
    // Later. free cam moving...
    }

}

public void avatar1_click() // button
{
    character1 = !character1;
    character2 = false;

}
public void avatar2_click() // button
{
    character2 = !character2;
    character1 = false;
}

```

It's possible to control both of them separately by one script by click on button to chose character ?

# Answer
> 1 votes
Just try to adjust first script and make it identify which player "object" is active when click.

```
   if (_active_character.character1 == true && this.gameObject.name == "Player1 Object Name")
    {
        Ray mouseRay = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit mousePoint;
        if (Input.GetMouseButtonUp(0))
        {
            if (Physics.Raycast(mouseRay, out mousePoint, 100))
            {
                point_ = mousePoint.point;
                this.mAgent.SetDestination(mousePoint.point);
                mark = Vector3.Distance(point_, gameObject.transform.position);
            }
        }

    }

if (_active_character.character2 == true && this.gameObject.name == "Player2 Object Name")
    {
        Ray mouseRay = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit mousePoint;
        if (Input.GetMouseButtonUp(0))
        {
            if (Physics.Raycast(mouseRay, out mousePoint, 100))
            {
                point_ = mousePoint.point;
                this.mAgent.SetDestination(mousePoint.point);
                mark = Vector3.Distance(point_, gameObject.transform.position);
            }
        }

    }

```

---
Tags: unity
---


# Question
Title: How to scale image at runtime in GameMaker?
I use this code to create a new enemy and preset some values:

It runs in the `step` event of the player object.

```
var inst_inst = instance_create_layer(newX, newY, "Instances_Enemies", obj_Asteroid01);
inst_inst.image_index.image_xscale = 0.1;
inst_inst.speed = 4;

```

The speed is set correctly but the code scales the image of the player sprite and **not the sprite** of `obj_Asteroid01`

---

**Edit after getting the answer**

My fault was to trust the autocomplete and the fact, that there were no compile errors.

This is something you need to get used to :)

# Answer
> 2 votes
```
inst_inst.image_xscale = 0.1;

```

`image_xscale` is a property of an instance. `image_index` also is a property of an instance. `image_xscale` is not a property of `image_index`.

Reason of the result you got is that instances (and any other resources) in GML are represented as IDs. For example, try `show_message(obj_Asteroid01)` and it will show you a number. So `inst_inst.image_index.image_xscale` will be interpreted as "get the instance with index `inst_inst.image_index` and then set `image_xscale` for this instance".

---
Tags: game-maker
---


# Question
Title: How would one generate a Navigation Grid for a 3D world?
I am attempting to find a solution to this problem. I'm trying to build a navigation mesh in the format of a grid of vertices locked to x, y floored coordinates in the shape of squares for 3D space. But I'm having problems trying to figure out a way to go about it.

I tried looking into the Recast library. It's a pretty robust method, but it apparently slows down with larger maps and open space. I also don't know how they generate vertices and edges for the world space with the height map.

My next thought was to do what Unreal Engine 3 used to do.

https://udn.epicgames.com/Three/NavigationMeshReference.html

Which was to use raycasts to generate the mesh. I couldn't figure out how to have the raycasts stop.

So... my next option was box, possibly a box cast. Create a subdivided volume with a size that's a power of 2. Align the box to the grid, and shoot rectangular prisms downwards as a ray. If it lands on a piece of geometry that's part of the ground and the rectangle is not being intersected, leave a square there. And continue down until the bounds of the volume is reached. To check if edges need to be linked, I suppose I could check to see if the slope between two pairs of vertices is within the walkable slope, merge them if this is true.

My main problems are... this doesn't seem to be very optimal. Without thinking of it, at estimation the process is O(N^3) for a multilayered level. Which can get pretty nasty.

And the last bit is for automatically creating rectangular groups of these squares. I'm not entirely sure how to do this. The Unreal implementation separates them by slopes. However, I'm trying to keep the grid format. So that's not entirely necessary. The trouble still remains on creating large rectangular tiles to split up the path finding process into a per tile basis. The tiles can't be too large, nor too small.

So the questions are...

What would be an efficient way to generate this girded navmesh? And what would be a good way to create the tiles?

# Answer
> 1 votes
A basic 3D world could be represented by a navigational mesh that can be conveniently built in most game engines. The Actor can travel along edges of polygons.

That would be a simple solution. There are many algorithms for path-finding and generating a navmesh.

I would like to share something i read a while ago.

This describes a possible solution where we can break our game world into square tiles. whenever a square tile is added into game(when player gets near an area/ procedural terrain), a square tile is added. However, we dont have to calculate the entire navmesh anymore. we just calculate it for that tile and add it into existing graph. Significant performance gain there.

The next problem tackled is the jagged movement from the previous example. I can understand that by considering future turns and generalizing the direction would reduce zigzag movement a lot and make the motion fluid. Games with detailed animation dont give it away but you can notice this in some open world games where i would assume navigation is baked mostly.

As for the question, i would recommend you to go check out Kromster's answer on a list of navmesh generating algorithms.

Also check out The AI Systems of Left 4 Dead of which the examples are a part of. Many more interesting topics covered

Good Luck.

# Answer
> 0 votes
there are many ways, why not just make it local to the player, make a small grid that follows the player and checks under each intersection whether or not its transversable, like is there a floor there and do a ray cast to see if there is a wall/building on any upcoming side..

# Answer
> -1 votes
This is a problem I've seen everywhere. The trick is "separation of concerns". "Say what?", I heard you think. What is displayed on the the screen is NOT what the "data structure" is. Keeping the visuals separate from the data to construct the visual is important. Doing so will always "future proof" your game when new underlying software versions are released.

Build a data structure (aka: model) that will represent your gaming world. Then construct a "view" of the data structure model. If you want to change the world from a checker-board grid to a hexagonal grid, the data structure (model) remains the same, but the display will "paint" (render) a different view.

# Answer
> -2 votes
Make an double array. And then if an object/objects are inpassable, have a methode to tell the array that position is notpassable. When an AI try to move they will look at the double array and see if it is passable.

---
Tags: c++, tiles, navmesh
---


# Question
Title: Could I get in to trouble for "rickrolling" users in my commercial game?
Not sure if this question is too stupid but, theoretically speaking...

Could you get into trouble for using something like Application.OpenURL in a commercial game to rickroll a player or would that be legally okay? (sorry this question is really stupid)

# Answer
Legally speaking, this is *probably* okay, barring any specific circumstances that may arise from either your jurisdiction, platform terms of service, et cetera. You should absolutely consult a lawyer to discuss the specific case you are envisioning, as there may be regulations about what you can do without user consent in force, as well as rules about how you need to market your application if it can, effectively, navigate to arbitrary URLs (see below).

Regardless of the legal issues, this seems like a phenomenally bad idea. If you don't control the URL you're navigating too, you are delegating some aspect of your product's experience to a third party that has no interest or obligation to support you. The entity with control over the URL could see all this traffic coming from your product, not like it (or just be a troll) and choose to change the content of that URL to something far less amusing. You still bear the responsibility for displaying the content at that URL, even if it is no longer what it was when you shipped the game.

If you *do* control the content of the URL, you're back in the legal arena (making sure you have the rights to the content at the URL for the use you are applying).

It also seems like a joke in pretty bad taste, especially at this point, as well as an unpleasant user experience overall.
> 5 votes

---
Tags: legal
---


# Question
Title: Do I need multiple exports from Game Maker to support Windows versions above 7?
I just created a game. At the time of exporting it, I targeted windows.

I use windows 7 on my computer. Obviously the game is compatible with windows 7, but I do not know if it is also compatible with windows 8 and 10, because just below appears windows 8.

I intend to launch the game on steam, and even if it was not, it is very important for me not to frustrate anyone.

My question is whether I will have to create multiple executables for different versions of windows, or if selecting the windows option, the game will work for windows 7, 8, 10 and XP.

I looked it up on the developer's website, but it did not help. =\> https://docs.yoyogames.com/source/dadiospice/000\_using%20gamemaker/009\_distributing%20your%20game.html

# Answer
> 1 votes
The first option creates a Windows executable application (.exe) Those options related to Windows 8 creates an app similar to those available in the Microsoft Store. They are compiled in a different way and need of a special SDK to be created.

# Answer
> 2 votes
I believe windows includes all the versions of windows, Windows 8 build is for functions specific to the windows 8 platform

---
Tags: game-maker, windows, compatibility
---


# Question
Title: 2D snake game ( how to rotate snake's head with movement ?)
I want to know:

1. how to rotate snake's head with movement
2. how to make tail prefabs (body) follows head direction.

```
public class Snake : MonoBehaviour {

    bool ate = false;
    bool isDied = false;
    public GameObject tailPrefab;
    Vector2 dir = Vector2.right;
    List<Transform> tail = new List<Transform>();

    void Start ()
    {
        InvokeRepeating("Move", 0.3f, 0.1f);
    }

    void Update () {
        if (!isDied) {
            if (Input.GetKey (KeyCode.RightArrow))
            {
                dir = Vector2.right;
                //transform.rotation=Quaternion.Euler(0, 0, 180);
            }
            else if (Input.GetKey(KeyCode.DownArrow))
            {

                dir = -Vector2.up;
                //transform.rotation = Quaternion.Euler(0, 0, 90);
            }
            else if (Input.GetKey(KeyCode.LeftArrow))
            {

                dir = -Vector2.right;
                //transform.rotation = Quaternion.Euler(0, 0, 0);
            }
            else if (Input.GetKey(KeyCode.UpArrow))
            {

                dir = Vector2.up;
                //transform.rotation = Quaternion.Euler(0, 0, 270);

            }
    }

    void Move() {
        if (!isDied) {
            Vector2 v = transform.position;

            transform.Translate (dir);

            if (ate) {
                GameObject g = (GameObject)Instantiate (tailPrefab,
                                  v,
                                  Quaternion.identity);

                tail.Insert (0, g.transform);

                ate = false;
            } else if (tail.Count > 0) {
                    tail.Last ().position = v;

                    tail.Insert (0, tail.Last ());
                    tail.RemoveAt (tail.Count - 1);
            }
        }
    }

    void OnTriggerEnter2D(Collider2D coll) {
        if (coll.name.StartsWith("Food")) {

            ate = true;

            Destroy(coll.gameObject);
        } else {
            isDied = true;
        }
    }
}

```

# Answer
I can't really help with the body, since I've never played snake before, but in regard to your head rotation, the below code should help. Note that I flipped the sprite horizontally in Photoshop, because if his default direction is moving right, then he should also be facing right.

```
void Update()
{
    if (!isDied)
    {
        if (Input.GetKey(KeyCode.RightArrow))
        {
            transform.rotation = Quaternion.Euler(Vector3.zero);
        }
        else if (Input.GetKey(KeyCode.DownArrow))
        {
            transform.rotation = Quaternion.Euler(Vector3.forward * -90);
        }
        else if (Input.GetKey(KeyCode.LeftArrow))
        {
            transform.rotation = Quaternion.Euler(Vector3.forward * 180);
        }
        else if (Input.GetKey(KeyCode.UpArrow))
        {
            transform.rotation = Quaternion.Euler(Vector3.forward * 90);
        }
    }
}

```

Basically, you don't need to keep resetting the 'dir'. All you have to do is set it once (Vector2.right) so it'll move, and then you just rotate it while it's moving.
> 1 votes

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


# Question
Title: Unity Graphics.DrawMesh lags behind rotation?
I have a setup in unity using Graphics.DrawMesh() to draw a mesh on my players camera location in the update loop, `Graphics.DrawMesh(viewModel, matrix, material, layer, null, 0);
matrix = Matrix4x4.TRS(cam.transform.position, cam.transform.rotation, scaleFps);` when I use my mouse to move around the camera, it lags behind where the camera is, as can be seen in the video. I have no idea how to fix this. I've tried not using the matrix, and it doesn't change anything.

https://youtu.be/eWFFYcOX\_4Q

Here's the script I use for moving the camera:

```
    //Get the current mouse input.
    yaw += Input.GetAxis("Mouse X") * mouseSensitivity;
    pitch -= Input.GetAxis("Mouse Y") * mouseSensitivity;

    //Clamp the camera rotation.
    pitch = Mathf.Clamp(pitch, -maxLookAngle, maxLookAngle);

    //Calculate and rotate the camera.
    currentRotation = Vector3.SmoothDamp(currentRotation, new Vector3(pitch, yaw), ref rotationSmoothVelocity, mouseSmoothScale);

    //Rotating the player.
    Vector3 bodyRotation = new Vector3(0, currentRotation.y, 0);
    transform.localEulerAngles = bodyRotation;

    //Rotating the camera.
    Vector3 cameraRotation = new Vector3(currentRotation.x, 0, currentRotation.z);
    playerCamera.transform.localEulerAngles = cameraRotation;'

```

# Answer
I fixed it by putting the render in lateupdate.
> -1 votes

---
Tags: unity, graphics, matrix
---


# Question
Title: Godot: error(10) expected '(' after Identifier
When trying to write up a new shader for a material, I've been trying to create a variable to use to alter speed and test animation. Now, the below outputs fine until I try to assign a value to number.

```
shader_type canvas_item;

uniform float time_factor = 1.0;
uniform vec2 amplitude = vec2(10.0,5.0);
uniform sampler2D frame1;
uniform sampler2D frame2;
uniform sampler2D frame3;
uniform float speed = 1.0;

float number = 1.9;

void vertex(){
    VERTEX.x += sin(TIME * time_factor + VERTEX.x + VERTEX.y) * amplitude.x;
    VERTEX.y += cos(TIME * time_factor + VERTEX.y + VERTEX.x) * amplitude.y;
   }

```

I had seen tutorials demonstrating that this would have worked fine in previous versions.

# Answer
You forgot uniform in front of "float number = 1.9;"

Everything else seems to be fine.

Good luck.
> 0 votes

---
Tags: shaders, rendering, godot
---


title: Shooting weapons Unity

text:
# Question
Title: Shooting weapons Unity
I'm trying to create a falling word game like z-type (code here). Once the game starts a few words are displayed on the screen. When the user types a letter and if that matches with the first letter of any of the words displayed, an "activeWord" tag is added to the word. I have also created a laser script that checks if the tag is active and when that happens, it shoots the laser. What's happening right now is that the laser is shot only once i.e when the first letter matches but doesn't shoot a laser when the remaining words are typed. Can someone please have a look at the code and tell me where I'm making a mistake.

this is the word display script where the active word is assigned:

```
public void RemoveLetter() // remove the first letter if its correct and so on for the remaining letters. change the color of the word to red and add the "activeddWord" tag.
 {
 text.text = text.text.Remove(0, 1);
 text.color = Color.red;
 text.gameObject.tag = "activeWord";
 }

public void RemoveWord()
{
    Destroy(gameObject); // removes the word from display
}

```

here is the input manager script:

```
public class WordInput : MonoBehaviour {

public WordManager wordManager;

void Update () {
    foreach (char letter in Input.inputString)
    {
        wordManager.TypeLetter(letter);
    }
}

```

**EDIT**

This is the player script where the laser is instantiated:

```
public class Player : MonoBehaviour {
public GameObject laserPrefab;
void Start () {
    transform.position = new Vector3(0.0f, -3.92f, 0); // player position
}

void Update () {
      Instantiate(laserPrefab, transform.position, Quaternion.identity);
        }
}

```

This is the updated laser script:

```
public class Laser : MonoBehaviour
{
public float speed = 10.0f;

private Vector3 laserTarget;

private void Start()
{

}

GameObject activeWord = GameObject.FindGameObjectWithTag("activeWord");

if (activeWord != null && activeWord.GetComponent<Text>().text.Length > 0){

  laserTarget = activeWord.transform.position; // find position of word
  transform.Translate(laserTarget * speed * Time.deltaTime);

  for (int i = 0; i < Input.inputString.Length; i++){

   Debug.Log("Character from input string: " + Input.inputString[i] + "\n" +
   "Character from word displayed: " + activeWord.GetComponent<Text>().text[0]);

   if (Input.inputString[i] == activeWord.GetComponent<Text>().text[0]){

     laserTarget = activeWord.transform.position; // find position of word
     transform.Translate(laserTarget * speed * Time.deltaTime); // shoot the laser
  }
 }
}

```

After I do this, there are two major errors that I get:

1. As soon as I hit play, the laser fires continuously without stopping.
2. The laser still shoots only once after the word is typed...This is the message I get in the console (screenshot attached). There is a difference of one word between the input string and whats displayed on the screen...Can someone please tell me how to rectify these.....

# Answer
> 1 votes
Firstly, every time you remove a letter, you assign it the tag "activeWord". So when you find with tag, it just finds the first object assigned with this tag and targets it. Maybe this is why your laser is shot once, because the laser is shot and it just goes and sticks at activeword.transform.position.

Secondly i do not see any line of code that actually destroys the word after it has been hit. That way your laser will target the next game object with tag "activeWord" automatically, and you wont need to write extra code.

If you want multiple lasers to be hitting at once, it is a good idea create an empty object that never moves in level and set it as parent to your laser shots. When a word is typed, take its position, assign it to a laser shot. parent it to empty and change tag for that word. Once that word is hit, destroy it. That way each laser will have a different position to go to.

Good Luck.

---
Tags: unity
---


# Question
Title: What are the semantics of these quaternion functions in XNA/Monogame?
I am having trouble understanding the semantics of some members of the XNA/Monogame `Quaternion` class. The docs are not helpful, and tutorials trying to explain quaternions are using heavy math, which isn't helpful for me either, since I simply do not have proper background for that.

My main questions currently are:

* Is there any difference between `Multiply` and `Concatenate`?
* What is the exact difference between `Inverse` and `Negate`?

# Answer
> 1 votes
There's minimal difference between concatenate and multiply, `concatenate(a, b) = b * a`

Inverse and negate are different. Negate flips the signs, inverse returns \\$q^{-1}\\$ so that \\$q * q^{-1} = identity = (1, 0, 0, 0)\\$, the inverse of the quaternion \\$(a, b, c, d)\\$ is \\$\frac{a -ib-jc-kd}{a^2+b^2+c^2+d^2}\\$

---
Tags: xna, monogame, quaternion
---


title: Order of rotation in Euler angles

text:
# Question
Title: Order of rotation in Euler angles
I'm want to control the direction my camera looks, so I'm using Euler angles, so rotating around an axis is relative to rotation around previous axis. Something like this.

I want to always rotate using the blue axes. So I'm using three separate matrices to track rotation along their respective axes.

```
...

glm::vec3 mulVec (glm::mat4 const&, glm::vec3&);

glm::vec3 camPos = glm::vec3(0.0f, 1.0f, 0.0f);
glm::vec3 target = glm::vec3(0.0f, 0.0f, -5.0f);
glm::vec3 camup  = glm::vec3(0.0f, 1.0f, 0.0f);

tulsi::ModelInput a1;

while (1) {

    ...

    a1.tick();  // Tracks user input.

    glm::mat4 lookat = glm::lookAt(
                    camPos,
                    mulVec(a1.yAxis * a1.xAxis, target),
                    mulVec(a1.yAxis * a1.xAxis, camup)
                    );
    ...
}

```

I get the desired output (rotate around x axis then y)

But when I switch the order of multiplication, I get different output (rotate around y then x axis)

```
glm::mat4 lookat = glm::lookAt(
                    camPos,
                    mulVec(a1.xAxis * a1.yAxis, target),
                    mulVec(a1.xAxis * a1.yAxis, camup)
                    );

```

So whats happening here. I'm assuming the order should not matter.

# Answer
Order does matter. For fps games it should generally be yaw -\> pitch -\> roll. When using matrices, note that multiplication order might be the complete opposite.

Think about it, doing the pitch first would also rotate the y axis, and rotating around that will make the y coordinate of the direction vector go up and down.
> 3 votes

---
Tags: opengl, camera, rotation, euler-angles
---


# Question
Title: Why does Unity not follow the z-value when drawing text?
I'm currently working on the credits of our game. For this I'm using multiple elements in a canvas:

I want the order that these elements are drawn in to be as follows, I gave them a z-value based on this:

```
 Z    Object                             Object type
=========================================================
 0    Text (The actual credits)          Text
---------------------------------------------------------
-1    Hider (Green for demonstration)    Sprite
---------------------------------------------------------
-2    Divider (The grey line)            Sprite
-2    Gametitle                          Text

```

The camera has a z-value of -10. The canvas is in "Screen Space - Camera" render mode.

But for some reason Unity is not drawing these items based on these Z-values:

As you can see, the Divider is drawn over Text, but Text is above Hider and Gametitle. Why is this happening and what can I do so the credits get properly drawn?

# Answer
*Credits for this idea go to @EdMarty, he placed a comment on the question.*

~~Why exactly I'm not sure, but apparently the sprites (2D game-objects) don't work well together with texts (UI game-objects).~~ As explained by @DMGregory in a comment:

> The reason is that SpriteRenderers predate the UI system — they're rendered by the usual camera pipeline. Then the UI Canvas and its UI-specific renderers like Images draw as their own group.

I replaced the the sprites (Hider and Divider) with images (UI game-objects). I also modified the hierarchy of the objects in the order they need to be drawn (the lower the later rendered) as was described in @steknika's answer. (But I did not use a panel).

This has fixed the issue and the elements are now drawn in the right order.
> 1 votes

# Answer
Use the canvas as the whole screen GUI. Under the canvas use a panel, that cover your needs and place the texts in it, where the order of the elements goes bottom to top. The lower the element the later it will be rendered. Also keep in mind that your Canvas rendering mode is need to be in Screen Space - Overlay for this. If you still want to do Z ordering it won't work till you change Canvas rendering mode to Screen Space - Camera. I hope it helps.
> 1 votes

---
Tags: unity
---


# Question
Title: How do I destroy a class/how do I link a class to a gameObject
I am fairly new to programming and I decided to create a Pong game. I created the sprites and was able to make the paddles and the dot work. The only help I needed was when I wanted the dot to recognize where it was hit.

Now I wanted to respawn the dot when it hits an wall behind the racket. I created an transparent sprite with a 2D Collider. Now I wanted to use this:

If dot hits LeftWall destroy gameobject dot

But when I use:

```
 if (col.gameObject.name == "WandLinks")
    {
      Destroy(Dot.gameObject);
    }

```

it tells me "Dot" is a class and can't be destroyed. This I understand. But why does the rest work? And how do I create a reference from the class to a new gameObject? Thank you very much.

(My next solution is to place the code for the destruction inside my wall but that's not my desired solution)

\- This is my whole code for the dot

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

public class Dot : MonoBehaviour

{
public float speed = 5;
public Transform spawnPoint;

void Start()
{
    // Initial Velocity
    GetComponent<Rigidbody2D>().velocity = Vector2.right * speed;
}

float hitFactor(Vector2 ballPos, Vector2 racketPos,
                float PaddleRight)
{
    // ascii art:
    // ||  1 <- at the top of the racket
    // ||
    // ||  0 <- at the middle of the racket
    // ||
    // || -1 <- at the bottom of the racket
    return (ballPos.y - racketPos.y) / PaddleRight;
}
public void RespawnDot()
{
    Instantiate(dot, spawnPoint.position, spawnPoint.rotation);
}

void OnCollisionEnter2D(Collision2D col)
{
    // Note: 'col' holds the collision information. If the
    // Ball collided with a racket, then:
    //   col.gameObject is the racket
    //   col.transform.position is the racket's position
    //   col.collider is the racket's collider

    // Hit the left Racket?
    if (col.gameObject.name == "PaddleLeft")
    {
        // Calculate hit Factor
        float y = hitFactor(transform.position,
                            col.transform.position,
                            col.collider.bounds.size.y);

        // Calculate direction, make length=1 via .normalized
        Vector2 dir = new Vector2(1, y).normalized;

        // Set Velocity with dir * speed
        GetComponent<Rigidbody2D>().velocity = dir * speed;
    }

    // Hit the right Racket?
    if (col.gameObject.name == "PaddleRight")
    {
        // Calculate hit Factor
        float y = hitFactor(transform.position,
                            col.transform.position,
                            col.collider.bounds.size.y);

        // Calculate direction, make length=1 via .normalized
        Vector2 dir = new Vector2(-1, y).normalized;

        // Set Velocity with dir * speed
        GetComponent<Rigidbody2D>().velocity = dir * speed;
    }

    if (col.gameObject.name == "WandRechts")
    {
        RespawnDot();
    }

    if (col.gameObject.name == "WandLinks")
    {

    }
}
}

```

# Answer
This what I use to destroy my objects: GameObject.Destroy(gameObject);
> 1 votes

---
Tags: unity, pong
---


# Question
Title: I can't find a way to make my projectile gameobject collide with my ofscreen collider
so my code on my collider is as followed

```
public class Collide : MonoBehaviour
{

    private void OnCollisionEnter2D(Collision2D collision)
    {
        Debug.Log("Collision");
    }
}

```

the projectile has a rigidbody2D and a capsule Collider 2D.

collider has a box collider 2D.

the projectile spawns from my player and moves upwards in the direction of the collider (the collider is large enough that the projectile cant miss it).

the projectile however goes straight through the collider and no message appears and I have no idea why.

what I've tried and made sure of :

* both are on the same layer and plane(z axis)
* gave the collider a rigidbody but changed nothing
* made the collider on trigger and not on trigger
* made the projectile dynamic and kinematic
* changed collider script to onCollisionEnter and onCollisionEnter2D

# Answer
> 1 votes
As stated nu Sebastien Servouze I reallised after some searching arround that there is indeed a collision array matrix, which solved my issue.

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


# Question
Title: Why does using .Lookat() cause the enemy to look left instead of at player, and how can I fix it?
I am new to Unity. I have searched but I couldn't find any answers on this. Here is my code:

```
somethingPosition = new Vector3(player.transform.position.x, transform.position.y, player.transform.position.z);
transform.LookAt(somethingPosition);

```

The `somethingPosition` only allows rotation of the Y axis so. Anyways, I have this script on the enemy AI.

The issue is this: the enemy looks at the player but looks to the left of the player. The same issue occurs when I have my follow code happen:

```
transform.position = Vector3.MoveTowards(transform.position, player.position, speed * Time.deltaTime);

```

The enemy will continue going to the left of the player but will not hit the player. What are some suggestions you guys can survive? Thanks!

I am aswell using a NavMesh and NavMeshAgent

# Answer
> 1 votes
Double check that your model of the character does not have an offset. If it does, the object's centre would be away from the model, which would cause all calculations (including `LookAt`) to point to that place. If you are using `NavMeshAgent`s, there's a chance you are doing collisions based on the mesh, creating a bounding box around it, which would explain why everything else seems to be working.

# Answer
> 1 votes
Firstly, you have set target y value to look at to be transform.position.y. This can be okay or not depending on if you are getting the AI to look straight forward.

Secondly, different 3d modeling softwares have either a z-up or a y-up configuration. Check axis of player and AI.

Thirdly, for good results take an empty axes and child it to your player at position where you want your AI to lookat.

Also, as TomTsagk pointed out, your player origin might not be within its mesh and check colliders.

good Luck.

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


# Question
Title: Second input not working when using 2 virtual joysticks
We are trying to make 2 virtual joysticks for both sides of the screen. Movement joystick can be enabled at any pressed position of the left side of the screen and shooting joystick can be enabled on right side.

So far we are trying to make second input to work when movement joystick is our first input. But it feels like second input is locked on the left side of the screen.

What happens when we try to move left side joystick as a first input and then press on the right side of the sceen with other finger (Second input) is that movement joystick locks and player just move to the last position first finger was pointing. Shooting is not happening.

Gameplay, that maybe will help to understand the issue

Code we are working with:

```
public bool LeftSideActive(int input)
{
    if ((Input.GetTouch(input).position.x >0) && (Input.GetTouch(input).position.x < halfScreenWidth))
    {
        if(Input.GetMouseButtonDown(0)) {
            LeftSideTouched = true;
            Debug.Log("Left side enabled: " + LeftSideTouched);
        }
        if(Input.GetMouseButtonUp(0)) {
            LeftSideTouched = false;
            Debug.Log("Left side enabled: " + LeftSideTouched);
        }
    }
    else if ((Input.GetTouch(input).position.x >halfScreenWidth && LeftSideTouched)){
        if(Input.GetMouseButtonUp(0)) {
            LeftSideTouched = false;
        }
    }
    return LeftSideTouched;
}

public bool RightSideActive (int input)
{
    if ((Input.GetTouch(input).position.x > halfScreenWidth) && (Input.GetTouch(input).position.x < Screen.width))
    {
        if(Input.GetMouseButtonDown(0)){
            RightSideTouched = true;
            Debug.Log("Right side enabled: " + RightSideTouched);
        }
        if(Input.GetMouseButtonUp(0)) {
                RightSideTouched = false;
                Debug.Log("Right side enabled: " + RightSideTouched);
            }
    }
    else if ((Input.GetTouch(input).position.x < halfScreenWidth && RightSideTouched)){
            if(Input.GetMouseButtonUp(0)) {
                RightSideTouched = false;
            }
    }
    return RightSideTouched;

}

public void LeftSideControls(int input){
    if ((Input.GetTouch(input).position.x >0) && (Input.GetTouch(input).position.x < halfScreenWidth))
    {
        if(Input.GetMouseButtonDown(0))
        {
            LeftSideTouched = true;
            movementA = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.transform.position.z));
            this.transform.position = movementA; //Updates position where joystick will appear

        }
        if(Input.GetMouseButtonUp(0))
        {
            LeftSideTouched = false;
        }

        // Sets new finger position on drag
        movementB = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.transform.position.z));
    }
    else if ((Input.GetTouch(input).position.x > halfScreenWidth && LeftSideTouched)){
            if(Input.GetMouseButtonUp(0)){
            }
            //Sets new finger position on drag; When finger is dragged from left to right side of the screen controls are kept.
            movementB = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.transform.position.z));
    }
}

public void RightSideControls(int input){
    if ((Input.GetTouch(input).position.x > halfScreenWidth) && (Input.GetTouch(input).position.x < Screen.width))
    {
        if(Input.GetMouseButtonDown(0)){
            RightSideTouched = true;
            shootingA = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.transform.position.z));
            this.transform.position = shootingA; //Updates position where joystick will appear
        }

        if(Input.GetMouseButtonUp(0))
        {
            RightSideTouched = false;
        }
        shootingB = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.transform.position.z)) - transform.position;
        shootingAngle =  Mathf.Atan2(shootingB.y,shootingB.x)*Mathf.Rad2Deg;
        playerGun.transform.rotation = Quaternion.Euler(0,0,shootingAngle);
    }
    else if ((Input.GetTouch(input).position.x < halfScreenWidth && RightSideTouched)){
        if(Input.GetMouseButtonUp(0)){
            RightSideTouched = false;
        }
        //Sets new finger position on drag; When finger is dragged from right to left side of the screen controls are kept.
        shootingB = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.transform.position.z)) - transform.position;
        shootingAngle =  Mathf.Atan2(shootingB.y,shootingB.x)*Mathf.Rad2Deg;
        playerGun.transform.rotation = Quaternion.Euler(0,0,shootingAngle);
    }
}
public void  JoystickEnabling()
{

    while( Input.touchCount > 0)
    {
        if(Input.touchCount>=3)
        {
            Debug.Log("More than 2 touches!!!!");
            return;
        }

        if(Input.touchCount == 1)
        {
            Debug.Log("Touch-count 1");
            FirstFinger = 0;
            SecondFinger = FirstFinger;

            if(LeftSideActive(FirstFinger)&&!RightSideActive(FirstFinger))
            {
                JoystickSpriteRenderer(moveJoyRenderer, true);
                JoystickSpriteRenderer(shootJoyRenderer, false);
                LeftSideControls(FirstFinger);
                //Debug.Log("LeftSideTouchy");
            }
            else if(!LeftSideActive(FirstFinger)&&RightSideActive(FirstFinger))
            {
                JoystickSpriteRenderer(moveJoyRenderer, false);
                JoystickSpriteRenderer(shootJoyRenderer, true);
                RightSideControls(FirstFinger);
                //Debug.Log("RightSideTouchy");
            }
            else{
                JoystickSpriteRenderer(moveJoyRenderer, false);
                JoystickSpriteRenderer(shootJoyRenderer, false);
            }
        }

        else if (Input.touchCount == 2)
        {
            Debug.Log("Touch-count 2");
            FirstFinger = 0;
            SecondFinger = 1;

            if (LeftSideActive(FirstFinger)){
                LeftSideControls(FirstFinger);
                if(LeftSideActive(SecondFinger)){
                    Debug.Log("Second left");
                    return;
                }
                else if(RightSideActive(SecondFinger)){
                    Debug.Log("LEft and Right");
                    RightSideControls(SecondFinger);
                }
            }
        }

        break;
    }
}
    void FixedUpdate(){
        if(LeftSideTouched){
            //Calculates offset between first and last finger position
            Vector2 offset = movementA - movementB;
            Vector2 direction = Vector2.ClampMagnitude(offset, 1.0f);
            //Moves character
            MoveCharacter(direction * -1f);
        }
    }

      void MoveCharacter(Vector2 direction) // Function for character movement
    {
        player.Translate(direction * speed * Time.deltaTime);
    }

    //Enable either joystick sprite
    void JoystickSpriteRenderer(SpriteRenderer joystick, bool enable){
        joystick.GetComponent<SpriteRenderer>().enabled = enable;
    }

}

```

# Answer
I have something to share about touch controls.

Perhaps this is a similar confusion of Unreal Engine having touch1, touch2 as first finger touch and second finger touch inputs. Unless you add and map touch2, only first touch/swipe input is taken as input.

After a quick visit to Unity docs, a similar system is applied as Input.GetTouch(1) and Input.GetTouch(2) as 2 finger gestures.

I have never used a joystick but perhaps you are facing similar troubles. Hope this solves your problem.

Good Luck.
> 0 votes

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


# Question
Title: Scrolling in 3d Shmup with 32Bit era effects
How can I create a scrolling effect like in Ikaruga, where the background is on Rails and the foreground is fixed with the player in Unity?

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

Some more features would be:

# Answer
I would actually do this with two separate cameras rendering objects with two different culling masks.

* One camera which moves through a 3d scene controlled by a Timeline \- Unity's new recommended way of doing cinematic cutscenes.
* One non-moving camera which shows the actual gameplay. This camera would be set to `Clear flag: Depth only` and `Depth` higher than the previous camera. This makes the render output of the first camera the background of the second.

This would allow me to implement the gameplay just like the official space shooter tutorial while I have the freedom to create the background scene in any way I want.

Another option: I suspect that some of these games might actually just play a pre-rendered movie in the background. If you want to go that way, you can use a Movie Texture to play videos created with a 3d animation software of your choice.
> 0 votes

---
Tags: unity, 3d, camera, scrolling, arcade
---


# Question
Title: Unity UI Buttons don't work when clicked, don't seem intractable at all
This is probably a quick and easy fix but I can't seem to get it. As the title says I've got UI buttons which appear when my character dies, they used to work just fine but now suddenly when doing a full test through they don't seem to work. I've found similar posts where the solution was to disable / enable raycasts, that didn't help. Another user was missing an input module from the event system, mine seems to be there an in check.

The only significant change that I think will have affected my UI buttons was the addition of a joystick and another UI button, i thought perhaps they are blocking the older buttons but I've disabled the joystick and new button, that didn't help, even tried changing the zaxis, that didn't help too.

I'm honestly not sure how to go about testing something like this.

The UI overlay is my canvas, the GameOver object is disabled on start then enabled when the player dies, showing the Gameover text, Button quit and rety, these are the buttons that no longer work.

My button retry's settings, mostly unchanged honestly.

Thanks

# Answer
# You need a graphic raycaster

The nearest direct parent *Canvas* of any UI element which is top receive mouse input needs to have a `GraphicRaycaster` component.

This is not to say that the button's patent needs this, but the first patent in the hierarchy that already had a `Canvas` needs to have it. In your case, likely the UIOverlay object in your scene hierarchy list, though it is possible that it is the GameOver object.

Unity automatically attaches both when you create any UI element with the GameObject menu, however if you are building UI yourself, or make use of child canvases (this can be a good thing) you need to attach a `GraphicRaycaster` if any element of that canvas needs mouse input.
> 2 votes

---
Tags: unity, gui
---


# Question
Title: checking if an array rank is not equal to an int C#
I'm creating an inventory system for a dungeon crawler, I've got world gen, and player controls down, and this is the only snag.\`

```
public Transform[] items;

public bool[] usingitem;

public int usingitemnumber;

public void Update()
{
    if (Input.GetKeyDown("1"))
    {
        usingitemnumber = 1;
    }

    if (Input.GetKeyDown("2"))
    {
        usingitemnumber = 2;
    }

    if (Input.GetKeyDown("3"))
    {
        usingitemnumber = 3;
    }

    if (Input.GetKeyDown("4"))
    {
        usingitemnumber = 4;
    }

    usingitem[usingitemnumber] = true;
    if (usingitem.Rank != usingitemnumber)
    {
        usingitem[!= usingitemnumber] = false;
    }

}

```

\`

i need to check if a rank on the `transform[] usingitem` array is not equal to the `int usingitemnumber` , and if it's not equal to it set it to false, and keep the on that is equal to it true

# Answer
If I understand you correctly:

* `usingitem` is an array of bools
* `usingitemnumber` is the index of the item that should be active / in use
* You want the `i`th entry of `usingitem` to be `true` if and only if `i` is equal to `usingitemnumber` (ie. this array item corresponds to the currently used item)
* All other entries in the `usingitem` array should be `false`

We can do this very simply with a `for` loop. This steps over each entry in the array in order, from index `i = 0` to index `i = usingitem.Length - 1`, and sets it to `true` if the index `i` matches `usingitemnumber`, otherwise it assigns the array entry to `false`.

```
for(int i = 0; i < usingitem.Length; i++)
   usingitem[i] = (i == usingitemnumber);

```
> 1 votes

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


title: Rewriting a text object

text:
# Question
Title: Rewriting a text object
I'm trying to set up a UI system. Say I have a text object 'text' which is visible onscreen. I want to change it with a button press using a script such that the text box's previous string is replaced with a new string held in a string variable 'chat'.

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

public class textchange : MonoBehaviour
{

public Text text; //the text box gameobject is dragged into this

public string chat; //the chat string is filled elsewhere

void Awake()
{

}

void Update()
{
(if button press logic here)
{
text.text = chat;
}
}

}

```

What I expect is for the text to dynamically change, but what happens is absolutely nothing, the gameobject does not have its text component rewritten. What gives?

# Answer
What you have here looks correct at first glance, but there might be a mistake in the `button press logic here` part you omitted.

Verify that the line `text.text = chat;` is actually being executed. You can do that by adding a line like `Debug.Log("changing content of " + text.name + " to " + chat)` in front of it and looking at the console output or by setting a debugger breakpoint in Visual Studio and running the game in debug mode.

It is also possible that you didn't assign a text field to the `public Text text` variable. The symptom would be a `NullReferenceException` error in your Unity console whenever the line `text.text = chat` is being executed. Open the inspector of the game object with this script and drag the text field you want to control into the "Text" slot of your component.
> 0 votes

---
Tags: unity, gui, text
---


# Question
Title: "RuntimeError: Validation failure (0)" using shaders
I'm trying to move away from using glVertex() in my game code because it doesn't seem to work well with a large quantity of vertices. At the moment I'm trying to make code that uses Shaders, but when compiling with shaders.compileProgram, it gives me the error shown in the title, with no explanation as to what is wrong.

Code so far:

```
import OpenGL
from OpenGL.GL import *
from OpenGL.GL import shaders
from OpenGL.arrays import vbo

import math
import pygame
from pygame.locals import *

VERTEX_SHADER = shaders.compileShader("""
#version 120
 void main() {
    gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
 }
""", GL_VERTEX_SHADER)

FRAGMENT_SHADER = shaders.compileShader("""
#version 120
void main() {
    gl_FragColor = vec4( 0, 1, 0, 1 );
}
""", GL_FRAGMENT_SHADER)

self.shader = shaders.compileProgram(VERTEX_SHADER,FRAGMENT_SHADER)

```

The full error message:

```
Traceback (most recent call last):
  File "PyOpenGl shader test from scratch.py", line 24, in <module>
    self.shader = shaders.compileProgram(VERTEX_SHADER,FRAGMENT_SHADER)
  File "/home/[my name]/.local/lib/python2.7/site-packages/OpenGL    /GL/shaders.py", line 196, in compileProgram
    program.check_validate()
  File "/home/[my name]/.local/lib/python2.7/site-packages/OpenGL/GL/shaders.py", line 108, in check_validate
    glGetProgramInfoLog( self ),
RuntimeError: Validation failure (0):

```

Is there a line I need to add for it to tell me what is wrong?

# Answer
This often happens also if you do not specify the context before compiling the shaders. For example, for QT Widgets (pytqt) you should have your shaders compiled when the gl context is enabled, for example in the `initializeGL` function. So in the case of using QT you can do something like:

```
class MyQtWidget(QOpenGLWidget, QWidget):
    def __init__(self, directory):
        super(MyQtWidget, self).__init__()
...

def initializeGL(self):
    """
    Initializes openGL context and scenery
    """
    self.shader = compileProgram(
            compileShader(my_vert_shader, gl.GL_VERTEX_SHADER),
            compileShader(my_frag_shader, gl.GL_FRAGMENT_SHADER)
        )

```

As for your case, please see the example from here:
https://github.com/tartley/opengl-tutorials/blob/master/pyopengl/05-lighting.py
Shaders are compiled after the context has been enabled (via the inheritance of BaseContext class).

Another example with the use of glfw also initializes the context beforehand:
https://github.com/totex/PyOpenGL\_tutorials/blob/master/main.py
So in here we have this `glfw.make_context_current` function.

However, even if you do the above, this does not mean that your shaders are correct, but if you do intialize the context, you should get a verbose error message on what is wrong with your shaders.
> 2 votes

# Answer
Well, it turns out that I've just completely missed the fact that this tutorial uses a special library specifically for the tutorial. (I hate when a tutorial does this... How am I supposed to do anything without the tutorial module?)

This is the tutorial in question.

It doesn't even appear that the problem was with the shaders, I was just missing functions from an inherited class.
> 1 votes

---
Tags: opengl, python
---


# Question
Title: Press f to interact with NPCs or objects
How do I change the method used for initiating the interaction. Instead of clicking object, check if within a certain radius of an object when you hit a key on your keyboard.

If within 1 unit, the player gets a message that they can press f to interact. When f is pressd, get the object they're close to and handle the interaction the same way.

PS. I'm using box collider.

Here are the script that I found. I tried this but once I start the game and press F key, its working. But I want the player to press the F key once the character is inside the collider of an object.

**WorldInteraction**

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

public class WorldInteraction : MonoBehaviour {
    NavMeshAgent playerAgent;

void Start() {
    playerAgent = GetComponent<NavMeshAgent>();
}

void Update() {
    if (Input.GetMouseButtonDown(0) && !UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject()) {
        GetInteraction();
    }
}

void GetInteraction() {
    Ray interactionRay = Camera.main.ScreenPointToRay (Input.mousePosition);
    RaycastHit interactionInfo;
    if(Physics.Raycast(interactionRay, out interactionInfo, Mathf.Infinity)) {
        GameObject interactedObject = interactionInfo.collider.gameObject;
        if (interactedObject.tag == "Interactable Object") {
            interactedObject.GetComponent<Interactable>().MoveToInteraction(playerAgent);
        } else {
            playerAgent.destination = interactionInfo.point;
        }
    }
}

```

}

**Interactable**

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

public class Interactable : MonoBehaviour {
    public NavMeshAgent playerAgent;

public virtual void MoveToInteraction(NavMeshAgent playerAgent) {
    this.playerAgent = playerAgent;
    playerAgent.destination = this.transform.position;

    Interact();
}

public virtual void Interact() {
    Debug.Log ("Interacting with base class.");
}

```

}

**NPC**

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

public class NPC : Interactable {

public override void Interact() {
    Debug.Log ("Interacting with NPC.");
}

```

}

# Answer
> 1 votes
You could use a boxcollider set as trigger, then do something like the below in your trigger enter and exit functions. No raytracing necessary, i.e. it works when you're not looking directly at the interacted object etc.

```
private GameObject interactedObject;

void OnTriggerEnter(Collider c){
    interactedObject = c.gameObject;

}
void OnTriggerExit(){
    interactedObject = null;

}

```

then you can use if(interactedObject!=null){....} wherever you want to do something different if you're interacting.

e.g.

```
void Update() {
    if (Input.GetKey(KeyCode.F) && interactedObject != null) {
        GetInteraction();
    }
}

```

# Answer
> 0 votes
The script uses a raycast hit to detect whether the interactible object is visible or not.

If you want to limit the interaction range, you can check `interactionInfo.distance` after `Physics.Raycast`. This allows you to verify whether the object is close enough to interact with or not. Or you can limit the range of the raycast in the first place by replacing `Mathf.Infinity` with your desired maximum interaction range.

---
Tags: unity, character, npc
---


# Question
Title: Keeping score server side to prevent cheating
For my Unity WebGL game, I'm looking into storing the score of users in a database to make a highscore table (it's not a multiplayer game). Because client side code can always be "hacked", the advice most people give is: "keep the score server side so you can validate it". But I don't quite understand how that would work. I could of course publish the score to the server using an Ajax call, and even hash it, but even then the cheater could just simply look at the hash method and use the same Ajax to upload a different score.

I'm assuming I should get a game server or something then? But again: no idea on how to start... I'm really just scratching the surface here.

So I'm basically looking for any sort of information on how to change my "regular", client side, WebGL Unity game to a game where I keep the score securely at server side so that the highscore table is valid.

I don't mind spending some money on both a server/assets that simplify the task. As I said, I'm just interested in implementing this feature, I don't need to become a game server wizard.

Note: even with server side scores, there's probably a way to cheat. There most likely always is, but at least it would be more secure than just inserting the final score into the database...

# Answer
> 1 votes
Don't send scores. Send game events as they happen, and calculate the score that results from those game events.

The server can then validate whether the claimed sequence of game events is plausible, and reject implausible play, stopping it from recording a high score.

For instance, if your client & server can both agree on the same sequence of enemy movements, the client can send "I shoot in this direction" and the server can check "would that shot kill an enemy at the time the message was sent?" and increment the score if so.

There are various types of validation you can do, like verifying the player isn't claiming to move or aim faster than the game allows, or aiming through occluders like walls. Any rule violations tell you that you're communicating with a modded or spoofed client (or you have a sychronization / replication bug to sort out, where the client's game state isn't correctly matching the server's)

The one thing this strategy can't do is distinguish between a perfect player and a bot that plays by the rules, perfectly. For that the best you can do is look for telltale signs of human error, and analyze patterns to detect signs of a bot using randomness to fake human imperfection.

---
Tags: unity, anti-cheat, unity-webgl
---


# Question
Title: Why isn't my sound playing on collision?
I tried several approaches to get my sound working. This is one of them which most of the online tutorials showed me:

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

public class WallLeftSound : MonoBehaviour
{
    private AudioSource audioSource;
    public AudioClip Scored;

    void OnCollisionEnter2D(Collider2D collider)
    {

        if (collider.tag == "dot")
        {
            audioSource = GetComponent<AudioSource>();
            audioSource.clip = Scored;
            audioSource.Play();
        }
    }

    // Start is called before the first frame update
    void Start()
    {

    }

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

    }
    }

```

It's not working. Please note that this is work in progress, I tried several other approaches too. Thank you for you help.

Edit Dot:

```
public class Dot : MonoBehaviour
{
public float speed = 5;
public Transform spawnPoint;
public GameObject dot;
public AudioClip pongSound;
public AudioSource pongSource;

void Start()
{
    // Initial Velocity
    GetComponent<Rigidbody2D>().velocity = Vector2.right * speed;
    pongSource.clip = pongSound;
}

void Update()
{

}

float hitFactor(Vector2 ballPos, Vector2 racketPos,
                float PaddleRight)
{
    // ascii art:
    // ||  1 <- at the top of the racket
    // ||
    // ||  0 <- at the middle of the racket
    // ||
    // || -1 <- at the bottom of the racket
    return (ballPos.y - racketPos.y) / PaddleRight;
}

public void moveDot()
{
    gameObject.GetComponent<Rigidbody2D>().AddForce(Vector2.right * speed);
}
void OnCollisionEnter2D(Collision2D col)
{
    // Note: 'col' holds the collision information. If the
    // Ball collided with a racket, then:
    //   col.gameObject is the racket
    //   col.transform.position is the racket's position
    //   col.collider is the racket's collider

    // Hit the left Racket?
    if (col.gameObject.name == "PaddleLeft")
    {
        // Calculate hit Factor

        float y = hitFactor(transform.position,
                            col.transform.position,
                            col.collider.bounds.size.y);

        // Calculate direction, make length=1 via .normalized
        Vector2 dir = new Vector2(1, y).normalized;

        // Set Velocity with dir * speed
        GetComponent<Rigidbody2D>().velocity = dir * speed;
    }

    // Hit the right Racket?
    if (col.gameObject.name == "PaddleRight")
    {
        // Calculate hit Factor
        playSound();
        float y = hitFactor(transform.position,
                            col.transform.position,
                            col.collider.bounds.size.y);

        // Calculate direction, make length=1 via .normalized
        Vector2 dir = new Vector2(-1, y).normalized;

        // Set Velocity with dir * speed
        GetComponent<Rigidbody2D>().velocity = dir * speed;
    }

    if (col.gameObject.name == "WandRechts")
    {

        RespawnDot();
        GameObject.Destroy(gameObject);
        scoreScript2.scoreValue += 1;

    }

    if (col.gameObject.name == "WandLinks")
    {

        RespawnDot();
        GameObject.Destroy(gameObject);
        scoreScript.scoreValue += 1;
        pongSource.Play();

    }
}

```

Edit2 PlayerLeft

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

public class PlayerLeft : MonoBehaviour
{
private Rigidbody2D PaddleLeft;
[SerializeField]
private float movementSpeed;
void Start()
{
    PaddleLeft = GetComponent<Rigidbody2D>();
}

// Update is called once per frame
void Update()
{
   if (Input.GetKey(KeyCode.UpArrow))
        {
        PaddleLeft.velocity = new Vector2(0, 1 * movementSpeed);
    }

  else if (Input.GetKey(KeyCode.DownArrow))

    {
        PaddleLeft.velocity = new Vector2(0, 1 *- movementSpeed);
    }

   else if (!Input.anyKeyDown)
    {
        PaddleLeft.velocity = Vector2.zero;
    }
}

private void HandleMovement()
{

}
}

```

Edit Picture BoxCollider

# Answer
> 0 votes
While I can not see how you configured the box collider of your "Wand Links", it seems to me like it would be a trigger-collider. This would make sense, because it seems to be a "kill zone" which removes the ball from the game and counts score. Those are usually implemented as trigger colliders.

* Trigger colliders are non-corporeal (things fly through them). They call the Trigger-events on their behviours (`OnTriggerEnter`, `OnTriggerStay`, `OnTriggerExit` and their respective 2D versions).
* Non-trigger colliders are corporeal (things crash into them). They call the Collision-events on their behaviours (`OnCollisionEnter`, `OnCollisionStay`, `OnCollisionExit` and their respective 2D versions).

For more information about which combinations of colliders and rigidbody settings cause trigger events and which cause collision events, see the collision tables in the Collider manual.

If I am right about the "Is Trigger" checkbox of the collider being marked, you need to use `OnTriggerEnter2D` instead of `OnCollisionEnter2D`.

Note that the trigger event methods take a `Collider`/`Collider2D` as a parameter, not a `Collision`/`Collision2D`.

**Edit:** Apparently the wall is not a trigger. But it also has no rigidbody and isn't marked as static, so it doesn't register collisions with rigidbodies either (check the collision matrix). Mark the "Is Trigger?" checkbox on the collider, use OnTrigger events, and it should work.

---
Tags: unity
---


# Question
Title: How can I check if the mouse hits a quad in 3d, and where it hits it?
I have a sketch that produces the following:

```
public void settings() {
  size(600, 600, P3D);
  pixelDensity(2);
}

float rot_y;

public void draw() {

  background(30);
  lights();
  float z = (float) ((height/2.0) / Math.tan(PI*30.0 / 180.0));
  translate(width/2, height/2, z);

  if (mouseX > width * 0.9) {
    rot_y += radians(0.5f);
  } else if (mouseX < width * 0.1) {
    rot_y -= radians(0.5f);
  }

  rotateY(rot_y);

  for (int i = 0; i < 8; i++) {
    pushMatrix();
    fill(255);
    rectMode(CENTER);
    rotateY(radians(45) * i);
    translate(0, 0, z);
    rect(0, 0, 400, 400);
    // how can I know it the mouseX, mouseY hits the rect?
    // and if so, also where it hit's the rect?
    popMatrix();
  }
}

```

Now I would like to know if the mouse is over the rect, and if so where the hit is on the rect is in x and y.

I have seen some topics about rays and quad detection and I found them hard to understand. Since I always have a quad that is basically a AABB but rotated in 3d and the mouse if always a ray coming straight out of the screen; I am hoping this would make a possible solution more easy.

Any help is welcome.

# Answer
> 1 votes
Since the comments made clear you're looking for a general solution, I'll describe that process here. Note the code is to show the principle, you will need to translate it to the framework you're using. I also assume you are familiar with projection, view and world matrices- and their role in 3D graphics.

**3D Mouse picking**

The idea is to create a ray from the mouse (screen) towards the distance.

A Ray is basically a line with one startpoint and a direction:

```
Ray r = new Ray(startpoint, directionVector);

```

Now let's create a ray from the mouse pointer. To do this, we consider a 'near' and a 'far' plane. The line is from the screen towards the horizon- however we only need the direction, so it does not really matter if the far point is actually near the horizon. So:

```
Vector3 nearPlaneMousePointer = new Vector3(mouseX, mouseY, 0);
Vector3 farPlaneMousePointer = new Vector3(mouseX, mouseY, 1);

```

Now we have two coordinates in the 3D space- in relation of the screen- the viewport.

To convert the coordinates in the worldspace, we actually need to "unproject" (inverse of the projection) to get the correct coordinates. Most frameworks have a 'Viewport.Unproject()' method- using the projection and view matrices, to calculate a given point to it's original unprojected object space.

```
Vector3 nearPlanePoint = Viewport.Unproject(nearPlaneMousePointer, _projection, _view, Matrix.Identity);
Vector3 nearPlanePoint = Viewport.Unproject(farPlaneMousePointer, _projection, _view, Matrix.Identity);

```

With these two points you can now get the direction and construct the ray:

```
Vector3 rayDirection = farPoint - nearPoint;
rayDirection.Normalize();
Ray r = new Ray(nearPoint, rayDirection);

```

Now we have a ray that is in the object space.

We can still not use it to do the ray picking. Why? Because the object space does not take the world matrices into account. If you only have AABBs or the worldspace is static, this step may not be needed. I'll provide the theory anyway in the event you plan to move things around a bit more and use world matrix.

So translate the ray into world space. To do this, use the inversion of the world matrix.

```
Matrix inverted = _world.Invert();
Ray worldRay = new Ray(Vector3.Transform(r.Origin, inverted),
                       Vector3.Transform(r.Direction, inverted));

```

If the target quads are also transformed to world space, a ray-triangle intersection test will provide your answer. Loop through the quads and check is the quad is hit. Some frameworks have a hit test function for rays and quads or triangles.

The result of the hit test can also be checked for distance from the ray's origin: this way you can select the first quad that is hit- if the viewpoint has overlapping quads. You can optimise this part als by checking only quads that were in the viewport (use the same culling mechanism as you would in drawing the world).

# Answer
> 2 votes
This is not a full answer, but these are the general steps to go through to get what you want

**Create a mouse-viewport ray**, this is a line segment that starts from the camera eye position and shoots out into the scene through the mouse position.

**Ray-plane intersection**, use some maths to check if and where the ray intersects the infinite plane defined by a position and normal of your square.

**Check if the point lies in the square**, because the square is AABB aligned you can check the intersection point's x, y and z co-ordinates to see if it's in the square.

---
Tags: raycasting, aabb, processing
---


# Question
Title: How can I prevent the balls from overlapping?
I am making a ball rolling game controlled by tilting an accelerometer.

In my game multiple balls overlap, so they end up showing as only one ball. How can I solve this problem, so balls do not overlap?

I have write this script:

```
public class Accelerometer : MonoBehaviour {
    public float Speed=0.5f;
    public float Speedy = 8f;
    public float HorizantalMin;
    public float HorizantalMax;
    public float VerticalMin;
    public float VerticalMax;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        float Horizental = Input.acceleration.x*Speed;
        float UP = Input.acceleration.y*Speedy;
        transform.Translate (Horizental, 0f,UP*Time.smoothDeltaTime);

        this.transform.position = new Vector3 (Mathf.Clamp (this.transform.position.x, HorizantalMin, HorizantalMax), this.transform.position.y, this.transform.position.z);
        this.transform.position = new Vector3 (this.transform.position.x, this.transform.position.y,Mathf.Clamp (this.transform.position.z, VerticalMin,VerticalMax));
    }
}

```

# Answer
Try this and make sure trigger is ON. this script attached on one ball

```
public float Speed=0.5f;
public float Speedy = 8f;
public float HorizantalMin;
public float HorizantalMax;
public float VerticalMin;
public float VerticalMax;

public GameObject second_ball;
public float disance_between_balls;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    float Horizental = Input.acceleration.x*Speed;
    float UP = Input.acceleration.y*Speedy;
    transform.Translate (Horizental, 0f,UP*Time.smoothDeltaTime);

    this.transform.position = new Vector3 (Mathf.Clamp (this.transform.position.x, HorizantalMin, HorizantalMax), this.transform.position.y, this.transform.position.z);
    this.transform.position = new Vector3 (this.transform.position.x, this.transform.position.y,Mathf.Clamp (this.transform.position.z, VerticalMin,VerticalMax));

disance_between_balls = Vector3.Distance(transform.position,second_ball.transform.position);

if (disance_between_balls < 0.5f)  // check if this distance good or not
{
    second_ball.SetActive(false);
}

}

```
> 0 votes

---
Tags: unity, physics, collision-resolution
---


# Question
Title: Why does my FPS go down so much when rendering basic sprites?
I have a UWP DX11 application and I've recently removed the vsync and noticed that my fps goes down drastically when I'm only drawing very basic sprites on the screen and I'm trying to learn why this is so I can improve it. I would *not* expect it to drop this low for only rendering sprites.

With only a single sprite drawing on the screen, and everything still present in the update loop I am getting around ~3000 fps which is what I would expect for my graphics card.

However, there is a huge drop when I'm only rendering the projectiles on the screen.

Just from rendering these projectiles I dropped from around ~3000 fps to ~500 which is an absurd amount when they are so small in size. When I render the other entities on the screen with no projectiles, I am dropping to around ~200.

The fact I can run modern 3d games at a higher fps than I can render about ~20 sprites on my screen proves I am doing something wrong, but I'm not sure what. Could anyone provide any points as to why this might be?

If there is any additional information required I can gladly assist, I just don't know what code is required for this type of issue.

---

```
void Update()
{
    m_timer.Tick([&]()
    {
        //update keypresses
        m_keybindManager->Update(m_timer);

        //update player
        m_player->Update(m_timer);

        //update projectiles
        m_projectileManager->Update(m_timer);

        uint32 fps = m_timer.GetFramesPerSecond();
        std::stringstream ss;
        ss << "FPS: " << fps << "\n" << std::endl;
        OutputDebugStringA(ss.str().c_str());

    });
}

bool Render()
{
    if (m_timer.GetFrameCount() == 0)
    {
        return false;
    }

    SpriteRenderer* renderer = m_spriteRenderer.get();

    //set up the renderer before drawing
    renderer->InitializeRenderer();

    //draw player
    Sprite& s = m_player->GetSprite();
    s.Render(*renderer);

    //draw projectiles
    m_projectileManager->Render(*renderer);

    return true;
}

```

ProjectileManager Render

```
void ProjectileManager::Render(IRenderer& renderer) {

    for (std::shared_ptr<Projectile>& projectile : m_projectiles) {
        Sprite& sprite = projectile->GetSprite();

        sprite.Render(renderer);
    }

}

```

Sprite Update/Render

```
void Sprite::Update(DX::StepTimer const & timer)
{
    if (m_cycleTextures) {

        uint64_t currentTime = Time::CurrentTimeMilliseconds();

        if (currentTime > (m_lastCycle + (uint64_t)m_cycleDelay)) {
            m_cycleId = (m_cycleId + 1) % m_textures.size();

            m_texture = m_textures[m_cycleId];

            m_lastCycle = currentTime;
        }
    }

}

void Sprite::Render(IRenderer& renderer) {
    Rendering::SpriteRenderDescription renderDescription =
        Rendering::SpriteRenderDescription(m_texture.Get(), m_vertexBuffer.GetAddressOf(), m_indexBuffer.GetAddressOf(), m_worldMatrix);

    renderer.Render(renderDescription);
}

```

SpriteRenderer Render

```
void SpriteRenderer::Render(Rendering::RenderDescription const& renderDescription)
{
    Rendering::SpriteRenderDescription const& spriteRenderDescription = dynamic_cast<Rendering::SpriteRenderDescription const&>(renderDescription);

    if (!m_loadingComplete)
    {
        return;
    }

    auto context = m_deviceResources->GetD3DDeviceContext();

    //stores the world/model for the object being rendered
    XMStoreFloat4x4(&m_constantBufferData.model, XMLoadFloat4x4(&spriteRenderDescription.m_world));

    // Prepare the constant buffer to send it to the graphics device.
    context->UpdateSubresource1(
        m_constantBuffer.Get(),
        0,
        NULL,
        &m_constantBufferData,
        0,
        0,
        0
    );

    // Each vertex is one instance of the VertexPositionColor struct.
    UINT stride = sizeof(ShaderStructures::VertexTextureCoordinates);
    UINT offset = 0;
    context->IASetVertexBuffers(
        0,
        1,
        spriteRenderDescription.m_vertexBuffer,
        &stride,
        &offset
    );

    context->IASetIndexBuffer(
        *spriteRenderDescription.m_indexBuffer,
        DXGI_FORMAT_R16_UINT, // Each index is one 16-bit unsigned integer (short).
        0
    );

    //update texture
    context->PSSetSamplers(0, 1, m_sampleState.GetAddressOf());
    context->PSSetShaderResources(0, 1, &spriteRenderDescription.m_texture);

    ID3D11RasterizerState* rasterState;
    D3D11_RASTERIZER_DESC wfdesc;
    ZeroMemory(&wfdesc, sizeof(D3D11_RASTERIZER_DESC));
    wfdesc.FillMode = D3D11_FILL_SOLID;
    wfdesc.CullMode = D3D11_CULL_NONE;
    m_deviceResources->GetD3DDevice()->CreateRasterizerState(&wfdesc, &rasterState);
    context->RSSetState(rasterState);

    context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

    context->IASetInputLayout(m_inputLayout.Get());

    // Attach our vertex shader.
    context->VSSetShader(
        m_vertexShader.Get(),
        nullptr,
        0
    );

    // Send the constant buffer to the graphics device.
    context->VSSetConstantBuffers1(
        0,
        1,
        m_constantBuffer.GetAddressOf(),
        nullptr,
        nullptr
    );

    // Attach our pixel shader.
    context->PSSetShader(
        m_pixelShader.Get(),
        nullptr,
        0
    );

    // Draw the objects.
    context->DrawIndexed(
        6,
        0,
        0
    );

}

```

# Answer
The big red flags I see after a quick look over the code you posted are

* You're using `dynamic_cast` inside your `Render` function; `dynamic_cast` has a runtime overhead and is often "smells" of a design problem. You should look at re-engineering the need for this cast. It seems to me that you can just pass `SpriteRenderDescription` in here, since `SpriteRenderer` can't render anything *else* anyhow. If `SpriteRenderer::Render` is taking the base type because it's part of some virtual interface, consider de-virtualizing that interface (I don't have enough context for your code to suggest how, unfortunately).
* You're updating the constant buffer for the sprite for every render of what appears to be every individual sprite. It also looks like you maybe have one vertex/index buffer (et cetera) per sprite. This generates a lot of overhead, whereas instead you could probably implement some kind of batching system where *multiple* sprites are contained in a single constant/vertex/index buffer (and thus a single draw call). This would reduce that overhead. Similar with the management of textures and input layout states for shaders, et cetera.
* You're doing calling `CreateRasterizerState` every time you render an individual sprite. You should only create these states once, at startup, and reference them as-needed during rendering (especially since they are exactly the same for every sprite). The runtime should de-duplicate the underlying state objects, but there's still overhead in that calculation that you can simply avoid by making the state object once.

I'd venture to guess that batching as much as you can is what's going to solve most of your performance woes. If you can only tackle one thing from the list above, I'd tackle that.
> 4 votes

# Answer
I wonder if **your bottleneck is the number of draw calls**, and not the number and size of sprites being drawn.

At some point I learned a heuristic that says you can execute about 3000 draw calls per frame to maintain a frame rate of 30 FPS. This limitation exists because of the *CPU overhead* imposed by DirectX and the GPU driver. In other words, even though you're only drawing a single tiny sprite per draw call, your frame rate will decline rapidly because of the overhead of setting up individual vertex buffers, index buffers, constant buffers, raster states, etc. Note that because this is a limitation in the GPU *driver* on the *CPU*, you will experience declining FPS despite having a very powerful GPU. On the other hand, it still looks like you're only calling `DrawIndexed` about 20x/frame, which leaves plenty of room for more. But I'm accustomed to being overjoyed at anything in excess of 60FPS, so I don't pay much attention to the bottlenecks in the 500FPS-3000FPS range.

If you are in fact limited by draw calls, you can fix it by rendering multiple sprites in a single draw call instead of many calls to `DrawIndexed` . (Perhaps SpriteBatch works this way, as @ChuckWalborn suggested, or try using instancing.) Another more invasive way to avoid draw call overhead is to use a low-overhead graphics API like Vulkan, Mantle, or DX 12's low level API.

The most obvious limitation when drawing a bunch of sprites is that you're limited by texture bandwidth on the GPU, but this seems implausible in your case given that you're drawing a small number of a single small sprite. Nevertheless, you can easily test for texture bandwidth bottleneck by cranking up the MIP bias on your GPU, which will force the GPU to use the highest (blurriest) MIP for all your textures, meaning it's only going to read a single texel for each texture.
> 0 votes

---
Tags: rendering, directx11, frame-rate
---


# Question
Title: BabylonJS strange behaviour when moving along a diagonal plane
so I'm trying to create a MOBA style game, this involves point and click movement.

I'm at the point now where i'm messing about with movement:

https://playground.babylonjs.com/#6R8BFY#11

The problem I'm having is that if I click on the ground (so that the mesh moves towards it). If its not perfectly diagonal or straight, then the x axis or the z axis is reached first.

It kind of goes diagonally for a bit before going straight for the rest of the route.

The code is really simple, And my feeling is the movement logic needs improving. I'm essentially applying a force of 1 or -1 depending on where the mesh is currently until it reaches its point as seen below:

```
/**
* The movement function,
*/
var applyImpulse = function(mesh, destination) {
   var position = mesh.getAbsolutePosition();
   var impulseX = 0;
   var impulseZ = 0;
   if(position.x > destination.x)
   {
     impulseX = -2;
   }
   else
  {
    impulseX = 2;
  }

  if(position.z > destination.z)
  {
     impulseZ = -2;
  }
  else
  {
    impulseZ = 2;
  }
  mesh.lookAt(destination);
  mesh.physicsImpostor.setLinearVelocity(new BABYLON.Vector3(impulseX,0, impulseZ));
}

```

Using physics means I am pushing it rather than setting, but I bet it would have the same problems even without applying force.

Is there a better way to do this. Like using the ray or something? It kinda sucks.

# Answer
> 0 votes
You just need the direction between the two, which can be calculated by subtracting the two Vector3's from each other: `var difference = destination.subtract(position)` Here is an updated PG: https://playground.babylonjs.com/#6R8BFY#14

---
Tags: javascript, babylonjs
---


# Question
Title: "RENDER WARNING: there is no texture bound to the unit 0" When not Rendering Texture
I have a webgl program that sometimes renders textures, but mostly renders triangles or lines. When I am not rendering a texture, webgl gives the warning, "`RENDER WARNING: there is no texture bound to the unit 0`". Here is some code from my rendering loop:

```
if (thing.hasOwnProperty('texCoords')) {
    gl.uniform1i(shaderProgram.useTexture, true);
    gl.bindBuffer(gl.ARRAY_BUFFER, thing.texCoords);
    gl.activeTexture(gl.TEXTURE0);
    gl.bindTexture(gl.TEXTURE_2D, thing.texture);
    gl.uniform1i(shaderProgram.tex_uniform, 0);
    gl.enableVertexAttribArray(shaderProgram.vertexPositionTex);
    gl.vertexAttribPointer(shaderProgram.vertexPositionTex, 2, gl.FLOAT, false, 0, 0);
} else {
    gl.uniform1i(shaderProgram.useTexture, false);
    gl.disableVertexAttribArray(shaderProgram.vertexPositionTex);
}

```

If a `thing` doesn't render a texture, there is code to set a flag in my shaders not to consult the `sampler2d` for texture values and instead just draw polygons.

I suppose "`there is no texture bound to the unit 0`" is correct: there isn't a texture bound since the last call to `drawArrays`, but why would that issue a warning when I don't try to access `TEXTURE0`?

# Answer
It doesn't matter if it only accesses the texture when `useTexture` is true. What matters is the shader uses a texture at all.

So keep a texture bound or follow best practices and either

(a) use two shaders, one that uses a texture and one that does not

or

(b) multiply the texture by the color, eg.

```
gl_FragColor = uniformColor * textureColor;

```

and when you don't want to use one or the other set it it white. If you don't want to use a texture then bind a 1 pixel white texture. If you don't want to use the color set it to white.

```
const vs = `
attribute vec4 position;
void main() {
  gl_Position = position;
  gl_PointSize = 80.0;
}
`;

const fs = `
precision mediump float;
uniform sampler2D tex;
uniform vec4 u_color;
void main() {
  vec4 t_color = texture2D(tex, gl_PointCoord.xy);
  gl_FragColor = u_color * t_color;
}
`;

const gl = document.querySelector('canvas').getContext('webgl');
const prg = twgl.createProgram(gl, [vs, fs]);

const positionLoc = gl.getAttribLocation(prg, "position");
const colorLoc = gl.getUniformLocation(prg, "u_color");
// don't need tex location because only 1 texture and uniform defaults
// to 0

const tex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, tex);
const pixels = new Uint8Array([
  255, 128, 128, 255,
  128, 255, 128, 255,
  128, 128, 255, 255,
  255, 128, 255, 255,
]);
gl.texImage2D(
    gl.TEXTURE_2D, 0, gl.RGBA, 2, 2, 0,
    gl.RGBA, gl.UNSIGNED_BYTE, pixels);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

const whiteTexture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, whiteTexture);
gl.texImage2D(
    gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0,
    gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 255, 255, 255]));

gl.useProgram(prg);

// draw with color
gl.bindTexture(gl.TEXTURE_2D, whiteTexture);
gl.uniform4fv(colorLoc, [1, 0, 0, 1]);
gl.vertexAttrib2f(positionLoc, -2 / 3, 0);
gl.drawArrays(gl.POINTS, 0, 1);

// draw with texture
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.uniform4fv(colorLoc, [1, 1, 1, 1]);
gl.vertexAttrib2f(positionLoc, 0, 0);
gl.drawArrays(gl.POINTS, 0, 1);

// draw with both
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.uniform4fv(colorLoc, [1, .5, .5, 1]);
gl.vertexAttrib2f(positionLoc, 2 / 3, 0);
gl.drawArrays(gl.POINTS, 0, 1);
```

```
<script src="https://twgljs.org/dist/4.x/twgl.min.js"></script>
<canvas></canvas>
```
> 2 votes

---
Tags: textures, javascript, rendering, webgl
---


# Question
Title: draw concave polygon from set of edge points
I'm having troubles trying to rearrange a set of points where each point is part of the edge of a concave polygone. My set of points is not sorted in any order, they are just randomly put in an array. See the example right below :

My goal is to rearrange these points to be able to build a polygon correctly where the next index in the array is the next point to draw :

I don't know how to do it fast, sometime arrays are made of 200 points, and I have like 20 of these arrays (I would use this to draw islands)

Thank you in advance.

# Answer
> 1 votes
Maybe sort them on angle of vector from average to point?

In pseudo code:

```
MID = AVERAGE(PTS)
ANGLES = []
FOR EACH PT:
    V = PT - MID
    ANG = ATAN2F( PT.Y, PT.X )
    ANGLES.APPEND( (ANG, PT ) )
SORT( ANGLES )
FOR ANG,PT IN ANGLES:
   OUTPUT(PT)

```

---
Tags: c++, mathematics
---


# Question
Title: Unity - Calculating a rotation based on game time
I have a simple script to make an object spin:

**Spin Speed** is the speed to rotate the object on each axis (preferably in degrees per second). **Local** is whether the rotation should be done based on world axes or object axes. **Starting Rotation** is the initial rotation of the object.

Normally I would use Transform.Rotate to do the rotation, but in this case I have to make the rotation a function of time, so you can pass in any time value and it will return what the rotation should be at that time.

Here is an example (this doesn't work properly for either world or object axis rotation):

```
private Quaternion getRotation(float time)
{
    return Quaternion.Euler(InitialRotation + SpinSpeed * time);
}

```

I just need some help figuring out the math behind calculating rotations for both world and object axes. I think that matrices can be used but I honestly don't remember anything about how to use them.

Here's an example of using world axes with a SpinSpeed of 180 on the y axis and an initial rotation of 45 on the x axis: https://i.gyazo.com/d7f41b6a88425b5d8b8237cd7ac40878.gif

An example of using local axes with the same parameters as above: https://i.gyazo.com/d453b3dd239c9f77b86ce372c499d068.gif

# Answer
This is a bit of a hack solution I came up with:

```
//Save rotation at the start of the frame
Quaternion rot = transform.rotation;
//Set rotation to InitialRotation
transform.rotation = Quaternion.Euler(InitialRotation);
//Perform rotation
transform.Rotate(SpinSpeed * time, Local ? Space.Self : Space.World);
//Save the calculated rotation
Quaternion targetRot = transform.rotation;
//Reset rotation to what it was at the start of the frame
transform.rotation = rot;
//Set rigidbody rotation to target
rigidbody.MoveRotation(targetRot);

```

I won't close this just yet in case someone can answer with a less-hacky way of doing this. Otherwise I will close this question if I don't get any answers.
> 0 votes

---
Tags: unity, c#, mathematics, rotation
---


title: Provide an SDK for Unity

text:
# Question
Title: Provide an SDK for Unity
I downloaded the SDK from over here. Namely, I downloaded and unpacked `sdk-tools-windows-3859397.zip`.

What should I do next with the files, to which one of them should I provide a path in Unity in order to build an app for `Android`?

# Answer
> 0 votes
From https://docs.unity3d.com/Manual/android-sdksetup.html

> # 4. Configure the Android SDK path in Unity
>
> The first time you create a Project for Android (or if Unity later fails to locate the SDK), Unity asks you to locate the folder in which you installed the Android SDK.
>
> If you installed the SDK using the sdkmanager, you can find the folder in \platforms\\.
>
> Example:
>
> `c:\<android tools install location>\platforms\android–27`
>
> If you installed the SDK when you installed Android Studio, you can find the location in the Android Studio SDK Manager. To open the SDK Manager from Android Studio, click Tools \> Android \> SDK Manager or click SDK Manager in the toolbar.

# Answer
> 0 votes
In **Unity 2018.3** I had to set the root folder:

```
C:\<android tools install location>

```

and NOT the platform one

```
C:\<android tools install location>\platforms\android–27

```

---
Tags: unity, android
---


# Question
Title: Pathfinding with non-deterministic transitions between nodes
Consider a map not unlike a board game, where some of the moves are made non-deterministic. For example, moving onto certain cells will require you to roll a dice to determine where you should move next. The map, I would like to navigate agents through have similar characteristics:

* Some of the map nodes have deterministic connections while others do not (e.g. rolls a dice)
* The move random events can have more than two outcomes, in fact most of them have many (e.g. move to random node in certain radius)
* there are various distances (cost) between nodes

What algorithm(s) can be used to find on average the shortest path through such map for an agent? Though not required a nice bonus would be configurable risky-ness or confidence the path will 'work'.

---

Some time after asking I realized the is a major problem with the question - *there is no path*. Because agents can stray from planned path unexpectidly, rather than ordered sequence of nodes the algorithm should find goal direction/distance from *every* node, much like reachability/distance output from Dijkstra's algmorithm.

# Answer
> 2 votes
You can use "expected values" like Continuum Crowds does it.

From the Treuille et al paper:

*Expected periodic field changes. A similar issue arises when the field deterministically changes over time. Consider an environ- ment with two exit doors rapidly opening and closing. An exiting crowd would continuously switch direction back and forth towards the currently open door. Similarly, when a traffic light turns red the speed field must be temporarily set to zero to prevent crossing. Individuals in our basic model would naively conclude that cross- ing is impossible, and pick another path. Here we offer a different solution. When computing the potential, we replace the actual in- verse speed with the expected inverse speed computed over a longer time period. For traffic lights, the expected inverse speed is com- puted from the percentage of time the traffic light is green during a period. Similar computations are performed for other periodic changes (e.g. opening doors). By the linearity of expectations, the optimal path cost given in equation (2) can then be interpreted as the minimizing the expected time to the goal.*

**The short of it**: if a traffic light is 3 times more likely to be red than green, then the cost of crossing that road is the inverse of the expected speed, which is 0.25 * S + 0.75 * 0, with S being regular walking speed.

Here is a video of that mechanism, in action:

# Answer
> 2 votes
One approach is to use the Monte Carlo method. Monte Carlo methods are mainly used in three problem classes: optimization, numerical integration, and generating draws from a probability distribution. This problem falls into the intersection of the first & third class, so Monte Carlo seems like a reasonable thing to try.

The basic idea behind the Monte Carlo method is to simulate a number of random attempts, accumulate information from the results & then use that data to make a decision. So for this particular problem, you would:

* simulate multiple attempts to get from one place to another
* for each attempt keep track of the number of moves (or other resources) required
* when done simulating attempts, use things like the min, max, average, standard deviation to make a decision

As a perk, you can use the collected stats in a variety of ways to simulate different flavors of AI. A risk averse AI might seek to avoid the worst case scenarios. An optimistic AI might favor greedy, unlikely moves that have a big pay off, but are prone to failure.

The number of attempts influences the strength of the conclusions, but is subject to diminishing returns (for an illustration of this, look up a simple coding experiment for using Monte Carlo to estimate Pi). As such it may require some tuning to make sure your not wasting a lot of time while only improving results by a fraction of a percent. In terms of implementation, the number of simulated attempts can be set by time, trial count or some combination of the two; use whichever is a good fit for your game / framework.

Also, for this problem, you might need to add in a simulation 'basement'. That is to say, it seems like it might be possible for a very unlucky attempt to end up cycling infinitely (the pawn always gets moved back to the start). To guard against that, I would add some logic that automatically bins any simulated trial that takes more than X moves. You might also want to keep track of where such cases end up - looking at those groupings might indicate that some map feature is acting like a probabilistic gravity well for luck & skewing your play.

The strengths of the Monte Carlo method are:

* relatively easy to code
* they often run quickly
* if the AI gets some extra processing cycles, you can improve your results
* often times you can change the underlying game play (say by adding teleporters or some other feature) and won't need to make many changes to the simulation
* you can simulate weaker AI by reducing the number of simulations
* they are used in both real world problems & games and thus have a fair body of research to all back on

The weaknesses are:

* determining the cutoffs can take a fair bit of tuning
* the don't guarantee optimal solutions
* if your problem size scales badly, they might not be practical

Some additional notes: if possible, I would first try to calculate a best path that completely avoids the non-deterministic nodes. If you can do so, this sets a lower bound. If a given simulation takes more distance (or time or what ever you're trying to minimize) than the purely non-deterministic path, you already know that there are better options.

---
Tags: algorithm, path-finding, probability
---