title: Handling input in a custom ECS engine

text:
# Question
Title: Handling input in a custom ECS engine
I've been implementing an Entity Component System into my custom toy engine so I can learn more about it. Currently I have the following problem:

I can't think of a way of implementing input as a system. Currently I just check for key presses in the main loop, like this:

```
if (glfwGetKey(Window, GLFW_KEY_A) == GLFW_PRESS)
    Camera.Translate(glm::vec2(-5.0f, 0.0f) * static_cast<float>(DeltaTime));

```

Here I check if key A is pressed, and if it is I move the camera, which isn't a component associated with an entity.

So what I thought is creating an Entity with a Input component associated (this component would have mouse coordinates, keys pressed, etc):

```
ECS::Entity * InputManager = EntityWorld->create();
InputManager->assign<Input>();

```

Then, each frame, after polling events, I would update the Entity directly like this:

```
InputManager->get<Input>()->MousePosition = MousePosition;
InputManager->get<Input>()->MouseWheelDelta = MouseWheelDelta;
....

```

Then, I'd have an InputSystem, where I can check mouse position, if some key is pressed, etc. But what I don't understand is, if the camera is not a component, how could I make it move now that I handle input through the InputSystem? If I make the camera a component, how would I implement all the functionality to move it around, and zoom in and out?

Let me know if something it's not clear.

# Answer
I think you're pretty close.

Here is one option, which I'd try to implement first. You need 2 components

* `Input`
* `Camera`

I assume you'd create an entity and add them like this:

```
ECS::Entity * UserCameraManager = EntityWorld->create();
UserCameraManager->assign<Input>();
UserCameraManager->assign<Camera>(getMainUserCamera());

```

Each frame, your `InputSystem` fetches all relevant information regarding the input (e.g. mouse, keyboard, joystick), and stores it in the `Input` component.

Then, the system that takes care of the camera (e.g. `CameraSystem`), updates all the entities that have both of these components, `Input` and `Camera`. (Yes, that's going to be only one pair, but that's ok.)

The `update(Input, Camera)` function will take the 'raw' input from the `Input` component, and 'translate' it to commands to move the `Camera`

```
CameraSystem::update(Input input, Camera camera)
  if ( input.isKeyPress(Input::A) || input.getMouseXScreenRatio() < 0.01 )
      camera.getCamera()->Translate(glm::vec2(-5.0f, 0.0f) * static_cast<float>(DeltaTime));

```

---

Now, it's a bit silly because all the instances of `Input` would be the same, so you might want to bend your ECS rules a bit to have an 'empty' `Input` component and use it only as something like a tag, letting those system that needs it poll an actual, more global `InputManager` instead of the component. (Or use it to store a reference to the more global input manager.)

So instead, each frame, the `InputSystem` fetches all relevant information regarding the input (e.g. mouse, keyboard, joystick), and stores it within itself, ready for polling.

```
ECS::Entity * UserCameraManager = EntityWorld->create();
UserCameraManager->assign<Input>(getGlobalInputManager());
UserCameraManager->assign<Camera>(getMainUserCamera());

CameraSystem::update(Input input, Camera camera)
  if ( input.getInputManager()->isKeyPress(Input::A) || input.getInputManager()->getMouseXScreenRatio() < 0.01 )
      camera.getCamera()->Translate(glm::vec2(-5.0f, 0.0f) * static_cast<float>(DeltaTime));

```

---

We programmers *love* layers. So let's add another layer onto it.

You need 3 components

* `Input`
* `Camera`
* `CameraController`

Let's re-use the `InputSystem` from the previous option, which updates the `Input` component (or a more global alternative).

Then let's use a System that will translate the 'input' into 'actions':

```
SystemCameraControl::update(Input input, CameraController cameraController)
  cameraController.resetValues()
  if ( input.getInputManager()->isKeyPress(Input::A) || input.getInputManager()->getMouseXScreenRatio() < 0.01
    cameraController.moveLeft(5)

```

Then the other system takes care of converting the 'actions' into 'implementation':

```
CameraSystem::update(CameraController cameraController, Camera camera)
  if ( cameraController.shouldMove() )
    camera.getCamera()->Translate(cameraController.getDisplacementPerSec() * static_cast<float>(DeltaTime));

```

This option is really there to let you add some other components that will control the camera in a different way: when you'll want to have your camera automatically follow a spline, for instance, it might be a bit easier to think about it like this.

And this is to hint you could eventually have other entities be controlled: the main character will be moved like this, but you'll also have to move AI characters, for instance.

Of course, you don't *need* that extra component, at least now, but that's an option.

---

To address your questions from the comments:

> When adding the Camera component to the entity in your example, the getMainUserCamera() function would return a Camera object? I thought that components are structs with data that we are not supposed to have an instance of, and should be managed with the systems.

There are no rules that say that you have to put *everything* in your ECS: you can limit the ECS to what makes sense. IMHO, it makes perfect sense to have your rendering engine or your physics engine not an integral part of your ECS. You can use your ECS components to *refer* to objects in your non-ECS software parts.

This is the case in this example, `getMainUserCamera()` would return a reference to the Camera that is part of this non-ECS software part. Your `Camera` component is used to link the two software parts together. It's still 'data'. The data is a pointer to something else.

If it makes more sense to you, you can have the `CameraSystem` create the `Camera` component, since they'll most likely have to interface with the Rendering part of your software.

> How would the InputSystem fetch the raw input? The only thing I can think of is accessing the entity that has the input component directly before ticking all systems in the main loop, not in a system.

Assuming that you don't want to repeat Input data in eacn `Input` component, you could have something like this (pseudo-c++):

```
class InputState
{
  public:

    enum Key
    {
      A = GLFW_KEY_A,
      B, C //...
      Z,
      NUM_KEYS = Z - A + 1
    };

    enum Mouse
    {
      ButtonLeft,
      ButtonMiddle,
      ButtonRight,
      NNUM_MOUSE_BUTTONS
    };

    enum ButtonState
    {
      DOWN,
      JUST_DOWN,
      RELEASED,
      JUST_RELEASED
    };

    bool isKeyDown(Key aKey) { return mKeyState[aKey - 'A'] == DOWN || mKeyState[aKey - 'A'] == JUST_DOWN; }
    bool isKeyJustDown(Key aKey) { return mKeyState[aKey - 'A'] == JUST_DOWN; }
    bool isMouseDown(Mouse aMouseButton) // ...

    // This has to be called before anything related to input is updated
    void perFrameUpdate()
    {
      // Update the keys
      for ( char i = Key::A; i <= Key::Z; ++i )
      {
        int vectorIndex = i - Key::A;
        bool isKeyDown = glfwGetKey(Window, i) == GLFW_PRESS;

        ButtonState lastKeyState = mKeyState[vectorIndex];

        if ( isKeyDown && lastKeyState == ButtonState::JUST_DOWN )
          mKeyState[vectorIndex] = ButtonState::DOWN;
        else if ( isKeyDown && ( lastKeyState == ButtonState::RELEASED || lastKeyState == ButtonState::JUST_RELEASED )
          mKeyState[vectorIndex] = ButtonState::JUST_DOWN;
        else if // ...
          // ...

      }

      // Do the same for mouse
    }

  private:

    std::vector<ButtonState> mKeyState;
    std::vector<ButtonState> mMouseState;

}

// This is your `Input` component
struct Input
{
  explicit Input( InputState& aGlobalState ) : mInputState( aGlobalState ) {}

  InputState& mInputState;
}

// This is your `Camera` component
struct Camera
{
  explicit Camera( Render::Camera* aCamera ) : mCamera( aCamera ) {}

  Render::Camera* mCamera;
}

class SystemCamera
{
  public:
    static void update_CameraInput( std::vector<ECS::Entity*>& aEntities, double DeltaTime )
    {
      Camera& camera = aEntities->get<Camera>();
      Input& input = aEntities->get<Input>();

      if ( input.mInputState.isKeyDown(InputState::A) || input.mInputState.getMouseXScreenRatio() < 0.01 )
          camera.mCamera->Translate(glm::vec2(-5.0f, 0.0f) * static_cast<float>(DeltaTime));
    }
}

// Main loop
class Game
{
  public:

    void init()
    {
      mMainCamera = // RenderManager::GetOrCreateMainCamera();

      ECS::Entity * UserCameraManager = EntityWorld->create();
      UserCameraManager->assign<Input>(mInputState);
      UserCameraManager->assign<Camera>(mMainCamera);
      mEntities.push_back( UserCameraManager );
    }

    void run()
    {
      while(true)
      {
        mInputState.perFrameUpdate();

        // No need for an additional system to update the `Input` component, as they all refer to the same up-to-date mInputState.
        std::vector<ECS::Entity*> entitiesThatHaveInputAndCamera = getRelevantEntities<Camera, Input>(mEntities);

        SystemCamera::update_CameraInput(entitiesThatHaveInputAndCamera, DeltaTime);
      }
    }

  private:

    InputState mInputState;
    std::vector<ECS::Entity*> mEntities;

    Render::Camera* mMainCamera;
}

```
> 5 votes

---
Tags: c++, architecture, entity-component-system
---


# Question
Title: Adding -90 degree Y rotation into script
I'm using the following script to move a spray bottle around a head.

It should looke like in a barber shop.

The code works fine: I have assigned the script to the spray bottle, and I have set the head as the target.

One thing that is wrong is that the spray bottle needs to have a -90 yaw rotation in order to face the head.

I have tried the wildest things to include these -90 degrees, all produced weird results.

Could anybody state how to include this -90 Y rotation into the script?

Thank you very much!

```
using UnityEngine;
using System.Collections;

[AddComponentMenu("Camera-Control/Mouse Orbit with zoom")]
public class MouseOrbitImproved : MonoBehaviour {

public Transform target;
public float distance = 5.0f;
public float xSpeed = 120.0f;
public float ySpeed = 120.0f;

public float yMinLimit = -20f;
public float yMaxLimit = 80f;

public float distanceMin = .5f;
public float distanceMax = 15f;

private Rigidbody rigidbody;

float x = 0.0f;
float y = 0.0f;

// Use this for initialization
void Start ()
{
    Vector3 angles = transform.eulerAngles;
    x = angles.y;
    y = angles.x;

    rigidbody = GetComponent<Rigidbody>();

    // Make the rigid body not change rotation
    if (rigidbody != null)
    {
        rigidbody.freezeRotation = true;
    }
}

void LateUpdate ()
{
    if (target)
    {
        x += Input.GetAxis("Mouse X") * xSpeed * distance * 0.02f;
        y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;

        y = ClampAngle(y, yMinLimit, yMaxLimit);

        Quaternion rotation = Quaternion.Euler(y, x, 0);

        distance = Mathf.Clamp(distance - Input.GetAxis("Mouse ScrollWheel")*5, distanceMin, distanceMax);

        RaycastHit hit;
        if (Physics.Linecast (target.position, transform.position, out hit))
        {
            distance -=  hit.distance;
        }
        Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);
        Vector3 position = rotation * negDistance + target.position;

        transform.rotation = rotation;
        transform.position = position;
    }
}

public static float ClampAngle(float angle, float min, float max)
{
    if (angle < -360F)
        angle += 360F;
    if (angle > 360F)
        angle -= 360F;
    return Mathf.Clamp(angle, min, max);
}
}

```

# Answer
> 2 votes
Here are four ways to solve this problem...

**First:**

In the general case, the easiest way to adjust the rotation of something in Unity is to wrap it.

1. Create a new empty GameObject called "parent"
2. Take the visual object you want to rotate and make it a child of this parent.
3. Take whatever animation/script/etc had been manipulating the visual object directly, and make it act on the parent object instead.

Now your visual object's orientation (and translation offset & scale) is decoupled from whatever the script is assigning, so you can rotate it relative to its parent to achieve whatever outcome you want. You can even do this in the scene view with the rotation gizmos, to visually match the look you want, if you have trouble visualizing it from the raw code/numbers.

---

**Second**, specifically when your script is assigning:

```
transform.rotation = rotation;

```

You can add an extra "shim" rotation to bias the result by any amount you like. eg...

```
transform.rotation = rotation * Quaternion.Euler(0, -90, 0);

```

This applies a -90 degree Y rotation about the local yaw axis *before* whatever the `rotation` want to do to the object. To apply this after / around the world Y axis, just flip the order of the multiplication.

---

**Third**, because you're calculating your rotation via:

```
Quaternion rotation = Quaternion.Euler(y, x, 0);

```

You can just offset this rotation directly:

```
Quaternion rotation = Quaternion.Euler(y, x - 90, 0);

```

Note however that since you're calculating `position` based on `rotation`, this will rotate your position by 90 degrees too - so you might want to adjust this by changing how you build `Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance)` or use one of the solutions above that leaves position unaffected.

---

**Fourth**, your script as-written already has a solution to this problem built-in:

```
void Start ()
{
    Vector3 angles = transform.eulerAngles;
    x = angles.y;
    y = angles.x;
    //...

```

This says "whichever way we're oriented when the scene loads / when I spawn into the scene, use that orientation as the starting/neutral point for any future motion".

So, just turn you object 90 degrees in your scene before you enter play mode (or rotate it 90 degrees when you spawn it with `Instantate()`) and the script will pick up that starting rotation automatically.

Similar to point 3, this will mean tweaking the way you assign the position so it acts at 90 degrees to the rotation.

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


# Question
Title: Variable from class doesn't show in editor
this may be another beginner question. I have a simple data holding script and want to pass one variable from it as parameter to a function. But in the editor it only shows me the script name, not the option of any variable. What attribute or change do I need to make to make the variable visible for selection? (Passing the whole object works, but I don't like the parsing of the object inside the called method and would just to pass the parameter directly) Picture for easier understanding.

# Answer
A `UnityEvent`, like the `Button`'s `OnClick` event acts on *methods*, not on variables.

The reason it looks like it's setting variables in the cases you showed is that it's acting on something in C# called a property. That's where you define something like this:

```
int _internalValue;
public int exposedValue {
    get {
        return _hiddenValue;
    }
    set {
        _hiddenValue = value;
    }
}

```

This creates something that *looks* to your code like it's a variable: I can say `exposedValue = 5` or `if(exposedValue > 0)` for example. But it "de-sugars" to methods: `SetExposedValue(5)` or `if(GetExposedValue() == 5`.

This is syntactic sugar to make it easier to write and work with simple getter and setter methods common in certain programming styles/patterns. In practice we'll often put validation/update/copying logic inside these methods, or make the getter or the setter private, to ensure outside interference can't put our internal hidden variables into an invalid state.

C# will let you sweeten this even more for simple cases that don't need extra logic, with an auto-implemented property:

```
public int exposedValue { get; set; }

```

Here we don't even have to explicitly declare and manipulate our "backing store" variable `_hiddenValue` \- the compiler generates code equivalent to the example above.

Since the `set` part of this property is a method that takes one argument, our `UnityEvent` can call it - as long as the argument (the type of our property) is a primitive type (eg. `int`, `float`, `string`, `bool`...) or something descending from `UnityEngine.Object` (eg. `GameObject`, `ScriptableObject`, `Component`/`MonoBehaviour`/descendents, `Material`, `Texture`...)

So your `Tile.tag` & `Tile.name` examples are referencing the *setter methods* of the *properties* called `tag` and `name`, not variables.

Since your `TileHelper` isn't a primitive type or descended from `UnityEngine.Object`, we won't be able to assign the whole object with a button click event this way. But we could add some properties to set parts of it at a time:

```
public TileHelper tileHelper;

public string tileHelper_CorrespondingLevel {
    set { tileHelper.correspondingLevel = value; }
}

```

This will expose the tileHelper's `correspondingLevel` field to be set by a `UnityEvent`.

Or, you could make your helper class derive from `ScriptableObject` to assign it all at once by reference to an asset in your assets folder.
> 3 votes

---
Tags: unity, ngui
---


# Question
Title: Get Cartesian coordinates from isometric coordinates
```
Coordenadas: X:140 Y:279
Coor Isometricas:128/69
X: 2  Y: 1.
CoordenadasConversas: 69:214.

```

CoordenadasConversas should be equal to Coordenadas.

CoordenadasConversas does not work. The function I use is CoordenadaAIsometrico() - see below.

I applied the formula to convert from isometric to Cartesian, but it does not seem to work.

```
float cartesianX = (2.0f * isometricY + isometricX) * 0.5f;
float cartesianY = (2.0f * isometricY - isometricX) * 0.5f;

```

```

function Isometrico(){

    ctx.save();

    ctx.translate(0, 300);

    ctx.scale(1, 0.5);

    var radianes=-45 * Math.PI /180;

    ctx.rotate(radianes);
}

function CorIsometrico(xI,yI){

    yI=yI-300;

    yI=yI*2;
    var angle = ((-45 * Math.PI /180) * -1)
    var x2 = xI;

    var y2 = yI;
    var cos = Math.cos(angle);
    var sin = Math.sin(angle);

    var xI2 = Math.floor(x2 * cos - y2 * sin);
    var yI2 = Math.floor(x2 * sin + y2 * cos);

    console.log("Coor Isometricas:" + xI2  + "/"+  + yI2 );

    CoordenadaAIsometrico(xI2,yI2);
}

function CoordenadaAIsometrico(Xc,Yc){

    var Xcc = (2 * Yc + Xc) * 0.5;

    var Ycc = (2 * Yc - Xc) * 0.5;

    //Xc=Xc-50;
    //Yc=Yc+300;

    console.log("CoordenadasConversas: " + Xcc + ":" +  Ycc);
}

```

# Answer
Thanks. The answer was to reverse your formula:

```
function IsometricoACartesiano(xI5,yI5){
    var angle2 = ((45 * Math.PI /180) * -1);
    var x22 = xI5;
    var y22 = yI5;
    var cos = Math.cos(angle2);
    var sin = Math.sin(angle2);

    var xI2 = Math.floor(x22 * cos - y22 * sin);
    var yI2 = Math.floor(x22 * sin + y22 * cos);
    yI2=yI2/2;
    yI2=yI2+300;
    console.log("U: " + xI2 + "/" + yI2 );
    context.restore();
    context.drawImage(habbo, xI2, yI2,ancho,alto);
  }

```
> 1 votes

---
Tags: isometric, coordinates
---


# Question
Title: Should your world map have it's own collision object?
I am attempting to understand collision detection at the moment. I have seen many examples of a simple flat plane with boxes or cubes which move around on the plane and react when the touch each other (or stop at the plane when dropped).

What I am not finding though are more advanced examples where instead of just a flat plane, your map is made up of hills, buildings, walls, etc.

Since all of the examples I have found this far use simple primitive collision object types (`boxes` and `spheres`), I am curious what the best approach would be for creating a collision object for something like a game map (like dust2 in counter-strike).

After reading through the bullet documentation I found that you can create a collision object from a triangle mesh, which leads me to believe this might be the best approach. However if your map consists of complex geometry (say hundreds of thousands of verticies and faces), would this be too detailed to use as a collision mesh? Would it then be better to create a separate collision version of the map which is made of simple low poly shapes?

My gut is saying "go with the separate low poly version", but if there is no reason for the extra work, it would make more sense to just use the high poly mesh.

# Answer
> 1 votes
Generating collision from the mesh itself is the usual approach for terrain. This is especially not a performance issue on counter strike-sized maps, as long as you keep the vert density at a somewhat sane value (0.5-10m).

If your level is already very geometric, or you need to have perfectly flat collision surfaces for some reason, look into replacing the collision with a bunch of collision boxes.

---
Tags: collision-detection, bullet-physics
---


# Question
Title: How can I Serialize other MonoBehaviour class for showing in inspector?
I have variables in my script but I can access these variables from other script but I want see them in other script without define again. I know about `[System.Serializable]` but I don't know how can I use for `MonoBehaviour` classes

like this:

```
using UnityEngine;
using System.Collections;

public class variables : MonoBehaviour {
    public static variables instance;
    public int health;
    public int bullets;

    void Awake(){
        instance = this;
    }
}

```

I want show variables class in below class's inspector

```
using UnityEngine;
using System.Collections;

public class access : MonoBehaviour {
// I have to define again variable for showing in inspector
public int bulletsAccess;
public int healthAccess;

void Update () {
    variables.instance.bullets = healthAccess;
    variables.instance.health = bulletsAccess;
  }
}

```

# Answer
> 2 votes
Do it like this :

```
using UnityEngine;
using System.Collections;
[System.Serializable]
public class Variables {

    public int health;
    public int bullets;

}

```

Then in your second class you simple define a field of type Variables

```
using UnityEngine;
using System.Collections;
    public class Access : MonoBehaviour
    {
         public Variables my_vars;// Now you will see a my_vars property in the inspector window of the Access component
    }

```

Friendly tip always name your classes with a capital letter.

# Answer
> 1 votes
As @Uri-Popov says, you can use the `System.Serialize` attibute to create an object that appears in the Inpector whenever it's included in your MonoBehaviour.

Depending on what you're actually storing in `variables` (i.e. if that class represents a player, actor, or gun) you may want to consider just extending the `access` object.

For example, if you have a `Player` class, but players and enemies share common properties and methods, you can extend them so that a common `Actor` class holds that informateion.

For example, your Actor may look like this:

```
using UnityEngine;

public class Actor : MonoBehaviour {
    public int Health;
    public int Bullets;
}

```

And then a player would look like this:

```
public class Player : Actor {
    void Update() {
        // Do player specific update tasks
    }
}

```

When you add the `Player` script to a GameObject the Health and Bullets properties will both be pulled through as if they belong to that class.

I realise your question was specific to Serialisation, but this may be a better solution to your problem, depending on what your ultimate aim is

# Answer
> 0 votes
The answer to the question is: ScriptableObject. That's what they're for.

Put your variables in a ScriptableObject and Unity will handle the serialisation and give you a custom editor and other nice features. Recommended.

# Answer
> -1 votes
***TL;DR:*** Uri has a good answer if you want to share functions, as well. If its just variables, follow the answer but with `struct` replacing `class`. If variables are shared because the other classes are similar in nature, it might be a good idea to inherit, more advantages listed below. If your still having trouble, you might be having problems with your keyword and/or attribute usage.

Above all else, you describe changing the values so that *all* instances change, including changes made directly to the "variables" script. You will most likely want to set each variable in "variables" to `static` to set up this behavior.

## `struct` is better if you only store variables to share.

If you only intend to share *variables*, you may want to consider using `struct` instead of a `class`. What is the difference, you may ask? Well, a `struct` is designed to hold a set of variables. A `class` is designed to *also* store *functions*. Generally, if you do not intend to hold any functions in your "variables" script, you would use a `struct` instead of a `class`. They pretty much work the same way, for the purpose of implementation.

```
[System.Serializable]
public struct Variables
{
    public int health;
    public int bullets;
}

public class MainScript
{
    public Variables variables;
}

```

## *Inheritance* is better if you want to share common functionality

***Hobnob*** addresses this in their answer, but I felt I should provide greater insight to help you determine if this is the right solution. Either way, inheritance is a powerful tool at your disposal. Sooner or later, it will make your life **a lot** easier, so take five minutes and watch the Unity tutorial video on it, if you are unfamiliar with the concept.

Basically, any class that *inherits* from another *automatically* passes in the variables and functions of the base class. For reference sake, the original class is referred to as the "parent", with the 'inheriting' class referred to as the "child".

```
public class Variables
{
    public int health;
    public int bullets;
}

public class MainScript : Variables
{
    // I can already see health and bullets;
    // They will also show under me in the Inspector.
}

```

There are other advantages you want to consider, that might provide greater functionality for you. Some of these advantages include:

* Children classes also inherit the parent functions, but can override them with their own logic. You can even call back to the parent logic with `base.`, if you need to 'do the same thing, but do something else before or after'.
* Children can all be classed as `typeof(parent)`, which is especially useful if you are looking for a particular 'base class' of objects. For example, if you wanted to look for *all* enemy scripts, but many were "specialized" variants. In the above example, you could successfully store `MainScript` in a reference for `Variables`. *This does limit your functionality*1, but is still *very* useful.
* It allows you to put all common function in one place, allowing you to reuse your code.

## Keywords and Attributes will provide greater functionality

The above suggestions may not get you where you want *on their own*. The addition of several keywords and attributes may give you greater functionality, and can mostly be used along with the above examples.

* `static`: You already know this one from your self-reference, but it sounds like this will definetly be using it. `static` means there will only ever be one instance. For example, if instance A of your script changes a static variable, it will also change in instance B of your script.
* `const`: Likely unwanted, but this sets the variable as "finalised", so that you can not change it. Good if you just want to reference a hard-coded value. Bad if you want to modify it from another script.
* `protected`: An access modifier, much like `private` and `public`. The difference is that, while `protected` variables will be as inaccessible as `private` fields to outside references, they will still be accessible to classes that inherit from that class. Likewise, `private` variables *will not* be accessible through inheritance.
* `virtual`: A function keyword that effectively marks that function as "overload-able". If you wish to overwrite a function from a parent class, the function needs to be marked as `virtual` in the parent class.
* `overload`: A function keyword that effectively marks that function as an "overwrite" of a parent class of the same name. You can only `overload` `virtual` functions, and you can still call back to the parent function with `base.<function name>`.
* `[System.Serializable]`: An attribute that tells Unity to serialise the below class or struct, to display it in the Inspector. As mentioned in the above answers, you need to use this if you include that class as a reference in another class, where you want its values to be drawn to the inspector.
* `[Serialize]`: An attribute that tells Unity to serialise the below variable, to display in the Inspector. You almost never need to use this, but this attribute will allow you to display `private` variables in the Inspector.

1 I have had experience before where you would store `MainScript` as a type of `Variables`, but only gain access to the functionality listed under `Variables`. I have previously assumed this to be a constraint of inheritance, but since have found bug reports where Unity will break inheritance with use of various serialisation-based attributes that I would commonly use in these situations. As such, I can neither confirm nor deny what limits are *real*, what were caused by *bugs* and what *were* caused by bugs but have since been fixed. Any comments to clarify would be very much appreciated.

# Answer
> -2 votes
Maybe using \[HideInInspector\] behind each variable in your second class will be a good choice.

But I suggest to make something cleaner, like custom inspector!

**EDIT:** I was outside, and I posted this using my mobile phone.

You should use inheritance, as I read your question better, as other said, the best choice is use this.

Also, I add, if you want to make private your class properties, you can still use \[SerializeField\] to make them available from Inspector.

Maybe, you can make it a little bit more messy:

```
using UnityEngine;
using System.Collections;

public class Variables : MonoBehaviour
{
    [SerializeField] private int health;
    [SerializeField] private int bullets;
}

```

You can import the following script only, and save a little bit more time:

using UnityEngine; using System.Collections;

```
public class Access : Variables
{
   void Update ()
   {
      base.Update(); //You can call Variable's Update method from child.
      //Do your work here!
   }
}

```

Good luck.

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


# Question
Title: How to move gameobject with touch on Android
I'm trying to make a game where you control a character via touch on Android devices.

The player will have two degrees of movement.

When you touch the touch screen and move your finger, the game object should move to your finger's location and follow your finger as you move it.

Here is an example of what I'm trying to do: http://www.youtube.com/watch?v=OoqRC8QptzM#t=01m01s (@ 1:02).

I already know I need to use Input.touches.

I've tried using Transform.translate and Vector3.Lerp, neither gave me the results I wanted.

Here is some of the code I've tried using:

```
#pragma strict

var speed : float = 1;

function Start () {

}

function Update () {
    if (Input.touchCount > 0 &&
        Input.GetTouch(0).phase == TouchPhase.Moved) {

        // Get movement of the finger since last frame
        var touchDeltaPosition:Vector2 = Input.GetTouch(0).deltaPosition;

        var touchPosition:Vector3;

        touchPosition.Set(touchDeltaPosition.x,
                           transform.position.y,
                           touchDeltaPosition.y);

        // Move object across XY plane
        transform.position = Vector3.Lerp(transform.position,
                                                touchPosition,
                                                Time.deltaTime*speed);
    }

}

```

# Answer
> 3 votes
I think you need to translate screen to world space.

Camera.ScreenToWorldPoint

# Answer
> 0 votes
I imagine you're working with an ortographic camera. With them, the position of the elements work with the X and Y elements defining the position on screen and the Z element defining its depth.

Check this link on how to use DeltaPosition: Input.GetTouch

# Answer
> 0 votes
The script does the same using `Vector3.Lerp` and at a constant speed regardless of the distance between the two points..

```
using UnityEngine;
using System.Collections;

public class TapToMove : MonoBehaviour {
//flag to check if the user has tapped / clicked.
//Set to true on click. Reset to false on reaching destination
private bool flag = false;
//destination point
private Vector3 endPoint;
//alter this to change the speed of the movement of player / gameobject
public float duration = 50.0f;
//vertical position of the gameobject
private float yAxis;

void Start(){
    //save the y axis value of gameobject
    yAxis = gameObject.transform.position.y;
}

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

    //check if the screen is touched / clicked
    if((Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) || (Input.GetMouseButtonDown(0)))
    {
        //declare a variable of RaycastHit struct
        RaycastHit hit;
        //Create a Ray on the tapped / clicked position
        Ray ray;
        //for unity editor
        #if UNITY_EDITOR
        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        //for touch device
        #elif (UNITY_ANDROID || UNITY_IPHONE || UNITY_WP8)
        ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
        #endif

        //Check if the ray hits any collider
        if(Physics.Raycast(ray,out hit))
        {
            //set a flag to indicate to move the gameobject
            flag = true;
            //save the click / tap position
            endPoint = hit.point;
            //as we do not want to change the y axis value based on touch position, reset it to original y axis value
            endPoint.y = yAxis;
            Debug.Log(endPoint);
        }

    }
    //check if the flag for movement is true and the current gameobject position is not same as the clicked / tapped position
    if(flag && !Mathf.Approximately(gameObject.transform.position.magnitude, endPoint.magnitude)){ //&& !(V3Equal(transform.position, endPoint))){
        //move the gameobject to the desired position
        gameObject.transform.position = Vector3.Lerp(gameObject.transform.position, endPoint, 1/(duration*(Vector3.Distance(gameObject.transform.position, endPoint))));
    }
    //set the movement indicator flag to false if the endPoint and current gameobject position are equal
    else if(flag && Mathf.Approximately(gameObject.transform.position.magnitude, endPoint.magnitude)) {
        flag = false;
        Debug.Log("I am here");
    }

    }
    }

```

You can refer this link for more info

# Answer
> 0 votes
You can try the following script

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

public class SelectObject : MonoBehaviour {

    // Use this for initialization
    GameObject hitObj;
    RaycastHit hit;
    private float speed = 1;

    void Start () {

    }

    // Update is called once per frame
    void Update () {
        foreach (Touch touch in Input.touches) {
            switch (touch.phase) {
                case TouchPhase.Began:
                    Ray ray = Camera.main.ScreenPointToRay (touch.position);
                    if (Physics.Raycast (ray, out hit, 10)) {
                            hitObj = hit.collider.gameObject;
                    }
                    break;
            case TouchPhase.Moved:

                // If the finger is on the screen, move the object smoothly to the touch position
                float step = speed * Time.deltaTime; // calculate distance to move
                if(hitObj != null)
                    hitObj.transform.position = Camera.main.ScreenToWorldPoint(new Vector3 (touch.position.x, touch.position.y, hitObj.transform.position.z));
                break;
            }
        }
    }
}

```

---
Tags: android, unity, ios, touch
---


# Question
Title: Applying Y offset to rotation / position script
I'm using the script stated below to move a spray bottle around a head.

The code works fine: I have assigned the script to the spray bottle, and I have set the head as the target.

However, I was not happy with the center that Unity seems to use for the spray bottle. The spray bottle never perfectly aimed at the center of the head.

To find out what is going on here, I added a long sphere to the spray bottle. Then I moved the sphere until it would perfectly visualize the center that Unity uses. As once can see, Unity uses the bottom of the spray bottle as its center. I have uploaded a video here to show the effect.

I imagined that I need to tell the script that the center of the spray bottle is different. I would have to include an offset (I guess a Vector3) in order to set the nozzle as the center.

I haven't been able to find out how to plug this "offset" into the script.

Can anybody tell me where / how I could do that?

Thank you very much!

```
using UnityEngine;
using System.Collections;

[AddComponentMenu("Camera-Control/Mouse Orbit with zoom")]
public class MouseOrbitImproved : MonoBehaviour
{

public Transform target;
public float distance = 5.0f;
public float xSpeed = 120.0f;
public float ySpeed = 120.0f;

public float yMinLimit = -20f;
public float yMaxLimit = 80f;

public float distanceMin = .5f;
public float distanceMax = 15f;

private Rigidbody rigidbody;

float x = 0.0f;
float y = 0.0f;

// Use this for initialization
void Start()
{
    Vector3 angles = transform.eulerAngles;
    x = angles.y;
    y = angles.x;
}

void LateUpdate()
{
    if (target)
    {
        x += Input.GetAxis("Mouse X") * xSpeed * distance * 0.02f;
        y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;

        Quaternion rotation = Quaternion.Euler(y, x, 0);

        Vector3 nTargetPos = target.position + new Vector3(0, 0.1f, 0);//10 centimetres lower. The original target.position's center would be around the nose. Instead I want the forehead to be the center, that's why I add 10 centimeters to the y position.

        Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);
        Vector3 position = rotation * negDistance + nTargetPos;

        transform.rotation = rotation * Quaternion.Euler(0, -90, 0);//compensate for the fact that the spray bottle should face the head (requiring yaw to be yaw-=90)
        transform.position = position;
    }
}

```

# Answer
> 1 votes
Things will be much simpler if you create another GameObject, put a GameObject with bottle model inside it, and adjust position and rotation of inner GameObject so the bottle should aim straight at its center. Then you can just set position of that outer GameObject to the point where the bottle should aim, and it will aim correctly with any rotation of outer object.

If you want to alter distance from bottle to target, change `localPosition` of inner object (most probably only z).

---

Okay, I made a working example.

There are:

* **man** \- the object where bottle should aim
* **botl** \- the object which contain elements of the bottle.
* **aimed botl** \- the object which contains the bottle rotated and moved to aim at *local* (0, 0, 0). The distance to target also adjusted here.

There is a script on **aimed botl** based on your script.

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

public class NewBehaviourScript : MonoBehaviour {

    public Transform target;
    public float xSpeed, ySpeed;
    float x, y;

    void Start () {
       var angles = transform.eulerAngles;
       x = angles.y;
       y = angles.x;
    }

    void Update () {
        if (target) {
            x += Input.GetAxis ("Mouse X") * xSpeed;
            y += Input.GetAxis ("Mouse Y") * ySpeed;
            y = Mathf.Clamp (y, -30, 75);
            var rotation = Quaternion.Euler (y, x, 0);
            transform.SetPositionAndRotation (target.position, rotation);
        }
    }

}

```

Transform is set to sphere of the **man**.
xSpeed is -5, ySpeed is 2.

That's all.

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


# Question
Title: Unity using raw mocap data without actually moving the character
I play around with animations and unitys raw motion capture data asset pack. My problem is as followed:

I have an idle, walkforward and a runforward animation and play them based on the keyboard input. But i realized when i move my character backwards (using a movement script) but still playing the walkforward animation the character basically moves backward and forward at the same time.

So how can i play the animation but without actually effecting the position of the character?

Thank you

# Answer
> 1 votes
You should simply uncheck “Apply Root Motion” on your Animator component, or you could also go on each animation you are using and check the options that say Lock Position and Rotation.

# Answer
> 0 votes
When recording the walk animation you want to adjust the models rotations while making sure the Positions are not being affected or it will want to move to that position no matter where in the world you are. In your case you can select the character and go into his animation window and remove the positions that are interfering.

I made a quick .gif example of a cubes position and rotation animating at the same time in the animation window and then after removing the position it leaves only the spin without moving position.

---
Tags: unity, animation, mecanim
---


title: Get rotation of camera in Google VR

text:
# Question
Title: Get rotation of camera in Google VR
I'm trying to move child of camera object smooth. To implement that, I need to know the movement of x and y axis, like Input.GetAxis in general PC platforms.

I saw the documentation and examples of Google VR, but there's not much explained well. One thing I found is GvrControllerInput.Gyro, but it's said it's deprecated and use GvrControllerInputDevice.Gyro instead, but there's no Gyro value in GvrControllerInputDevice.

Seems like basic usage is totally changed, so they are not providing static methods, and force to using internal method of the object, but couldn't find any related information about this.

So, how do I get gyro from GvrControllerInputDevice? Or is there an alternative way to make child object rotate smooth from their parent? Any advice will very appreciate it!

# Answer
Check out the Gyroscope class

you can access using `Input.gyro` to get info from several different variables you may want.

you can still use `Input.GetAxis("Vertical")` or "Horizontal" to get the players x and y.
> 0 votes

---
Tags: unity, virtual-reality, google-cardboard
---


# Question
Title: How to change transform.position code to Rigidbody.AddForce?
```
Vector2 vec = new Vector2(horizontal, vertical);
        vec = Vector2.ClampMagnitude(vec, 1);

        Vector3 camF = cam.transform.forward;
        Vector3 camR = cam.transform.right;

        camF.y = 0;
        camR.y = 0;
        camF = camF.normalized;
        camR = camR.normalized;

        transform.position += (camF * vec.y + camR * vec.x) * Time.deltaTime * MoveSpeed;

```

That's how i do my movement, but i need to change it to Rigidbody.AddForce 'cause the way that i use right now makes my character doesn't collide with objects **perfectly.**

**Note:** What i mean with "perfectly" is, if you walk to the corner of walls, you can pass through it and that's the thing that i want to prevent.

# Answer
> 0 votes
The most drop-in solution is to convert your position to a velocity needed to reach that position, then accelerate yourself to that velocity:

```
void FixedUpdate() {
    // Calculate your desired position however you like.
    Vector3 desiredPosition = GetDesiredPosition();

    // What velocity gets us there in one timestep?
    Vector3 desiredVelocity = (desiredPosition - transform.position)/Time.deltaTime;

    // If you want to preserve velocity on the y to let gravity accumulate, uncomment:
    // desiredVelocity.y = body.velocity.y;

    // Apply a sufficient impulse to hit reach that velocity.
    body.AddForce(desiredVelocity - body.velocity, ForceMode.VelocityChange);
}

```

Though generally I'd advise thinking of your control as seeking a target velocity rather than teleporting to a target position. I show an example of that style in this answer.

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


# Question
Title: How do I add collision between two player controlled turtles
How do I add collision between two player controlled turtles? I asked the question before but misunderstood my own groundings on the plan. I cannot figure out how to make two player controlled turtles in the game to hit each other and end the game. This is what I have so far:

```
import turtle
import pygame
import math
import string

wn = turtle.Screen()
wn.bgcolor("black")

#Write Tron

text=turtle.Pen()
text.pencolor("aqua")
text.hideturtle()
text.penup()
text.setposition(150, 300)
text.write("TRON", font=("system", 30))

#Draw border
mypen = turtle.Turtle()
mypen.penup()
mypen.pencolor('white')
mypen.setposition(-300,-300)
mypen.pendown()
mypen.pensize(3)
for side in range (4):
    mypen.forward(600)
    mypen.left(90)
mypen.hideturtle()

pygame.display.update
#Create player 1
player = turtle.Turtle()
player.setposition(240,240)
player.setheading(180)
player.color("red")
player.shape("triangle")

player.speed(0)

#Create player 2
player2 = turtle.Turtle()
player2.setposition(-240,-240)
player2.color("aqua")
player2.shape("triangle")
player2.position()
player2.speed(0)

#Set speed variable
speed = 3

#Define functions
def turnleft():
    player.left(30)

def turnright():
    player.right(30)

def increasespeed():
    global speed
    speed += 3

#Set keyboard bindings for p1ayer 1

turtle.listen()
turtle.onkey(turnleft,"Left")
turtle.onkey(turnright,"Right")

#Define player 2 functions

def turnleft():
    player2.left(30)

def turnright():
    player2.right(30)

def increasespeed():
    global speed
    speed += 3

#Set keyboard bindings for player 2
turtle.listen()
turtle.onkey(turnleft,"a")
turtle.onkey(turnright,"d")
turtle.onkey(turnleft,"A")
turtle.onkey(turnright,"D")

#turtle.onkey(increasespeed,"Up")

while True:
    player.forward(speed)
    player2.forward(speed)

    #Bouandary
    if player.xcor() > 300 or player.xcor() < -300:
        print("GAME OVER")
        quit()
    #Boundary
    if player.ycor() > 300 or player.ycor() < -300:
        print("GAME OVER")
        quit()
    #Bouandary2
    if player2.xcor() > 300 or player2.xcor() < -300:
        print("GAME OVER")
        quit()
    #Boundary2
    if player2.ycor() > 300 or player2.ycor() < -300:
        print("GAME OVER")
        quit()

    #Collision
while True:
  if player.setposition(player.ycor()+10, player.xcor()+10) and player2.setposition(player2.xcor()+10, player2.ycor()+10):
      quit

```

# Answer
The code formatting for your answer has mostly broken down, it would be a lot easier to help you if you fixed it.

What does it mean for turtles to collide? It means that they occupy the same space, so the easiest thing to do is:

```
if player.position() == player2.position():
    print("GAME OVER")
    quit()

```

however, this doesn't quite work because turtle keeps the position as a floating point, so the turtles could be separated by a distance of 0.00000001 and count as not colliding, when anyone would think they would do. One way to get around this is to use math.is\_close. A minimal example of this is:

```
import turtle
import math
import time

player_1 = turtle.Turtle()
player_1.setposition((-100, 0))

player_2 = turtle.Turtle()
player_2.setposition((100, 0))
player_2.left(180)

while True:
    player_1.forward(1)
    player_2.forward(1)

    if(math.isclose(player_1.xcor(), player_2.xcor(), abs_tol=1e-10) and
       math.isclose(player_1.ycor(), player_2.ycor(), abs_tol=1e-10)):
        print("CRASH!")
        print("GAME OVER")
        break

    if player_1.xcor() > 300 or player_1.xcor() < -300:
        print("GAME OVER")
        break

    if player_1.ycor() > 300 or player_1.ycor() < -300:
        print("GAME OVER")
        break

    if player_2.xcor() > 300 or player_2.xcor() < -300:
        print("GAME OVER")
        break

    if player_2.ycor() > 300 or player_2.ycor() < -300:
        print("GAME OVER")
        break

print("Thanks for playing!")
time.sleep(2)

```

Note that if you increase the argument in forward() then this doesn't work. That's because the turtles then "jump" from one position to the other and collisions are only checked in between jumps. It should not be complicated to modify the basic idea here to make that work however.
> 2 votes

---
Tags: python, pygame
---


title: Can't control smoothness in Simple Lit

text:
# Question
Title: Can't control smoothness in Simple Lit
Smoothness slider is not active. Why and how to make it active?

# Answer
Consulting the Unity documentation on the Simple Lit shader, it says:

> # Simple Lit Shader
>
> Use this Shader when performance is more important than photorealism. This Shader uses a simple approximation for lighting. Because this Shader does not calculate for physical correctness and energy conservation, it renders quickly.

And following that second link:

> # Simple Shading
>
> This shading model is suitable for stylized visuals or for games that run on less powerful platforms. With this shading model, Materials are not truly photorealistic. The Shaders do not conserve energy. This shading model is based on the Blinn-Phong model.
>
> In this Simple shading model, Materials reflect diffuse and specular light, and there’s no correlation between the two. The amount of diffuse and specular light reflected from Materials depends on the properties you select for the Material and the total reflected light can therefore exceed the total incoming light. Specular reflection varies only with camera direction.
>
> Light attenuation is only affected by the light intensity.

So, to unpack that a bit:

"Smoothness" is a physically-based way of describing how the material divides incoming light energy between diffuse reflection (rough materials that scatter light all over) and specular reflection (shiny materials with mirror-like reflection)

Since the simple lit shader does not use a physically based model, it does not use the smoothness slider in quite the same way as the other built-in materials.

Under the "Advanced" parameter fold-out, you'll find a checkbox for "Specular Highlights"

* If this is unchecked, then the object is rendered with pure diffuse rendering (ie. maximally rough), and the specular map, specular colour, smoothness, and smoothness source parameters are all disabled.
* If this is checked, then the specular colour/map parameters affect the colour & brightness of the specular highlight (often called the "specular colour" or "specular intensity" in Blinn-Phong shaders), and the smoothness slider affects the size/sharpness of the specular highlight (often called "specular power")

So, what you can do if you need control over smoothness:

* Switch to the "Lit" shader to use physically-based shading, at a higher rendering cost (profile to find out if this is an issue for your game on your target hardware)
* Stick with the "Simple Lit" shader, and check the "Specular Highlights" box to enable using the slider to control specular power to approximate smoothness, if this Blinn-Phong approximation is sufficient for the look you want
* Or, if neither of these options gives you the look you want with acceptable performance, you can create a new custom shader using these shaders as a starting point, and implement your own lighting model to give you the appearance-vs-performance balance that you need.
> 1 votes

---
Tags: unity
---


title: Hold touch at the screen to move object

text:
# Question
Title: Hold touch at the screen to move object
I'm using unity2D and C#, and I have a code for touch screen:

```
if (Input.touchCount > 0)
    {
        Touch touch = Input.GetTouch(0);

        if (touch.phase == TouchPhase.Began)
        {
            startTime = Time.time;
            startPos = touch.position;

        }
        else if (touch.phase == TouchPhase.Ended)
        {
            endTime = Time.time;
            endPos = touch.position;
            swipeDist = (endPos - startPos).magnitude;
            swipeTime = endTime - startTime;

            if (swipeTime < maxTime && swipeDist > minSwipeDist)
            {
                swipe();
            }

```

And this code for swipe:

```
void swipe()
{
     Vector2 distance = endPos - startPos;
    if (Mathf.Abs(distance.x) > Mathf.Abs(distance.y))
    {
           if (distance.x > 0)
        {
            Debug.Log("Right swipe");
        }
        if (distance.x < 0)
        {
            Debug.Log("Left swipe");
        }
    }
    if (Mathf.Abs(distance.x) < Mathf.Abs(distance.y))
    {
        if (distance.y > 0)
        {
            Debug.Log("Up swipe");
        }
        if (distance.y < 0)
        {
            Debug.Log("Down swipe");
        }
    }
}

```

}

How can I add to this code hold function, for for example move object at the screen?

# Answer
To add a simple drag functionality to your touch code you're going to need to know first what you're moving. This can be done by checking what is under the finger when the touch begins by whatever method you prefer and storing it just like your startTime and startPos.

Once you've got the object that you want to move stored you simply need to update the object's position on touch frames where it hasn't ended or canceled yet (you could probably rely on TouchPhase.Moved but I don't know if TouchPhase.Stationary is completely stationary, which is almost impossible in real use, or just close to it, which would cause a small amount of drift).

You can do this one of two ways: You can track of the difference between that frame and the previous frame's touch position and apply that difference to the touched gameobject's position; or, by also storing the offset of the touch to the object's position when you initially store the object, you can simply set the object's position each frame to that offset from whatever the touch position is.

Regardless of what method you use to move it, at this point all you have to do is make sure to clear the variable(s) you used on ended or canceled to make sure a drag only lasts one touch and you're set!
> 0 votes

# Answer
You can try this,

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

public class SelectObject : MonoBehaviour {

    // Use this for initialization
    GameObject hitObj;
    RaycastHit hit;
    private float speed = 1;

    void Start () {

    }

    // Update is called once per frame
    void Update () {
        foreach (Touch touch in Input.touches) {
            switch (touch.phase) {
                case TouchPhase.Began:
                    Ray ray = Camera.main.ScreenPointToRay (touch.position);
                    if (Physics.Raycast (ray, out hit, 10)) {
                            hitObj = hit.collider.gameObject;
                    }
                    break;
            case TouchPhase.Moved:

                // If the finger is on the screen, move the object smoothly to the touch position
                float step = speed * Time.deltaTime; // calculate distance to move
                if(hitObj != null)
                    hitObj.transform.position = Camera.main.ScreenToWorldPoint(new Vector3 (touch.position.x, touch.position.y, hitObj.transform.position.z));
                break;
            }
        }
    }
}

```
> 0 votes

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


# Question
Title: Gameobject rotation around anchored pivot
I'm looking for the best way to rotate the Camera(EYES) around a center of my character (Player Prototype) because if I turn around, the Camera enter inside the character. My FPS script is attached to Player Prototype, but the Camera isn't because i have to make particular rotation. So I don't know what I have to do.

* Have will I make the parent? If I will make it, Eyes will sum rotations to those of the parent.
* Or maybe I have to handle this in LateUpdate()?
* With RotationAround() I don't understand how to pass the second argument which is a Vector3, but I have a Quaternion.Euler.

So at this point I accept all the advice or examples of what I can do to solve it.

# Answer
> 0 votes
One of the solutions could be: that the player only rotates around the straight line Y and the camera only around the X axis.

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


# Question
Title: Should I compress WebSocket payload data in a game where latency matters?
I have started work on a new game project where users are in an open environment and fight each other in a fast-paced shoot-out. I know that compressing all of the WebSocket's payload data using zlib can be a significant improvement over non-compressed data in terms of bandwidth, but does the latency of packing/unpacking data have more advantages over not packing it?

I know using zlib on the data can have some advantages - less bandwidth and harder for hackers to read the data, but it also has a disadvantage - takes time to \[un\]pack.

Should I use zlib in a game where latency could be the difference between life or death?

# Answer
The time it takes to pack and unpack the data is likely negligible.

But there is a different problem: Compression works best when you have a lot of data to compress. So if you want compression to be effective, you might end up withholding data until you have enough of it that it is worth compressing. This is at odds with the goal of reaching low latency.

Also, most of the data you send in a typical "fast-paced shoot-out" won't be very compressible anyway.

However, there might be situations where you need to send a lot of well-compressible data at once. In these situations, compressing the message payload might be a worthwhile endeavour.
> 1 votes

# Answer
TL;DR: Will compression hurt? No. But it probably won't help you if your goal is a very responsive game.

You have two problems to solve with connectivity...

**Can I get enough data to the client in time?**
In other words, is my bandwidth enough? Is the "pipe" I have to send data big enough to carry the data? If you can't send enough data in time, then compressing it helps as it lets you send more down that pipe in the same amount of time.

**Can I get data to the client fast enough?**
In other words, is my latency low enough? Is there enough "pressure" in the pipe I have high enough to push data quickly? If you can't get data fast enough, then compression doesn't help. If you can send all the data you want, but not fast enough (no matter how small the data packet), latency is important.

Bandwidth ("Can I get enough data to the client on time?") is where compression will help you. Think like streaming a high quality video - you need to send as much as possible as fast as possible. But unless you are watching a live event where seeing what happens immediately is important, you don't care if it's a few seconds behind.

Latency ("Can I get data to the client fast enough?") is where compression will not help you. It doesn't matter how much data you can send if you can't send it fast enough. Compression doesn't make it faster, it just means you can send more. You could want to send only 1 byte really fast, but, if the connection is slow (high latency), compression won't do a thing for you.

So based on your desire for a very responsive game, then no - compression won't help you. That's because you want very low latency. If a player presses a button to trigger an action, you want your message to get to the other player as fast as possible.

If you do think your latency is low but your data still lags, then yes maybe compression will help. But you're better off focusing on
> 1 votes

---
Tags: websocket, compression, latency
---


# Question
Title: How to disable script component while in game?
I'm trying to make a C# script to disable the First person controller script component for my character. I'm doing this so that while I'm controlling something else such as a vehicle, the only control script enabled at the time is the vehicle, and vice versa for when I'm not in the vehicle.

I did find a tutorial on the Unity Web site for Enabling and Disabling components but it uses a light component as an example, and I have no idea of how to do the same thing with a script component. I really appreciate any help I can get to solve this problem.

Thank you

This is the code in C# provided by the tutorial:

```
public class EnableComponents : MonoBehaviour
{
    private Light myLight;

    void Start ()
    {
        myLight = GetComponent<Light>();
    }

    void Update ()
    {
        if(Input.GetKeyUp(KeyCode.Space))
        {
            myLight.enabled = !myLight.enabled;
        }
    }
}

```

# Answer
Assume that you have a script like so:

```
public class CustomScript: MonoBehaviour
{
    void Start ()
    {
     //does some stuff
    }
    void Update ()
    {
     //does some other stuff
    }
}

```

Now, let's also assume you have a gameObject which has this script and also another script to enable / disable this script:

```
public class EnableDisableForCustomScript : MonoBehaviour
{
CustomScript myScript;
    void Start ()
    {
         myScript = gameObject.GetComponent<CustomScript>();
    }
    void Update ()
    {
        if(Input.GetKeyUp(KeyCode.Space))
        {
            myScript.enabled = !myScript.enabled;
        }
    }
}

```

You can also extend the last part with two keys that will enable or disable at will:

```
void Update ()
    {
        if(Input.GetKeyUp(KeyCode.Space))
        {
            myScript.enabled = true; //enable the script when space is pressed
        }
        else if (Input.GetKeyUp(KeyCode.Escape))
        {
            myScript.enabled = false; //disable the script when escape is pressed
        }
    }

```

Remember, you need both scripts on the same object or you need to first find that object in the scene and then the component named as your script.
> 3 votes

# Answer
The only thing you need to change in that script is the call to `GetComponent`. Change `<Light>` to the name of the class which implements your 1st person controller behavior. So when your first person controller is implemented as a `class FirstPersonController : MonoBehaviour`, get a reference to it with `GetComponent<FirstPersonController>()`. The `.enabled` property is inherited from MonoBehaviour, so it is available on every scripted behavior.
> 2 votes

# Answer
You can disable script component by using the following syntax,

```
GameObject.Find("Cube").GetComponent<MoveObject>().enabled = false;

```

Here I disable the MoveObject script from the object named Cube.
> 1 votes

# Answer
Use this:

```
//your other object
public GameObject otherobj;

// your secound script name
public string scr;

void Start () {
    (otherobj.GetComponent(scr) as MonoBehaviour).enabled = false;
}

```
> 0 votes

---
Tags: unity, c#, component-based
---


title: Pygame - Maze collisions problem

text:
# Question
Title: Pygame - Maze collisions problem
I am a beginner in Python and Pygame and I have a problem with my game in pygame. I have Maze class and Player class but I can't do proper collisions. I reached the moment where I have no idea why my code isn't working.

Here is my code:

```
class Maze(pygame.sprite.Sprite):
def __init__(self):
    self.W = 25
    self.H = 14
    self.maze = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
                 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
                 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1,
                 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1,
                 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1,
                 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1,
                 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
                 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1,
                 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1,
                 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1,
                 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1,
                 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1,
                 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1,
                 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ]
def draw(self,screen):
    block_surf = pygame.image.load(os.path.join(img_folder, "new.png")).convert()
    bx = 0
    by = 0
    for i in range(0,self.W*self.H):
        if self.maze[ bx + (by*self.W) ] == 1:
            screen.blit(block_surf,( bx * 40 , by * 40))
        bx = bx + 1
        if bx > self.W-1:
            bx = 0
            by = by + 1

def collisions(self):
    bx = 0
    by = 0
    for i in range(0, self.W * self.H):
        if self.maze[ bx + (by * self.W) ] == 1:

            rect = pygame.Rect(bx * 40, by * 40, 40, 40)

            if rect.colliderect(Player.get_rect):
                pass  # Collision!
                return False

            bx = bx + 1
            if bx > self.W-1:
                bx = 0
                by = by + 1
class Player(pygame.sprite.Sprite):
    def __init__(self): #sprite for a player
        pygame.sprite.Sprite.__init__(self) #for sprite working
        self.image = pygame.image.load(os.path.join(img_folder, "player.png")).convert() #look of the sprite
        self.image.set_colorkey(white) #to delete black things around rect img
        self.rect = self.image.get_rect() #kind of border around it
        self.rect.centerx = width/2 + 40
        self.rect.bottom = height- 120
        self.speedx = 0
        self.speedy = 0
    def update(self): #moving player
        maze = Maze()
        collisions = maze.collisions
        self.speedx = 0
        self.speedy = 0
        keystate = pygame.key.get_pressed()
        if keystate[pygame.K_LEFT]:
            if collisions == False:
                self.speedx = 0
            else:
                self.speedx = -1
        elif keystate[pygame.K_RIGHT]:
            if self.rect.x > 920:
                self.speedx = 0
            # elif self.rect.y <= 636 and self.rect.y > 580:
                # self.speedy = 0
            elif self.rect.x == 40 and self.rect.y < 482 and self.rect.y > 401:
                self.speedy = 0
            elif self.rect.x == 40 and self.rect.y < 399 and self.rect.y > 282:
                self.speedy = 0
            elif self.rect.x == 40 and self.rect.y < 279 and self.rect.y > 160:
                self.speedy = 0
            elif self.rect.x == 40 and self.rect.y < 157 and self.rect.y > 41:
                self.speedy = 0
            else:
                self.speedx = 1
        elif keystate[pygame.K_UP]:
            if self.rect.y < 41:
                self.speedy = 0
            elif self.rect.y == 159 and self.rect.x > 46 and self.rect.x < 160:
                self.speedy = 0
            elif self.rect.y == 281 and self.rect.x > 45 and self.rect.x < 154:
                self.speedy = 0
            else:
                self.speedy = -1
        elif keystate[pygame.K_DOWN]:
            if self.rect.y > 480:
                self.speedy = 0
            elif self.rect.x > 405 and self.rect.x < 634 and self.rect.y > 440:
                self.speedy = 0
            elif self.rect.y == 280 and self.rect.x > 46 and self.rect.x < 155:
                self.speedy = 0
            else:
                self.speedy = 1
        self.rect.x += self.speedx
        self.rect.y += self.speedy
    def get_rect(self):
        return pygame.Rect(self.rect.x, self.rect.y, 40, 40)

```

https://pastebin.com/70fkATnB

Can someone explain to me why it isn't working and help to improve it?

I tried many ideas - even writing from hand positions x and y to create collisions. But it's really bad practice to do so I turned to pygame option sprite.colliderect(sprite2)

https://pastebin.com/70fkATnB

I want to receive information why my code isn't working properly and tips for improving it.

# Answer
I think you are confused between functions/methods themselves, and calling a function/method.

Take the example

```
def square_num(num):
    return num * num

print(square_num)
print(square_num(5))

```

This has output

```
<function square_num at 0x00950858>
25

```

That is. when we use square\_num without any arguments, python returns a reference to the function, but it doesn't evaluate it. When you give it the arguments (or, for a function without arguments, write () after it) then it actually runs the function. As another example:

```
def say_hello():
    print("Hello world!")

say_hello
say_hello()

```

will only print "hello world!" once, only the last line actually runs the function.

Do you understand why the line

```
if rect.colliderect(Player.get_rect)

```

can't work now? It is because you are trying to collide a rect with a function, which is meaningless.

The second mistake in that line is calling get\_rect on the class Player, rather than an instance of that class. Conceptually this is a rather similar distinction as between a function and an execution of that function. There are many many guides online that explain the difference between a class and a class instance (the latter is also called an object).

To cut a long story short, you need to change your functions to

```
def collisions(self, player_instance):
    ....
    if rect.colliderect(player_instance.get_rect()):
        print("We've had a collision!")
    ...

def update(self): #moving player
    maze = Maze()
    collisions = maze.collisions(self)

```

Note, I'd also define the maze in the **init** method of Player rather than recreating it on every update
> 1 votes

# Answer
I think the main problem stems from this

```
collisions = maze.collisions

```

and this

```
if collisions == False:

```

You are setting the value of `collisions` to be a function, when you are apparently trying to call that function and use the result.

I would recommend to learn some debugging techniques so you can check your programs control flow as well as the state of its variables.
> 0 votes

---
Tags: python, pygame
---


# Question
Title: Collision detection problem in monogame C#
```
    protected virtual void CollisionDetection()
    {
        if (CanGoRight() == false) pos.X -= velocity;
    }

    protected bool IsTouchingLeft(Basic2d asset)
    {
        return pos.X + dims.X / 2 > asset.pos.X &&
               pos.X - dims.X / 2 < asset.pos.X &&
               pos.Y + dims.Y / 2 < asset.pos.Y + dims.Y &&
               pos.Y - dims.Y / 2 > asset.pos.Y;
    }

    protected bool CanGoRight()
    {
        foreach (Basic2d asset in Globals.GameAssets)
            if (IsTouchingLeft(asset) == true) return false;
        return true;
    }
}

```

That's my code(just starting) for collision detection. All of this code is in Character class which has also methods for moving and updating and displaying character.

I struggle with collision detection. I have all my assets(blocks) in the list of objects which is in the class named **Globals**. Class character is a subclass of a **Basic2d** class(this is class for all bricks assets).

So I check if a character is overlapping with any of bricks from the list. Criteria for checking left side overlapping is in the **IsTouchingLeft** method and it doesn't work. I cannot see what is wrong with this code, but every time I change sth it works differently but not well.

What should I change?

And the object of **Character** class has an origin point in in the center of the texture, but the object of **Basic2d** class has origin point in the bottom left corner.

# Answer
> 0 votes
Try the method below (just use `hitLeft` for your case):

```
public HitState checkHit(Rectangle r1, Rectangle r2)
{
   HitState retv;
    retv.hit = false;
    retv.hitTop = false;
    retv.hitBottom = false;
    retv.hitLeft = false;
    retv.hitRight = false;
    retv.hitInside = false;
    retv.hitExact = false;

    Rectangle temp1 = Rectangle.Intersect(r1, r2);
    if (temp1.Width == 0 && temp1.Height == 0)
    {
        return retv;
    }

    retv.hit = true;
    if (temp1.Y == r1.Y) retv.hitTop = true;
    if (temp1.Y+temp1.Height == r1.Y+r1.Height) retv.hitBottom = true;
    if (temp1.X == r1.X) retv.hitLeft = true;
    if (temp1.X+temp1.Width == r1.X+r1.Width) retv.hitRight = true;

    return retv;
}

public struct HitState
{
    public bool hit; // true if hit
    public bool hitTop; // true if hit top
    public bool hitBottom; // true if hit bottom
    public bool hitLeft; // true if hit left
    public bool hitRight; // true if hit right
    public bool hitInside; // true if one inside other
    public bool hitExact; // only true if both bounding boxes exact size
}

```

---
Tags: c#, xna, monogame
---


# Question
Title: Multiple glControl on same winform is not working - OpenTK C#
I have to show frames from two cameras in two openGl control separately at same time. For that I have put two opengl control in my form and pass those frames to opengl accordingly. But when running the app, only second opengl control is working. First one is remain with black screen. When i remove the second opengl control first one is working. Means only one is working at a time. Can I solve this? Please check my code. I have created a common class (openTK.cs) for define all function related to opengl and calls it for each glcontrol. Also I created a new GraphicsContext on the thread I want to render my stuff.

```
Bitmap videoFrame = null;//should show this frames in glcontrol1
Bitmap videoFrame2 = null;//should show this frames in glcontrol2
IGraphicsContext control2Context;
openTK obj_openTK = new openTK();//common class for opengl functions
private void Show_Click(object sender, EventArgs e)
{
control2Context = new GraphicsContext(GraphicsMode.Default,glControl2.WindowInfo);
GL.ClearColor(Color.MidnightBlue);
GL.Enable(EnableCap.DepthTest);
TexUtil.InitTexturing();
GL.Hint(HintTarget.PerspectiveCorrectionHint, HintMode.Nicest);
GL.DepthFunc(DepthFunction.Lequal);
GL.ColorMaterial.ColorMaterial
(MaterialFace.FrontAndBack,ColorMaterialParameter.AmbientAndDiffuse);
GL.Enable(EnableCap.ColorMaterial);
GL.Enable(EnableCap.Blend);
GL.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha);
GL.Ext.BindFramebuffer(FramebufferTarget.FramebufferExt, 0); // render per default onto screen, not some FBO

glControl1.Resize += new EventHandler(glControl1_Resize);
glControl1.Paint += new PaintEventHandler(glControl1_Paint);
glControl2.Resize += new EventHandler(glControl2_Resize);
glControl2.Paint += new PaintEventHandler(glControl2_Paint);

Application.Idle += Application_Idle;
glControl1_Resize(glControl1, EventArgs.Empty);
glControl2_Resize(glControl2, EventArgs.Empty);
}
private void Application_Idle(object sender, EventArgs e)
{
while (glControl1.IsIdle)
{
glControl1.MakeCurrent();
Render();
GL.Flush();
glControl1.SwapBuffers();

control2Context.MakeCurrent(glControl2.WindowInfo);
Render2();
GL.Flush();
glControl2.SwapBuffers();
}
}
public void Render ()
{
GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0); // use the visible framebuffer
if (videoFrame != null)
lock (videoFrame)//frames from video 1
{
    if (videoTexture != -1)
    GL.DeleteTextures(1, ref videoTexture);
    videoTexture = LoadTexture(videoFrame);
    videoFrame.Dispose();
    videoFrame = null;
 }
GC.Collect();
GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
obj_openTK.DrawImage(videoTexture, glControl1);
 }
public void Render2()
{
 GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0); // use the visible framebuffer
 if (videoFrame2 != null)
 lock (videoFrame2) // frames from video 2
 {
    if (videoTexture2 != -1)
    GL.DeleteTextures(1, ref videoTexture2);
    videoTexture2 = LoadTexture(videoFrame2);
    videoFrame2.Dispose();
    videoFrame2 = null;
}
GC.Collect();
GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
obj_openTK.DrawImage(videoTexture2,glControl2);
}
private void glControl1_Paint(object sender, PaintEventArgs e)
{
obj_openTK .Render();
}
private void glControl1_Resize(object sender, EventArgs e)
{
obj_openTK.Init();
}
private void glControl2_Paint(object sender, PaintEventArgs e)
{
obj_openTK.Render2();
}
private void glControl2_Resize(object sender, EventArgs e)
{
obj_openTK.Init();
}
========================
class openTK
{
int positionLocation1;
int program;
int positionLocation;
int vertShader;
int fragShader;
int buffer;
float[] vertices = {
        // Left bottom triangle
        -1f, -1f, 0f,
        1f, -1f, 0f,
        1f, 1f, 0f,
        // Right top triangle
        1f, 1f, 0f,
       -1f, 1f, 0f,
       -1f, -1f, 0f
};

public int LoadTexture(Bitmap bitmap)
{
    int tex = -1;
    if (bitmap != null)
    {
        GL.Hint(HintTarget.PerspectiveCorrectionHint, HintMode.Nicest);

        GL.GenTextures(1, out tex);
        GL.BindTexture(TextureTarget.Texture2D, tex);

        bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);
        BitmapData data = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
       ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

        GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, data.Width, data.Height, 0,
        OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);
        bitmap.UnlockBits(data);

        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge);
        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge);
    }
    return tex;
}
public void DrawImage(int image, GLControl glControl)
{
    GL.MatrixMode(MatrixMode.Projection);
    GL.PushMatrix();
    GL.LoadIdentity();
    GL.MatrixMode(MatrixMode.Modelview);
    GL.PushMatrix();
    GL.LoadIdentity();
    GL.Disable(EnableCap.Lighting);
    GL.Enable(EnableCap.Texture2D);
    GL.ActiveTexture(TextureUnit.Texture0);
    GL.BindTexture(TextureTarget.Texture2D, image);
    GL.Uniform1(positionLocation1, 0);

    RunShaders();

    GL.Disable(EnableCap.Texture2D);
    GL.PopMatrix();

    GL.MatrixMode(MatrixMode.Projection);
    GL.PopMatrix();

    GL.MatrixMode(MatrixMode.Modelview);

    ErrorCode ec = GL.GetError();
    if (ec != 0)
        System.Console.WriteLine(ec.ToString());
    Console.Read();
}
  private void RunShaders()
 {
 GL.UseProgram(program);
 GL.DrawArrays(PrimitiveType.Triangles, 0, vertices.Length / 3);
 ErrorCode ec = GL.GetError();
 if (ec != 0)
 System.Console.WriteLine(ec.ToString());
 Console.Read();
 }
 private void Init()
 {
 CreateShaders();
 CreateProgram();
 InitBuffers();
 }
 private void CreateProgram()
 {
 program = GL.CreateProgram();
 GL.AttachShader(program, vertShader);
 GL.AttachShader(program, fragShader);
 GL.LinkProgram(program);
 }
private void InitBuffers()
{
buffer = GL.GenBuffer();
positionLocation = GL.GetAttribLocation(program, "a_position");
positionLocation1 = GL.GetUniformLocation(program, "sTexture");
GL.EnableVertexAttribArray(positionLocation);
GL.BindBuffer(BufferTarget.ArrayBuffer, buffer);
GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(vertices.Length * sizeof(float)), vertices, BufferUsageHint.StaticDraw);
GL.VertexAttribPointer(positionLocation, 3, VertexAttribPointerType.Float, false, 0, 0);
}
private void CreateShaders()
 {
/***********Vert Shader********************/
 vertShader = GL.CreateShader(ShaderType.VertexShader);
 GL.ShaderSource(vertShader, @"attribute vec3 a_position;
                        varying vec2 vTexCoord;
                        void main() {
                        vTexCoord = (a_position.xy+1)/2 ;
                        gl_Position = vec4(a_position, 1);
                        }");
 GL.CompileShader(vertShader);

/***********Frag Shader ****************/
fragShader = GL.CreateShader(ShaderType.FragmentShader);
GL.ShaderSource(fragShader, @"precision highp float;
uniform sampler2D sTexture;varying vec2 vTexCoord;
                 void main ()
                 {
               vec4    color   = texture2D (sTexture, vTexCoord);
               gl_FragColor    = color;
                 }");
 GL.CompileShader(fragShader);
   }
  }

```

# Answer
I may assume that this happens due to fact that OpenTK opens OpenGL context on its creation. It is clearly stated here: https://www.khronos.org/opengl/wiki/Creating\_an\_OpenGL\_Context\_(WGL)#Create\_the\_Context that a single window at the moment can operate with only one context. In theory you can do switching contexts, as seen here: https://stackoverflow.com/questions/40578910/opentk-multiple-glcontrol-with-a-single-context

Also here: https://opentk.net/api/OpenTK.GLControl.html is a note about it:

> When using multiple GLControls, ensure that Context is current before performing any OpenGL operations. MakeCurrent()

When things are really strange you may ask question at OpenTK Discord: https://discord.gg/6HqD48s . Developers of OpenTK are often seen there.
> 1 votes

---
Tags: c#, opengl, opentk, windows-forms
---


# Question
Title: How to make object that moves with constant speed not overshoot the object it collides with?
To learn LOVE2D I am creating a simple project. Player moves the square with arrows keys until it hits the goal square, at which point the game is won.

```
function isCollision(x1,y1,w1,h1,x2,y2,w2,h2)
    return (x1<x2+w2)and(x2<x1+w1)and(y1<y2+h2)and(y2<y1+h1)
end

function love.update(dt)
    if love.keyboard.isDown("escape") then love.event.quit() end
    if isCollision(player.x,player.y,player.w,player.h,goal.x,goal.y,goal.w,goal.h) then
        gameOver=true
        if love.keyboard.isDown("space") then love.load() end
    else
        delta = player.speed*dt
        if love.keyboard.isDown("right") and player.x<=800-player.w then player.x=player.x+delta end
        if love.keyboard.isDown("left") and player.x>=0 then player.x=player.x-delta end
        if love.keyboard.isDown("down") and player.y<=600-player.h then player.y=player.y+delta end
        if love.keyboard.isDown("up") and player.y>=0 then player.y=player.y-delta end
    end
end

```

But sometimes the square overshoots the goal and it becomes lodged in the goal.

How do I make it so that engine detects when the player simply touches the goal and stops there, without moving further in the frame?

*Disclaimer: Using a collision detection library like bump.lua would be too easy. I want to learn the relevant practices so that I can apply it to retro consoles and computers in the future.*

# Answer
> 1 votes
At the moment you are checking for a collision between where the player is now and the goal square. Instead, you can define a rectangle which goes from where the player was last frame and where he is now. If there is a collision between this rectangle and the goal square this means one of three things:

1) The player collided with the square last frame (impossible, would have been noted already)

2) The player collided with the square this frame (what you're checking for now)

3) The player collided with the square "in between" the frames (the extra thing you want to check)

Where 2) and 3) are exactly what you want to check!

Note that to construct this new rectangle this you have to keep track of the square's old position. Or, equivalently, of how it moved last frame.

---
Tags: collision-detection, collision-resolution, lua, love2d
---


# Question
Title: Why is integer value not updating as a text?
I have a space shooter game and I am trying to create a shield power for the player ship. My mechanic for shield is working. When I press the shield power button(P), the shield power decreases from 100 to 0 at a certain pace.

Problem is that I am trying to draw this shield power value on screen but it's just showing the starting shield power value(which is 100) and not showing the decrease in shield power value when I press the shield button.

What am I missing?

Here's the relevant code: Game.cpp

```
if (keyboard->IsKeyPressed('P'))
{
    if (player_->shield == true)
        player_->shield = false;
    else
        player_->shield = true;
}

if (player_->shield && player_->shieldPower > 0)
{
    if (keyboard->IsKeyPressed(VK_SPACE))
    {
        XMVECTOR playerForward = player_->GetForwardVector();
        XMVECTOR bulletPosition = player_->GetPosition() + playerForward * 10.0f;
        SpawnBullet(bulletPosition, playerForward);
    }

    player_->shieldActive = true;
    if (GetTickCount() - player_->time > 100)
    {
        player_->time = GetTickCount();
        player_->shieldPower--;
        if (player_->shieldPower <= 40)
        {
            player_->shieldPowerLow = true;
        }
        else
        {
            player_->shieldPowerLow = false;
        }
    }
}
else
    player_->shieldActive = false;

```

TextClass.cpp

```
void TextClass::OnRender(System *system)
{
Graphics *graphics = system->GetGraphics();
FontEngine *fontEngine = graphics->GetFontEngine();
Player *player = new Player();

Game *game = system->GetGame();
game->RenderEverything(system->GetGraphics());

std::stringstream buffer;
buffer << player->shieldPower;

fontEngine->DrawText(buffer.str().c_str(), 50, 100, 0xffffffff,
FontEngine::FONT_TYPE_SMALL);
}

```

Player.h

```
class Player
{
public:

int shootDelay;
int time;
int shieldPower;
bool shield;
bool shieldActive;
bool fullShield;
bool shieldPowerLow;
bool shoot;
}

```

Player.cpp

```
Player::Player() :
shootDelay(500),
shieldPower(100),
fullShield(true),
shieldPowerLow(false),
shield(false),
shieldActive(false),
shoot(false)
{
}

```

# Answer
Your OnRender method needs to get access to several dependencies:

* Graphics
* Font Engine
* Player
* Game

And for three of the four you use one perfectly sensible pattern: a getter method accessible from the `System` you've been passed as an argument, or something get-able from it.

```
void TextClass::OnRender(System *system)
{
    Graphics *graphics = system->GetGraphics();
    FontEngine *fontEngine = graphics->GetFontEngine();
    // ... //
    Game *game = system->GetGame();

```

But when it comes to the `Player`, you throw all that away and try to create a new `Player` from scratch:

```
Player *player = new Player();

```

Since this is a new instance, it always has the default values. Instead, we want to reference the *existing* player instance that Game.cpp is already updating each frame.

So, use the same pattern you're already using everywhere else: give `Game` a `GetPlayer()` method to return the player it's holding onto, and have the `TextClass` ask the `Game` it got from the `System` to get access to this existing player.
> 1 votes

---
Tags: c++, rendering, text
---


# Question
Title: How can I do a Metroid like transition between two tilemaps with Monogame Extended?
I want to do a transition like those in the Metroid games. Here is an example of what i mean: https://www.youtube.com/watch?v=RKJ3MAi0ZI0.
You enter the door, the screen fades to black and the camera scrolls to the next room where the screen fades in again.

I'm using Monogame Extended and i have a TiledMap. I use them like described in the documentation. I have a camera with a view matrix and a projection matrix

```
   Camera2D camera;

   ...

   public void DrawGame(GameTime gameTime, SpriteBatch spriteBatch)
   {
        var viewMatrix = camera.GetViewMatrix();
        var projectionMatrix = Matrix.CreateOrthographicOffCenter(0, gDevice.Viewport.Width, gDevice.Viewport.Height, 0, 0f, -1f);

        tiledMap.Draw(viewMatrix, projectionMatrix);
   }

```

My idea is now to create a second tiledMap to placing them directly next to the first one where the transition occurs. Then i just have to move the camera from one map to the next one. My problem now is that i have no clue how to put them next to each other. From my understanding i somehow have to use the view and projection matrix to draw the tiledMap but i can't figure out how it should work with two tiledMaps.

# Answer
Trying to scroll the camera to match the positions of the door will be to complicated for what you are trying to achieve. Instead you can try something simpler.

* Fade out the first level and draw the door sprite as a separate layer with full opacity and normal colour.
* Load the second level on the background but keep it faded out. At this point you know the position of the door your character will come out.
* Play a short animation where your original door (the one you have as a separate layer) moves from it's current position to the target position (the new door). From what I can see from the video, the door sprite moves only in one axis per time.

Once the door movement animation finishes start fading in the second level. At this point you can show your character and delete the extra door sprite.
> 1 votes

---
Tags: xna, monogame, tilemap, monogame-extended
---


# Question
Title: Should my terrain be one big mesh or several medium ones?
While creating a subterranean level with probuilder (irregularly shaped rooms and corridors), I was wondering if I should merge all "terrain" meshes into one or keep them as separate meshes? What are the good practices ?

I'm creating each room as I go and its not hard to create openings and align doors vertices (with progrids) but once I start moving them around (like with polybrush) I'm sure it will soon be a nightmare. I can see pros and cons for both. Separate meshes would be easier to edit, duplicate or replace, probably better performances but at the risk of overlaps or holes because it would get hard to keep connected cleanly. I guess with one mesh you take the risk of having it eat memory and computation time, or having it too big to edit easily.

I settled on each mesh consisting of a room and all half-corridors going out of it, to hide the stitching and keep it simple. Still I wonder if there's a consensus.

# Answer
It sounds like you understand the trade-off here between ease of creation and runtime performance.

What position along that trade-off spectrum is both...

* sufficiently efficient to render for the way your game runs / the content you're putting in it
* sufficiently simple to edit for the way your development workflow operates

...is a judgement call that only you have the information to make. We have neither your game nor your dev team here in front of us to run tests on.

So:

1. Find a level of division that you like working with (maybe just one huge chunk), and mock up a map at that scale.

It doesn't have to be beautiful/final - you can create it slapdash and just fill it with randomly placed objects to represent your expected content density, without having to put too much time into making the test.
2. Profile this sample in-game, on your target hardware, and measure how long it's taking to update/render from worst-case viewpoints.
3. Evaluate, based on your goals for the game, whether the performance is acceptable with this chunk size, or if you need to break into smaller chunks.

If you need to go smaller, break the chunk into pieces and profile it again, until you find a size that gives you the best compromise between runtime and editing efficiency.

You can also look for workflows to make editing the map chunks easier - like tools that will let you modify your map as one piece, then chop it up on export so you don't have to fuss with fixing seams yourself.
> 2 votes

---
Tags: unity
---


title: Bullet Projectile Verticle Rotation

text:
# Question
Title: Bullet Projectile Verticle Rotation
I'm very new to C# and Unity, and have been working on a projectile based weapon, and for the most part it's been working well. However, although the bullet fires facing the direction it's being shot horizontally, when shot up or down, the bullet is still parallel to the ground when shot. Any help would be appreciated, thanks!

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

public class PlayerWeapon : MonoBehaviour
{
public GameObject bulletPrefab;

public Transform BulletSpawn;

public float bulletSpeed = 30;

public float lifeTime = 3;

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

}

// Update is called once per frame
void Update()
{
    if (Input.GetKeyDown(KeyCode.Mouse0))
    {
        Fire();
    }
}

private void Fire()
{
    GameObject bullet = Instantiate(bulletPrefab);

    Physics.IgnoreCollision(bullet.GetComponent<Collider>(),
        BulletSpawn.parent.GetComponent<Collider>());

    bullet.transform.position = BulletSpawn.position;

    Vector3 rotation = bullet.transform.rotation.eulerAngles;

    bullet.transform.rotation = Quaternion.Euler(rotation.x, transform.eulerAngles.y, rotation.z);

    bullet.GetComponent<Rigidbody>().AddForce(BulletSpawn.forward * bulletSpeed, ForceMode.Impulse);

    StartCoroutine(DestroyBulletAfterTime(bullet, lifeTime));
    }

private IEnumerator DestroyBulletAfterTime(GameObject bullet, float delay)
{
    yield return new WaitForSeconds(delay);

    Destroy(bullet);
}
}

```

# Answer
> 0 votes
Two things:

1. Don't futz with Euler angles, just face the direction you want to shoot.

`bullet.transform.forward = BulletSpawn.forward;`

This is equivalent to:

`bullet.transform.rotation = Quaternion.LookRotation(BulletSpawn.forward);`

Though with this form you, can also provide a second argument to control the twist rotation of the bullet around its forward axis.
2. If `bulletSpeed` is a speed, ie. it's a distance travelled per second, then use it to calculate a velocity, not an impulse. This way you get exactly the speed you asked for, and you don't have to mentally convert your m/s numbers to N\*s in the Inspector:

`bullet.GetComponent<Rigidbody>().AddForce(BulletSpawn.forward * bulletSpeed, ForceMode.VelocityChange);`

Or, more concisely, if this is the only influence acting on the bullet at launch:

`bullet.GetComponent<Rigidbody>().velocity = BulletSpawn.forward * bulletSpeed;`

---
Tags: unity, 3d, projectile-physics
---