title: Unity open UI from ScriptableObject

text:
# Question
Title: Unity open UI from ScriptableObject
I have a `Canvas` that has multiple UI `Panels` in it for an inventory, crafting, etc. To open these panels I currently have a `monobehaviour` class on the `Canvas` with methods like `OpenInventory()`, etc.

For every item within the inventory I use `ScriptableObjects`. However, some items open the crafting panel when right clicking, I created a class that extends the `Item` class and added a method to it that gets added to the inventory slot and gets called when right clicking that item.

Because the `monobehaviour` on the `Canvas` is an instance, I can't access it from a `ScriptableObject`.

Long story short, is there a way to open a UI panel from a ScriptableObject? If not, what would be the best way to fix this issue?

# Answer
> 2 votes
**Bad solution**:

* Add to ScriptableObject public field of type `Canvas` (better - private field with public setter).
* On Monobehaviour's Awake() write current canvas' reference to ScriptableObject.
* Now you can call canvas from ScriptableObject! Any new canvas on Awake() automatically overwrites reference to itself so you always get actual canvas.

**Kinda bad solution**:

Transform canvas into Singleton. Or, better, create a whole UI manager as Singleton with link to Canvas in question. Then you could access any UI window like this:

```
UiManager.Instance.OpenInventory();

```

or:

```
UiManager.Instance.Inventory.Show();

```

**Nice solution**:

You are calling a method inside ScriptableObject from somewhere, right? Could you pass reference to Canvas as method parameter? Or maybe you could wrap the whole method and pass it as delegate?

Another option is to make use of UnityEvent system or create your own event-based system (which is extremely helpful while you trying to pass data between separate modules). In that case you can achieve anything using some creative subscriptions/event triggering.

# Answer
> 1 votes
You can tag the Canvas (for example with the tag "Menu") and then in your scriptable object do a GameObject.FindGameObjectWithTag("Menu") and then you can call the method via GetComponent\<...\>().OpenCraftingPanel()

---
Tags: unity, gui
---


# Question
Title: How do I tag an empty space for an 'InAir' Boolean?
I've been working with my game's settings to get the perfect jump height, gravity and movement that suits the player, however my problem is my player essentially floats back down to the ground, when I want them to fall much faster (it's a 3D game) but I don't want to tamper the gravity anymore solely for the player.

What I've done is created 2 extra Booleans alongside my Grounded Boolean, one for In Air and another for Extra Gravity, and this is where my problem comes in.

I have no idea how to set a tag to the empty space in the air, and I was wondering if anyone knew how to do this, or if there is a better method for detecting when my player is in the air?

This is what my script currently looks like:

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

public class PlayerScript : MonoBehaviour
{
    public float movementSpeed = 5f;
    public float jumpForce = 7;
    public float jumpSpeed = 7;
    public Rigidbody rigidbody;
    private Vector3 input;
    public GameObject Player;
    public bool grounded;
    public bool inAir;
    public float ExtraGravity;

    // Use this for initialization
    void Start()
    {
        var rigidbody = GetComponent<Rigidbody>();
        var col = GetComponent<CapsuleCollider>();
        Player = GameObject.FindWithTag("Player");
    }
    void FixedUpdate()
    {
        if (Input.GetKeyDown("space"))
        {

            if (grounded)
            {
                Debug.Log("Spacebar pressed");
                rigidbody.AddForce(0, jumpForce, 0);
            }

            if(inAir)
            {
                Vector3 vel = rigidbody.velocity;
                vel.y -= ExtraGravity * Time.deltaTime;
                rigidbody.velocity = vel;
            }

        }
    }

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

        if (Input.GetKey("w"))
        {
            transform.position += transform.TransformDirection(Vector3.forward) * Time.deltaTime * movementSpeed * 5.5f;
        }
        else if (Input.GetKey("s"))
        {
            transform.position -= transform.TransformDirection(Vector3.forward) * Time.deltaTime * movementSpeed * 4.5f;
        }
        else if (Input.GetKey("d"))
        {
            transform.position += transform.TransformDirection(Vector3.right) * Time.deltaTime * movementSpeed * 5.5f;
        }
        else if (Input.GetKey("a"))
        {
            transform.position -= transform.TransformDirection(Vector3.right) * Time.deltaTime * movementSpeed * 5.5f;
        }

        if (Input.GetKey(KeyCode.LeftShift))
        {
            transform.position += transform.TransformDirection(Vector3.forward) * Time.deltaTime * movementSpeed * 20.5f;
        }

    }

    void OnCollisionStay(Collision collision)
    {
        if (collision.gameObject.CompareTag("Floor"))
        {
            grounded = true;
        }
    }

    void OnCollisionExit(Collision collision)
    {
        if (collision.gameObject.CompareTag("Floor"))
        {
            grounded = false;
        }
    }

}

```

# Answer
> 0 votes
There's a lot we can improve here:

* Don't use a force to jump. Forces are for a gradual push over time, like gravity or wind. A jump is a single sharp change in motion, so we should apply it with an impulse or velocity change.

+ This ensures we won't have to go change our tuning numbers if we later change the project's fixed timestep, because the whole jump is occurring instantaneously, not integrated over the duration of the step like a force.
* Keep your tuning parameters in intuitive units.

+ If you have a variable called `movementSpeed`, make it actually the speed of movement in units per second. Don't add extra fudge factors into the equation that make this parameter only one fifth of the actual runtime speed. These arbitrary factors make our numbers harder to reason about, and require looking at both the code and the Inspector values together to work out the true speed.
    + Trying to find the right force/impulse/velocity value for a jump is hard - we don't have a good intuition for what the numbers mean in practical terms, so it ends up being a lot of trial & error. Instead, let's express our jump in terms of the height we want to hit, and how long it should last. We can reason about the effect of those numbers much more easily. Converting those intuitive parameters to the required physics values is the computer's job. ;)
    + You're shadowing your `rigidbody` variable in `Start` \- effectively declaring a new one-off variable only for that one method, populating it with `GetComponent`, then throwing away the result. The `rigidbody` you've assigned in the inspector is the one you're currently using.
* Instead of using hard-coded keys to detect movement direction, you should use axes. By default, Unity already maps WASD to horizontal & vertical axes, so this will give you similar behaviour out of the box, with a bunch of extra wins:

+ Simpler, less repetitive code
    + The ability to support gamepad input with no code changes
    + The ability to synonymize controls (so if a player prefers using the arrow keys instead of WASD, that will "just work" without needing to change settings)
    + The ability for players to remap the controls in the launch dialog, for comfort and accessibility
* Don't mix `transform` movement with `rigidbody` movement. If you're using one or the other, use it exclusively. Mixing these two means control is constantly being ripped out of the physics engine's hands, and it needs to clean up the resulting mess on the next frame, leading to unwanted behaviour like jittering, tunnelling, and inaccurate collisions.
* Don't clear your grounded flag using `OnCollisionExit` \- this gets called when you walk off one floor object, even if you're still standing on another floor object. A short raycast or shapecast is much more reliable.

+ If you use a physics layer and layer mask to mark what's ground vs not, then you don't need to compare tags at all. Stuff that isn't ground will not even be checked, making the query more efficient.
* Checking for key/button down events in `FixedUpdate` can lead to undesired behaviour, because `FixedUpdate` can sometimes be called multiple times in one frame (leading to double-handling input), or not at all for a frame (leading to missed input). Holds are OK, since by nature we expect these to persist across several frames, But presses we need to handle in update

Here's what a player movement controller with these changes might look like:

```
// This script needs a body to work, so let's ensure the engine knows.
[RequireComponent(typeof(Rigidbody))]
public class PlayerMovement : MonoBehaviour {

    // Set this in the Inspector to filter to physics layers the
    // player can jump off of. (And put your platforms on those layers)
    public LayerMask whatIsGround;

    // Speeds in world units per second.
    public float movementSpeed = 5f;
    public float dashSpeed = 20f;

    // Peak height of the jump, in world units.
    public float jumpHeight = 3f;
    // Duration of the rising and falling phases of the jump.
    public float secondsToPeak = 0.3f;
    public float secondsToFall = 0.2f;

    // Physics quantities calculated from the above.
    [SerializeField, HideInInspector]
    float _jumpVelocity;
    [SerializeField, HideInInspector]
    float _ascentGravity;
    [SerializeField, HideInInspector]
    float _descentGravity;

    // References to our physics components.
    [SerializeField, HideInInspector]
    Rigidbody _body;
    [SerializeField, HideInInspector]
    CapsuleCollider _collider;

    // This flag does double-duty as both on-ground and not-in-air. ;)
    bool _isGrounded;

    // OnValidate gets called when we change stuff in the editor.
    // So this keeps our components & values up-to-date.
    void OnValidate() {
        _body = GetComponent<Rigidbody>();
        _collider = GetComponentInChildren<CapsuleCollider>();

        // Total gravity on the ascent & descent phases.
        _ascentGravity = -2f * jumpHeight / (secondsToPeak * secondsToPeak);
        _descentGravity = -2f * jumpHeight / (secondsToFall * secondsToFall);

        // Vertical velocity needed to reach desired peak height.
        _jumpVelocity = -_ascentGravity * secondsToPeak;

        // Remove gravity already accounted for by the built-in physics,
        // leaving only the extra we need to apply while rising/falling.
        var defaultGravity = Physics.gravity.y;
        _ascentGravity -= defaultGravity;
        _descentGravity -= defaultGravity;
    }

    // This check assumes your character's origin is at the bottom of its collider.
    // You can adjust the origin of the query if that's not true for your case.
    void UpdateGroundedState() {
        Vector3 origin = transform.position;
        origin.y += _collider.radius + Physics.defaultContactOffset * 2f;

        Ray ray = new Ray(origin, Vector3.down);

        // We fire a sphere a tiny bit smaller than our capsule
        // straight down a tiny distance to see if it hits anything.
        _isGrounded = Physics.SphereCast(
                ray,
                _collider.radius - Physics.defaultContactOffset * 2f,
                Physics.defaultContactOffset * 6f,
                whatIsGround
            );
    }

    void FixedUpdate() {
        UpdateGroundedState();

        // Apply the extra gravity if we're in the air,
        // ie. not on ground.
        if (_isGrounded == false) {
            // Use different gravity for the up & down phases.
            float extraGravity = _body.velocity.y > 0f ?
                _ascentGravity : _descentGravity;

            // Apply the extra gravity as an acceleration (ignore mass).
            _body.AddForce(extraGravity * Vector3.up, ForceMode.Acceleration);
        }

        // Gather input as a vector from our axes.
        Vector3 input = Vector3.zero;
        input.x = Input.GetAxis("Horizontal");
        input.z = Input.GetAxis("Vertical");

        // Make sure we don't exceed full speed diagonally.
        input = Vector3.ClampMagnitude(input, 1f);

        // Construct a desired velocity from input and our speed.
        Vector3 velocity = input * movementSpeed;

        // Add the dash (keeping it similar to your existing version).
        if (Input.GetButton("Dash")) {
            velocity += dashSpeed * transform.forward;
        }

        // Compute the net change in velocity we want,
        // and cancel out the vertical effect
        // so we don't interfere with jumping & falling.
        Vector3 deltaV = velocity - _body.velocity;
        deltaV.y = 0f;

        // Apply the velocity change.
        _body.AddForce(deltaV, ForceMode.VelocityChange);
    }

    void Update() {
        UpdateGroundedState();

        // Handle our jump in Update so we never miss/double a press.
        if (_isGrounded && Input.GetButtonDown("Jump")) {
            _body.AddForce(_jumpVelocity * Vector3.up, ForceMode.VelocityChange);
            _isGrounded = false;
        }
    }
}

```

# Answer
> 0 votes
First of do a raycast facing downwards from the player to check for ground, Using oncollision methods are a terrible idea. For example if you are jumping at a box in midair and then collide with said box the way you have it setup will tell your player that you are currently grounded.

---
Tags: rigidbody, boolean
---


title: How to use TEnumAsByte Unreal 4.22

text:
# Question
Title: How to use TEnumAsByte Unreal 4.22
---

**The problem**

I am attempting to use a `TEnumAsByte` in one of my class headers:

I get compilation errors:

---

**Code sample**

I have included everything relevant to the member variable I am trying to create:

Header File:

```
#pragma region Engine Includes

#include <Containers/EnumAsByte.h>

#pragma endregion

UCLASS( Blueprintable, ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) )
class PLATFORMER_API UGrappleAbilityComponent : public UActorComponent
{
    GENERATED_BODY()

protected:
    // Begin AActor Interface //

    /** Called when play starts */
    virtual void BeginPlay() override;

    // End AActor Interface //

public:
    /** Determines what type of debug draw is used for the continuous grapple scanning */
    UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "Grapple Scan", meta = (AdvancedDisplay, DisplayName = "Grapple Cont Scan Debug Draw Type"))
        TEnumAsByte<EDrawDebugTrace::Type> m_GrappleScanDebugDraw;
}

```

Source File:

```
UGrappleAbilityComponent::UGrappleAbilityComponent()
{
    PrimaryComponentTick.bCanEverTick = true;

    // Give an initial value to the debug draw mode for the continuous grapple scanning.
    m_GrappleScanDebugDraw = EDrawDebugTrace::None;
}

...

void UGrappleAbilityComponent::GrappleScanContinuous(FHitResult & OutHit)
{
    // Only scan if the player is not attached and their airbrake is not active
    if (!m_GrappleHook->IsAttached() && !m_OwnerCharacter->IsAirbrakeActive()) {

        // Increment the trace lerp value.  -   Then wrap the Trace lerp value back around to 0.
        m_GrappleScanTraceLerp += 0.1f;         if (m_GrappleScanTraceLerp > 1.f) { m_GrappleScanTraceLerp = 0.f; }

        // Calculate the proposed end point of the grapple.
        FVector EndPoint = m_StartPoint + m_StartPointDirection * m_GrappleCastDistance;
        float zOffset = FMath::Lerp(m_GrappleContScanLowHeight, m_GrappleContScanHighHeight, m_GrappleScanTraceLerp);
        EndPoint.Z += zOffset;

        // Perform the box traces.
        UKismetSystemLibrary::BoxTraceSingle(GetWorld(),
            m_StartPoint, EndPoint, m_GrappleContScanHalfSize, FRotator::ZeroRotator,
            UEngineTypes::ConvertToTraceType(ECollisionChannel::ECC_GameTraceChannel5),
            false, {}, m_GrappleScanDebugDraw.GetValue(), OutHit, true);
    }
}

```

---

**Additional Info**

The compilation errors relating to the BoxTraceSingle call are irrelevant as they only occur due to the compilation errors with the TEnumAsByte. Aside from the `.GetValue()` call. Removing this still causes similar compilation errors however.

I can confirm this as, by looking at Epic's engine code, they use TEnumAsByte in *exactly* the way I have done here, aside from the `.GetValue()` call.

What the hell is going on here?

# Answer
> 2 votes
Error C2653, the first one, says that `EDrawDebugTrace` isn't a class or namespace name, which is another way of saying (in this context) that the compiler has not yet seen a definition for `EDrawDebugTrace`. That's the root of your problem.

Error C2923 is telling you that you cannot use `EDrawDebugTrace::Type` as a parameter for the template `TEnumAsByte<>`. The *reason* you cannot use `Type` is because the compiler doesn't know what it is, since it's nested inside `EDrawDebugTrace` which the compiler *also* doesn't know about (because of the first error).

At this point in your code, the only `#include` you have is for `TEnumAsByte<>` itself. This header does not define `EDrawDebugTrace` (instead, it comes from the `KismetSystemLibrary.h` header).

To fix this, you should include `KismetSystemLibrary.h` (or some other header that includes it indirectly) in your code before you try to use `EDrawDebugTrace`.

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


# Question
Title: C++ SDL2:2D tilemap with every tile has its own behavior
I am working on 2D tile based game. I want to render the **tilemap** from a file but every tile has its own **behavior** for example: **magmablock : poorlava();** **slimeblock : knockback();**

I have this files **Tile**, (**magmablock**;**slimeblock**;**iceblock**)(just examples and they inherit from tile ) ,**handler**

This is what I did I loaded the map in class with an array in every character i create a **tile** object in an array and give it an **ID** in the **tile constructor**i do a **switch** statement if the ID is *1* for example create **magmablock** and i call the *deconstruct* so the **tiles array** will be empty

in the **magmablock** class i add **magmablock** object(this) to a **handler** class which update them and render them **this is the codes so u can understand more**

**levels.h**

```

#ifndef LEVELS_H
#define LEVELS_H
#include <iostream>
#include <fstream>
#include <vector>
#include "tile.h"
using namespace std;

vector< vector<tile> > tiles;

class levels
{
public:

    static void loadworld(string levelfile)
    {
        int mw = 0,mh = 0;
        string tempNum;
        ifstream readLevel(levelfile);
        string mapCode;

        //i read from file i get the width and height (mw,mh) and the array
        //here i loop in the array

                for (int j = 0 ; j <= mh ; j++)
                {
                    for (int i = 0 ; i <= mw; i++)
                    {
                                tile t(stoi(tempNum),i,j);
    //tempnum is the ID
    //it's not important here
    //so i deleted it so the code will not be complicated

                                tiles[j][i] = t; //j - i
    // i create tile object in the array
                    }
                }
    }
};

#endif // LEVELS_H

```

**tile.cpp**

```

#include "tile.h"
#include "magma.h"
#include "slimeblock.h"
#include "wall.h"

tile::tile(int id,int x,int y)
{
        switch (id)
        {
            case 001:
        {
                tile *wallBlock = new wall(x,y); //create new objects
        }
            case 002:
        {
                tile *magmaBlock = new magma(x,y);
        }
            case 003:
        {
                tile *slime = new slimeblock(x,y);
        }
            default:
                break;
        }

        this->~tile(); // here i destroy it
}

```

**magmablock.cpp**

```
#include "magma.h"
#include "game.h"

magma::magma(int x,int y)
{
    this->id = magmaID;
    this->tileID = tile::tileID;
    tile::tileID++;
    this->tex = game::textures[0]; //this just load the texture

    this->crop.x = 32; //its texture from the spritesheet
    this->crop.y = 0;

    this->pos.x = x*32; // its position
    this->pos.y = y*32;

    game::hand->addTile(this); // hand is the handler
}

void wall::init(){}

void wall::tick(){}

void wall::render(SDL_Renderer *ren)
{
    SDL_RenderCopy(ren,tex,&crop,&pos);
}

```

**handler.h**

```

#ifndef HANDLER_H
#define HANDLER_H

#include "tile.h"
#include <vector>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>

using namespace std;

class handler
{
    public:

    handler(SDL_Renderer* ren){this->rend = ren;}

    SDL_Renderer* rend;

    vector<tile> tiles;

    /// Insert The  Tile ///

    void addTile(tile t)
    {
        tiles.push_back(t);
    }

    /// Destroy  The Tile ///

    void removeTile(tile t)
    {
        for(int i = 0;i < tiles.size();i++)
        {
                if(tiles[i].tileID = t.tileID)
                {
                    tiles.erase(tiles.begin() + i);
                    tiles[i].destroy();
                }
        }
    }

    void init()
    {

    }

    void tick()
    {
        /// Tile Tick

        for(int i = 0;i < tiles.size();i++)
        {
            tiles[i].tick();
        }

        /// Tile Tick

        for(int i = 0;i < objects.size();i++)
        {
            objects[i].tick();
        }
    }

    void render()
    {
          for(int i = 0;i < tiles.size();i++)
        {

            tiles[i].render(rend);
        }
    }
};

#endif // HANDLER_H

```

Hope you understand me i know that this is too much but I didn't find another way to describe it.

**is this a good way?** **how to do it?**

# Answer
I think this is more an opinion-based question but here are my thought (I'm not a C++ expert):

* Create a base class **Tile** that will handle generic stuff like rendering, animations if any, behavior of the tile...
* For each of your special tiles, create a new class that inherits from your base class **Tile** and override the behavior if your new tile has a custom behavior, or override the animation/render if it is a special case.
* Read the level file, and based on these informations, create your level and handle special cases like you did it.

To store the level you can either store it in a text file with special characters or if you need more data (i.e. a magma block can have different levels of damage done) I would take a shot at JSON or XML serialization. That way you can encode full objects to a file and read them directly as an array of tiles, it would make your method **loadworld** obsolete and you will have to just deserialize your JSON/XML file into a map.

This is what your level could looks like as a JSON file :

```
{
    "levelName" : "Level 1",
    "tiles" : [
        [{"type": "magma", "damages": 2}, {"type": "wall","color": "blue"}],
        [{"type": "floor"}, {"type": "floor"}]
    ]
}

```

This would translate to :

```
MW
FF

```

But you are able to pass in data into your tile objects.

I invite you to read a little bit more about Inheritance and Polymorphism in C++ if you are not so familiar with it.

I also think that the most used JSON library out there is this one.
> 1 votes

---
Tags: c++, 2d, rendering, tilemap, sdl2
---


# Question
Title: Can I put a Creative Commons license on my game?
Title says all, I would like to publish my game under a Creative Commons license. What licenses can I use for a game if any?

# Answer
Well, you *can* do that. You can use any license you want for your game. But Creative Commons does not recommend it. The reason is that there are a lot of licenses available which were written specifically for software. These licenses have the same basic intentions as CC licenses, but have a wording and include clauses which are much more appropriate for this particular use-case. Here are a few licenses I would recommend as alternatives for CC licenses (but please note that I am not a lawyer):

But with games in particular there is the problem that usually about half the work are art assets which are not appropriately covered by software licenses. We ran into that problem once during an open source project licensed under GPL when people started to wonder what the "sourcecode" of a spritesheet is supposed to be.

A good solution can be to separate the programming of the game from the art assets. You can license the programming under a software license and the assets under a Creative Commons license.
> 2 votes

# Answer
Apparantly since video games count as software I can't put a CC license on them.
> -1 votes

---
Tags: copyright
---


# Question
Title: Should I create thread for both UDP and TCP?
So I have TCP connection for stuff like leveing, player info, etc..And I have UDP datagram for stuff like player position, rotation, etc..Should I create new thread for both TCP and UDP on both client and server side?That won't be resource heavy on client side but on server side with up to 15 players that will be 30 new threads. I don't know if that amount if threads are not much or is there a better way of solving this issue.

# Answer
30 threads on the server is no big deal... much less on a dedicated server. My PC has, at the moment of writing, around 1750 open threads (in Windows, you can find this in the task manager).

Well, unless your hosting service limits that.

---

However, why do you need threads per client on the server?

In general you do not. A server thread for listening to UDP, and another for listening to TCP, would do. *In fact, it is possible in a single thread (baring language and libraries).*

Assuming you are using sockets, the messages from multiple clients get queued up. In addition, there is nothing preventing the server to send messages to different clients from the same thread.

Besides, you cannot open a port multiple times, and sharing a socket – if possible in whatever platform you are using – is a bad idea. Thus, we would be talking about assigning a different port to each client. Well, as I said above, the socket will queue messages from multiple clients, thus opening a port for each client is unnecessary.

---

If you really want to have multi-threading, remember that you can have a single thread listening and have it queue a task (on a thread pool, for example) to handle each message.

Also remember that the performance improvement you get is limited by the number of cores, and that you need to worry about threading issues. In particular, you want players to interact on the server, right? Thus, if every client is on a different thread you will need some kind of channels or shared memory at some point.
> 2 votes

# Answer
UDP, 15 players, 5 packets/sec = 75 packets/sec of UDP traffic. If the packets are maximally sized (65,507 data bytes), that is roughly 5MB/s. One thread should be plenty.

It may also be worth looking at this post: https://stackoverflow.com/questions/26578692/how-many-threads-is-good-for-a-datagram-receiver

Granted it's regarding Java, but datagrams are datagrams.
> 0 votes

---
Tags: networking, multithreading, udp
---


# Question
Title: What does the Node2D transform property do?
Following a Godot tutorial I encountered the `transform` property, but I'm not sure what it means nor how to use it.

I read the official Godot documentation, but it didn't give me a full explanation about the theme. I just got this:

> Transform2D **transform**
>
> *Setter* `set_transform(value)`
>
> *Getter* `get_transform()`

Could someone explain to me more about this?

# Answer
In games, a "transform" refers to how an object is positioned, oriented, or scaled within the game world.

To move an object, to rotate an object, or to squash and stretch an object are all forms of "transformation". The transform is a data structure that stores the current transformation state of the object: where it is, which way it's facing, and how big it is.

Frequently games use a "transformation hierarchy" - meaning that objects are organized into nested relationships of "parent" objects that contain "child" objects, arranged so that if you transform the parent, all of its children and grandchildren etc. get transformed together with it.

In this context, an object has two transforms: its local transform relative to its parent node, and a global transform representing its ultimate position/orientation/scale in the world after factoring in all the effects of its parent, grandparent, etc.

In Godot, `Node2D.transform` is the local transform. It offers members like...

* `get_origin()`: where should this node sit, relative to its parent's origin and rotation?
* `get_rotation()`: how is this node rotated relative to its parent (in radians)?
* `get_scale()`: how has this node been squashed or stretched relative to its parent's scale?

Another way to think of transformation is to think of "local space". As I sit at my desk, I am facing southward. If I extend my right arm out to the side, it represents my "local x+ axis", currently pointing west. If I turn 90 degrees to my right, my right arm now points north. So I carry my own local coordinate system with me as I move and orient myself in space.

Game objects do this too. A Godot transform gives you vectors representing the direction that the object's local x+ axis and local y+ axis point, within its parent's local space. Its parent's space in turn can be transformed relative to the grandparent's local space, all the way up to the global coordinate system.

There is also a `Node2D.global_transform` representing the object's net transformation in the world, after its parent, grandparent, etc.'s local transforms have all been stacked-on.

Under the hood, a transform might be stored as a transformation matrix, or as a position vector, a rotation angle / quaternion, and a scale touple.
> 4 votes

---
Tags: transformation, terminology, godot, hierarchy
---


# Question
Title: How can I cut a doorway through my wall at runtime?
I am working on a Unity project where I have 3 models: a stacked, rounded wall (think logs), a flat wall (think bricks), and a door.

The door has an animation to open / close itself, and when it's attached to a wall, there's one major problem -- when the door swings in, it reveals not the empty space one would expect, but the segment of wall it's layered on top of!

Since all 3 models are part of dynamic mesh structures, I can't "pre-calculate" what the model should look like to account for the empty space of the door -- what if the player puts the door on the next segment of wall instead?

I considered expanding the "door" model to a "door + wall segment" model (replacing that wall segment entirely), but because I already have two separate shapes of wall, it quickly becomes a combinatorics problem -- 2 models for each door, per door shape (not to mention windows, or a 3rd \[or fourth!\] wall shape!). In short, this doesn't seem like a tenable solution.

What would work most cleanly is if I could remove a "Door-shaped" segment of my Wall segment mesh, leaving a clear hole that the Door model could snugly fit.

**In an equation:** Final Mesh A = Mesh A Volume - (Mesh A Volume ∪ Mesh B Volume)

Is an operation like that *feasible*? My gut tells me that polyhedron intersection is **hard**, and there might be a better way to do this. I'm also equally interested if someone has a better suggestion on how to solve the initial problem of doors intersecting with wall segments.

# Answer
Actually cutting this hole in the mesh can be challenging. It's doable - 3D modelling packages manage it all the time - but it can be computationally intensive to handle every potential case, and it requires topological information about a mesh that we normally don't use for rendering in games, which can be a pain to create/maintain.

It's easier with raymarching techniques like the one Demetre Saghliani linked to - if you're already using a raymarching renderer. But if you're using conventional polygonal rasterization, this too can be a big ask.

Fortunately, for simple tasks we can get by with a simple trick: don't actually compute the full intersection and internal surfaces or change the mesh in any way, just abort rendering any pixels inside the doorway when drawing your frame. Inside the wall's shader we can use some simple math to work out whether we're in the rectangle of the doorway, and if so, tell the blending pipeline "nevermind, forget this fragment was even trying to draw here".

It's basically an inversion of the shader shown here.

Note that this will leave a visible gap in the mesh - it's not generating new faces to cap the edges of the hole. But in the context of a doorway, that's not a big problem really. We can just add a door frame mesh that covers this raw edge, so the player never sees our cheat.

You can even cheat the collisions in a similar way. Place a trigger collider inside the doorway, small enough that a character outside the doorway won't touch it, but large enough that you can't pass through the door without touching it. Use this trigger collider to disable collisions between the character and the wall, and re-enable them when the character exits the trigger, allowing them to pass through the wall like there was nothing there.
> 3 votes

---
Tags: unity, models, dynamic-mesh
---


# Question
Title: Problem with diagonal collision response using PyGame
So I have been having this problem for the last few days and it has me really frustrated. What I am trying to do is resolve collisions with custom hitboxes in PyGame and it looks something like this:

Everything works fine until I collide with something diagonaly, then I get a weird bug where the character suddenly teleports to the opposite axis side of what I am colliding with, like this:

https://gyazo.com/62c53cc4f3a944c317a951c0f8ae14ea

I have read a lot about this the last day and from what I have gathered this has to do with the fact that I don't resolve the x and y axis independently? maybe?

If I have a print("x") and print("y") statement in their respective code I get this when colliding with something on the "y" axis:

The bug seems to come from that somewhat random "x" in the middle there. The code resolves a collision as if the character was colliding with something on the "x" axis when in fact it was the "y" axis. It is worth nothing that this **ONLY** happens when diagonaly colliding with the last axis I check (y in this case). So I suppose that is my question really, why does this happen?

Here is my collision handling code:

```
def collide(self, direction):

    hits = pg.sprite.spritecollide(self, all_sprites_wall, False, rectconverter)
    if direction == "x":
        if hits:
            print("x")
            if self.vx > 0:
                hits[0].update()
                self.x = hits[0].hitboxrect.left - self.rect.width - camera.camera.x
                self.hitboxrect.right = hits[0].hitboxrect.left
            if self.vx < 0:
                self.x = hits[0].hitboxrect.right - self.rect.width + self.hitboxrect.width - camera.camera.x
                self.hitboxrect.left = hits[0].hitboxrect.right
            self.rect.x = self.x

    if direction == "y":
        if hits:
            print("y")
            if self.vy > 0:
                self.y = hits[0].hitboxrect.top - self.rect.height - camera.camera.y
                self.hitboxrect.bottom = hits[0].hitboxrect.top
            if self.vy < 0:
                self.y = hits[0].hitboxrect.bottom - self.rect.height + self.hitboxrect.height - camera.camera.y
                self.hitboxrect.top = hits[0].hitboxrect.bottom
            self.rect.y = self.y

```

And here is the players update function:

```
def update(self):
    self.move()

    self.hitboxrect.y = self.y + camera.camera.y + self.rect.height - self.hitboxrect.height
    self.rect.y = self.y
    self.collide("y")
    self.hitboxrect.x = self.x + camera.camera.x
    self.rect.x = self.x
    self.collide("x")

```

I think the problem lies somewhere in this code, but if you think otherwise feel free to say so and I would happily add more code!

# Answer
**Somehow I found the answer myself:**

The problem was in the fact that I was adding and subtracting the camera values, so by removing the cameras x and y values the bug disappeared. I am not really sure why this solved it to be honest but I will take it. Here is how the code looks now for anyone curious:

```
def collide(self, direction):
    hits = pg.sprite.spritecollide(self, all_sprites_wall, False, rectconverter)
    if direction == "x":
        if hits:
            print("x")
            if self.vx > 0:
                self.x = hits[0].hitboxrect.left - self.rect.width
                self.hitboxrect.right = hits[0].hitboxrect.left
            if self.vx < 0:
                self.x = hits[0].hitboxrect.right - self.rect.width + self.hitboxrect.width
                self.hitboxrect.left = hits[0].hitboxrect.right
            self.rect.x = self.x
    if direction == "y":
        if hits:
            print("y")
            if self.vy > 0:
                self.y = hits[0].hitboxrect.top - self.rect.height
                self.hitboxrect.bottom = hits[0].hitboxrect.top
            if self.vy < 0:
                self.y = hits[0].hitboxrect.bottom - self.rect.height + self.hitboxrect.height
                self.hitboxrect.top = hits[0].hitboxrect.bottom
            self.rect.y = self.y

```
> 1 votes

---
Tags: 2d, python, collision-resolution, pygame
---


# Question
Title: Error CS1585: Member modifier 'private' must precede the member type and name
I've been knocking errors out of my script after working thoroughly through them but this one has me stumped, even though I'm sure it's something really simple. This is the following error that I'm getting:

> Assets\Scripts\Movement\_Scripts\FirstPersonCharacter\Scripts\FirstPersonController.cs(44,9): error CS1585: Member modifier 'private' must precede the member type and name

From my script:

```
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
using UnityStandardAssets.Utility;
using Random = UnityEngine.Random;
using MouseLook = UnityEngine.MouseLook;

public class FirstPersonController : MonoBehaviour
{
    [SerializeField] private bool m_IsWalking;
    [SerializeField] private float m_WalkSpeed;
    [SerializeField] private float m_RunSpeed;
    [SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten;
    [SerializeField] private float m_JumpSpeed;
    [SerializeField] private float m_StickToGroundForce;
    [SerializeField] private float m_GravityMultiplier;
    [SerializeField] private MouseLook m_MouseLook;
    [SerializeField] private bool m_UseFovKick;
    [SerializeField] private FOVKick m_FovKick = new FOVKick();
    [SerializeField] private bool m_UseHeadBob;
    [SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob();
    [SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob();
    [SerializeField] private float m_StepInterval;
    [SerializeField] private AudioClip[] m_FootstepSounds;    // an array of footstep sounds that will be randomly selected from.
    [SerializeField] private AudioClip m_JumpSound;           // the sound played when character leaves the ground.
    [SerializeField] private AudioClip m_LandSound;           // the sound played when character touches back on ground.

    private Camera m_Camera;
    private bool m_Jump;
    private float m_YRotation;
    private Vector2 m_Input;
    private Vector3 m_MoveDir = Vector3.zero;
    private CharacterController m_CharacterController;
    private CollisionFlags m_CollisionFlags;
    private bool m_PreviouslyGrounded;
    private Vector3 m_OriginalCameraPosition;
    private float m_StepCycle;
    private float m_NextStep;
    private bool m_Jumping;
    private AudioSource m_AudioSource;
    readonly AudioSource AudioSource;
    public UnityStandardAssets.Characters.FirstPerson.MouseLook

    // Use this for initialization
    private void Start()   /* This is line 44 */
    {
        m_CharacterController = GetComponent<CharacterController>();
        m_Camera = Camera.main;
        m_OriginalCameraPosition = m_Camera.transform.localPosition;
        m_FovKick.Setup(m_Camera);
        m_HeadBob.Setup(m_Camera, m_StepInterval);
        m_StepCycle = 0f;
        m_NextStep = m_StepCycle / 2f;
        m_Jumping = false;
        m_AudioSource = GetComponent<AudioSource>();
        m_MouseLook.Init(transform, m_Camera.transform);
    }

    // Update is called once per frame
    private void Update()
    {
        RotateView();
        // the jump state needs to read here to make sure it is not missed
        if (!m_Jump)
        {
            m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
        }

        if (!m_PreviouslyGrounded && m_CharacterController.isGrounded)
        {
            StartCoroutine(m_JumpBob.DoBobCycle());
            PlayLandingSound();
            m_MoveDir.y = 0f;
            m_Jumping = false;
        }
        if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded)
        {
            m_MoveDir.y = 0f;
        }

        m_PreviouslyGrounded = m_CharacterController.isGrounded;
    }

...

```

Now I know the problem is `private void Start()` on line 44, and from everything I've read, it's in the wrong place (to make sure, I changed it to public void, then just left it as void, both resulting in errors) however I'm stumped as to *where* I should move Private Void too.

I appreciate any and all advice on this.

# Answer
> 2 votes
As Casanova says, it looks like your problem is here:

```
public UnityStandardAssets.Characters.FirstPerson.MouseLook

// Use this for initialization
private void Start()
{

```

Note that you didn't finish writing the declaration of your `MouseLook` field, or end the line with a semicolon. So the parser figures the declaration must continue on one of the subsequent lines. It keeps reading on, ignoring white space and comments, until it has a complete declaration. In its reading, it thinks you're trying to say this:

```
public UnityStandardAssets...MouseLook private void Start() { ...

```

...which is gibberish. This is not a valid declaration in C#, so it fails to parse and tells you the first thing it found that was wrong with the declaration, which is that you have `private` after the type, when modifiers like this need to go before the type. That's true, but in context, the real fix is this:

```
public UnityStandardAssets.Characters.FirstPerson.MouseLook giveThisVariableAName;

// Use this for initialization
public void Start()
{

```

Now there's a complete declaration for the parser to find:

```
public      UnityStandardAssets...MouseLook    giveThisVariableAName  ;
 ^ Modifier   ^ Type                            ^ Identifier          ^ End of Line

```

So it parses the `Start` declaration as its own separate statement, rather than trying to interpret it as a continuation of the line above.

This is a basic programming syntax error that doesn't require game-specific expertise to solve, so you should always check our general programming sister site StackOverflow for topics like this. Often you'll find them answered already, sometimes several times over.

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


title: Color palettes in video games

text:
# Question
Title: Color palettes in video games
I’ve spent the days reading all sources I can find on the use of Color palettes in games, but there is a real lack of real world examples. Most Color palette tools generate 4-5 colours.

I am making a game where I have environment, houses, characters, items, etc. How does one Color coordinates that? How large should my palette be and should it contain the shades/tints of each Color?

Having a hard time understanding how to use Color in games, my game is low poly but I feel like I always end up with ugly colours.

# Answer
> 1 votes
There's no definitive answer to this. Most modern games don't really use a color palette, per se, unless you're going with an 8-bit or 16-bit vibe. Not to say that you shouldn't or couldn't use a palette.

As for coordination, learning a little bit about color theory never hurts. You can also use web tools like Paletton to help coordinate color groups.

But as with anything related to art, it's all rather subjective.

---
Tags: color, art
---


title: Imperfect pong AI

text:
# Question
Title: Imperfect pong AI
So I'm starting to learn Java and some OpenGL while using the LWJGL. To start off easy, I'm writing a clone of the Atari Pong. I got set up correctly the game screen, collision detection, and all the game is mostly working, actually, if it were a 2 player game I'd be done by now, but as I'm planning on doing this a single player game, I have to come up with a simple AI to control the second player.

Knowing where the ball will hit seems fairly trivial, and creating an AI which always hits the ball seems like an easy thing to do, but I want the game to be able to be won, so I can't always make the IA hit the ball.

So here's my question, how should I code this to add human-like imperfections to the AI. Should I randomly decide if the AI is going to fail at a given point? Or there's an smarter (or maybe just obvious) thing I'm missing here?

Thank you very much.

# Answer
My favourite imperfect pong AI is brutally simple, yet lets one do some rather nice AI failure.

# Invisible Ball AI

**AI Setup**: When the ball reflects off your paddle, you know where it is and how fast it is going. Spawn an invisible ball at that point but at a greater speed. It will wind up where the visible ball is going. Each frame, have the AI move towards the location of the invisible ball. Stop the invisible ball once it reaches the AI's side, so it is where the AI should move its paddle.

**Results**: The AI looks like it's trying to predict the path of the ball. Say the player has reflected the ball at a steep angle so that it will bounce off a wall. The AI will track the ball down a little ways, and then -- being slower than the ball -- will fail to track it back up fast enough. You have tricked the AI, and it looks fairly logical from a human point of view. You can see the computer trying to predict where the ball will go, and then -- oh, it missed, it was too slow, and you have won a point.

This is significantly better than inserting randomness, since it makes the AI look relatively intelligent. A worthy opponent. It also lets the AI play by the exact same rules as the human, which looks better to the player and makes your job easier.

**Settings**: You can also tweak the speed of the invisible ball, since that will determine how far ahead the AI will plan. The faster the invisible ball, the more time the paddle will have to move to block, and the better the player will have to aim.
> 22 votes

# Answer
The Pong games I've played seem to behave the following way: the AI-controlled paddle knows where the ball will hit but is limited in how fastly it can reach that position. So sometimes it misses. I think this is the most obvious way to do that.
> 24 votes

# Answer
When I created an oh-so-awesome almost-pacman clone on my TI83? calculator, the biggest problem I ran into was that the "ghosts" were far too fast. I had to slow them down somehow. So, I put in a big old sin(cos(tan(x-coordinate))) in there. Easier levels would do that calculation a few times, and harder levels would do only one of the operations.

The point is, REACTION TIME. Research what a typical human reaction time is, and add 10ms onto it. Use that as a starting point. As the levels get harder, remove time from the reaction time...which can be a simple `Thread.sleep(time);` for the AI. Wait that amount of time before the AI starts moving.

You can also control how fast the paddle moves, or, if you REALLY wanted to get complicated, determine where the ball will be based upon varying degrees of information...say only 2 pixels rather than a vector. Add angle modifiers to the walls to add a degree of randomness, forcing the AI to recalculate.
> 14 votes

# Answer
If you simply slow down the paddle, then any time you hit the ball at an acute angle (i.e. moving up and down a lot instead of straight to the other side), the computer would almost always miss because the ball is moving up/down faster than the paddle can compensate.

Instead, what I would do is play with the speed of the paddle, and the point at which the AI reacts. For example:

* when the user hits the ball
    + the AI can react immediately and go to where the ball will be. If it is fast enough, it will get there in time
* when the ball crosses the middle of the field
    + the AI must wait until it crosses the middle of the field before reacting

Another thing to change is *how* the AI reacts. You've highlighted a strategy where the paddle always moves to the position where the ball will be. A person cannot always do that. They are more likely to follow the ball up and down, not knowing where exactly the ball will be when it gets to them due to all the bounces.

Thus, a more *human* method for reaction is to always move towards the ball. For example, if the ball is moving up, then the paddle moves up. If the paddle is fast enough, it can react to the bounces off the top and bottom. If it paddle is not fast enough, then it will over compensate by moving up when the ball moves up, but then when it bounces, the paddle may not be able to move down quick enough.

Lastly, you could play with the paddle size as well to increase/decrease the difficulty.
> 6 votes

# Answer
One factor to consider is randomness - human players always have some degree of variation in their play, so if you want your AI to seem human-like then you'll also want to have some variation in their play.

You can set up ranges for:

* Reaction time (how quickly the AI starts moving)
* Speed (how quickly the AI moves the paddle)
* Accuracy (how close the AI will get to where it actually wants to move their paddle, giving a chance to undershoot or overshoot where they want to be)

Then on each hit by the opponent, the AI can pick a value within those ranges and make its decisions (and movements) based on that. For easier AI opponents, you can make those ranges all rather poor, but also have wide ranges to give the AI some "lucky shots". For more difficult opponents, you can tighten those ranges and put them all in the "good" range.
> 2 votes

# Answer
I'm going to suggest a more general solution that isn't specific to just pong. I believe this could be applied to any game - not just pong. You want human like behavior, right? So that a human can feel like they're playing a human... and therefore by extension hope to win. So, what do you do?

**Observe a human!** How can a player lose at pong? Well, if we watch two pong players it's quite obvious. Usually, the loss is because the ball is simply too fast and the players reaction time was delayed. That's two parameters, one of which is adjustable. The other is the players ability to press the right direction. So you have an error frequency and a reaction frequency - both can be tuned depending on difficulty.

An easy AI would have higher input lag and more tendency to make random mistakes - where as a more difficult AI would be tuned to have these parameters geared to be difficult.

This can be applied to nearly any game - even one such as tic tac toe or even more complex models. This approach breaks down in more complicated scenarios but it is plenty sufficient where games in which the numbers of parameters and scope is narrow.
> 2 votes

# Answer
Here's a list of a few options, some of which have been covered already:

* Make smarter computer players aim the ball so that it's harder for the player to reach with lots of bounces, and do the opposite for easy opponents.
* A smart player will move their paddle towards the middle while the ball is on it's way to the opponent and they don't know where it will come back to.
* Before the final bounce it's harder for a human to predict where the ball will end up. Make the AI have a similar inaccuracy.
* Limit the speed of the paddle so it's slower than the ball. It needs to be less than half the vertical speed to miss with perfect play.
* Increase the speed of the ball based on difficulty, match duration, etc.
* Humans don't react instantaneously. AI players shouldn't either.
* Give the AI a random chance of making a mistake and missing the ball.
> 1 votes

# Answer
I did a small Pong clone too (in LUA).

My AI is very simple but it is not that bad, imho.

I just check for the y position of the ball and if lower I move the paddle down, if higher I move the paddle up.

Then, to fine tune difficulty, I increase or decrease the distance from the ball from which the computer paddle starts to move.
> 0 votes

---
Tags: java, ai
---


title: How to form a sphere from Voxels

text:
# Question
Title: How to form a sphere from Voxels
I want to form a Sphere given radius from blocks given size. And can't figure out the code / algorithm. Any help appreciated.

Edit: I dont wan't the Sphere to be filled, just the outer shell

Edit: I tried this

```
function ds(r)
    for tx=-r, r do
        for ty=-r, r do
            for tz=-r, r do
                if math.sqrt(math.pow(tx, 2)  +  math.pow(ty, 2)  +  math.pow(tz, 2)) <= r-2 then
                    Terrain:FillBlock(Vector3.new(tx, ty, tz), Vector3.new(1,1,1), material)
                end
            end
        end
    end
end

```

But it's very much iterations and so slow and odes the filling that is extra calls.

# Answer
Found this https://jsfiddle.net/mtimmerm/ay2adpwb/

I think it needs some tweaking for spacing between voxels, but it works and was what I wanted.

Code:

```
var radiusInVoxels=10.5
var voxelsize=1/radiusInVoxels;
var shrink=0.9;
var material = new THREE.MeshLambertMaterial( { color: 0xd0d0d0, transparent: true, opacity: 0.85 } );
var group = new THREE.Group();

function drawSphere(R) {
    var maxR2 = Math.floor(R*R);
  var x,y,z;
  var zx = Math.floor(R);
    for (x=0; ;++x)
    {
    //max z for this x value.
    while(x*x+zx*zx > maxR2 && zx>=x)
        --zx;
    if (zx<x)
      break; //with this x, z can't be largest
    z=zx;
    for(y=0; ;++y)
    {
      while(x*x+y*y+z*z > maxR2 && z>=x && z>=y)
        --z;
      if (z<x||z<y)
        break; //with this x and y, z can't be largest
      fillAll(x,y,z); //... and up to 23 reflections of it
    }
  }
}

function fill1(x,y,z) {
    var box = new THREE.BoxGeometry( voxelsize*shrink, voxelsize*shrink, voxelsize*shrink );
    box = new THREE.Mesh( box, material );
    box.translateX(x*voxelsize);
  box.translateY(y*voxelsize);
  box.translateZ(z*voxelsize);
    group.add( box );
}
function fillSigns(x,y,z) {
    fill1(x,y,z);
  for (;;) {
    if ((z=-z) >= 0) {
      if ((y=-y) >= 0) {
        if ((x=-x) >= 0) {
          break;
        }
      }
    }
    fill1(x,y,z);
  }
}
function fillAll(x,y,z) {
    fillSigns(x,y,z);
  if (z>y) {
    fillSigns(x,z,y);
  }
  if (z>x && z>y) {
    fillSigns(z,y,x);
  }
}

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75,
    window.innerWidth/window.innerHeight, 0.1, 1000 );

var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

scene.add(new THREE.AmbientLight( 0xFFFFFF, .1 ));
var light = new THREE.DirectionalLight( 0xFFFFFF, .9 );
light.position.set( 5, 10, 10 );
scene.add( light );

drawSphere(radiusInVoxels);
scene.add( group );

camera.position.z = 2;
camera.position.x = 0;

var render = function (ms) {
  requestAnimationFrame( render );

  var angle1 = ms/10000;angle1-=Math.floor(angle1);
  var angle2 = (ms+1200)/17000;angle2-=Math.floor(angle2);
  group.rotation.x= Math.sin(angle2*Math.PI*2)*0.25+0.6;
  group.rotation.y = angle1*Math.PI*2;
  renderer.render(scene, camera);
};

requestAnimationFrame( render );

```
> 0 votes

# Answer
There are a couple of micro-optimizations you can do here.

1. `math.pow(value, 2)` is often slower than just doing `value * value` (although this might be something worth benchmarking - I do not know your technology stack).
2. The value of `tx * tx` is not going to change during the outermost loop
3. The value of `ty * ty` is not going to change during the second outermost loop
4. The condition `math.sqrt(something) > r` is equivalent to the condition `something > r * r`. But square-roots are usually much more expensive than multiplication, and you only have to do a multiplication once because `r` stays constant throughout the algorithm.
5. You are creating a `new Vector3(1,1,1)` for each block. Does `Terrain:FillBlock` actually require a completely new vector object for each block? Can't you reuse the same vector?

This is how I would optimize this:

```
function ds(r)
    size_vector = Vector3.new(1,1,1)
    r_squared = (r - 2) * (r - 2)
    for tx=-r, r do
        tx_squared = tx * tx
        for ty=-r, r do
            ty_squared = ty * ty
            for tz=-r, r do
                tz_squared = tz * tz
                if (tx_squared  +  ty_squared  +  tz_square) <= r_squared then
                    Terrain:FillBlock(Vector3.new(tx, ty, tz), size_vector, material)
                end
            end
        end
    end
end

```

There is of course also the question if you really need to iterate through a whole cube if you only want to fill a sphere. So you could use trigonometry to calculate the beginning and the end of each loop. But I doubt that this is worth it. Trigonometric functions are again pretty expensive and you are saving less than half of the inner loop iterations (a sphere has 0.5236 times the volume of a cube with the same diameter).
> 2 votes

---
Tags: procedural-generation, sphere
---


# Question
Title: Don't block Camera with Blocking Volume in Unreal Engine
I use Blocking Volumes to prevent players from falling off platforms in a third-person perspective game in UE4.

These Blocking Volumes however block the camera, as if they were a physical wall.

How can I easily add block the player, without blocking the camera?

Ideally without coding/blueprints. If that's impossible, a simple blueprint would be best.

Camera at normal distance from player, when it's not being restricted by a blocking volume

Camera being restricted by a blocking volume

# Answer
> 1 votes
In Details, in Collision, set "Collision Presets" to "Custom..." and then set "Camera" to "Ignore":

---
Tags: collision-detection, unreal-4
---


# Question
Title: Four (4) color channel png has black "background"
I am experimenting with C++ code to load a png file, using libpng. When I get to the color data in the file, I load it into a `std::vector`. I have found that the interface between the C code libpng and my C++ code is straightforward.

I then draw the image using OpenGL.

When the image file is opened in GIMP, it displays as,

When I display the image with my OpenGL code it displays as,

The file I am using is an RGBA image without a backround, i.e., no kBKG chunk.

In looking at the pixel data in my `std::vector`, it appears that the OpenGL data for the lower right is all RGBA = (0, 0, 0, 0).

I was expecting that the png IDAT chunk would carry and display the transparency information.

In OpenGL I am setting the background to RGBA = (1, 1, 1, 1), i.e., in 8-bit RGBA terms (255, 255, 255, 255), white.

I am obviously missing something, but cannot see what it might be.

# Answer
DMGregory's comment of two days ago put me onto the solution by reminding me of something I had read in *Learn OpenGL* some time ago.

In *Learn OpenGL*, by Joey de Vries, Learn OpenGL - Introduction, and specifically his page on blending, Blending, he discusses the combining of two images each with 4-channels of RGBA color data. The formula,

shows how to blend a solid green area, which has an A, alpha, value of 0.6 (OpenGL uses 0.0 to 1.0 to represent 8-bit colors from 0 to 255), and a solid red background with an A value of 1.0.

Since my software was reading an image pixel by pixel, I applied this formula to each pixel and blended it with a solid white, (1.0, 1.0, 1.0, 1.0), background. It seems that without specifying a background image for blending, which could be anything, OpenGL will default to solid black background. This produced the following image:

You can see the shadow detail is now present when it wasn't when I simply used OpenGL's `glDrawArrays()` to render the png image without blending. The new image is still being rendered with `glDrawArrays()`, though it is the modified, blended image.

This is calculation intensive and I know there are better ways of doing this "in production". However, this project was for my own edification.
> 0 votes

---
Tags: opengl, c++, png
---


# Question
Title: How do Idle games progress while not active?
A hallmark of many idle games is the ability to still progress (or at least regain resources) while the game isn't active. The device can even be off.

Initially I figured they just calculated progress off system time next time it was started, but they do not appear fooled by messing with the clock.

How do they manage this specific feat?

# Answer
They do actually use the clock the way you think they do, but they'll sometimes make network requests to get the time from a more reliable source. Try disabling the internet, closing the game and then setting the clock. They should either completely refuse to load or have the wrong values.
> 2 votes

# Answer
They **do** mess with some time and calculate everything from it. The question is which time do they use?

Some games *do* use system time, and on their case, if you change your time locally, you can fool them to earn rewards.

Other games use server time, so when the game starts, it attempts to connect to a server to get that time and make all the calculations. This is more likely the case with web games, as you can't access them as easily as other games.
> 2 votes

---
Tags: unity, android, realtime
---


# Question
Title: Fill with Transparency in Built-In Sprite Editor
When I imported an image for a sprite, I realized it had a white background. I went into the built-in sprite editor to remove it. I tried using fill as there was a transparent color in the color selector. It did not work. Is there a way to do this, or an easier way than erasing it all by hand?

# Answer
You can use the color remover tool. It works just like the fill tool, but it removes the color and replaces it with transparency. It does not work perfectly, but it should do the job. Keep in mind when using it, it removes all of that color in the sprite.
> 0 votes

---
Tags: sprites, game-maker
---


# Question
Title: Is there a standardized way for creating a 2D ball physics movement method?
Is there a standardized method for creating a 2D ball physics movement like you can see on gif below?

# Answer
> 1 votes
This behavior could be characterized as 2D physics reflection. I would recommend reading on physics reflection, for example on the wikipedia page on physics reflection, especially the first opening section about Reflection of Light.

Of special importance is this diagram:

This diagram demonstrates the law of reflection, that \\$θi = θr\\$, or rephrased: the angle of incidence equals the angle of reflection.

Beyond the basics physics, the game in the gif likely also has special behavior to avoid situations where the ball gets stuck bouncing back and forth indefinitely. Additionally there is screen shake, motion blur, particles, and color tinting, all of which could be called "juice" or "game-feel".

---
Tags: unity, 2d, physics
---


# Question
Title: Why don't raytracing algorithms include the speed of light?
From what I understand about ray-tracing, it is instantaneous in its speed from the light source to the user. Is there a type of ray-tracing where the "rays" move at the speed of light or are affected by gravity? Such methods would be useful in simulating large scale systems (like planets).

Also, can the same method be applied to sound?

# Answer
It would be possible to create a raytracing renderer which does this.

You would just need to know the delta-time of the frame you are calculating (time since last frame) and keep track of the distance each ray traveled (which you often do anyway in order to implement certain effects). When the distance traveled exceeds the distance light is able to travel in the current delta-time timeframe, you simply store the current data of the ray in some data-structure and continue computing it the next frame.

You might need some more memory and you might have to calculate a couple more rays per frame, but there are a lot of quality tradeoffs you can make in raytracing to get down to what your target platform can manage.

But the question is if there is a use-case for this feature.

Most games take place on scales where the speed of light isn't relevant. You would need a game which takes place on astronomic scales for the speed of light to have any observable effects. But most games of that kind take place in science fiction scenarios where the speed of light is conveniently ignored anyway for narrative reasons.
> 2 votes

# Answer
I'm going to answer my own question here since I realise the ambiguity of the original question.

It is not impossible in theory to adapt an existing ray-tracing solution so that the rays are limited in distance.

For example, for a simulation at 60 frames per second, a ray of light would travel a maximum of `c/60` *(in a vacuum)* every frame. However, in a simulation with many objects, if the light would need to reflect multiple times before reaching the distance required, it will be computationally intensive to run at close to real time (so a break out value will be needed).

The same solution can be adapted for sound or another wave at a specific speed.
> 0 votes

---
Tags: raycasting, raytracing
---


# Question
Title: Do i need license for make free demo based on Futurama world?
I want to make demo that shows my skills (for hiring) and chose a theme - Simulate Interactive District of Futurama world. So it will consist 3d models and maybe sounds from Futurama tv series. Also it will be published as video on my blog site and probably Youtube (channel without any monetization).

Do i need any Rights/Agreements for doing this?

Thanks.

# Answer
> 3 votes
Whenever you distribute creative works you did not create yourself to an audience, you need to have copyright on those works. It does not matter if you have commercial interest or not.

So if you use the intellectual property of 20th Century Fox without their permission, they can sue you.

<sub>(but do not rely on legal advise of anonymous strangers on the Internet like me)</sub>

But regardless of the legal situation, you have to consider what impression a portfolio like that makes on people you apply to. When they see "oh, I have seen that asset on Futurama", then they will wonder how much more of your portfolio are 3rd party resources you didn't create yourself. A portfolio is supposed to show off what *you* can do, not what work from other people you like. That means your portfolio should consist mainly of things *you* created. Preferably *only* things you created, but if you use any 3rd party resources in your portfolio, make very clear what you have taken from elsewhere and what you created yourself.

---
Tags: licensing, demo
---


# Question
Title: Recalculating normals on a tesselated cubed sphere with heightmap applied
I'm learning about the graphics pipeline using C++, HLSL and DirectX 11 for my course. I'm currently tesselating a cubed sphere with an applied height map.

My issue is figuring out how to recalculate the normals after the tesselated height map is applied. I'm trying to recalculate them in the domain shader like so:

```
// Tessellation domain shader
// After tessellation the domain shader processes the all the vertices
Texture2D HightMapTexture : register(t0);
SamplerState Sampler  : register(s0);

cbuffer MatrixBuffer : register(b0)
{
    matrix worldMatrix;
    matrix viewMatrix;
    matrix projectionMatrix;
};

cbuffer TessellationBuffer : register(b1)
{
    float4 TessellationFactor;
    float4 CameraPosition;
    float4 padding;

};

struct ConstantOutputType
{
    float edges[4] : SV_TessFactor;
    float inside[2] : SV_InsideTessFactor;
};

struct InputType
{
    float3 position : POSITION;
    float4 colour : COLOUR;
    float3 normal : NORMAL;
    float2 tex : TEXCOORD0;
};

struct OutputType
{
    float4 position : SV_POSITION;
    float4 colour : COLOUR;
    float3 normal : NORMAL;
    float2 tex : TEXCOORD0;
};

[domain("quad")]
OutputType main(ConstantOutputType input, float2 uvwCoord : SV_DomainLocation, const OutputPatch<InputType, 4> patch)
{
    float3 vertexPosition;
    float3 normalPosition;
    float2 UV;
    OutputType output;

    float3 v1 = lerp(patch[0].position, patch[1].position, uvwCoord.y);
    float3 v2 = lerp(patch[3].position, patch[2].position, uvwCoord.y);
    vertexPosition = lerp(v1, v2, uvwCoord.x);

    float3 np1 = lerp(patch[0].normal, patch[1].normal, uvwCoord.y);
    float3 np2 = lerp(patch[3].normal, patch[2].normal, uvwCoord.y);
    normalPosition = lerp(np1, np2, uvwCoord.x);
     // Send the input normalPosition into the pixel shader.
    output.normal = normalPosition;

    float2 uv1 = lerp(patch[0].tex, patch[1].tex, uvwCoord.y);
    float2 uv2 = lerp(patch[3].tex, patch[2].tex, uvwCoord.y);
    UV = lerp(uv1, uv2, uvwCoord.x);
    output.tex = UV;

    float hightColour = HightMapTexture.SampleLevel(Sampler, output.tex, 0).r;
    vertexPosition += (2 * hightColour) * float4(output.normal, 0);

    //vertexPosition.z =    sin((vertexPosition.y *2) + (padding.x * 2) *2);
    //vertexPosition.z += cos((vertexPosition.x *2) + (padding.x * 2)*2);

    // Calculate the position of the new vertex against the world, view, and projection matrices.
    output.position = mul(float4(vertexPosition, 1.0f), worldMatrix);
    output.position = mul(output.position, viewMatrix);
    output.position = mul(output.position, projectionMatrix);

    //output.worldPosition = float4(vertexPosition, 1.0f);

    // Send the input color into the pixel shader.
    output.colour = patch[0].colour;
    output.normal = mul(output.normal, (float3x3)worldMatrix);
    output.normal = normalize(output.normal);

    return output;
}

```

# Answer
Recalculating surface normals for a given triangle is simple:

Given a triangle is composed of 3 points (p0, p1, p2), The face normal(Nf) can be defined as:

```
Nf =  (p1-p0) x (p2-p1) ) + ( (p2-p1) x (p0-p2) ) + ( (p0-p2) x (p1-p0)
     --------------------------------------------------------------------
     | (p1-p0) x (p2-p1) ) + ( (p2-p1) x (p0-p2) ) + ( (p0-p2) x (p1-p0)|

```

That is, you take the cross product of two edges, and add it to a vector. Repeat for each set of edges, then normalize the product.

That's the easy part.

To compute the vertex normals, you need two passes over the entire mesh:

First, for each vertex, compute a normal:

```
Nv(i) =  ( V(i+1) - V(i) ) x ( V(i) - V(i-1) )
       ----------------------------------------
       | (V(i+1) - V(i) ) x ( V(i) - V(i-1) ) |

```

Then add this to the normal for each vertex in the mesh, (assuming it is an indexed mesh)

When the whole mesh has been recalculated, you can then go through each vertex and normalize the normal vector.

The problem, is that in graphics memory, a mesh is just a series of floats in sets of 3 x 3, representing a triangle, with no sense of neighbours. Thus, you need to figure out which triangles neighbor others, in order to know which triangles share vertices with others.

You can, however, fudge it a little, by just computing the normals as above per vertex. It's not really correct though, but it works.
> 1 votes

---
Tags: c++, directx11, hlsl, normals, computational-geometry
---


# Question
Title: How can "Box Collider is trigger" apply to the Player, not the enemies (make them collide, not pass through)?
So, in my game, the Powerup (capsule) has a RigidBody and a Box Collider. I’ve set the Box Collider to «is trigger». When the player hits the powerup, it disappears - just as it’s supposed to.

Is it possible to let the enemies collide with the powerup (bump into it) instead of just passing through it? From the Enemy script:

```
    void Start()
{

        enemyRb = GetComponent<Rigidbody>();
        gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
        player = GameObject.Find("Player");

}

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

    if (player != null && gameManager.isGameActive)
    {
        enemyRb.AddForce((player.transform.position - transform.position).normalized * speed);
    }

    if (transform.position.y < -4)
    {
        Destroy(gameObject);
        gameManager.UpdateScore(pointValue);
    }
}

```

From the PlayerController script:

```
private void OnTriggerEnter(Collider other)
{
        if (other.CompareTag("Powerup"))
        {
            hasPowerup = true;
            Destroy(other.gameObject);
        }
}

```

# Answer
> 1 votes
Firstly, i would recommend to move OnTriggerEnter from PlayerController to PowerupController:

```
private void OnTriggerEnter(Collider other)
{
        if (other.CompareTag("Player"))
        {
            other.GetComponent<PlayerController>().HasPowerup = true;
            Destroy(gameObject);
        }
}

```

It is not character's job to detect and destroy powerups; it would be better not to clutter characters scripts with additional logic when possible.

**Now to collisions.**

The best way is to use layers: https://docs.unity3d.com/Manual/LayerBasedCollision.html

Simply attach another collider as a child gameobject to powerup and set it physics layer to intersect with enemies and not intersect with the player.

... Or you could use OnCollisionEnter(Collision other) instead of triggers, but using triggers almost always is better idea.

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


# Question
Title: JsonUtility is throwing exception when there is \" in the string
The following is my JSON file:

```
{
    "data" : [
               {
                 "nameString" : "My name is \"Ansar\"",
                 "id" : 1234
               }
    ]
}

```

When I try to parse this JSON file using **JsonUtility**, it is throwing an exception because of the **\\"** character. If I remove the character from the string, it works smoothly.

**Exception**:

```
ArgumentException: JSON parse error: Missing a comma or '}' after an object member.
UnityEngine.JsonUtility.FromJson (System.String json, System.Type type) (at /Users/builduser/buildslave/unity/build/Modules/JSONSerialize/Public/JsonUtility.bindings.cs:50)

```

Why this is happening? Is this a **JsonUtility** bug? Anyways to fix this?

# Answer
> 0 votes
Found the solution.

The `"nameString" : "My name is \"Ansar\""` should be kept as `"nameString" : "My name is \\\"Ansar\\\""`. That is *Backslash* is replaced with \\ .

Resource: https://www.freeformatter.com/json-escape.html

---
Tags: unity, json
---


title: Create and serve AssetBundle at runtime

text:
# Question
Title: Create and serve AssetBundle at runtime
What I am developing is not a game, but is done in Unity3d, so I believe here is a good place to ask.

Context:

* The unity application runs in the WebPlayer inside a web application

Case:

* User uploads a file on the website
* Webserver processes the file, does conversion and business stuff. Ends up with a DAE(Collada) file
* The DAE file that has been generated on the server needs to be loaded and shown in the Web player inside the browser of the one who uploaded it

Now, I am not very well versed in Unity, so I just want to lay out what I expect to do, and then hope to get feedback on whether that is smart, or whether there is a better approach.

So starting from top down, here's my thinking

* In order for the Web Player to find the file and use it as an asset, it should be an AssetBundle, which I can load with UnityWebRequestAssetBundle.GetAssetBundle
    + that shouldn't be much trouble. If the `AssetBundle` is stored somewhere that the web app can serve it, I expect that to just work? I see in docs that Unity can load "AssetBundles from the project folder", but I don't expect that "project folder" is part of the game when loading from a URL. How would it?
* In order to generate the `AssetBundle`, I would need to have a Unity application running on the server (a headless build of unity), which would pick up the generated DAE file and use BuildPipeline.BuildAssetBundle to create the `AssetBundle` and store it where the web app can serve it
* The communication between browser, unity web player, web app server, and unity server instance is something I can manage on my own. I can work with sockets and jslibs to sort out my needs, so that doesn't need to be described here
* Instantiating the `GameObject` after loading the `AssetBundle` into the Web Player, I expect to be simple, just following the docs for the AssetBundle

Extra credit:

* Sources for how to do the headless unity instance would be great. Sort of like a game server, but not really caring about clients connecting, but rather working with the filesystem on the server

# Answer
You don’t seem to have a lot of questions here, so I’ll answer the ones I see.

Loading an asset bundle from a web server using a normal http/s URL works just fine. It can *also* load bundles from within the project, in the StreamingAssets folder, using `Application.streamingAssetsPath`, but that is irrelevant to your needs.

As for the extra credit, you can run Unity in batch mode, and specify a public static method to execute on start.

See here : https://docs.unity3d.com/Manual/CommandLineArguments.html

The example on that page shows this, which is a barebones implementation similar to your needs:

```
using UnityEditor;
class MyEditorScript
{
     static void PerformBuild ()
     {
         string[] scenes = { "Assets/MyScene.unity" };
         BuildPipeline.BuildPlayer(scenes, ...);
     }
}

```

Windows:

```
C:\program files\Unity\Editor\Unity.exe -quit -batchmode -executeMethod MyEditorScript.PerformBuild

```

Mac OS:

```
/Applications/Unity/Unity.app/Contents/MacOS/Unity -quit -batchmode -executeMethod MyEditorScript.PerformBuild

```
> 2 votes

---
Tags: unity, asset-management, assetbundle, unity-webgl
---


# Question
Title: Twine Harlowe: Can I create passage links with the gui? Or any alternative way?
I'm confused how I am expected to organize and write a story within Twine using just the tools outlined in the manual. The main concern revolves around initiating links between my squares/charts/whatever (the passage link system). Am I expected to always manually type \[\[\]\] with the correct name of the passage to assign any flow of passage?

I see this as being problematic when designing a story, as you would need to consistently re-position/delete/add-new squares to tell the story properly. I am confused why the gui doesn't seem to support the drop and drag between existing flow arrows? OR does it..? Going in and manually changing the names of everything each time I have to change a position...and needing to use a brand new name cause the existing name won't overwrite or swap. Some people seem to recommend ordering the passage titles by number, but this creates the very problem I am outlining where when changing the position of 3 and 4 you'd have to use like some offbrand title, and do about 8 steps just to swap positions.

Am I supposed to use a different program instead when concocting my story and only use twine once I know where everything goes? Doesn't that defeat the point of it to begin with?

# Answer
Twine does not support GUI based passage linking, you can find a list of story map GUI actions here, on the Twine Docs.

The standard Harlowe linking technique is the `[[link text | passage name]]` format, as stated here in the Harlowe docs, as well as in the general Twine docs, here.

If you are looking to iterate rapidly on changing passage linkages from a big picture view like the story map, I would consider using a flowchart/diagramming software like draw.io to create a diagram representing the desired story shape and implementing it in Twine.
> 2 votes

---
Tags: twine, harlowe
---


# Question
Title: I created a preview of my player camera with another camera but when disabling the main menu it show no cameras exist why?
I created a Render Texture named it : GUICameraRenderTexture

This is a screenshot of the Player camera : I assigned to the Target Texture the new GUICameraRenderTexture :

Then on the bottom of the hierarchy I have a Main Menu \> Camera : The new Camera I changed the Clear Flags to Don't Clear and Culling Mask to Nothing :

Then there is a Canvas the Canvas Render Mode is set to Screen Space - Overlay

And last the Raw Image I assigned to the Texture the GUICameraRenderTexture :

The problem is either in the editor mode or in runtime where the game is running if I disable the new GUI Camera the camera under Main Menu it give error that there is no cameras to render even if the Player camera is enabled.

I want to start the game with the Player camera and then on escape key to switch to the main menu gui camera.

Screenshot if I'm disabling the main menu gui camera :

# Answer
The second camera is the only one rendering to the screen. The "master camera" is rendering to a texture, which means that it will not render to the screen. If you want to allow the camera to render to the screen, you need to set the render texture target to null.
> 1 votes

---
Tags: unity, camera
---


title: How do I get rights to an game?

text:
# Question
Title: How do I get rights to an game?
I' looking to get rights to an game called *Grand Theft Auto: Chinatown Wars for the Nintendo DS*. I am a Nintendo 3DS Developer trying to make a remastered version for the Nintendo 3DS. How would I go about getting the rights for the game. Do I get the rights from Rockstar, Nintendo, or another party. I'm not sure.

# Answer
**You find out who currently owns the IP and you make them an offer**.

It's that simple, but...

**First complication** is that the owner of an IP is not necessarily the same as the developer, who in turn is not necessarily the same as the publisher. The probability is that the IP was licensed to multiple parties during the course of making the game, and all of these licenses will come with their own terms and conditions.

**Second complication** is that you're very unlikely to get full rights. Best case is you'll likewise get a license, likewise with terms and conditions, and of limited duration.

**Third complication** is that, for a franchise like GTA, this is going to be outside of your price range. How do I know this? Because you're asking on a SE site, that's how. That tells me you're not a development house backed up with agents and lawyers and publishers, because if you were you would be talking to them instead. You're probably a solo hobbyist developer.

So the real answer to your question is: **you don't**. Instead you set your aspirations a little lower; consider making a clone or something.
> 7 votes

---
Tags: game-design, legal, copyright, nintendo, intellectual-property
---


# Question
Title: Get all objects of Additively loaded Scene? (LoadSceneMode.Additive)
I learned how to Load and unload scenes in unity. using LoadSceneMode.Additive.

I like to spit up my scenes as much as possible and retain the stuff I need as I go along.

I'd like to be able to find all objects loaded from a specific scene. Obviously Unity knows but I can't find how to get them.

For now, my workaround is to put them in a specifically named empty or have them tagged in a certain way, but that is a workaround.

Is there an easier way?

# Answer
From this answer mixed with your needs, I would proceed in this way:

```
List<GameObject> FindSceneObjects(string sceneName){
    List<GameObject> objs = new List<GameObject>();
    foreach (GameObject obj in Object.FindObjectsOfType(typeof(GameObject)))
    {
        if(objs.scene.name.CompareTo(sceneName) == 0){
            objs.Add(objs);
        }
    }
    return objs;
}

```

Or you can compress the for-loop using a linqstatement

```
var objs = from GameObject go in GameObject.FindObjectsOfType(typeof(GameObject)) where go.scene.name == sceneName select go;

```
> 1 votes

# Answer
Cache all objects at the start and detect the changes in the array (or the list).

To elaborate more, have a list like this:

```
//This list holds all the GameObjects that are currently in the game.
private List<GameObject> _existingObjects = new List<GameObject>();

```

And call this method at the beginning of the game, and every time a scene is loaded:

```
//using System.Linq;

public List<GameObject> FindNewGameObjects()
{
    //Get all GameObjects.
    var allObjects = (FindObjectsOfType(typeof(GameObject)) as GameObject[]).ToList();

    //Substract the existing GameObjects from all GameObjects, so the result will be the new ones.
    var result = allObjects.Except(_existingObjects).ToList();

    //Update our list.
    _existingObjects = allObjects;

    //Return the result.
    return result;
}

```

The return of the `FindNewGameObjects()` method will be the list of GameObjects that came with the loaded scene.

***Note:*** *The code is not tested.*
> 1 votes

# Answer
Unity has a struct named `Scene`. From `Scene` you can get all of the root `GameObjects` of this particular scene.

> Note that the code is not tested.

```
public static class SceneExtensions
{
    public static void GetAllGameObjects(this Scene scene, out List<GameObject> allGameObjects)
    {
        GameObject[] rootGameObjects = scene.GetRootGameObjects();

        allGameObjects = new List<GameObject>(rootGameObjects);

        for (int a = 0; a < rootGameObjects.Length; a++)
        {
            //? This is kind of a hack because you can use recursive or other methods to access children via `Transform - GetChild()`. I haven't tested which method is more efficient.
            Transform[] childrenTransform = rootGameObjects[a].GetComponentsInChildren<Transform>();

            for (int b = 0; b < childrenTransform.Length; b++)
                allGameObjects.Add(childrenTransform[b].gameObject);
        }
    }

    public static GameObject[] GetAllGameObjects(this Scene scene)
    {
        scene.GetAllGameObjects(out List<GameObject> allGameObjects);

        return allGameObjects.ToArray();
    }
}

```

Then the usual approach is to get scene by build index.

```
Scene scene = SceneManager.GetSceneByBuildIndex(sceneBuildIndex);

```

> From my own experience, only loaded scenes will give you the correct result when using this method to get a scene. I couldn't find a way to get a `Scene` of unloaded `SceneAsset` at run-time (I would appreciate if someone shared this with me if such thing is achievable).

Then you can proceed to getting all of the `GameObject`s of that `Scene`.

```
GameObject[] sceneGameObjects = scene.GetAllGameObjects();

```
> 1 votes

# Answer
My problem got solved. I will put points toward Leggy7 as he gave me the idea to solve my the problem.

The Old procedure is his way of solving it....

```
List<GameObject> FindSceneObjects_Old(String sceneName)
{
    List<GameObject> objs = new List<GameObject>();
    foreach (GameObject obj in GameObject.FindObjectsOfType(typeof(GameObject)))
    {
        if (obj.scene.name == sceneName)
        {
            objs.Add(obj);
        }
    }

    return objs;
}

```

This is my way of solving it using LINQ

```
List<GameObject> FindSceneObjects(String sceneName)
{
    var objs = from GameObject go in GameObject.FindObjectsOfType(typeof(GameObject)) where go.scene.name == sceneName select go;

    return objs.ToList();
}

```

**Note: Both codes tested and functional**

I am aware there is a shorthand for writing LINQ statements but since I have a Background in SQL I am used to this format.
> 0 votes

---
Tags: unity, scene, scenemanager
---


# Question
Title: How to draw a rectangle with a border pixel over a camera/viewport?
**With this code I intended to visually delimit the complete view of the circuit and the two controlled cars:**

```
draw_rectangle(0,0,1279,719,true);
draw_rectangle(0,720,639,1079,true);
draw_rectangle(640,720,1279,1079,true);

```

**It turns out that only the complete view of the circuit that is drawn directly in the room is correctly delimited (observe the black line of a thick pixel):**

**Where there should be the rectangle strokes (red line, not necessarily at this thickness):**

**This happens because of this camera/viewport:**

I believe the rectangle is being drawn under the camera/viewport.

What do I need to do to make this rectangle draw over the camera/viewport?

# Answer
> 0 votes
Just draw everything you want to overlay the camera image the way you would draw a **HUD/UI**. Using the **draw GUI event**.

**Result:**

---
Tags: camera, game-maker, viewport
---


# Question
Title: How can I skew a SpriteRenderer in an animation to grow a side and decrease the opposite side by the same amount?
I am interested in the maths and maybe the shader code. I am almost sure that this would be a great starting point but I do not have any knowledge about shaders and the language they are written in.

The little project is just an attempt to create a flippable sprite, like the one I did in WPF but more interesting because of the "closer" perception. The objective is to learn. I have two animations, one rotating around the Y axis and the other one is this skew that I do not know how to do.

On the web I have found old answers and answers that use `Image` instead of `SpriteRenderer`, some complex math that I cannot comprehend yet.

Ideally the animation would go through all these states, from left to right, and then in the inverse order, from right to left (blue means unflipped state, green means flipped state):

I have started working with Unity since less than a week and I have forgotten a lot of maths and geometry I learned in school. But I am eager to learn again.

Thank you.

# Answer
> 1 votes
Having 3 sprite renderers in the scene, with a script attached which makes them rotate around the Y axis of each of them, and the Main Camera selected, it is visible in the screenshot below that I changed the `Projection` property of the `Camera` component inside the `Inspector` pane to `Perspective` (it is written with blue `Projection` and in the right there is a combo box). This makes the animations work the way I asked in the question.

Below there is one of the game objects with sprite renderer selected and the `Inspector` pane shows the usage of the `Player Script` (source code below).

# Script

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

public class PlayerScript : MonoBehaviour
{
    private SpriteRenderer sr;
    public Color32 unflippedColor = new Color32(0, 255, 0, 255);
    public Color32 flippedColor = new Color32(0, 0, 255, 255);

    // Start is called before the first frame update
    void Start()
    {
        sr = GetComponent<SpriteRenderer>();
        StartCoroutine(FlipLoop());
    }

    private bool IsFlipped = false;

    bool isUnflippedAngle(float a)
    {
        return !(a <= 90 || (a >= 270 && a <= 360));
    }

    IEnumerator FlipLoop()
    {
        while (true)
        {
            float startAngle = transform.rotation.eulerAngles.y;
            float angle = Time.deltaTime * 15f;
            transform.Rotate(new Vector3(0, 1, 0), angle);
            float endAngle = transform.rotation.eulerAngles.y;

            if (isUnflippedAngle(endAngle))
            {
                sr.color = unflippedColor;
                IsFlipped = false;
            }
            else
            {
                sr.color = flippedColor;
                IsFlipped = true;
            }
            yield return new WaitForEndOfFrame();
        }
    }

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

    }
}

```

# The sprite

# Video screen capture

Thank you.

---
Tags: unity, c#, shaders, matrix, scale
---


# Question
Title: How do I account for the velocity difference between a ship and it's fired projectile?
In my project, I have a ship that moves and increases it's movement speed with respect to time and how long the acceleration button is being pushed(just like the way a real life car works), now as expected, the ship fires projectiles when I press the fire button.

The problem here, is that at a point in the game, the ship reaches it's highest speed/terminal velocity, and now it's faster than the projectile it fired which is not what I want, so, how do I create a realistic projectile movement based on the ship's velocity? This is so that if the projectile is fired when the ship is moving slowly through the game scene, it doesn't move so fast that we can't see it travelling in the forward direction, and at the same time if it is fired when the ship is moving at top speeds, the ship is not seen to be faster than or as fast as the projectile's speed.

I want to keep the code as optimized as possible, so I am using this line for the projectile's movement:

```
public float velocity = 100f;
void Update() {
transform.position += transform.forward * Time.deltaTime * velocity;

}

```

# Answer
On your ship, you should have some sort of instantiation for the bullet, or wherever else you have it. Let's say you're instantiating your bullet like so:

```
{
   GameObject bullet = GameObject.Instantiate(bullet, transform.position, transform.rotation);
}

```

Instead of doing just this, give its velocity an initial value, like so:

```
{
   GameObject bullet = GameObject.Instantiate(bullet, transform.position, transform.rotation);
   bullet.velocity = bullet.velocity + ship.velocity;
}

```

Since you've changed your velocity value, it should now use that value instead. You should have some way to calculate the velocity of your ship (or ideally, you already have the velocity of the ship stored on a script on the ship itself).

If your ship is going -100f and your bullet's speed is 100f, your bullet will stand still, but that's actually just how physics works. So, destroy the bullets after some time. Remember, even if a bullet leaves the screen and cannot be seen by the camera, it still exists in game.
> 0 votes

---
Tags: unity, c#, physics, unityscript, projectile-physics
---


# Question
Title: What is the proper, legal way to make a derivative video game?
I want to make a game derived from an existing game. That game is owned by a live company.

How do I go about contacting the rights owners correctly and negotiating for the rights to the content?

# Answer
> 6 votes
> Are there any legal ways to acquire the rights to make a derivative video game?

Yes, it's frequently done.

> The game is owned by a live company, so how would I contact them correctly and negotiate for the rights to the content?

Find their contact information on the web. Typically with a "Contact Us" page. You're likely not going to find a "Use this number to contact us about making a derivative game". Find their main contact number and work your way through the channels. You may not be able to talk to anyone about it, they might reject you before then.

> What are some different deals that we could make?

Lots, or none. Depends on what you have available to offer and what they're willing to offer.

# Answer
> 1 votes
IP can get EXPENSIVE, and it gives a third party way to much control over your game (including, potentially, an expiration date).

Ever heard of Starwars Galaxies? It was pretty infamous for two reasons. 1) \[unrelated\] they nigh-completely changed their gameplay well after release. Was not well received. 2) They shut down for no apparent reason.

The reason however isn't all that hard to deduce.

* Starwars Galaxies shutdown: December 15, 2011
* Starwars The Old republic released: December 20, 2011

Only **5 days later**.

In fact, I understand that the then-president of SOE (the devs behind SWG), John Smedley, SWORE OFF others' IP as a direct result. Someone else shut one of his games down, and he had no say in the matter, no recourse. "Take this corncob, right where it'll hurt most. Oh, and take the blame for shutting your game down so it doesn't hurt the sales of the next one."

I can't imagine why he'd be upset by the experience.

On the "up side", the game industry has a Long and Storied history of "borrowing ideas" from one another. iD made the first FPS. To some extent, everyone who made one afterwards was "ripping them off". If you want to mimic gameplay, go for it. You can't patent/copyright/etc GAMEPLAY.

If you want their characters, backstory... not so much. Still, it's not that hard to make up your own similar characters. Superman (DC comics) knockoffs: Marvel: Gladiator, Hyperion, Sentry. Image: Apollo (who is (was?) married to "Midnighter", their Batman knockoff, good times!). Gladiator even has the same "last of his species" thing going.

Other Peoples Intellectual Property can be an "I Win" button for initial sales. OPIP can also be a boat anchor around your neck, dragging you under.

YMMV.

---
Tags: legal, intellectual-property
---