# Question
Title: Unity SceneView Positionning object with mouse position in Editor script
I would like to create an editor tool who can change the position of an object in the scene view into other object in the world, based on mouse position, like in the picture bellow (the red pyramid is my object to positionnate/rotate)

I would like to do a raycast from the scene view camera to the mouse position (or something like that), to get the gameObject over the mouse, and then get the position of the verticle / normal for position and rotation of my gameObject

For now, I have tryed some code who didn't work, I have my object named "preview", and inside the methode OnSceneGUI() in a editor script i have managed to move my preview object, but now I have to know where to put it... Thanks !

EDIT: here some of my try:

```
Transform previewPoint; //here my transform

void OnSceneGUI()
{
   PointCreator();
}

 private void PointCreator()
  {
  //test 1
      Camera sceneCam = SceneView.GetAllSceneCameras()[0];
      Vector3 spawnPos = sceneCam.ViewportToWorldPoint(Event.current.mousePosition);
      previewPoint.position = spawnPos;

      //test 2
      Vector3 mousePosition = Event.current.mousePosition;
      mousePosition.y = SceneView.currentDrawingSceneView.camera.pixelHeight - mousePosition.y;
      mousePosition = SceneView.currentDrawingSceneView.camera.ScreenToWorldPoint(mousePosition);
      mousePosition.y = -mousePosition.y;

      previewPoint.position = mousePosition;

  }
```

# Answer
> 2 votes
Ok, After a lot of research, I finnalt got this to work:

```
Transform objectPreview;  //the transform to move
Transform objectTouched = null; //the reference of the last object hit

Ray worldRay = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);

RaycastHit hitInfo;

if (Physics.Raycast(worldRay, out hitInfo, Mathf.Infinity))
{
    if (hitInfo.collider.gameObject != null)
    {
        objectTouched = hitInfo.collider.gameObject;
        objectPreview.position = hitInfo.point;
        objectPreview.rotation = hitInfo.normal;
    }
}
```

---
Tags: unity, mouse, scene, editors
---


# Question
Title: Why doesn't this weaponpickup script work properly?
I'm making an FPS game. My guns are disabled at the start.

When I use this script to pick up and hold one weapon at a time, requiring that you click J to drop it, it simply doesnt work!

There are two guns using the same pickup script with different prefabs, and all the prefabs but "MyGun" and "playertransform" are the same.

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

public class weaponpickup : MonoBehaviour {

    public GameObject MyGun;
    public GameObject WeaponOnGround;
    public GameObject DroppedWeapon;
    public Transform playertransform;

    // Use this for initialization
    void Start () {
        MyGun.SetActive(false);
    }

    // Update is called once per frame
    void Update () {
        if(Input.GetKeyDown(KeyCode.J))
        {
            Instantiate(DroppedWeapon, playertransform.position, playertransform.rotation);
            MyGun.SetActive(false);

        }
    }
    public void OnTriggerEnter(Collider other)
    {
        if(other.gameObject.tag == "Player" && MyGun.activeInHierarchy == false)
        {
            MyGun.SetActive(true);
            WeaponOnGround.SetActive(false);
        }
    }
}

```

# Answer
> 1 votes
I can actually see a number of issues with that code at first glance. First comes the obvious question: Are all the weapons already on your character when the game starts or do you collect them from the world?

Why I ask is because:

* you instantiate DroppedWeapon exactly at the player position and then you have a trigger setup to let the player pickup whatever it collides with (i.e. as soon as you instantiate the dropped weapon it will get picked up the very next frame) however, you don't actually add any logic to get rid of the gun you are holding or collecting the new weapon, you just disable MyGun while still holding on to it (unless that is handled elsewhere)
* as soon as you collide with a weapon you immediately enable MyGun, not the actual weapon you just collided with
* there doesn't seem to be any actual swapping of dynamic weapons, rather it looks like you are just spawning/enabled/disabling stuff you have already placed on the component

Unless there is more code that does stuff you are not showing us, here is what I see when looking at the code:

1. Start and disable MyGun (no testing if you HAVE anything set there so I assume you are sure MyGun exists. a parent node maybe?)
2. If you press J then you Instantiate DroppedWeapon (again, not seeing you verifying that there is actually anything TO spawn, just assuming it is there. I am assuming you assigned it in the inspector then?). Right now you are Instantiating DroppedWeapon no matter what you are holding (if anything at all)
3. Place DroppedWeapon exactly at the player's position, thus triggering the player to pick up DroppedWeapon immediately
4. The pickup function simply enables the previous MyGun and disables the DroppedWeapon without actually picking up DroppedWeapon. Thus dropping the weapon simply makes your gun active again while creating and leaving a new game object disabled in the world
5. If you collide with an active weapon in the world it will do nothing with it. All you are doing is setting MyGun to active if it's disabled and then disabling the one in the world. If MyGun is already active when you collide with this weapon you simply don't do anything and continue using MyGun

As you can see, there is quite a few things that need to be fixed (unless it is being handled elsewhere) but the main problem here is that you are spawning a new pickup inside your player's collider and then have a trigger setup to simply enable whatever gun you previously had while hiding the one you just collided with.

A good start would be this (assuming MyGun is a parent object):

```
float RandOff() {
    float result = Random.Range(0.5f,2f);
    if (Random.Range(0f, 1f) > 0.5f) result *= -1;
    return result;
}

void DropGun() {
    if (MyGun.transform.ChildCount == 0) return;
    Vector3 newLocation = new Vector3(RandOff(), 0, Randoff());
    GameObject gun = MyGun.transform.GetChild(0).gameObject;
    Instantiate(gun, playerTransform.position.TransformPoint( newLocation, Quaternion.Identiity);
    Destroy(gun);
}

void OnTriggerEnter(Collider other) {
    if (MyGun.transform.ChildCount > 0) return;
    //do whatever other tests to see if this is a weapon to pickup then...
    other.gameObject.SetParent(MyGun);
    other.transform.localPosition = Vector3.zero;
    other.transform.localRotation = Quaternion.identity;
}

```

---
Tags: unity, c#, first-person-shooter
---


# Question
Title: Which Pathfinding Algorithm is Best For My Case?
I'm creating a top-down space shooter game where there is no real "map" per say since there is no real terrain, but there are obstacles in the form of asteroids, other ships and a few circular structures, but nothing like a maze where an AI would need to find a path to get out of -more like things an AI doesn't want to collide with.

I want my AI to navigate around these objects. However, as you may have guessed, asteroids and ships aren't static, they have a scale and a velocity and can be destroyed. What's the best algorithm/method to use for navigating around moving obstacles in open space?

For context, my AI ships have a waypoint at all times that determines where they want to move to. Basically what I'm asking for is a way to ensure that if an asteroid or other ship were to fly in front of my ships as they fly toward their waypoint that the ship would make some effort to avoid it. Currently they just keep ramming into them and dying :(

# Answer
You can't reliably create a full path that you can actually follow through completely to your destination since the ships interaction with the world is very unpredictable (physics-simulation is costly to predict and player input mixes everything up anyway).

---

Path-finding is good to get an route that is valid at that point in time but it can be unstable, something changes and BOOM your path goes the other way around, your ship has to stop and/or turn.

If you rely on path-finding you will need to periodically regenerate the path since in your case a previously valid path isn't guaranteed to stay valid for long when everything moves around. This isn't anything new, other games have to do this too but asteroids is a special case since the whole environment changes continuously.

You need something more dynamic and faster, that's where steering behaviors, like obstacle avoidance, are useful. You can use them stand-alone or in conjunction with path-finding to smooth out the generated path.

---

Let's say you want to implement obstacle avoidance, first you need to detect and select the obstacles you want to navigate around.

You need to check for them in the flight path of the ship, by basically pre-calculating the future positions of the asteroids and your ship and doing a collision check on all of these extrapolated positions. This is easy for asteroids that simply move in one direction with constant speed, for the others not so much, but an approximation is often enough.

Now when you have predicted a collision you can change your direction accordingly, there are lot's of algorithms out there that you can borrow from, it's up to you.

---

**I recommend you to read up on obstacle avoidance and keep path-finding for later. You will be able to handle many situations by just moving towards your goal and avoiding obstacles on the way there.**

Moving around/avoiding obstacles

---

If you want to use for example A\* for pathfinding you could take into account the clearance of the space you want to move through to select paths with less chance of a collision.

Clearance-based Pathfinding

Depending on your requirements vanilla A\* might be more than enough.
> 1 votes

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


# Question
Title: Deproject Screen To World Coordinates (Unreal Engine 4.15)
I am working on a small game in Unreal Engine 4.15 using blueprints only and encountered a behaviour I don't understand.

The game is based on the Top Down Example. As I'd like to teleport an actor to a **world location** corresponding to a **screen location** (i.e. left edge of the viewport). I use "*Deproject Screen To World*". Giving `screen X = 0` and `screen Y = 0` as input to this node, outputs world coordinates close to the bottom center of the viewport. In order to get a test actor to move to outputted world coordinates close to the left edge of the viewport, input screen coordinates need to unexpectedly high (around -20000.00 for both x and y). This occurs strange to me, as the viewport is much smaller (around 1400x740 in editor preview).

I was hoping to use something like `-(viewport width/2)` for x screen coord (in case the x origin is centered.

Where is the origin for screen coordinates?
What unit are they measured in?

*Note: The location on screen is not set from mouse position, so i can not use "Get Hit Result Under Cursor".*

# Answer
> 0 votes
Origin screen coord in Unreal 4.21 are x=0.5, y=0.5. The coords you are giving (0,0) are the bottom left of the screen. The scale is based on a 1:1 scale, so that all screens regardless of number of pixels, shape, or size can display the crosshair (or other output) in the same "relative" location. So if you wanted a health bar at the bottom left of the screen you could code something like this "x=0.025, y=0.025" and it would be in the same relative bottom left corner of every screen (i.e. iPhone, PC, tablet, landscape mode, portrait mode, etc...

---
Tags: coordinates, unreal-4, projection, projection-matrix
---


title: MUD programming: socket handling

text:
# Question
Title: MUD programming: socket handling
I'd like to build a multi user dungeon in Java/C# (also open to other suggestions). Below I have listed two ways of handling connections, and would like to know which would be the recommended way?

I think a good way to build it would be something like this:

Currently, I'm working on the connection handling portion (shown in the picture on the left, heavy black rectangle). It would take care of the connection handling between multiple clients and basically shove commands received from clients (denoted by newline char) into a queue, which the game engine can then pull off of and process. If there is a reply, the game engine would shove it into another queue so the connection handler can send it back to the client.

I see two ways to work this part:

### Thread per connection

```
class Server {
    public void Listen() {
        // configure
        final int portNumber = 81;

        try {
            ServerSocket serverSocket = new ServerSocket(portNumber);

            while (true) {
                Socket socket = serverSocket.accept();
                new ProcessThread(socket).start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class ProcessThread extends Thread {
    protected Socket socket;

    public ProcessThread(Socket clientSocket) {
        this.socket = clientSocket;
    }

    public void run() {
        try {
            OutputStream os = socket.getOutputStream();
            PrintWriter pw = new PrintWriter(os, true);

            while (true) {
                BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String str = br.readLine();

                // do processing here
            }
        }
    }
}

```

Pros:

* Easier implementation

Cons:

* Thread per connection not scalable
* Multithreading = potential yuckiness

### Async socket

```
public class Server {
    // use hashmap to keep track of current input
    private HashMap<SelectionKey, StringBuilder> strings = new HashMap<>();

    public void Listen() {
        // configure
        Selector selector = Selector.open();
        ServerSocketChannel serverSocket = ServerSocketChannel.open();
        serverSocket.bind(new InetSocketAddress("localhost", 5454));
        serverSocket.configureBlocking(false);
        serverSocket.register(selector, SelectionKey.OP_ACCEPT);
        ByteBuffer buffer = ByteBuffer.allocate(256);

        while (true) {
            selector.select();
            Set<SelectionKey> selectedKeys = selector.selectedKeys();
            Iterator<SelectionKey> iter = selectedKeys.iterator();
            while (iter.hasNext()) {

                SelectionKey key = iter.next();

                if (key.isAcceptable()) {
                    // register new connection
                    register(selector, serverSocket);
                }

                if (key.isReadable()) {
                    // process input
                    // add input to hashmap, if not newline terminated
                    process(buffer, key);
                }
                iter.remove();
            }
        }
    }
}

```

Pros:

* Will definitely process in order received
* Less resource intensive (?)

Cons:

* Handling readline is more difficult

What would be the recommended way?

I'm leaning towards the thread per connection, as it seems to be slightly easier to implement. For a MUD, I would expect less than 200 simultaneous connections (50 might be a more accurate estimate), which would not be too resource intensive.

# Answer
Think about this: it's not much code to rewrite the details of the I/O handling later after you've built a lot more of the system, because this is a fairly straightforwardly separable module. But there's a choice to be made which decides which one is better to pick for the moment:

**Do you want your *game logic* to have to be thread-safe, or would you rather run it on a single thread?**

If you want single-threaded game logic, then it makes sense to use async I/O to go with it, because threads would just have to use some kind of message queue. And if you want to have multithreaded game logic then it makes sense to have a thread for each connection/session.

Now, to answer the new question for you, **you almost certainly want single-threaded game logic**. Systems which have multiple threads accessing the same objects, where those objects are not specifically and carefully designed to *be* inter-thread communication/coordination/shared-data-storage mechanisms, are very subtle and frustrating to debug when you make mistakes — and you will.

---

On the other hand, there are some advantages to be had with using a thread per connection even if your game logic is single-threaded. Not only is implementing line reading easier, but you can also more directly implement special modes, like multiline text editing or mini-games, as methods which don't return until the user exits that mode. So, given that you don't need optimum performance for your fun project, a thread per connection may be a practical way to go.

…but using the call stack like that has some caveats; for example, if the connection is dropped you need to make sure that each of those modes on the stack cleans up after itself when it sees an IO error, rather than (say) perpetually trying again to read text until it sees a newline.

Also, the more code you run on the per-connection threads, the more code has to correctly communicate with the single-threaded game logic (using some kind of message passing or `Executor`-style mechanism). If you have async IO, or your IO threads only do passing command lines to the game thread, then you don't have this problem.
> 2 votes

# Answer
I'll build on what @kevin-reid said, which is all pretty sound advice.

Single-threading is the traditional approach to game development, and even today many new games don't leverage additional cores for their heavy lifting. That is, there's a solid chance you can get away with one thread for all your heavy lifting, even for a triple-A game. Additional threads for things like I/O are small potatoes, and as @kevin-reid said you can easily separate that later if you choose.

But, since this is a learning project, learning techniques to leverage additional cores for your heavy lifting is perhaps a goal worth considering... Processors are getting wider, not faster, after all. To that end, a single game-thread which handles everything is not a great starting point, as you'll enjoy the benefit of assumptions you don't even realize you're making.

If you think that you might parallelize later on, you should consider early-on which axis you'd parallelize on... would you allow events to happen in parallel, or computations of outcomes / AI decisions? All of those are legitimate options, but each presents its own synchronization problems:

* Parallel events cannot affect the same entities at the same time; put differently, events affecting the same entities *must* be serialized.
    + You can naively achieve this with a mutex on every entity, but you'll quickly find that enforcing entity-relationship invariants forces you to either invent something akin to transactions (yuck) or choose a larger group of things than a single entity to protect. A popular term for such a group of things is an "aggregate".
* Parallel computations may still need to be sequenced.
    + For instance, in a 3D game you'd need to compute all movement before computing any collision-detection. Similarly, in a MUD you'd need to process combat and movement serially, even if combat calculations are parallelized, so that e.g. you can't be hit by a sword-blow when you're already in the next room.

The lesson you should expect to take away is that, when designing a system for parallel processing, you'll need to relax some of the assumptions you'd make in a single-threaded design. So e.g. you may choose to let AI running in a different thread to operate on a not-100%-consistent view of the world; without this relaxation you'd have to either freeze the main thread so it stops updating the game-state, or take a snapshot of the entire game-state for the AI to operate on. The exercise of identifying what can be relaxed, what can't, and where that leaves room for parallel processing is a good one that should translate well into non-hobby projects you work on.
> 0 votes

# Answer
I've already created a game server and I used netty for I/O handling. My design is use multi-thread for I/O and single thread for game logic. It looks like your image, where netty is connection handler, input/output queues I used LMAX Disruptor's ring buffer. With this design, thread-safety is not problem because game logic is handled in a single thread -\> no multi-threading bug :D
> 0 votes

---
Tags: java, mud
---


title: C++ create array of multiple types

text:
# Question
Title: C++ create array of multiple types
I tried to create an array `Entity[]` with elements `Human` and `Zomby`.

```
Entity ent[5];
ent[0].set("human");
ent[1].set("human");
ent[2].set("human");
ent[3].set("human");
ent[4].set("zomby");

```

or

```
Entity ent[5];
ent[0] = new Human();
ent[1] = new Human();
ent[2] = new Human();
ent[3] = new Zomby();
ent[4] = new Zomby();
delete[] ent;

```

They are in different classes because `Human` and `Zomby` need different ai functions. They are in the same array to compare them, like this:

```
for (int a = 0; a < entL; a++)
{
    for (int b = 0; b < entL; b++)
    {
        ent[a].ai( ent[b] ); // process ai interaction with other entities
    }
}

```

Is there a way for an array to have multiple types, or is there a better way to handle objects? Here's my example code:

```
class Entity // base class
{
public:
    float x, y;
};

class Human : public Entity // sub-class
{
public:
    void ai(Entity &n){}
};
class Zomby : public Entity // sub-class
{
public:
    void ai(Entity &n) {}
};

int main(int argc, char **argv)
{
    // create entities in one container
    const int entL = 5;
    Entity ent[entL];
    ent[0] = new Human();
    ent[1] = new Human();
    ent[2] = new Zomby();
    ent[3] = new Zomby();
    ent[4] = new Zomby();

    // inside game while-loop
    for (int a = 0; a < entL; a++)
    {
        for (int b = 0; b < entL; b++)
        {
            ent[a].ai( ent[b] );
        }
    }

    delete[] ent;

    system("PAUSE");
    return 0;
}

```

**RESOLVED**

I can make variants of functions in sub-classes like `ai` using `virtual` and `override`.

```
class Entity // base class
{
public:
    Position pos;
    virtual void ai(Position& other) { }

};

class Human : public Entity // sub-class
{
public:
    virtual void ai(Position& other) override {
        // human-specific AI code
    }
};

class Zomby : public Entity // sub-class
{
public:
    virtual void ai(Position& other) override {
        // zomby-specific AI code
    }
};

Entity* ent[5];
ent[0] = new Human (); // set sub-class elements
ent[1] = new Zomby ();
ent[2] = new Zomby ();
ent[3] = new Zomby ();
ent[4] = new Zomby ();

ent[0]->ai(ent[1]->pos); // call human.ai() passing zomby.pos

delete[]* ent;

```

Now, an array-pointer of a base-class can store elements of sub-classes.

# Answer
When you have an array of type `Entity` then you can only call methods on the entries which are declared in the class `Entity`.

If you want `Human` and `Zomby` to have different implementations for that method, then you can declare that function as `virtual` in the `Entity` class. You can then override that implementation in both sub-classes. That means when you call the method `.ai` on an `Entity` the program checks what kind of entity it is and calls the corresponding method of the corresponding class.

Another thing you might want to consider is to pass the argument by reference instead of by value. When you pass objects by value, then you are creating a copy of the object in memory, pass that copy to the function and then discard that copy when the function finishes. But when you pass objects by reference, you are passing *that object*. This has two advantages:

1. it's faster because the program doesn't need to create a copy of the object.
2. You can do changes to the object in the function which are applied to the original object.

Example:

```
class Entity // base class
{
public:
    float x, y;
    virtual void ai(Entity& other) { }

};

class Human : public Entity // sub-class
{
public:
    virtual void ai(Entity& other) override {
           // human-specific AI code
    }
};

class Zomby : public Entity // sub-class
{
public:
    virtual void ai(Entity& other) override {
           // zomby-specific AI code
    }
};

```
> 2 votes

# Answer
In this case you want to use virtual functions on the base class like so:

```
class Entity // base class
{
  virtual void ai(Entity n){}
}

```

Even though this is just example code, I can see that it might cause problems because you are passing by value instead of by reference.
> 1 votes

---
Tags: c++, game-loop, objects
---


# Question
Title: Handmade Terrain vs. Terrain Engine in Unity?
I'm planning a game right now, to be made in Unity, and I'm trying to decide how I'll approach the basic level construction. Essentially, my game takes place on an island in an infinite ocean, very similar to Wuhu Island:

My question concerns all the stuff heightmaps can't handle. To use Wuhu Island as an example, note the lighthouse cliff, and the nearby similarly jutting-out cliff. The volcano itself is also empty, and there are some tunnels through it on the other side.

I was thinking I would just model the entire island myself in Cinema 4D, but as I read more about the terrain system, it seems Unity has special optimized rendering systems in place for terrain objects. Would I be shooting myself in the foot performance-wise if I just built my island entirely by hand? This will be for mobile, so the little stuff might well count. Am I even approaching this question correctly - if not, how would you best go about creating (something very close to) Wuhu Island as a level in Unity? Is there any reason for me to not do it as one mesh? I have effectively zero experience with 3D game dev - only rendered 3D video/stills for other applications, so this is a learning process.

# Answer
> 2 votes
Polybrush \- Polybrush is a free tool, that allows unique terrain sculpting. It may have a feature to blend between terrains. Or you can use this as a main terrain solution.

There are many ways to optimize the terrain. One of them is splitting the terrain in chunks, loading and unloading them on fly if you don't want loading screens. Divide And Conquer.

In this case I would suggest a combination of unity terrain and custom modeled terrain parts. Most of the time where height map can handle the layout use Unity terrain and for parts where you require more complex layout - use custom terrain parts. This causes a lot of work, like how to make both terrains fit. And additional advanced scripting would be required.

Easiest solution if you `know` how to program would be to create a custom terrain, split it in chunks, load and unload them. Implement those unity terrain mentioned optimizations yourself.

Easiest solution if you `don't know` how to program would be to buy some plugin that does what you need. Or use built in terrain removing the complex parts of terrain in game design. If it's not possible then having multiple scenes with different parts of terrain parts could solve this, but you would have to load and unload scenes, which is more or less an easy task that anyone can handle when they put enough effort.

While Unity internal terrain is lacking some features the only way is to create your own terrain solution with features you need if Unity terrain doesn't allow to access and change its internal behaviour. \[Unity now has a dedicated Terrain development team that can add necessary features in the future, but if the main solution for terrain will be heightmap then it would prove difficult to have caves or holes in the terrain (I would appreciate any comments that address issues like caves, holes in Unity terrain, and if it's possible to do now)\]

# Answer
> 1 votes
Creating your whole game world as one huge model is likely not a good idea.

First, it might be too slow. The engine can't use LOD groups to simplify far away objects and can't use occlusion culling to not render those parts which aren't visible at the time.

Second, your world is just one asset. So you can't have more than one 3d artist work on it at the same time.

The Unity terrain out-of-the-box is heightmap-based, which means it can't handle overhangs or caves. Possible workarounds could be:

* Minimize the damage by modeling only the terrain itself as one big 3d model, but use separate models for all the objects on the map.
* Create those sections of the map which require overhangs as separate models and then add those as separate game objects to the scene which clip out of the terrain. But if you do that you might run into some issues with the seams between objects and terrain. They might cause visible rendering artifacts or unintended physics gliches.
* Use one of the 3rd party assets from the store which promises to add terrain with overhang capability. A quick search finds a couple of paid assets like Digger, Ultimate Terrains or Voxeland which look rather promising. There is also a free asset endorsed by Unity Technologies called Polybrush which at the time of writing is still in beta status. Unfortunately I haven't worked with any of those myself, so I can't tell how well they work.

I am looking forward to exploring your island.

---
Tags: unity, optimization, terrain, 3d-meshes, 3d-modeling
---


# Question
Title: LibGDX: How to make an object falls with random speed
I'm trying to make an object (ball) fall into position Y and when the ball collides with the base. The sprite changes and along with the change I want the speed of the fall to change according to the sprite

```
public void create () {
    circleBall = new Circle();
    rectangleBase = new Rectangle();
    ball = new Texture("ball.png");
}

public void render () {
    spriteBatch.begin();
    fallBall();
    rand();
    spriteBatch.end();
}

void fallBall(){
    fallSpeed++;
    if(posYBall > 0){
        posYBall -= fallSpeed * 2 / 2;
    }
}

void rand(){
    int rand1 = random.nextInt(15 - 1) + 1;
    int rand2 = random.nextInt(10 - 1) + 1;
    int rand3 = random.nextInt((55 - 35) + 1) + 35;
    collisionBallBase(rand1, rand2, rand3);
}

void collisionBallBase(int rand1, int rand2, int rand3){
    if(Intersector.overlaps(circleBall, rectangleBase)){
        if(rand1 <= 5){
            ball = new Texture("ball.png");
        }else if(rand1 <= 10){
            ball = new Texture("ballb.png");
        }else{
            ball = new Texture("ballc.png");
        }

        if(rand2 >= 5){
            ballDirection = 4;
        }else{
            ballDirection = -4;
        }
        fallSpeed = -rand3;
    }
}

```

# Answer
Instead of calling the `rand` function in a render, you can call the function when your action happened.

If you want to have a ball with a random speed on creation time do it on the constructor.

If you want the ball to have a random speeds every time for each activity such a collision, set it in the 'on event' function.

If you really want to call a function in a render function then try something like this

```
boolean collided = false

somefunctionto
if(collided){
   set_random_speed_to_a_ball(..);
   collided = false;
}

render(){
   if(collisionhappend){
   collided = true;
}

```
> 1 votes

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


# Question
Title: How can I update the size of a button after adding it to a table?
I have a table that acts as the HUD for my game. It features a bar (as a text button) and label showing how much shields are left. So I initially add the shield bar to the table, with the cell set at a certain size to correspond to maximum width of the shield bar when shields are at 100%.

I then want to be able to change the width of the shield bar to show shields dropping but my code doesn't seem work. Is anyone able to tell me how I change the size of a button after having added it to a table and having added it to the stage?

```
// Add shield bar and label to table
table.add(enemyShieldBar).align(Align.right).colspan(2).expandX();
table.add(enemyshieldLabel);
table.add(fillerLabel).row();

// Attempt to update the label and button size
enemyshieldLabel.setText("new text ");
enemyShieldBar.setSize(5,5);

```

# Answer
you can use this, just use width and height methods.

```
table.add(enemyshieldLabel).width(300).height(500).align(Ali.......

```
> -3 votes

---
Tags: libgdx
---


# Question
Title: How to retrive the original position of an axis to Vector3?
```
float x = Random.Range(-1f , 1f) * magnitude;
        float y = Random.Range(-1f , 1f) * magnitude;

        transform.localPosition = new Vector3(x, y, originalPos.z);

```

Here I'm trying to retrive the original position of z(without any changes) to the vector3. But in visual studio 2017 is showing an error like this

How to resolve this?

# Answer
It looks like you've failed to define a variable called `originalPos` somewhere that the compiler can find it.

You could write something like this:

```
 // Define the variable we want to use, and copy the old values into it.
 Vector3 originalPos = transform.localPosition;

 float x = Random.Range(-1f , 1f) * magnitude;
 float y = Random.Range(-1f , 1f) * magnitude;

 transform.localPosition = new Vector3(x, y, originalPos.z);

```

Or, even more concisely:

```
 // Create a copy of the local position that we can modify.
 Vector3 modifiedPos = transform.localPosition;

 // Store our changes directly into this local variable.
 modifiedPos.x = Random.Range(-1f , 1f) * magnitude;
 modifiedPos.y = Random.Range(-1f , 1f) * magnitude;
 // Since we didn't modify z, it keeps the old value we copied from local position.

 // Copy our local variable to the transform's local position.
 transform.localPosition = modifiedPos;

```
> 1 votes

---
Tags: unity
---


# Question
Title: What happens to my already-published game when I upgrade to Unity Pro?
I made a game with Unity's Standard liscense, and published it (version 1.0) on Google Play. If I buy a Unity Pro license can I publish an update to my game (version 2.0) with it on Google Play, or must I create a new game on Google Play for the updated version?

# Answer
> 3 votes
Building with Pro Unity as opposed to Standard will not change how you submit the application to Google. It will be the same app with the same ID. Make sure you keep your signing password.

---
Tags: unity
---


# Question
Title: Having the player face themselves after the mid-game
I am writing a game, in the vein of a jRPG, in which you begin playing as the main villain. You don't know it. You think you are playing the hero and the more successful you are and the stronger you make them the harder they will be to defeat at the very end of the game.

My main concern is anyone who puts in a significant effort early game could feel punished for it. It is also troublesome if the player finds the challenge of the final boss insurmountable because of actions from very early in the game. Is there a way I can signal early on in the second act that if they over-powered the villain it may haunt them? And there is also the possibility the twist will get out and people will just game it from the beginning. It is my intent to get some replay value out of it by having people do multiple runs based on different villain playthroughs. But is it a distraction if everyone learns the twist. Or conversely is it better if I reveal it myself in-game so everyone knows what they are working at from the start?

**How do I make my potentially disengaging design hold up without turning people away?**

# Answer
> 82 votes
Having the player play against their own earlier accomplishments actually seems like a viable approach to implement dynamic difficulty. The better the player, the more challenging the game will become.

But when the player becomes aware of this mechanic (and you have to assume they will find out about this before playing - because it's an unique mechanic and you should use it to promote your game), then they will likely intentionally play bad in the first act of the game so they can exploit their weakness in the second act. This might in fact be an interesting meta-mechanic which could be a challenge in itself: How do you successfully complete the first act while staying as weak as possible? This also can become a neat self-balancing difficulty mechanic. The more skillful the player, the more they can challenge themselves by trying to complete the first act with the least mechanical strength possible.

You might encourage the player to try both approaches for the game by using achievements. Give them an achievement for beating their 1st act character in an extremely short amount of time (which can in practice only be accomplished with the "1st act low level run" strategy) and another one for maxing out their 1st act character and then beating it at all.

But I am seeing a few design pitfalls here you need to be careful to avoid:

1. Is a first act low-level run actually interesting to play or just annoying?
2. Does the 2nd act become too easy when the player plays this way?
3. Does the 2nd act become too hard when the player does not play this way?

How to solve problem 1 heavily depends on your game mechanics, how much they allow the player to accomplish with sheer skill but lacking mechanical strength and how satisfying this way of playing feels. Unfortunately the question does not provide enough information about the core game mechanics of the game to provide any more concrete advise in this regard.

Problems 2 and 3 can be mitigated by making sure that the performance in act 1 does not completely dominate the difficulty in the 2nd act. Make sure that the player's success in act 1 is *one* aspect of the difficulty of the 2nd act, but that there are also many other obstacles for the player which are completely independent from their 1st act performance.

To solve problem 3, you should make it possible for the player to gain more mechanical strength in act 2 than they could ever achieve in act 1, so everyone becomes able to out-grind their act 1 character, no matter how hard they tried. Another option could be to provide an alternative story path where the battle between the act 1 and the act 2 character doesn't happen at all. This path might only become available when the act 1 character exceeds a certain power level. This might in fact be a good opportunity for the "golden ending" where the two player-characters reconcile their differences in a peaceful way and then they face the True Final Boss together.

I am looking forward to beating myself up in your game.

# Answer
> 19 votes
**1. Reward the player throughout the game** for building (and later fighting) a strong villain. Depending on the genre, playstyle and target demographic, that might be "just" a higher score or mechanical rewards like more experience points/better loot etc. to smooth out the difficulty curve a little.

Typically, games that allow you to (knowingly) affect the difficulty will also reward taking the harder path in some way. In your case, to avoid frustration, you should make sure that at least some of those rewards are attainable during or even before the second half - ideally with a mechanic that you introduce before the big reveal and switch, which would also help tie the two halves of the game together a bit better.

**2. Consider focusing more on "side-grades"** for your villain's progress. If you find that doing really well in the early game makes the boss fight too hard, change some of the best rewards to something rare and cool, but ultimately not that poweful. Make it flashy, give it big numers and a weakness that - perhaps - the AI isn't smart enough to exploit but a clever player might be. You want them to think

> Cool, so I get to fight against *that*? Ha, good thing I already know its weakness.

Essentially, reward them with coolness factor, unique options and replayability, which will persist throughout the second half, rather than just bigger numbers.

**3. Hide some soft counters to earlier progress in the second half**. Design some items/units/whatever to be especially effective against the stronger things the player can attain in the first half of the game. As in point 2, you can make these more challenging to find or use than other options, as long as they're effective enough to level the playing field a bit. A player that did exceptionally well in the early game can be expected to handle that, and the trope of "unlikely hero searches for lost artifact to be able to face nigh unbeatabe villain", while perhaps overused, has storytelling potential *because* it's not a macguffin to get the plot going but a consequence of the player's earlier actions.

# Answer
> 12 votes
## Keep the abilities, not the power level

Let players control the direction in which the character evolves, but keep control of how powerful it is when the players eventually face it. This lets them customize the final battle to their hearts content, but prevents them from gaming the system, and allows you to add a few surprises where you can make things more interesting.

## Thematically, this might even make more sense

If time has passed between the end of the first part of the game and the final battle, it is logical that the villain has continued to upgrade themselves beyond what they had under the player's control.

## Mechanically, this will feel better to your players

It's not a great feeling for a player to reach the pinnacle of their abilities half way through the game, and then get reset back to basic and then have to spend the rest of the game getting back to where they were before.

Power resets *can* make for exciting gameplay, but they should be relatively brief, so that players can return to all the fun and powerful abilities they've grown to love.

The solution is to let the second character reach the power levels of the previous one relatively quickly, and then push onward, breaking new and interesting ground.

This can help you pull off your twist, too. If the player can see that they're only halfway towards their peak power level, they won't expect their progression to suddenly end and switch to a different character.

Of course, this doesn't work if the final boss is at the original power level they were left at. But if their power has grown off-screen, then it won't be an issue!

# Answer
> 5 votes
If the game is an RPG, one possible way to deal with this would be to make it a **moral action**.

First, display things like the enemies being **morally innocent**, or displaying themes of **bloodthirst and war** being punished. For example, if you grind too much in certain areas, show the civilisations of the enemies you're grinding against start to wither, or cause the people in town to start mentioning how it's affecting the area in negative ways.

This way, any player that would be grinding for power and to make the game easier would have to directly ignore what characters and locations are implying. This could also lead to a "Hey, I found a way to cheat the game" situation caused by them levelling up too much despite the themes, which would then be punished by them fighting themselves, who has also levelled up a similar amount. In addition, people who choose to respect the area, obey the games wished and make the game harder would be rewarded for their nature.

One extra thing to consider if implementing this would be the external factors that would be necessary to show the difference in power, as if it's just You v Your other self, the attack/defense levels would just vary, and not actually display power. Allies and spells/abilities with set damage are necessary to actually display the difference in power.

Overall, this would make a memorable experience for the player, as the theming is a way to make the entire game lead up to a point where they fight themselves, as opposed to other solutions which may just make people see it as another point in the story.

# Answer
> 3 votes
# Make it spoiler-proof

If the game becomes popular, any secrets will be spoiled, so don't make it depend on secrets being kept from the player for it to be fun.

# Dr. Jekyll, meet Mr. Hyde

Give the main character some trait that allows them to be both superhero and villain at the same time without realizing it, though somehow with two separate but inextricably linked bodies. Gradually reveal this fact with clues (perhaps revealed as a reward for good game-play) so that astute players can figure out early on and have the best possible chance against themselves. At certain points clearly reveal pieces of this info to *all* players (e.g. in cut scenes) so that no player is blindsided when they reach the final battle.

# The greater the struggle, the greater the honor

Reward players who take the most difficult path *and win* with the greatest honor (points, badges, etc.) so players will not be motivated to slack off in the beginning just to win.

# Why play only one side?

In fact you could have the player actually *play* both hero and villain simultaneously (switching back and forth between the two separate "games" representing the hero's and villain's journey to face one another), and winning the game requires that they win *both halves* of the game along with the final battle from the hero's perspective. After all, what's a hero without villain? So if the player makes the main character so weak that they can't get the villain to the final battle to face the hero, they lose. And likewise for the hero. They only win if they get both halves (Jekyll and Hyde) to the final battle and then the hero defeats the villain.

*P.S. If you want the villain to win as the goal, then just reverse the labels "hero" and "villain" in the description above.*

# Answer
> 3 votes
# Limit or extend the hero's potential relative to the villain

Make it so you essentially can't truly max your hero unless you first max your villain.

The straightforward but boring way to do this would be to set a level cap at the start of the second half of the game relative to the level you reached as the villain, which would itself be capped at half of the hero's max-max level or less (and the villain would also grow relative to this until the final fight).

The more interesting way would be something like Josh Part suggested, with the villain changing the persistent world in ways that affect how the hero plays, such as unlocking additional areas, shaping the geography of the map, or, indeed, hiding away items for the hero to find later.

IMO, some blend of the two would be interesting.

# Answer
> 2 votes
# Create a system of counters.

For example if players are going to be mages, create a system where there are 3 schools of magic: fire, water and nature. Fire is powerful against nature, weak against water. Water is powerful against fire, weak against nature. Nature is powerful against water, weak against fire. Then when the player creates a powerful fire mage villain, make the hero a water mage. And so on...

Or when the villain is a stealth-based character, give the hero high perception and revealing spells. When the villain is a high-mobility character, give the hero some items that slow down and/or restrict movement. When the villain is heavily armored, give the hero spells that ignore armor (or even ones where metal armor amplifies the damage).

# Answer
> 2 votes
**Exclusive Choices**

There are sources of "power" in the game (be they artifacts, allies, skills or actual supernatural/futuristic powers), but the first character can't get all of them. Getting one locks another out (perhaps it's an issue that the powers actually counter each other or you can't wear two pieces of the same kind of equipment or just there's not enough time to get all of them). Character 2 will have to go get the complementary powers to fight character 1.

Bonus points if getting too many powers causes the first character to go villain so the second character can't get all the complementary powers and has to deal with being less powerful for extra difficulty.

# Answer
> 1 votes
This actually seems like a very neat idea that can lead to some interesting mechanics.

A couple points that comes to mind to answer your question:

1. Dont' just take into considerations level, abilities, or equipment. The player must eventually fight his own creation, but why stop there? Have events and choices made by the villain affect also the hero's quest, an example as simple as it might get: as the villain you have to choose to either destroy some magic mcguffin or put it somewhere safe; then when you play as the hero it turns out you need said mcguffin: if you destroyed it, the hero needs to find a way to repair it or make another; if you hid it, the hero needs to track down where it was hidden.
2. Some games give the player the chance to play a second quest once the game is finished, this time controlling the villain. You can do that but having your entire first quest as the villain, and after the game ends, the player can start a new quest controlling the hero, whose mission will be to stop the very villain the player itself created on the first quest.

Both options give you a huge replay value as the choices made during the first act/play affect the rest of the game; just make sure you don't make way too many possibilities as that can become overwhelming for the player.

# Answer
> 1 votes
In Japanese style RPG's, Breath of Fire IV quite successfully pulled off what you are trying to accomplish, by having the main protagonist Ryu and antagonist Fou-Lu being split halves of the same dragon god. You play both of them in different chapters of the game, and get to explore their personalities and reasons for their moral stance. The ending changes depending on how you play the game,

Now as to how to deal with the leveling problem, this game does it very easily: it cheats. Fo-Lou already starts with relatively high levels, and his level and growth only matter in his own chapters. Ryu on the other hand starts with lower levels and his level and growth only matter in his chapters. RAt the final conftrontation, which is played with Ryu, Fou-Lu will be of a preprogrammed level and difficulty degree, that has no relation to the level he had in his chapters. This is justified by leaving some in game time between the final chapters of the two characters, in which Fou Lu supposedly powers himself up off-screen.

While cheating like this may seem unfair, it is an acceptable break from reality and it works remarkably well. Start out with the "dark self" at high levels and give him difficult opponents so the player cannot hold back, then let his counterpart the "light self" start from a low level and struggle even more to beat his "dark self". And if the level of the "dark self" is too low, just give him a few bonus levels at the final confrontation and handwave it with "I was holding back, but now I will show you the true power of darkness".

# Answer
> 1 votes
## Unlock more second chapter content based on the first chapter's events

Philipp's (by now acceptated) answer is excellent, but I want to add one more mechanic that should help you provide replay value and balance at the same time.

Unless the twist is completely out of the blue, your hero/villain has likely been sliding down the "ends justify the means" scale, leaving more and more collateral damage.

The stronger and more successful the villain is in the first chapter, the more people he has impacted and the more resistance will grow. These become resources for the second chapter's hero as well as extra story elements to explore.

As an example, suppose there is a "steal the artifact" mission in the first chapter. The player could sneak/bribe their way in and out, gaining only a few XP, or slaughter every last person in the building, take all their loot and gain an extra level.

In the second chapter you could then have either a small "investigate the theft" side-quest providing low resources or a whole new henchman with an "out-for-revenge" line of quests that provides a lot more loot and a level.

This provides some measure of balance. It can also go the other way, with careful play in the first chapter leading to less help and more resistance in the second.

Replayability can also be improved if choices in the first chapter affect the story or play styles available in the second. If the villain rises up the ranks in the Mages' guild, they will be unavailable for help in the second chapter, etc.

# Answer
> 1 votes
Pure Levels are a relatively boring way to advance a character. Bigger numbers. More treadmill.

Use a variant advancement scheme that ties to the narrative.

Instead of just "gain levels", have the villian unlock power sources of some kind. You do have to spend time *practicing* those power sources ("leveling them up"), but each power source can grant only a certain number of "levels", and is tied to some specific portion of the character's capabilities.

Suppose you have a game with rune magic. Then power sources could be getting new runes, and you'd level up your skill in each rune as you leveled up. The character has a certain number of capabilities; and what that capability does is determined by what the rune-sentence they use and the levels of the runes in question.

`Ik Ro Na Tuk` might create a whip of fire that entangles foes, then leaves behind a serpent with a special ability to attack them. Your levels in each of those runes would determine accuracy, damage, serpent toughness, and the serpent's special ability.

(These special moves can be hardcoded with variations; then, which rune sentence is assigned which move could be randomized before the start of each game, so learning rune sentences is part of the game's advancement system.)

Once you have done this, the runes that the villian unlocks are the ones that the hero has an opportunity to learn, at least initially, with two exceptions (the "evil" rune for the villian, and the "good" rune for the hero).

Between the first and second part of the game, the villian automatically "levels up" all runes and uses combinations that you have pre-determined. (The villian gets to know *every* rune sentence, while the hero only gets the ones you have discovered.)

So now, a weak initial half of the game results in a weaker villian, but also a weaker hero. Possibly really careful choice of runes could result in a villian that is using abilities that the computer isn't good at using, but the player is, or that combine really well with "good" but poorly with the "evil" rune, but it isn't a direct "earn a level, boss is a level tougher"; it is "find a rune, both you and your foe have an extra ability to play with".

If the non-boss foes are mostly the same in the second half, doing well in the first half can make the non-boss parts of the second half easier, while at the same time making the boss harder.

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


# Question
Title: how are semantics used when declaring a struct?
I don't understand how semantics are used in shaders. While reading Unity's shader tutorials, I come across this

```
struct v2f {
    float worldPos: TEXCOORD0;
    half3 worldNormal: TEXCOORD1;
    float4 pos : SV_POSITION;
};

```

and also this

```
       struct v2f {
            float3 worldPos : TEXCOORD0;
            half3 tspace0 : TEXCOORD1;
            half3 tspace1 : TEXCOORD2;
            half3 tspace2 : TEXCOORD3;
            float2 uv : TEXCOORD4;
            float4 pos : SV_POSITION;
        };

```

Microsoft's documentation says

> A semantic is a string attached to a shader input or output that conveys information about the intended use of a parameter.

I know there is some kind of interpolation of data because vertices and pixels aren't one to one, thus I think semantics are used for telling the graphics library what to do about the data. But here it uses TEXCOORDX for things like world position and tangent space vectors. They don't seem to have anything to do with UV coordinates. So how are these semantics actully used?

# Answer
Keep in mind that the struct in HLSL is just a language convenience. It doesn't really mean anything in the hardware. You can use HLSL structs to group parameters to shaders and outputs from shaders. They can be used in constant buffers (either globally in the case of legacy Direct3D 9, or in constant buffers in Direct3D 10+ where there's actually some context to the grouping as a `cbuffer`).

These particular semantics are associated with the outputs of vertex shaders and the inputs of pixel shaders. You must have a `SV_Position` (or the older `POSITION`) as that's used to drive the rasterization and invocation of pixel shaders. The rest are just 'interpolators' that calculate smooth values between each vertex on the triangle when drawing. That includes `NORMAL`, `TEXCOORD0`, etc. They are often used by shaders with this convention, but there's nothing special about these values in most cases.

See Microsoft Docs
> 0 votes

---
Tags: unity, hlsl, shaderlab
---


title: Lerp UI Color outside update method?

text:
# Question
Title: Lerp UI Color outside update method?
I'm able to Lerp the color of a UI panel within the Update method. However I'd like to trigger behavior a single time when needed. If I put it in a method and call it it only changes for a brief time and doesn't fully complete. I could probably set a bool flag within the update method but that seems sloppy.

# Answer
> 0 votes
Using a Coroutine gives the desired effect.

```
IEnumerator ChangeColorTest()
    {
        for (var i = lerpDuration; i >= 0; i -= 0.1f)
        {
            UIPanel.color = Color.Lerp(startColor, endColor, Time.time / lerpDuration);

            yield return new WaitForSeconds(0.1f);
        }
    }

```

I'd like the color transition to be smoother but this might be how Coroutines work.

---
Tags: unity
---


# Question
Title: Can I run a script and generate warning when Unity project is saved?
### Context:

I'm working with Unity using Git and we have .gitignore setup so that we could create "\_local" folder anywhere in Assets and it won't be commited. It makes for kind of a Debug/Backup folder, where I can put any of textures I want to check or any script I want to test in Unity, but keep it locally.

---

### Problem:

That unfortunately causes problems. After referencing many local files I decide to commit the project, so I make all the references pointing files that will be commited. Sometimes though I don't notice one wrong reference and I commit the project which causes errors on collaborators' devices.

---

### Idea:

I came up with an idea that I could write a script which goes through every reference and if any of them points to a local file it should generate a warning or error. All that would happen after saving the project.

---

### But can it be done?

Is there a way to find all the references and call the script once the project is saved?

# Answer
Yes, it can be done:

https://docs.unity3d.com/ScriptReference/AssetModificationProcessor.html

https://docs.unity3d.com/ScriptReference/AssetModificationProcessor.OnWillSaveAssets.html

Example of usage:

```
using UnityEngine;
using UnityEditor;
using System.Collections;

public class FileModificationWarning : SaveAssetsProcessor
{
    static string[] OnWillSaveAssets(string[] paths)
    {
        Debug.Log("OnWillSaveAssets");
        foreach (string path in paths)
            Debug.Log(path);
        return paths;
    }
}

```
> 1 votes

---
Tags: unity, c#, debugging, git
---


# Question
Title: RTS game: How to handle disconnects in a fully connected peer to peer architecture?
I'm currently working on a game in which I am considering implementing a networking architecture as described in this article: http://www.gamasutra.com/view/feature/131503/1500\_archers\_on\_a\_288\_network\_.php

In order for the implementation as described in the article to work, all peers need to be interconnected without any exceptions. Like so:

This works fine when everything is well. But I am wondering how to agree on disconnects in such a network. (Sadly something the article does not go into). It is relatively easy if one client goes down. Just give every client a timeout, and if a client does not respond for a certain time, it is removed from that client.

However, how should the system solve a case in which one client does not respond to another, but still responds to all others. In such a system the following could happen, resulting in a invalid state:

Of course this can be solved by giving one of the clients some kind of "master" role. It being the only one that can decide whether or not to disconnect other clients. But I'm wondering if it can be achieved in a pure p2p network.

Note I realize this case is not one that can likely occur "naturally". But I want to prevent players from being able to ruin a networking game for others by playing a trick like this by using the firewall for example.

# Answer
First of all you need a way of detecting such issues and separate them from simple packet loss. Once you know you really have this happening and really need to work around this, there are several solutions you could try:

* Simplest solution, just drop the player
* Allow to re-route messages/packets via different peer (i.e. assign a peer who will send out not only his commands, but other peers commands to "problematic" peer)
* Upgrade the topology and introduce a stable host that will act as a re-transmitter for all the peers. Optionally it could also become a short-time cache to drastically reduce number of packets in exchange.

---

P.S. We have RTS topology with all packets routed through the host/server (option #2, to avoid the OP problem in the the first place) and recently started to struggle with packet counts, after raising players count in a game from 8 to 12 - that is 12 players, 10 ticks/sec, each sending message and ack = (1+11+11\*2) * 10 = 320 packets/sec for each peer. Applying option #3 about now, iirc. If you have more questions, feel free to contact!
> 2 votes

---
Tags: networking, rts, udp, peer-to-peer
---


# Question
Title: How to unpack game data files encrypted with AES key?
In game development pak files are secured by some encryption and one of these are AES key. I want to know that for security purpose is the AES key is stored in the game files itself? I know that computer cannot store the AES key in his mind so it need some clues or files to extract these Ppak files, so where does these AES keys gets stored in a game file itself?

# Answer
Yes, the encryption key must be somewhere, otherwise the game would be unable to open those archives. But unfortunately there are just too many ways one could store such a key. It could be somewhere in the executable files or in some other file which comes with the game. It might even be possible that the game connects to the Internet when it starts up and downloads the decryption key from the publisher's website. The developers might also try to obfuscate the key in various ways so you won't find it that easily.
> 2 votes

---
Tags: unity, security, encryption
---


title: Reading a Binary File in Unity

text:
# Question
Title: Reading a Binary File in Unity
I am trying to display the first two bytes of a binary file as a test. I have the following code.

```
 void DisplayValuestext(){
  Stream s = new FileStream("Assets//testbinary.bin", FileMode.Open);
  BinaryReader br = new BinaryReader(s);
  int dataVal = br.ReadUInt16();
  Debug.Log(dataVal);
 }

```

The first 2 bytes of the binary file are "1E44" which the function ReadUInt16() should read. However, it reads the first byte of data, "1E" rather then the first 2 bytes "1E44". I believe it is because it reads 2 characters, rather than 2 bytes. When I display the 16 bit unsigned integer "dataVal" in the console, I get 25905. The value I am trying to get is 17438 which is "1E44" little-endian encoded value converted to decimal.

I have also attempted to use the function "ReadUInt32". This method should read the first 4 bytes, however it instead displaces by 4 characters, which is 2 bytes "1E44". The console displays "875849009".

Why do I get these strange values "25905" and "875849009" and how can I resolve this to get the desired value of 17438?

# Answer
> 2 votes
Your file is not a binary file.

It contains ASCII text, starting "1e"...

The value of which is 65 31 in Hex (Little endian encoded), Or 25905 in Decimal.

1e44(ascii)= 34 34 65 31 (hex) = 875849009 (dec)

---
Tags: unity, data, file, processing, binary
---


# Question
Title: How can I let players "scrape away" one texture to reveal another?
In this game I'm making, I want my players to be able to remove rust from an object based on collisions from another object such as a wire brush. Since it's a VR game, performance is key.

I've been having a hard time getting on the right track; I think I'm not asking the right questions. The closest I've gotten was a video about making a scratch-off lotto ticket. Someone in the comments to that video says:

> Good Idea. But, this isn't practical for any real world apps. It instantiates too many gameobjects. There are better more efficient ways of achieving this effect using shaders or render texture.

They don't really expand on that further, but I did do a little more searching to see how I might do this using shaders. I found this video about using replacement shaders, but I'm still not sure if that's the right track. I don't know If something like that is the smartest way to do it.

I'm basically a complete noob when it comes to shaders and textures so this is new territory for me. I apologize if this is a duplicate question, I've tried searching but haven't found anything quite like what I'm looking for. Please let me know if there's anything I can explain further, and any help that gets me pointed in the right direction would be greatly appreciated.

# Answer
> 4 votes
If you're okay with mesh colliders, take a look at this. The example describes a (primitive) version of what you want.

The next step would probably be to write a shader that takes three textures: a "rusty" version, a "clean" texture and a "splatmap" that stores where to apply which texture. Instead of the main texture, the script should paint into this splatmap.

All the shader needs to do is "fade" between the two textures. I'm at work right now and can't give you all the boilerplate from memory, but the relevant line should look something like this:

```
out.rgba = _rusty.rgba * _splat.r + _clean.rgba * (1.0 - _splat.r)

```

I'm using the splatmap's red channel here, any other will do as well. The splatmap can have a different resolution than your other textures so play around with that and pick whatever looks best on your object.

EDIT: Here's the final code that did the trick (made by OP). DotClick.cs should be applied to the camera and ClearableShader should be applied to the object in question.

ClearableShader.shader:

```
Shader "Custom/ClearableShader"
{
    Properties
    {
        _Color ("Color", Color) = (1,1,1,1)
        _CleanTex("Clean Texture", 2D) = "white" {}
        _RustTex("Rust Texture", 2D) = "white"
        _SplatTex ("Splat Map", 2D) = "white"
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 200

        CGPROGRAM
        // Physically based Standard lighting model, and enable shadows on all light types
        #pragma surface surf Standard fullforwardshadows

        // Use shader model 3.0 target, to get nicer looking lighting
        #pragma target 3.0

        sampler2D _CleanTex;
        sampler2D _RustTex;
        sampler2D _SplatTex;

        struct Input
        {
            float2 uv_CleanTex;
        };

        half _Glossiness;
        half _Metallic;
        fixed4 _Color;

        // Add instancing support for this shader. You need to check 'Enable Instancing' on materials that use the shader.
        // See https://docs.unity3d.com/Manual/GPUInstancing.html for more information about instancing.
        // #pragma instancing_options assumeuniformscaling
        UNITY_INSTANCING_BUFFER_START(Props)
            // put more per-instance properties here
        UNITY_INSTANCING_BUFFER_END(Props)

        void surf (Input IN, inout SurfaceOutputStandard o)
        {
            fixed4 rustTex = tex2D(_CleanTex, IN.uv_CleanTex);
            fixed4 cleanTex = tex2D(_RustTex, IN.uv_CleanTex);
            fixed4 splatTex = tex2D(_SplatTex, IN.uv_CleanTex);

            o.Albedo = (rustTex.rgba * splatTex.r) + (cleanTex.rgba * (1.0 - splatTex.r));
        }
        ENDCG
    }
    FallBack "Diffuse"
}

```

DotClick.cs

```
// Write black pixels onto the GameObject that is located
// by the script. The script is attached to the camera.
// Determine where the collider hits and modify the texture at that point.
//
// Note that the MeshCollider on the GameObject must have Convex turned off. This allows
// concave GameObjects to be included in collision in this example.
//
// Also to allow the texture to be updated by mouse button clicks it must have the Read/Write
// Enabled option set to true in its Advanced import settings.

using UnityEngine;
using System.Collections;

public class DotClick : MonoBehaviour
{
    public Camera cam;

    void Start()
    {
        cam = GetComponent<Camera>();
    }

    void Update()
    {
        if (!Input.GetMouseButton(0))
            return;

        RaycastHit hit;
        if (!Physics.Raycast(cam.ScreenPointToRay(Input.mousePosition), out hit))
            return;

        Renderer rend = hit.transform.GetComponent<Renderer>();
        MeshCollider meshCollider = hit.collider as MeshCollider;

        if (meshCollider == null|| rend == null || rend.sharedMaterial == null || rend.material.GetTexture("_SplatTex") == null)
            return;

        Texture2D tex = rend.material.GetTexture("_SplatTex") as Texture2D;
        Vector2 pixelUV = hit.textureCoord;
        pixelUV.x *= tex.width;
        pixelUV.y *= tex.height;

        Circle(tex, (int)pixelUV.x, (int)pixelUV.y, 10, Color.red);
        // tex.SetPixel((int)pixelUV.x, (int)pixelUV.y, Color.red);
        tex.Apply();
    }

    // Taken from https://answers.unity.com/questions/590469/drawing-a-solid-circle-onto-texture.html
    public void Circle(Texture2D tex, int cx, int cy, int radius, Color color)
    {
        int x, y, px, nx, py, ny, d;

        for (x = 0; x <= radius; x++)
        {
            d = (int)Mathf.Ceil(Mathf.Sqrt(radius * radius - x * x));

            for (y = 0; y <= d; y++)
            {
                px = cx + x;
                nx = cx - x;
                py = cy + y;
                ny = cy - y;

                tex.SetPixel(px, py, color);
                tex.SetPixel(nx, py, color);

                tex.SetPixel(px, ny, color);
                tex.SetPixel(nx, ny, color);
            }
        }
    }
}

```

---
Tags: unity, shaders, textures, virtual-reality
---


# Question
Title: Finding shortest path on a hexagonal grid
I'm writing a turn based game that has some simulation elements. One task I'm hung up on currently is with path finding. What I want to do is move each turn an AI adventurer one tile closer to his target using his current x,y and his target x,y.

In trying to figure this out myself I can determine 4 directions no problem by using

```
dx = currentX - targetY
dy = currentY - targetY

```

but I'm not sure how to determine which of the 6 directions is actually the "best" or "shortest" route.

For example, the way it's setup currently, I use East, West, NE, NW, SE, SW but to get to the NE tile I move East then NW instead of just moving NW.

I hope this wasn't all rambling. Even just a link or two to get me started would be nice. Most of the info I've found is on drawing the grids and groking the weird coordinate system needed.

# Answer
> 22 votes
A few answers!

The coordinate system I've seen most often for hex-based traversal is one where the player can move in every normal NSEW direction, as well as NW and SE. Then you just render each row half-a-square offset. As an example, the location (2,7) is considered adjacent to (1,7), (3,7), (2,6), (2,8), and the weird ones: (1,6) and (3,8). Meanwhile, if we assume (2,7) is rendered at the center of the screen, (2,6) will be rendered up-and-to-the-right, (2,8) will be rendered down-and-to-the-left, (1,7) and (3,7) will bracket it to the left and right respectively, and (1,6) and (3,8) will place themselves top-left and bottom-right respectively.

A diagram of what I mean:

If you're doing it this way, finding the shortest direct path isn't difficult - travel the maximum NW/SE distance that you can without overshooting your target along a cardinal axis, then travel directly along that axis to the target.

But of course that will happily run you straight through mountains or other impassable terrain. To answer a question you haven't yet asked: The A\* Search Algorithm is a common and reasonably good approach to pathfinding. It will handle not only weird non-grid layouts, but will happily deal with obstacles and even obstructed/slow ground.

# Answer
> 5 votes
I have just posted a library of hex-grid utilities.

The library includes path-finding (using A-\* a la Eric Lippert) and includes utilities for automated conversion between jagged (termed User) coordinates and non-jagged (termed Canonical) coordinates. The path-finding algorithm allows the step cost for each node to vary both with the entry hex and te traversed hex-side (though the example provided is simpler). Also, elevated field-of-view using shadow-casting is provided, \[edit: words removed\].

Here is a code sample that converts readily between three hex-grid coordinate systems:

```
static readonly IntMatrix2D MatrixUserToCanon = new IntMatrix2D(2,1, 0,2, 0,0, 2);
IntVector2D VectorCanon {
  get { return !isCanonNull ? vectorCanon : VectorUser * MatrixUserToCanon / 2; }
  set { vectorCanon = value;  isUserNull = isCustomNull = true; }
} IntVector2D vectorCanon;
bool isCanonNull;

static readonly IntMatrix2D MatrixCanonToUser  = new IntMatrix2D(2,-1, 0,2, 0,1, 2);
IntVector2D VectorUser {
  get { return !isUserNull  ? vectorUser
             : !isCanonNull ? VectorCanon  * MatrixCanonToUser / 2
                            : VectorCustom * MatrixCustomToUser / 2; }
  set { vectorUser  = value;  isCustomNull = isCanonNull = true; }
} IntVector2D vectorUser;
bool isUserNull;

static IntMatrix2D MatrixCustomToUser = new IntMatrix2D(2,0, 0,-2, 0,(2*Height)-1, 2);
static IntMatrix2D MatrixUserToCustom = new IntMatrix2D(2,0, 0,-2, 0,(2*Height)-1, 2);
IntVector2D VectorCustom {
  get { return !isCustomNull ? vectorCustom : VectorUser * MatrixUserToCustom / 2; }
  set { vectorCustom  = value;  isCanonNull = isUserNull = true; }
} IntVector2D vectorCustom;
bool isCustomNull;

```

`IntMatrix2D` and `IntVector2D` are homogeneous integer implementations of affine2D Graphics Vector and Matrix. The final divide by 2 on the vector applications is to re-normalize the vectors; this could be buried in the `IntMatrix2D` implementation, but then the reason for the 7th argument to the `IntMatrix2D` constructors is less obvious. Note the combined caching and lazy-evaluation of non-current formulations.

These matrices are for the case:

* Hex grain vertical;
* Origin in upper-left for Canonical & User coordinates, lower-left for Custom coordnates;
* Y-axis vertically down;
* Rectangular X-axis horizontally across; and
* Canonical X-axis to the North-East (ie up and to the right, at 120 degrees CCW from Y-axis).

The code library mentioned above provides a similarly elegant mechanism for hex-picking (i.e. identifying the hex selected with a mouse click).

In canonical coordinates, the 6 cardinal direction-vectors are (1,0), (0,1), (1,1) and their inverses for all hexagons, without the asymmetry of jagged coordinates.

# Answer
> 0 votes
This is a solved problem, with much literature to back it up. The best resource I know is on Red Blob Games: https://www.redblobgames.com/grids/hexagons/.

In brief, the most likely reason is that you started with the wrong coordinate system. Using a Cube coordinate system implementing the A\* algorithm is quite simple. See live demo on the above link.

If you *really* want to use some other system, then convert to and from when needed.

---
Tags: path-finding, hexagonal-grid
---


title: 3d isometric projection matrix?

text:
# Question
Title: 3d isometric projection matrix?
I have 3d vectors that I want to project as 2d vectors to draw my shapes. I got a 3d vector cameraPosition, a 3d vector cameraDirection, a float renderDistance. I need to create an orthogonal / isometric matrix with those values to project my 3d vectors.

Here is what I currently have :

```
matrix4x4(vec3 camera, vec3 camreaDir, vec3 camreraScale){
    //get isometric projection matrix
    vec3 xImage = vec3(-sinf(camreaDir.x), cosf(camreaDir.x), 0) *
camreraScale.x; //unused member : z
    vec3 zImage = vec3(-sinf(camreaDir.x + camreaDir.z), cosf(camreaDir.x + camreaDir.z), 0) * camreraScale.z; //unused member : z

    matrix[0][0] = xImage.x;
    matrix[1][0] = 0;
    matrix[2][0] = zImage.x;
    matrix[0][1] = xImage.y;
    matrix[1][1] = camreraScale.y;
    matrix[2][1] = zImage.y;
}

```

# Answer
You should try having a separate camera and projection matrix, since isometric projection is just ortographic with a very specific camera placement.

If you are using a modern matrix library (you should be), then those two can be created with built-in methods. The projection matrix is just an ortographic matrix, the camera matrix is a model matrix, where you first rotate the camera -45 degrees along the xz plane (y axis) and then -30 degrees along the yz plane (x axis). You could also move it back, but if you set the near and far values of your projection matrix so that it can show stuff behind the camera too, then you won't have any problems with it.

If your library doesn't have these functions or you rolled your own, then you can just replicate them based off of these pictures:

Projection matrix:

Rotation matrices:
> 2 votes

---
Tags: c++, 3d, matrix, isometric, projection
---


# Question
Title: When to stop taking items from ever-growing queue and start processing them?
I am developing a fast-paced multiplayer shooting game and following instructions from this source http://www.gabrielgambetta.com/entity-interpolation.html. In the article it says that:

> several clients may be sending inputs simultaneously, and at a fast pace (as fast as the player can issue commands, be it pressing arrow keys, moving the mouse or clicking the screen). Updating the game world every time inputs are received from each client and then broadcasting the game state would consume too much CPU and bandwidth.
>
> A better approach is to queue the client inputs as they are received, without any processing. Instead, the game world is updated periodically at low frequency, for example 10 times per second. The delay between every update, 100ms in this case, is called thetime step. In every update loop iteration, all the unprocessed client input is applied (possibly in smaller time increments than the time step, to make physics more predictable), and the new game state is broadcast to the clients.

now I am wondering how to implement such a queue system? I can have an in memory queue where each input is added. and after say 100ms ***how many number of inputs do I process?*** ***i.e when should I stop popping events from queue and apply simulation?***

from my point of view clients are sending inputs constantly which are being added to the *input queue*. below is the psuedocode.

```
queue inputQueue;

gameloop() {
   while (inputQueue not empty) { //<------obviously i cannot use this condition, what should i use then?
      inputEvent = inputQueue.front()
      updateState(inputEvent)
   }
}

```

# Answer
> 2 votes
The purpose of the server's time-keeping is to **enforce a common view of the order in which events occur**, so all players can (eventually) agree on "who shot first" and other time/sequence-related gameplay distinctions.

So, when a client sends you an action, **your server assigns it a timestamp that it will consider to be its "effective time of action"**. This could be the time of receipt, or a back-dated time to try to compensate for the estimated network latency.

**Each server update also has an effective timestamp**, "This is the up-to-date state of the match as of XX:XX." You can compute this timestamp by adding exactly one fixed update interval to the timestamp of the previous server update.

During the server update pass, **process all items in your priority queue whose effective time of action is before the effective time of this update**. Any later actions happened "after" the current update pass, and can stay in the queue until the next update step.

If you do compensate for latency, this can mean a client message sent after an update has been processed can be assigned an effective time of action that should have been processed in that past update. Servers that operate this way will rewind the logical game state to this moment, to apply the action at the appropriate effective moment, then re-simulate back up to the current timestep and send corrections as needed, to keep the final view of the sequence of actions consistent for all players. This is more complex than working off of time of receipt, but can improve perceived fairness in the presence of latency.

# Answer
> 1 votes
You could combined the "is the queue not empty" check with a current time check.

Essentially just process the queue one item at a time, up to a time limit. Then anything that is still in the queue will get processed on the next step.

```
queue inputQueue;

// This should be low enough that you process enough items per
// slowing down your overall simulation, but high enough that
// step without your simulation doesn't lag too much. Tuning
// this is dependent on your application.
const uint TIME_LIMIT = 5;

gameloop() {
   uint processUntilTime=now() + TIME_LIMIT; //process the queue for up to _TIME_LIMIT ms from now

   while (inputQueue not empty && now() <= processUntilTime) {
      inputEvent = inputQueue.front()
      updateState(inputEvent)
   }
   // Either inputQueue is empty or TIME_LIMIT has been reached
}

```

---
Tags: networking, multiplayer, game-loop
---


# Question
Title: Unity AudioSource.PlayClipAtPoint - controlling attenuation
New developer here, looking to do some raycasting and controlling audio positioning in 3D space based on the raycasts interactions with other objects. I've got the raycast 'casting' and able to report back where it collides other objects and managed to get audio to play back at that raycast point using `AudioSource.PlayClipAtPoint()`

However, `PlayClipAtPoint` doesn't allow me to change the audio 3d attenuation settings as a one shot audio object is generated and then removed immediately and I can't find any parameters to control this new object apart from a volume 0-1 float value.

I came across this post by Aldonaletto:

```
function PlayClipAt(clip: AudioClip, pos: Vector3): AudioSource; {
   var tempGO = GameObject("TempAudio"); // create the temp object
   tempGO.transform.position = pos; // set its position
   var aSource = tempGO.AddComponent(AudioSource); // add an audio source
   aSource.clip = clip; // define the clip
   // set other aSource properties here, if desired
   aSource.Play(); // start the sound
   Destroy(tempGO, clip.length); // destroy object after clip duration
   return aSource; // return the AudioSource reference
 }

```

But can't seem to get the local function to work in Unity as it complains about not using C# version 7 or above. If I upgrade the C# version in visual studio I get compiler errors on Unity's side.

Little bit stuck, would appreciate some advice! Some code below, just not sure what to put into the result of the if statement to get this to work.

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

public class raycasting : MonoBehaviour
{
    public float raycastlength = 3;
    public AudioClip playthis;
    public float ER_Volume = 1F;

    // Use this for initialization
    void Start()
    {
        //Debug.Log("I'm a sphere, yo!");
    }

    // Update is called once per frame
    void Update()
    {
        RaycastHit hit;
        Ray forwardray = new Ray(transform.position, Vector3.forward);

        //draw the raycast in scene view
        Debug.DrawRay(transform.position, Vector3.forward * raycastlength, Color.white);

        if (Input.GetMouseButtonDown(0))
        {
            //Debug.Log("We pressed the fire button!");
            if (Physics.Raycast(forwardray, out hit, raycastlength))
            {
                if (hit.collider.tag == "evil")
                {
                    Debug.Log("Raycast Hit!");
                    Debug.Log("Distance to object:" + hit.distance);
                    //Debug.Log("Object hit point:" + hit.point);

                    //play a sound using playclipatpoint, but this doesn't allow us to change attenuation settings
                    AudioSource.PlayClipAtPoint(playthis, hit.point, ER_Volume);
                }
            }
        }
    }
}

```

# Answer
> 0 votes
Thanks to DMGregory for putting me on to the Unity converter tool. The tool Unity have created seemed to struggle to convert the script for some reason. Instead, I tasked myself with breaking it down and re-creating the function in c~ by hand, and think I figured it out. For the people googling this in the future, I managed to get it to work with an empty prefab called 'playclipat' that has an AudioSource attached to it. The Vector3 in the Instantiate command is "hit.point" as that's part of the raycast. The newly cloned 'playclipat' object is then destroyed after the audio clip has finished.

```
GameObject playclipatclone = Instantiate(playclipat, hit.point, Quaternion.identity);
AudioSource clonecliplength = GetComponent<AudioSource>();
Destroy(playclipatclone,clonecliplength.clip.length);

```

---
Tags: unity, raycasting, audio
---


# Question
Title: Linking Unreal Engine with OpenCV libraries built with RTTI on Linux
Unreal Engine has a plugin for integrating with OpenCV. Currently that plugin works on Windows. I'm trying to modify this plugin to work on Linux. I've worked through many issues but I have one I can't resolve.

When I try to build the plugin without modification, I get this error:

> cannot use typeid with -fno-rtti

The error is from a file `any.h` which is a part of the OpenCV FLANN feature set and appears to have been copied over from boost.

To address this, I enable RTTI for the module of the plugin I'm building. Unfortunately, this leads to load time errors like the following:

> dlopen failed: /home/lvl-dev/Projects/TestOpenCVModules/Plugins/OpenCVLensDistortion/Binaries/Linux/libUE4Editor-OpenCVLensCalibration.so: undefined symbol: \_ZTI7UObject
>
> ModuleManager: Unable to load module '/home/lvl-dev/Projects/TestOpenCVModules/Plugins/OpenCVLensDistortion/Binaries/Linux/libUE4Editor-OpenCVLensCalibration.so' because the file couldn't be loaded by the OS.

As far as I can tell, this is because Unreal builds by default with '-fno-rtti'. And now the Unreal objects in my plugin expect RTTI information to be available for the Unreal objects when my libraries are loaded at runtime. I found you can pass `RTLD_LAZY` to `dlopen()`, which I thought would address this, but when I looked at the source it was already using it.

The next obvious thing is to just build everything with RTTI but I've been unable to accomplish this. I've seen on some forums that building Unreal with RTTI is possible after version 4.15 or so. However, when I've tried to build the engine with RTTI I get errors from attempting to link compiled third party dependencies that are now incompatible with Unreal (WebRTC for example). I'd really rather not work my way through building every Unreal dependency from source myself.

Strangely nothing is done to handle this issue on Windows. It seems the Microsoft linker and runtime handles both RTTI and non-RTTI definitions of the object without issue.

Is there a straight forward way to build and successfully run wtih C++ RTTI enabled?

Is there a way to mix RTTI and non-RTTI objects, as Microsoft seems to do, and suppress the link errors from the runtime?

Is there some solution I'm not considering?

# Answer
I wasn't able to mix the RTTI and non-RTTI definitions but I was able to get Unreal to work with OpenCV on Linux. I did this by disabling the FLANN features. This can be done via a cmake switch. Disabling this no longer triggered the #include path that was pulling in the call to RTTI related features. Thus I was able to build my Unreal module without RTTI.
> 1 votes

---
Tags: c++, unreal, linux, build-process, plugin
---


# Question
Title: For PC game development with Visual Studio, how do AAA developers reconcile their dozens-of-GB games with VS's 4 GB memory limits?
As far as I understand it, Visual Studio is the de-facto standard for Windows development in C# and C++, but it is limited by the fact that it's a 32-bit application and thus only has access to 4 GB of RAM for loading projects (Microsoft wrote a blog post 10 years ago explaining(?) why there is no 64-bit version). AAA games, however, are dozens of GB large, and even after factoring out the assets (which VS doesn't load), still amount to quite a bit of executable code.

Are AAA developers able to work within those limits for PC development, or do they use other IDEs that have 64-bit versions?

(I am aware that Visual Studio often uses out-of-process facilities for actually building and running projects, but the IDE itself is 32-bit and a lot of its functions, such as CodeLens, run in process).

# Answer
A 4GB limit is simply rarely a problem.

Most of what makes games so large in total are assets that are never loaded by Visual Studio. Even assets that are referenced in VS's project files are not loaded *until* they are opened, and usually end up unloaded afterwards (once any editing windows for those assets are closed).

Generally, most of what Visual Studio loads in terms of user data is text, and the text is simply just not that big (generally measured in megabytes, not gigabytes) and there is generally not that much of it open at once (relatively speaking) or, indeed, at all.
> 3 votes

---
Tags: visual-studio, memory, ide
---


# Question
Title: How to have an object follow the mouse, even if not clicked in Unity?
I have this object. I want to click on it and drag it around. Also if I click anywhere on the screen, I want the object to move but keep the distance.

In the script below I made the object follow the mouse, but I can't do the second part.

I have a couple rays for debugging. Any ideas?

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

public class Player : MonoBehaviour
{
    Vector3 playerPosition;
    Vector3 mouseF;
    Vector3 mouseN;

    void FixedUpdate()
    {
        if (Input.GetMouseButton(0))
        {
            setMouseF();
            setMouseN();

            Debug.DrawRay(mouseN, mouseF - mouseN, Color.green);
            Debug.DrawRay(mouseN, (playerPosition - mouseN), Color.red);

            // move the player base on mouse position
            transform.position = mouseF;
        }

        if (Input.GetMouseButtonUp(0))
        {

            // on mouse release, set the new player position
            playerPosition = mouseF;
        }

    }

    void setMouseF()
    {
        Vector3 mouseFar = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10f);
        mouseF = Camera.main.ScreenToWorldPoint(mouseFar);
    }

    void setMouseN()
    {
        Vector3 mouseNear = new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.nearClipPlane);
        mouseN = Camera.main.ScreenToWorldPoint(mouseNear);
    }
}

```

# Answer
> 0 votes
After playing some more with it, I sound a solution.

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

public class Player : MonoBehaviour
{
    Vector3 playerPosition;
    Vector3 mouseF;
    Vector3 mouseN;
    Vector3 diff;

    void FixedUpdate()
    {
        if (Input.GetMouseButtonDown(0))
        {
            InitPlayer();
        }

        if (Input.GetMouseButton(0))
        {
            SetMouseF();
            SetMouseN();

            Debug.DrawRay(mouseN, mouseF - mouseN, Color.green);
            Debug.DrawRay(mouseN, (mouseF + diff) - mouseN, Color.red);

            // move the player base on mouse position
            transform.position = mouseF + diff;
        }

        if (Input.GetMouseButtonUp(0))
        {
        }

    }

    void InitPlayer()
    {
        SetMouseF();

        // set player position where the object is
        playerPosition = transform.position;

        // get the distance between the player and mouse click
        diff = playerPosition - mouseF;
    }

    void SetMouseF()
    {
        Vector3 mouseFar = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10f);
        mouseF = Camera.main.ScreenToWorldPoint(mouseFar);
    }

    void SetMouseN()
    {
        Vector3 mouseNear = new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.nearClipPlane);
        mouseN = Camera.main.ScreenToWorldPoint(mouseNear);
    }
}

```

# Answer
> 0 votes
You want to drag & drop an object and keep the distance between the mouse and the object is that right?

If this is what you want it might be something like

```
Vector3 initialMousePos;
Vector3 offset;

private void Update() {
    if(Input.GetMouseButtonDown(0))
    {
        initialMousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    }
    if(Input.GetMouseButton(0))
    {
        offset = initialMousePos - Camera.main.ScreenToWorldPoint(Input.mousePosition);
        transform.position += offset;
    }
}

```

Tell me if that helps.

---
Tags: unity
---


# Question
Title: Do Gradle 'implementation' replace Unity Jar Resolver dependencies?
I have a project with several `*Dependencies.xml` files which the Unity Jar Resolver resolves fetching the .aar files and storing them on Plugins/Android.

When installing Ironsource, I saw in the documentation that it says to add the dependencies to the mainTemplate.gradle file:

```
dependencies {
    // Your other dependencies //
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.google.android.gms:play-services-ads-identifier:16.0.0'
    compile 'com.android.support:support-v4:27.1.1'
    **DEPS**
     // Your other dependencies //
     // ... //
     // AdMob's dependency //
    compile 'com.google.android.gms:play-services-ads:17.1.1'
}

```

Because one of my dependencies that the jar resolver imports is an older version of support-v4 my build fails.

Seeing this new alternative, can I move all the dependencies files to the gradle file and let Gradle auto resolve this problem on the post build process?

Is there any pros/cons that the jar resolver has that Gradle doesn't? For what I know the Jar Resolver uses gradle.

# Answer
> 1 votes
The section you have here is ironSource telling you how to get Google Mobile Ads implemented in Unity. They seem to be behind the times, because Google’s recommended way of doing this is using the Jar resolver instead. I don’t think any of the stuff listed there is actually necessary. That is, you shouldn’t need to create a custom Gradle template just for this if you’re already getting the Google Mobile Ads SDK the Right Way (i.e. import the AdMob unity package which uses the Jar resolver).

Assuming you are, you should probably make sure that the versions in your google mobile ads dependency xml file matches up with ironSource’s required versions. That is, version 17.1.1 or earlier, apparently. Also, tell ironSource to stop requiring old versions of SDKs to function.

**Edit:** Switching to use the Gradle file exclusively is certainly an option, if you want to do that for every android library manually which otherwise gives you instructions to use the jar resolver, keeping in mind that you’ll need to redo it whenever you update the libraries.

---
Tags: unity, gradle
---


# Question
Title: The types of buffers typically used in robust WebGL/OpenGL apps
I am trying to get a feel for how to structure WebGL/OpenGL apps and have been looking through sources for the types of buffers they use. I've found these:

1. uvs
2. occlusion
3. noise
4. bitangents
5. tangents
6. normals
7. vertices
8. indices
9. position
10. color

I'm wondering if there are typically just these when building a robust WebGL/OpenGL app, or if there are more or fewer usually. This will help in figuring out why things are done certain ways. Also wondering what these ones above are typically used for. I am only really interested in 2D stuff at the moment. I'm not really sure yet what the `indices` one is for or the tangents, I can figure out the others.

# Answer
If you set up an project with your idea, - what you want to archive as a final result. You also need to question yourself, how to structure different data. With the question you asked, everything can be a buffer. Just because their is no limit of what you can do, and what you what to be done as a project. A Buffer for Keyboard input or for previous mouse position is also a buffer. It always depends on what you try to archive. Generally speaking complicated user interaction with a 3D scene comes with a lot of buffers, yes.

For example a Mesh -Buffer would be used if you read an \*.obj data format (or whatever) with normals (for light calculation), vertices(position in 3D space) , indices(triangle rasterization). Means your 3d modeling program you were using exported your Mesh and saved all these data. Now you need to unpack it create a Buffer for all provided data in WebGL/OpenGL and send in for processing to the graphics pipeline.

If you want to make a 3D Shooter, like Crysis remake, a rough sketch of the data/buffers yout need would be:

**MESH** ( buffer )

* normals
* vertices
* indices

**TEXTURE**

* noise (for effects like clouds, vertex displacement)
* uvs (for correct texturing)
* color (red brick wall texture)
    + **LIGHT** calculation
    + occlusion (map)

**LIGHT**

* bitangents
* tangents

The point here is: When you project become more advanced, you also would need to provide more buffers.
> 3 votes

---
Tags: opengl, shaders, webgl, vertex-buffer, index-buffer
---