# Question
Title: Animation Change Delay When Landing On Ground
I am working on a 2d platformer-like game in Unity. My problem is that when my player character jumps and lands back on the ground, there is a slight delay at times when transitioning to the player idle animation. **This is not due to exit time.** Instead, upon researching this topic, I found that my real problem lies in the Unity physics loop(FixedUpdate).

`FixedUpdate`, as the name implies, is called a fixed amount of times, not every frame. My animator relies on a `Jumping` boolean to tell it whether or not to be in the jumping animation. In my code, the `Jumping` boolean is set to false when the player lands on the ground. This is handled by `OnCollisionEnter2D`, which runs on `FixedUpdate`.

This is were I think my problem lies:

```
private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.CompareTag("Ground"))
    {
        _isOnGround = true;
        _animator.SetBool("Jumping", false);
    }
}

```

I need to know whether or not the player is colliding with the ground, So I setup a tag. I need to find a way to constantly check whether or not I am colliding with the ground, So that I do not see an animation transition delay.

Any Ideas of how I could accomplish this?

# Answer
I found that changing the rigidbody collision detection type to **continuous** helped remedy the delay. Although it still is there to an extent, this is the best solution I could find for the time being.
> 0 votes

# Answer
You should check out Physics2D.OverlapArea. It takes a rectangle and checks if it is overlapping with another sprite. Here is some code I have been using that works well.

```
//Corners of the rectangle to check
 public var top_left : Transform;
 public var bottom_right : Transform;
 public var ground_layers : LayerMask;
 var grounded : bool;

 function FixedUpdate(){
     grounded = Physics2D.OverlapArea(top_left.position, bottom_right.position,
   ground_layers);
  }

```
> 0 votes

---
Tags: unity, c#, physics, animation
---


# Question
Title: How do I convert a panorama image into a skybox?
I have two panoramas (, ) that are the same but are shaped a little different.

I don't care which one, but how should I go about converting them into a Skybox? I was looking for something like this:

(Image source here.)

How can I do this? I will use an image editing software if I have to.

# Answer
> 2 votes
That software you've linked seems to do what you want, but I presume you would need something that's free?

This tutorial has a blender file that you can use (see section "CONVERT TO CUBE"): https://aerotwist.com/tutorials/create-your-own-environment-maps/

# Answer
> 3 votes
I had the same issue on my project. If you're on Windows 10, I created a utility called Qbit that will export the six faces from the source image. There's a free version available here: https://pragmar.com/qbit/

---
Tags: projection, skybox
---


title: Camera follow 3D Object OpenGL

text:
# Question
Title: Camera follow 3D Object OpenGL
I'm trying to make my camera follow a 3D object, the X and Y values from the camera position are the same as the 3D object, but the Z axis is not the same, it has an offset of 13.0f so the camera looks to the object from a distance. The problem is that, the more I go up with the object, more the object disappears on the screen, its like the camera is following it slowly, or like, since the camera is far away then the object goes up faster than the camera, so how do I center the object in the middle of the camera?

\[my current code for the view matrix of the camera\]

```
view = glm::lookAt(position, position + forward, up);

```

# Answer
Hard to tell how you are using it but if you set it up like this,

`glm::lookAt(cameraPosition,
 targetPosition,
 up);`

then it should work.
> -1 votes

---
Tags: opengl, c++, glm
---


# Question
Title: Why the canvas text is gray and not really white?
This script change the text color to white:

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

public class DisplayInfo : MonoBehaviour
{
    public string myString;
    public Text myText;
    public float fadeTime;
    public bool displayInfo = false;

    // Use this for initialization
    void Start()
    {
        if (myText == null)
        {
            Debug.LogError(myText + " Is null please add Text component !");
        }

        if (myString == "")
        {
            Debug.LogWarning(myString + " Is empty, No text will be display.");
        }

        myText.color = Color.clear;
    }

    // Update is called once per frame
    void Update()
    {
        FadeText();
    }

    void FadeText()

    {
        if (displayInfo)
        {
            myText.text = myString;
            myText.color = Color.Lerp(myText.color, Color.white, fadeTime * Time.deltaTime);
        }

        else
        {
            myText.color = Color.Lerp(myText.color, Color.clear, fadeTime * Time.deltaTime);
        }
    }
}

```

This is the script i'm using with the DisplayInfo:

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

public class DetectInteractable : MonoBehaviour
{
    public Camera cam;
    public float distanceToSee;
    public string objectHit;
    public Image image;
    public bool interactableObject = false;
    public DisplayInfo displayInfo;
    public Canvas canvas;

    private RaycastHit whatObjectHit;

    private void Update()
    {
        Debug.DrawRay(cam.transform.position, cam.transform.forward * distanceToSee, Color.magenta);

        if (Physics.Raycast(cam.transform.position, cam.transform.forward, out whatObjectHit, distanceToSee))
        {
            if (whatObjectHit.collider.gameObject.tag == "Interactable")
            {
                image.color = Color.red;
                objectHit = whatObjectHit.collider.gameObject.name;
                interactableObject = true;
                displayInfo = whatObjectHit.collider.gameObject.GetComponent<DisplayInfo>();
                displayInfo.displayInfo = true;
            }
            else
            {
                image.color = Color.white;

                if (displayInfo != null)
                    displayInfo.displayInfo = false;
            }
        }
        else
        {
            image.color = Color.white;

            if (displayInfo != null)
                displayInfo.displayInfo = false;
        }
    }
}

```

When it's "Interactable" then i display the info about this object.

The DetectInteractable is attached to the Player (FPSController) in the hierarchy:

And on each "Interactable" item i attach the script DisplayInfo: For example the door:

And this is the editor screenshot before running the game: Display Infomration is Canvas. The Text i set it's color to white in the inspector.

But when running the game the text i see on objects is gray and i see that on the inspector the white is becoming gray: On the game view window there is a text Security Door in fray it's hard to see it. It should be in white and bright enough to see it clear:

# Answer
> 1 votes
```
public float t = 0f;

// Use this for initialization
void Start()
{
    if (myText == null)
    {
        Debug.LogError(myText + " Is null please add Text component !");
    }

    if (myString == "")
    {
        Debug.LogWarning(myString + " Is empty, No text will be display.");
    }

    myText.color = Color.clear;
}

// Update is called once per frame
void Update()
{
    FadeText();
}

void FadeText()

{
    if (displayInfo)
    {
        myText.text = myString;
        myText.color = Color.Lerp(Color.clear, Color.white, t);
        if (t < 1)
        {
            t += Time.deltaTime / fadeTime;
        }
    }

    else
    {
        myText.color = Color.Lerp(Color.white, Color.clear, t);
        if (t < 1)
        {
            t += Time.deltaTime / fadeTime;
        }
    }
}

```

this should work as you want
make t = 0 every time you want to show or fade the text
if the color still not changed then check if there is other script that change the text color

other solution use dotween
it's faster than figuring how Lerp is working

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


title: Unity virtual method with return

text:
# Question
Title: Unity virtual method with return
I'm trying to have my virtual update method set up so it can return in case the mouse is over a UI object.

The thing is, if it returns, the method that override it and uses "base.Update()" still keeps running, as the override also override the original return.

This is the rough code:

**Level.cs** *(for example)*

```
protected virtual void Update () {
    if (EventSystem.current.IsPointerOverGameObject())
        return;
}

```

**Level1.cs** *(for example)*

```
protected override void Update () {
    base.Update();

    // Code that I don't want to run in case the original method returned
}

```

Thank you so much.

# Answer
> 1 votes
Overriding is not the right tool for this job. Returning from a base method, just like returning from any method, only passes control back to the method that called it (in this case, resuming your child class's Update).

To tell the calling method not to proceed, you need to send it an explicit signal, something like this:

```
public class BaseBehaviour : MonoBehaviour {

    protected bool ShouldContinueAfterSharedUpdate() {
        // Put logic you always want to execute here.

        if(EventSystem.current.IsPointerOverGameObject())
            return false; // "No, don't continue."

        // Put logic that should execute only conditionally here.
        // ...

        return true; // "Yes, continue with subclass-specific updates."
    }
}

public class DerivedBehaviour : BaseBehaviour {

    void Update() {
        // Run shared update logic and detect if we should abort.
        if(ShouldContinueAfterSharedUpdate() == false)
            return; // We got an abort signal, so we're done.

        // Put logic that should execute only conditionally here.
        // ...
    }
}

```

In general, be a bit wary about relying too heavily on inheritance in Unity. Because of its component-based structure, you often get better code flexibility (and fewer serialization woes) from going with the flow of composition over inheritance. If all you need is a common way to early-out of updates, a static utility method works just as well, and can be called from any class regardless of its relationship in the inheritance hierarchy.

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


# Question
Title: Calling out stored variables in class all at once?
I have a class PlayerStatistics that doesn't sit on a monobehaviour:

```
public class PlayerStatistics
{
    public int currentHealth;
    public int maxHealth;
    public bool hasWeapon;
    public Collider weapon;
    public Transform weaponChild;
    public Animator weaponAnim;
    public GameObject droppedWeaponObject;
    public DialogueManager DM;
}

```

and I have PlayerController script that contains those variables shown above as well as a Save and Load function:

```
    public int currentHealth;
    public int maxHealth = 100;
    public bool hasWeapon;
    public Collider weapon;
    public Transform weaponChild;
    public Animator weaponAnim;
    public GameObject droppedWeaponObject;
    public DialogueManager DM;

    public PlayerStatistics localPlayerData = new PlayerStatistics();
    public void LoadPlayer()
    {
        localPlayerData = GlobalControl.Instance.savedPlayerData;
    }
    public void SavePlayer()
    {
        GlobalControl.Instance.savedPlayerData = localPlayerData;
    }

```

And a GlobalControl to store values for said variables across scenes:

```
    public class GlobalControl : MonoBehaviour {
    public static GlobalControl Instance;
    public string savedJson;
    public PlayerStatistics savedPlayerData = new PlayerStatistics();
    void Awake()
    {
        if (Instance == null)
        {
            DontDestroyOnLoad(gameObject);
            Instance = this;
        }
        else if (Instance != this)
        {
            Destroy(gameObject);
        }
    }
    private void Update()
    {
        Debug.Log(savedJson);
    }
}

```

I can get each value by doing:

```
GlobalControl.Instance.savedPlayerData.<variablehere> = variableNameHere;

```

but the question is, if I have a lot variables, how do I get all of it at once. I followed a tutorial that thought me this and it was like:

```
GlobalControl.Instance.savedPlayerData = localPlayerData;

```

# Answer
1. Make PlayerStatistics a `struct` instead of a `class`.

That way, this line: `localPlayerData = GlobalControl.Instance.savedPlayerData;` will *copy* the `GlobalControl`'s version of `savedPlayerData` instead of just taking a reference to it, and likewise create a separate copy when we save the data back to the GlobalControl.

(This keeps us from accidentally corrupting our saved copy when we modify variables in the local copy)
2. Make PlayerStatistics `[System.Serializable]` so that its members show up in the inspector, so you don't lose any editing flexibility.
3. Delete everything in your `PlayerController` script that duplicates variables that are already in `PlayerStatistics`.

You already have an up-to-date version of that data, so why make extra copying work for yourself? Just read and write straight from `localPlayerData.currentHealth` and such. `localPlayerData` is then your live working copy of all of these variables.
> 2 votes

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


# Question
Title: Object in Box2d doesn't sit perfectly on top of other object
I have a rectangle in my player class with the following properties

```
b2BodyDef player;
player.type = b2_dynamicBody;
player.position.Set(x + width, 10.17f - (y + height));

m_PhysicsBody = level->GetPhysicsWorld().CreateBody(&player);

b2PolygonShape shape;
shape.SetAsBox(width, height);

b2FixtureDef fixture;
fixture.shape = &shape;
fixture.density = 1.0f;
fixture.friction = 1.0f;

m_PhysicsFixture = m_PhysicsBody->CreateFixture(&fixture);
m_PhysicsFixture->SetUserData(this);

```

and another rectangle in my level class with the following properties

```
b2BodyDef ground;

ground.position.Set(x + width, 10.17 - (y + height));

b2PolygonShape groundBox;
groundBox.SetAsBox(width, height);

b2Body* m_Body = m_PhysicsWorld.CreateBody(&ground);

b2FixtureDef fixture;
fixture.shape = &groundBox;

fixture.friction = 1.0f;

m_PhysicsFixture = m_Body->CreateFixture(&fixture);

m_PhysicsFixture->GetShape()->ComputeAABB(&aabb, m_Body->GetTransform(), 0);

```

The problem is that unless the player object is a perfect square (the width and the height are exactly the same) it won't sit exactly on top of the ground object I created in the level class. It intersects it a little bit before coming to a rest. I've attached a picture so you guys can see.

The way that I render the shapes is as follows

```
b2AABB aabb;
m_PhysicsFixture->GetShape()->ComputeAABB(&aabb, m_PhysicsBody->GetTransform(), 0);

DrawRectangle(aabb.lowerBound.x * 100.0f, (m_Window.GetHeight() - (aabb.lowerBound.y * 100.0f)), (aabb.upperBound.x - aabb.lowerBound.x) * 100.0f, (aabb.upperBound.y - aabb.lowerBound.y) * 100.0f);

```

I multiply the values by 100.0f to make it bigger, and y is the height of the window minus y. This is because I'm using SDL, which sets the upper-left corner as the 0,0 origin. So all the way at the very top, y = 0, and all the way at the bottom, y = the window height.

# Answer
> 1 votes
Box2D objects sitting on top of each other in a non-zero gravity situation will have some overlap, at least overlap within their shapes' "skins" (their outer shapes). That's normal and intentional.

The skins are buffer zones of a sort that serve to eliminate jitter; to help get the system to a steady state. In Box2D, the skin's size is determined by the value of the `b2Shape::m_radius` member variable.

Usually overlap is not visible though. It can become visible if:

1. Your view is more zoomed in than is typical (like if the scales aren't in the recommended ranges) and you are viewing the outer shapes or viewing their AABBs.
2. The density/mass of the upper object's fixture(s) is significantly higher than that of the lower body's.
3. There are a bunch of bodies stacked on top of one another.
4. The simulation isn't using enough position iterations.
5. The simulation is failing to match up with the impulses of previous contact IDs which can sometimes happen in more dynamic simulations where contacts persist a while like in the Tumbler Testbed test.

Changing the position iteration count can effect how much overlap there will be each world step. Typically I'd expect increasing the position iterations to resolve excess overlap quicker. This should reduce overlap for situations 2, 3, or 4. Changing the fixture densities so they're closer to each other may also help. Changing the scale(s) may help with situation 1. Situation 5 doesn't seem related to what you've described but it requires changing Box2D's source code to deal with.

You can observe overlap in the native Box2D Testbed with like the Sphere Stack test if you zoom in enough on the lowest two circles.

Hope this helps!

---
Tags: box2d
---


# Question
Title: How to clip 3D object in projection (octants)?
In example we've wrote some code in Pascal (graph unit) which rotates 3D object in oblique frontal (dimetric) projection in **all octants** positioned in center of them.

The projection's type:

The code **1** (native FPC):

```
program p7;

    uses PtcCrt, PtcGraph; // FPC crt, graph units

    type
      TArea = record
        xc, zc, yc, xd, zd, g, gl, gb, h: integer;
      end;
      TPoint3D = record
        x, y, z: real;
      end;
      TModel = record
        p: array [ 1..16 ] of TPoint3D;
        x, y, z, l, w, h: real;
      end;
      TArray2 = array [ 1..2 ] of real;

    var
      Driver, Mode, ns, th, ii: integer;
      model_1, model_2, model_a, model: TModel;
      area: TArea;
      s: string;

      // This procedure draws axes
      procedure XYZ( area_t: TArea );
      var
        i, n, nn, ah, aw, lg, o, oo: integer;
        s, s1: string;
      begin
        ah := 8; aw := 8; lg := 15; oo := 5;

        area_t.xd := area_t.xd - ( area_t.g * 2 );
        area_t.zd := area_t.zd - ( area_t.g * 2 );
        SetFillStyle( HatchFill, 19 );
        Bar(
          area_t.xc - ( area_t.xd div 2 ) + area_t.gl, area_t.zc - ( area_t.zd div 2 ),
          area_t.xc + ( area_t.xd div 2 ), area_t.zc + ( area_t.zd div 2 ) - area_t.gb
        );

        SetLineStyle( 0, 0, 1 );

        SetColor( 21 ); Line( area_t.xc - ( area_t.xd div 2 ), area_t.zc, area_t.xc, area_t.zc );
        SetColor( 17 ); Line( area_t.xc + 1, area_t.zc, area_t.xc + ( area_t.xd div 2 ), area_t.zc );

        SetColor( 21 ); Line( area_t.xc, area_t.zc, area_t.xc, area_t.zc - ( area_t.zd div 2 ) );
        SetColor( 17 ); Line( area_t.xc, area_t.zc + 1, area_t.xc, area_t.zc + ( area_t.zd div 2 ) - area_t.gb );

        SetColor( 21 ); Line( area_t.xc, area_t.zc, area_t.xc + ( area_t.zd div 2 ) - area_t.gb, area_t.zc + ( area_t.zd div 2 ) - area_t.gb ); // Y main
        SetColor( 17 ); Line( area_t.xc, area_t.zc, area_t.xc - ( area_t.zd div 2 ), area_t.zc - ( area_t.zd div 2 ) ); // Y

        SetColor( 21 );

        Line( area_t.xc - ( area_t.xd div 2 ), area_t.zc, area_t.xc - ( area_t.xd div 2 ) + ( ah ), area_t.zc - ( aw div 2 ) );
        Line( area_t.xc - ( area_t.xd div 2 ), area_t.zc, area_t.xc - ( area_t.xd div 2 ) + ( ah ), area_t.zc + ( aw div 2 ) );
        Line( area_t.xc, area_t.zc - ( area_t.zd div 2 ), area_t.xc - ( aw div 2 ), area_t.zc - ( area_t.zd div 2 ) + ( ah ) );
        Line( area_t.xc, area_t.zc - ( area_t.zd div 2 ), area_t.xc + ( aw div 2 ), area_t.zc - ( area_t.zd div 2 ) + ( ah ) );
        Line( area_t.xc + ( area_t.zd div 2 ) - area_t.gb, area_t.zc + ( area_t.zd div 2 ) - area_t.gb,
              area_t.xc + ( area_t.zd div 2 ) - area_t.gb - round( ( ( ah + ( aw / 2 ) ) / sqrt( 2 ) ) ),
              area_t.zc + ( area_t.zd div 2 ) - area_t.gb - round( sqrt( ( sqr( aw / 2 ) + sqr( ah ) ) -
                sqr( ( ( aw / 2 ) / sqrt( 2 ) ) + ( ah / sqrt( 2 ) ) ) ) ) );
        Line( area_t.xc + ( area_t.zd div 2 ) - area_t.gb, area_t.zc + ( area_t.zd div 2 ) - area_t.gb,
              area_t.xc + ( area_t.zd div 2 ) - area_t.gb - round( sqrt( ( sqr( aw / 2 ) + sqr( ah ) ) -
                sqr( ( ( aw / 2 ) / sqrt( 2 ) ) + ( ah / sqrt( 2 ) ) ) ) ),
              area_t.zc + ( area_t.zd div 2 ) - area_t.gb - round( ( ( ah + ( aw / 2 ) ) / sqrt( 2 ) ) ) );
        SetColor( 2 );

        OutTextXY( area_t.xc - ( area_t.xd div 2 ) - lg, area_t.zc - round( th / 2 ), 'X' );
        OutTextXY( area_t.xc - 3, area_t.zc - ( area_t.zd div 2 ) - lg, 'Z' );
        OutTextXY( area_t.xc + ( area_t.zd div 2 ) - area_t.gb + lg, area_t.zc + ( area_t.zd div 2 ) - area_t.gb + lg, 'Y' );
      end;

      // This procedure calls XYZ() with center variables
      procedure XYZCenter( area_t: TArea );
      begin
        area_t.xc := GetMaxX div 2 + 1;
        area_t.zc := GetMaxY div 2 + 1;
        area_t.xd := GetMaxX + 1;
        area_t.zd := GetMaxY + 1;
        XYZ( area_t );
      end;

      // This procedure draws a line in oblique frontal projection
      procedure LineXYZ( sp_t, ep_t: TPoint3D; model_t: TModel; area_t: TArea );
      var
        x1, y1, x2, y2, xs, ys, zs, xe, ye, ze: real;
      begin
        SetColor( 14 );
        xs := sp_t.x;
        ys := sp_t.y / 2;
        zs := sp_t.z;
        xe := ep_t.x;
        ye := ep_t.y / 2;
        ze := ep_t.z;

        x1 := - xs - cos( pi / 4 ) * ys;
        y1 :=   zs - sin( pi / 4 ) * ys;
        x2 := - xe - cos( pi / 4 ) * ye;
        y2 :=   ze - sin( pi / 4 ) * ye;

        Line(
          round( area_t.xc - x1 ),
          round( area_t.zc - y1 ),
          round( area_t.xc - x2 ),
          round( area_t.zc - y2 )
        );
        SetColor( 13 );
        Str( round( sp_t.x ), s ); OutTextXY( round( area_t.xc - x1 ) + 2, round( area_t.zc - y1 ) + 10, s );
      end;

      // Let's guess that this function is supposed to send to LineXYZ function only the 1st octant's lines.
      procedure DrawFirstOctant( model_t: TModel; sp_t, ep_t: integer; area_t: TArea );
      var
        mxyz: TArray2;
        a, b, a2, b2: TPoint3D;
      begin
        a2.x := model_t.p[ sp_t ].x;
        a2.y := model_t.p[ sp_t ].y / 2;
        a2.z := model_t.p[ sp_t ].z;
        b2.x := model_t.p[ ep_t ].x;
        b2.y := model_t.p[ ep_t ].y / 2;
        b2.z := model_t.p[ ep_t ].z;

        a := a2;
        b := b2;

        LineXYZ( a, b, model_t, area_t );
      end;

      // This procedure draws each line from point3d to point3d
      procedure DrawModel( model_t: TModel; area_t: TArea );
      begin
        DrawFirstOctant( model_t, 1, 2, area_t );
        DrawFirstOctant( model_t, 2, 3, area_t );
        DrawFirstOctant( model_t, 3, 4, area_t );
        DrawFirstOctant( model_t, 4, 1, area_t );
        DrawFirstOctant( model_t, 5, 6, area_t );
        DrawFirstOctant( model_t, 6, 7, area_t );
        DrawFirstOctant( model_t, 7, 8, area_t );
        DrawFirstOctant( model_t, 8, 5, area_t );
        DrawFirstOctant( model_t, 1, 5, area_t );
        DrawFirstOctant( model_t, 2, 6, area_t );
        DrawFirstOctant( model_t, 3, 7, area_t );
        DrawFirstOctant( model_t, 4, 8, area_t );
        DrawFirstOctant( model_t, 9, 10, area_t );
        DrawFirstOctant( model_t, 10, 11, area_t );
        DrawFirstOctant( model_t, 11, 12, area_t );
        DrawFirstOctant( model_t, 12, 9, area_t );
        DrawFirstOctant( model_t, 13, 14, area_t );
        DrawFirstOctant( model_t, 14, 15, area_t );
        DrawFirstOctant( model_t, 15, 16, area_t );
        DrawFirstOctant( model_t, 16, 13, area_t );
        DrawFirstOctant( model_t, 9, 13, area_t );
        DrawFirstOctant( model_t, 10, 14, area_t );
        DrawFirstOctant( model_t, 11, 15, area_t );
        DrawFirstOctant( model_t, 12, 16, area_t );
      end;

      // This function rotates an object around X axis
      function RotateX( model_t: TModel; angle: real; cs, ce: integer ): TModel;
      var
        y, z: real;
        i: integer;
      begin
        angle := angle * pi / 180;
        for i := cs to ce do
        begin
          y := model_t.p[ i ].y;
          z := model_t.p[ i ].z;
          model_t.p[ i ].y := y * cos( angle ) - z * sin( angle );
          model_t.p[ i ].z := z * cos( angle ) + y * sin( angle );
        end;
        RotateX := model_t;
      end;

      // This function rotates an object around Y axis
      function RotateY( model_t: TModel; angle: real; cs, ce: integer ): TModel;
      var
        x, z: real;
        i: integer;
      begin
        angle := angle * pi / 180;
        for i := cs to ce do
        begin
          x := model_t.p[ i ].x;
          z := model_t.p[ i ].z;
          model_t.p[ i ].x := x * cos( angle ) - z * sin( angle );
          model_t.p[ i ].z := z * cos( angle ) + x * sin( angle );
        end;
        RotateY := model_t;
      end;

      // This function rotates an object around Z axis
      function RotateZ( model_t: TModel; angle: real; cs, ce: integer ): TModel;
      var
        x, y: real;
        i: integer;
      begin
        angle := angle * pi / 180;
        for i := cs to ce do
        begin
          x := model_t.p[ i ].x + model_t.x;
          y := model_t.p[ i ].y + model_t.y;
          model_t.p[ i ].x := -model_t.x + x * cos( angle ) - y * sin( angle );
          model_t.p[ i ].y := -model_t.y + y * cos( angle ) + x * sin( angle );
        end;
        RotateZ := model_t;
      end;

      // This function rotates an object around axes
      function RotateXYZ( model_t: TModel; rx_t, ry_t, rz_t: real; cs, ce: integer ): TModel;
      begin
        model_t := RotateX( model_t, rx_t, cs, ce );
        model_t := RotateY( model_t, ry_t, cs, ce );
        model_t := RotateZ( model_t, rz_t, cs, ce );
        RotateXYZ := model_t;
      end;

      // This procedure moves an object
      function MoveXYZ( model_t: TModel; x_t, y_t, z_t: real; cs, ce: integer ): TModel;
      var
        i: integer;
      begin
        for i := cs to ce do
        begin
          model_t.p[ i ].x := model_t.p[ i ].x - x_t;
          model_t.p[ i ].y := model_t.p[ i ].y + y_t;
          model_t.p[ i ].z := model_t.p[ i ].z + z_t;
        end;
        MoveXYZ := model_t;
      end;

    begin
      // Initializing
      Driver := D8bit;
      Mode := m800x600;
      InitGraph( Driver, Mode, '' );
      th := 6; // Symbol's height
      area.g := 20; // Padding
      area.h := 20; // Hatch step
      area.gl := 20; // Left padding
      area.gb := 40; // Bottom padding
      if ( GraphResult <> GrOk ) then WriteLn( '800x600x256''s not supported' ) else
      begin
        ClearDevice;
        area.xc := ( GetMaxX div 2 ) + 1; // The X axis center
        area.zc := ( GetMaxY div 2 ) + 1; // The Z axis center
        SetRGBPalette( 17, 55, 55, 55 ); // Colors
        SetRGBPalette( 18, 30, 30, 30 );
        SetRGBPalette( 19, 10, 10, 10 );
        SetRGBPalette( 20, 44, 44, 44 );
        SetRGBPalette( 21, 88, 88, 88 );

        // A characteristics of part of objects
        model_1.l := 40; model_1.w := 40; model_1.h := 80; model_1.x := 0; model_1.y := 0; model_1.z := -60;
        model_2.l := 300; model_2.w := 40; model_2.h := 40; model_2.x := 0; model_2.y := 0; model_2.z := 0;
        model_a.x := 0; model_a.y := 0; model_a.z := 0;

        // A 3D points of first part of object
        model_1.p[ 1 ].x := - model_1.l / 2; model_1.p[ 1 ].y := - model_1.w / 2; model_1.p[ 1 ].z := - model_1.h / 2;
        model_1.p[ 2 ].x := - model_1.l / 2; model_1.p[ 2 ].y :=   model_1.w / 2; model_1.p[ 2 ].z := - model_1.h / 2;
        model_1.p[ 3 ].x :=   model_1.l / 2; model_1.p[ 3 ].y :=   model_1.w / 2; model_1.p[ 3 ].z := - model_1.h / 2;
        model_1.p[ 4 ].x :=   model_1.l / 2; model_1.p[ 4 ].y := - model_1.w / 2; model_1.p[ 4 ].z := - model_1.h / 2;
        model_1.p[ 5 ].x := - model_1.l / 2; model_1.p[ 5 ].y := - model_1.w / 2; model_1.p[ 5 ].z :=   model_1.h / 2;
        model_1.p[ 6 ].x := - model_1.l / 2; model_1.p[ 6 ].y :=   model_1.w / 2; model_1.p[ 6 ].z :=   model_1.h / 2;
        model_1.p[ 7 ].x :=   model_1.l / 2; model_1.p[ 7 ].y :=   model_1.w / 2; model_1.p[ 7 ].z :=   model_1.h / 2;
        model_1.p[ 8 ].x :=   model_1.l / 2; model_1.p[ 8 ].y := - model_1.w / 2; model_1.p[ 8 ].z :=   model_1.h / 2;

        // A 3D points of second part of object
        model_1.p[  9 ].x := - model_2.l / 2; model_1.p[  9 ].y := - model_2.w / 2; model_1.p[  9 ].z := - model_2.h / 2;
        model_1.p[ 10 ].x := - model_2.l / 2; model_1.p[ 10 ].y :=   model_2.w / 2; model_1.p[ 10 ].z := - model_2.h / 2;
        model_1.p[ 11 ].x :=   model_2.l / 2; model_1.p[ 11 ].y :=   model_2.w / 2; model_1.p[ 11 ].z := - model_2.h / 2;
        model_1.p[ 12 ].x :=   model_2.l / 2; model_1.p[ 12 ].y := - model_2.w / 2; model_1.p[ 12 ].z := - model_2.h / 2;
        model_1.p[ 13 ].x := - model_2.l / 2; model_1.p[ 13 ].y := - model_2.w / 2; model_1.p[ 13 ].z :=   model_2.h / 2;
        model_1.p[ 14 ].x := - model_2.l / 2; model_1.p[ 14 ].y :=   model_2.w / 2; model_1.p[ 14 ].z :=   model_2.h / 2;
        model_1.p[ 15 ].x :=   model_2.l / 2; model_1.p[ 15 ].y :=   model_2.w / 2; model_1.p[ 15 ].z :=   model_2.h / 2;
        model_1.p[ 16 ].x :=   model_2.l / 2; model_1.p[ 16 ].y := - model_2.w / 2; model_1.p[ 16 ].z :=   model_2.h / 2;

        // Moves two parts to it start positions
        model_1 := MoveXYZ( model_1, model_1.x, model_1.y, model_1.z, 1, 8 );
        model_1 := MoveXYZ( model_1, model_2.x, model_2.y, model_2.z, 9, 16 );

        // Copies all parts to full one
        for ii := 1 to 16 do
        begin
          model_a.p[ ii ].x := model_1.p[ ii ].x;
          model_a.p[ ii ].y := model_1.p[ ii ].y;
          model_a.p[ ii ].z := model_1.p[ ii ].z;
        end;

        SetColor( 14 );
        // Draws axes
        XYZCenter( area );
        // Moves a whole ( full ) object
        model := MoveXYZ( model_a, model_a.x, model_a.y, model_a.z, 1, 16 );
        // Draws a whole moved object ( full )
        DrawModel( model_a, area );

        // Rotating cycle
        repeat Delay( 100 ) until KeyPressed; ReadKey;
        SetActivePage( 1 );
        SetVisualPage( 0 );
        repeat
          ClearDevice;
          XYZCenter( area );
          // Rotates an object
          model := RotateXYZ( model, 0, 0, 1, 1, 16 );

          // Draws rotated object
          SetColor( 14 );
          DrawModel( model, area );
          // Draws a circle at the center of axes
          SetColor( 12 );
          Circle( area.xc, area.zc, 2 ); OutTextXY( area.xc + 3, area.zc + 3, '[ 0, 0 ]' );

          delay( 1 );

          // Changes drawing page to smooth render
          if ns = 0 then
          begin
            SetActivePage( 0 );
            SetVisualPage( 1 )
          end
          else
          begin
            SetActivePage( 1 );
            SetVisualPage( 0 )
          end;
          if ns = 0 then ns := 1 else ns := 0;
          until KeyPressed; ReadKey;
        repeat Delay( 100 ) until KeyPressed;
        CloseGraph;
      end;
    end.

```

The result of code:

Octants:

Is it possible to draw an object only in first octant ( where points coordinates \[**x**\>0; **y**\>0; **z**\>0 \] and how ? Is it calls *clipping* and how I'd do this ?

I've read a lot information about this, and nothing about 3D, but 2D **Cohen Sutherland Line Clipping Algorithm**. Should we use it to achieve this ?

So I've tried with algorithm which **@Bálint** gave and I think that this one is something close. Also he wrote 2D clipping algorithm.

The **@Bálint**'s algorithm:

> A.x in our case is x1, A.y is y1, A.z is z1, B.x is x2, etc. If one of them is outside the drawing area ( outside of **I** octant ) (has a negative x, y or z coordinate) then get the one, that's the farthest away from the positive part of the coordinate system. If the X coordinate is the farthest, then you set it to 0 and yiu set the Y and Z coordinates to -A.x / (B.x - A.x) * (B.y - A.y) + A.y and -A.x / (B.x - A.x) * (B.z - A.z) + A.z respectively. Same with Y and Z, but you replace the Ys and Zs with the X and Z and X and Y respectively.
>
> The formula for the endpoint is a bit different. You need to replace every x1, y1 and z1 with x2, y2 and z2 respectively and vice-versa.

Might be that I've made something wrong. Btw I've got this:

The code **2** is on hastebin.com because of stack's text limits.

The strange result of **2** code:

As you see, now the part of **II** octant is something close to which one should be in **I** octant.

Best regards, V7

# Answer
First of all, you need to check if the line intersects the octant. You have 3 cases:

* The line is completely contained within the octant (the x, y, and z coordinates of the endpoints are positive). This is the easiest one to solve, you simply draw the line as it is.
* One of the endpoints is outside, but one of them is inside the octant
* Both endpoints are outside, but the line intersects it

I'm going to refer to the line interpolation formula a couple of times. It has 2 parts. Given a position on the x coordinate `x` the y coordinate of the point on the line at that x position is

```
D = (x - Ax) / (Bx - Ax)
if D is between 0 and 1, then y = D * (By - Ay) + Ay
otherwise the line doesn't have a point at that x position

```

`Ax` is the x coordinate of one of the endpoints and `Bx` is the x coordinate of the other. `x` and `y` can be changed to other axes.

So, first get the `D`s on the x, y and z coordinates with the values `x=y=z=0`:

```
Dx = (0 - Ax) / (Bx - Ax)
Dy = (0 - Ay) / (By - Ay)
Dz = (0 - Az) / (Bz - Az)

```

If at least one of them is in the range `[0, 1]`, then the line intersects the octant.

Now you'll need to get the remaining of the x, y and z coordinates with these, the complete code is

```
let points be a set of vectors

if Dx >= 0 and Dx <= 1, then
    y = Dx * (By - Ay) + Ay
    z = Dx * (Bz - Az) + Az
    if y >= 0 and z >= 0, then
        add (0, y, z) to points
    endif
endif

if Dy >= 0 and Dy <= 1, then
    x = Dy * (Bx - Ax) + Ax
    z = Dx * (Bz - Az) + Az
    if x >= 0 and z >= 0, then
        add (x, 0, z) to points
    endif
endif

if Dz >= 0 and Dz <= 1, then
    x = Dz * (Bx - Ax) + Ax
    y = Dz * (By - Ay) + Ay
    if x >= 0 and y >= 0, then
        add (x, y, 0) to points
    endif
endif

```

This will give you the lines endpoints, if the line intersects 2 axes and one of the endpoints, if it only intersect axis and one of the points is in the octant. In the latter case, you can get the other end point by using the endpoint in the octant:

```
if Ax >= 0 and Ay > 0= and Az >= 0, then
    add A to points
endif

if Bx >= 0 and By > 0= and Bz >= 0, then
    add B to points
endif

```

Now you only need to draw the line defined by the points set
> 3 votes

# Answer
## The solution by **@Bálint**:

The code:

```
  program p7;

  uses PtcCrt, PtcGraph, math;

  type
    TArea = record
      xc, zc, yc, xd, zd, g, gl, gb, h: integer;
    end;
    TPoint3D = record
      x, y, z: real;
    end;
    TModel = record
      p: array [ 1..16 ] of TPoint3D;
      x, y, z, l, w, h: real;
    end;
    TArray2 = array [ 1..2 ] of real;

  var
    Driver, Mode, ns, th, ii: integer;
    model_1, model_2, model_a, model: TModel;
    rx, ry, rz: real;
    area: TArea;
    s: string;
    c: char;

    procedure XYZ( area_t: TArea );
    var
      i, n, nn, ah, aw, lg, o, oo: integer;
      s, s1: string;
    begin
      ah := 8; aw := 8; lg := 15; oo := 5;

      area_t.xd := area_t.xd - ( area_t.g * 2 );
      area_t.zd := area_t.zd - ( area_t.g * 2 );
      SetFillStyle( HatchFill, 19 );
      Bar(
        area_t.xc - ( area_t.xd div 2 ) + area_t.gl, area_t.zc - ( area_t.zd div 2 ),
        area_t.xc + ( area_t.xd div 2 ), area_t.zc + ( area_t.zd div 2 ) - area_t.gb
      );

      SetLineStyle( 0, 0, 1 );

      SetColor( 21 ); Line( area_t.xc - ( area_t.xd div 2 ), area_t.zc, area_t.xc, area_t.zc );
      SetColor( 17 ); Line( area_t.xc + 1, area_t.zc, area_t.xc + ( area_t.xd div 2 ), area_t.zc );

      SetColor( 21 ); Line( area_t.xc, area_t.zc, area_t.xc, area_t.zc - ( area_t.zd div 2 ) );
      SetColor( 17 ); Line( area_t.xc, area_t.zc + 1, area_t.xc, area_t.zc + ( area_t.zd div 2 ) - area_t.gb );

      SetColor( 21 ); Line( area_t.xc, area_t.zc, area_t.xc + ( area_t.zd div 2 ) - area_t.gb, area_t.zc + ( area_t.zd div 2 ) - area_t.gb );
      SetColor( 17 ); Line( area_t.xc, area_t.zc, area_t.xc - ( area_t.zd div 2 ), area_t.zc - ( area_t.zd div 2 ) );

      SetColor( 21 );

      Line( area_t.xc - ( area_t.xd div 2 ), area_t.zc, area_t.xc - ( area_t.xd div 2 ) + ( ah ), area_t.zc - ( aw div 2 ) );
      Line( area_t.xc - ( area_t.xd div 2 ), area_t.zc, area_t.xc - ( area_t.xd div 2 ) + ( ah ), area_t.zc + ( aw div 2 ) );
      Line( area_t.xc, area_t.zc - ( area_t.zd div 2 ), area_t.xc - ( aw div 2 ), area_t.zc - ( area_t.zd div 2 ) + ( ah ) );
      Line( area_t.xc, area_t.zc - ( area_t.zd div 2 ), area_t.xc + ( aw div 2 ), area_t.zc - ( area_t.zd div 2 ) + ( ah ) );
      Line( area_t.xc + ( area_t.zd div 2 ) - area_t.gb, area_t.zc + ( area_t.zd div 2 ) - area_t.gb,
            area_t.xc + ( area_t.zd div 2 ) - area_t.gb - round( ( ( ah + ( aw / 2 ) ) / sqrt( 2 ) ) ),
            area_t.zc + ( area_t.zd div 2 ) - area_t.gb - round( sqrt( ( sqr( aw / 2 ) + sqr( ah ) ) -
              sqr( ( ( aw / 2 ) / sqrt( 2 ) ) + ( ah / sqrt( 2 ) ) ) ) ) );
      Line( area_t.xc + ( area_t.zd div 2 ) - area_t.gb, area_t.zc + ( area_t.zd div 2 ) - area_t.gb,
            area_t.xc + ( area_t.zd div 2 ) - area_t.gb - round( sqrt( ( sqr( aw / 2 ) + sqr( ah ) ) -
              sqr( ( ( aw / 2 ) / sqrt( 2 ) ) + ( ah / sqrt( 2 ) ) ) ) ),
            area_t.zc + ( area_t.zd div 2 ) - area_t.gb - round( ( ( ah + ( aw / 2 ) ) / sqrt( 2 ) ) ) );
      SetColor( 2 );

      OutTextXY( area_t.xc - ( area_t.xd div 2 ) - lg, area_t.zc - round( th / 2 ), 'X' );
      OutTextXY( area_t.xc - 3, area_t.zc - ( area_t.zd div 2 ) - lg, 'Z' );
      OutTextXY( area_t.xc + ( area_t.zd div 2 ) - area_t.gb + lg, area_t.zc + ( area_t.zd div 2 ) - area_t.gb + lg, 'Y' );
    end;

    procedure XYZCenter( area_t: TArea );
    begin
      area_t.xc := GetMaxX div 2 + 1;
      area_t.zc := GetMaxY div 2 + 1;
      area_t.xd := GetMaxX + 1;
      area_t.zd := GetMaxY + 1;
      XYZ( area_t );
    end;

    procedure DrawLine( X1, Y1, X2, Y2: Integer; model_t: TModel; area_t: TArea );
    var
      HL, VL, L: Integer;
      dX, dY, X, Y, xxs, yys, zzs, xxe, yye, zze: Real;
      Count: Integer;
    BEGIN

      HL := X2 - X1;
      VL := Y2 - Y1;
      L := Abs(HL) + Abs(VL);
      dX := HL / L;
      dY := VL / L;
      X := X1;
      Y := Y1;

      FOR Count := 0 TO L DO
      BEGIN

        PutPixel(Round(X), Round(Y), GetColor);
        X := X + dX;
        Y := Y + dY
      END
    END;

    function MinXYZ( p_t: TPoint3D ): TArray2;
    var
      mxyz: TArray2;
    begin
      if ( ( p_t.x < 0 ) or ( p_t.y < 0 ) or ( p_t.z < 0 ) ) then
      begin
        if ( p_t.x < p_t.y ) then
        begin
          if ( p_t.x < p_t.z ) then
            begin
              mxyz[ 1 ] := 1;
              mxyz[ 2 ] := p_t.x;
            end else
            begin
              mxyz[ 1 ] := 3;
              mxyz[ 2 ] := p_t.z;
            end;
        end else if p_t.y < p_t.z then
        begin
          mxyz[ 1 ] := 2;
          mxyz[ 2 ] := p_t.y;
        end else
        begin
          mxyz[ 1 ] := 3;
          mxyz[ 2 ] := p_t.z;
        end;
      end else mxyz[ 1 ] := 0;
      MinXYZ := mxyz;
    end;

    procedure LineXYZ( sp_t, ep_t: TPoint3D; model_t: TModel; area_t: TArea );
    var
      x1, y1, x2, y2, xs, ys, zs, xe, ye, ze: real;
    begin
      xs := sp_t.x;
      ys := sp_t.y / 2;
      zs := sp_t.z;
      xe := ep_t.x;
      ye := ep_t.y / 2;
      ze := ep_t.z;

      x1 := - xs - cos( pi / 4 ) * ys;
      y1 :=   zs - sin( pi / 4 ) * ys;
      x2 := - xe - cos( pi / 4 ) * ye;
      y2 :=   ze - sin( pi / 4 ) * ye;

      SetColor( 14 );
      DrawLine(
        round( area_t.xc - x1 ),
        round( area_t.zc - y1 ),
        round( area_t.xc - x2 ),
        round( area_t.zc - y2 ),
        model_t, area_t
      );

      SetColor( 13 );
      Str( round( sp_t.x ), s ); OutTextXY( round( area_t.xc - x1 ), round( area_t.zc - y1 ), s );
    end;

    var
      points: array [ 0..40 ] of TPoint3D;
      indx: integer;

    procedure DrawFirstOctant( model_t: TModel; sp_t, ep_t: integer; area_t: TArea );
    var
      mxyz: TArray2;
      a, b, a2, b2: TPoint3D;
      dx, dy, dz: real;
    begin
      indx := 0;

      a2.x := model_t.p[ sp_t ].x;
      a2.y := model_t.p[ sp_t ].y;
      a2.z := model_t.p[ sp_t ].z;

      b2.x := model_t.p[ ep_t ].x;
      b2.y := model_t.p[ ep_t ].y;
      b2.z := model_t.p[ ep_t ].z;

      dx := - a2.x / ( b2.x - a2.x );
      dy := - a2.y / ( b2.y - a2.y );
      dz := - a2.z / ( b2.z - a2.z );

      if ( dx >= 0 ) and ( dx <= 1 ) then
      begin
        a.x := 0;
        a.y := dx * ( b2.y - a2.y ) + a2.y;
        a.z := dx * ( b2.z - a2.z ) + a2.z;
        if (a.y >= 0) and (a.z >= 0) then
        begin
           points[ indx ] := a;
           Inc( indx );
        end;
      end;

      if ( dy >= 0 ) and ( dy <= 1 ) then
      begin
        a.x := dy * (b2.x - a2.x) + a2.x;
        a.y := 0;
        a.z := dy * (b2.z - a2.z) + a2.z;
        if (a.x >= 0) and (a.z >= 0) then
        begin
           points[ indx ] := a;
           Inc( indx );
        end;
      end;

      if ( dz >= 0 ) and ( dz <= 1 ) then
      begin
        a.x := dz * (b2.x - a2.x) + a2.x;
        a.y := dz * (b2.y - a2.y) + a2.y;
        a.z := 0;
        if (a.x >= 0) and (a.y >= 0) then
        begin
           points[ indx ] := a;
           Inc( indx );
        end;
      end;

      if ( a2.x >= 0 ) and ( a2.y >= 0 ) and ( a2.z >= 0 ) then
      begin
        a.x := a2.x;
        a.y := a2.y;
        a.z := a2.z;
        points[ indx ] := a;
        Inc( indx );
      end;

      if ( b2.x >= 0 ) and ( b2.y >= 0 ) and ( b2.z >= 0 ) then
      begin
        b.x := b2.x;
        b.y := b2.y;
        b.z := b2.z;
        points[ indx ] := b;
        Inc( indx );
      end;

      if (indx >= 2) then LineXYZ( points[ 0 ], points[ 1 ], model_t, area_t );

    end;

    procedure DrawModel( model_t: TModel; area_t: TArea );
    begin
      DrawFirstOctant( model_t, 1, 2, area_t );
      DrawFirstOctant( model_t, 2, 3, area_t );
      DrawFirstOctant( model_t, 3, 4, area_t );
      DrawFirstOctant( model_t, 4, 1, area_t );
      DrawFirstOctant( model_t, 5, 6, area_t );
      DrawFirstOctant( model_t, 6, 7, area_t );
      DrawFirstOctant( model_t, 7, 8, area_t );
      DrawFirstOctant( model_t, 8, 5, area_t );
      DrawFirstOctant( model_t, 1, 5, area_t );
      DrawFirstOctant( model_t, 2, 6, area_t );
      DrawFirstOctant( model_t, 3, 7, area_t );
      DrawFirstOctant( model_t, 4, 8, area_t );
      DrawFirstOctant( model_t, 9, 10, area_t );
      DrawFirstOctant( model_t, 10, 11, area_t );
      DrawFirstOctant( model_t, 11, 12, area_t );
      DrawFirstOctant( model_t, 12, 9, area_t );
      DrawFirstOctant( model_t, 13, 14, area_t );
      DrawFirstOctant( model_t, 14, 15, area_t );
      DrawFirstOctant( model_t, 15, 16, area_t );
      DrawFirstOctant( model_t, 16, 13, area_t );
      DrawFirstOctant( model_t, 9, 13, area_t );
      DrawFirstOctant( model_t, 10, 14, area_t );
      DrawFirstOctant( model_t, 11, 15, area_t );
      DrawFirstOctant( model_t, 12, 16, area_t );
    end;

    function RotateX( model_t: TModel; angle: real; cs, ce: integer ): TModel;
    var
      y, z: real;
      i: integer;
    begin
      angle := angle * pi / 180;
      for i := cs to ce do
      begin
        y := model_t.p[ i ].y;
        z := model_t.p[ i ].z;
        model_t.p[ i ].y := y * cos( angle ) - z * sin( angle );
        model_t.p[ i ].z := z * cos( angle ) + y * sin( angle );
      end;
      RotateX := model_t;
    end;

    function RotateY( model_t: TModel; angle: real; cs, ce: integer ): TModel;
    var
      x, z: real;
      i: integer;
    begin
      angle := angle * pi / 180;
      for i := cs to ce do
      begin
        x := model_t.p[ i ].x;
        z := model_t.p[ i ].z;
        model_t.p[ i ].x := x * cos( angle ) - z * sin( angle );
        model_t.p[ i ].z := z * cos( angle ) + x * sin( angle );
      end;
      RotateY := model_t;
    end;

    function RotateZ( model_t: TModel; angle: real; cs, ce: integer ): TModel;
    var
      x, y: real;
      i: integer;
    begin
      angle := angle * pi / 180;
      for i := cs to ce do
      begin
        x := model_t.p[ i ].x + model_t.x;
        y := model_t.p[ i ].y + model_t.y;
        model_t.p[ i ].x := -model_t.x + x * cos( angle ) - y * sin( angle );
        model_t.p[ i ].y := -model_t.y + y * cos( angle ) + x * sin( angle );
      end;
      RotateZ := model_t;
    end;

    function RotateXYZ( model_t: TModel; rx_t, ry_t, rz_t: real; cs, ce: integer ): TModel;
    begin
      model_t := RotateX( model_t, rx_t, cs, ce );
      model_t := RotateY( model_t, ry_t, cs, ce );
      model_t := RotateZ( model_t, rz_t, cs, ce );
      RotateXYZ := model_t;
    end;

    function MoveXYZ( model_t: TModel; x_t, y_t, z_t: real; cs, ce: integer ): TModel;
    var
      i: integer;
    begin
      for i := cs to ce do
      begin
        model_t.p[ i ].x := model_t.p[ i ].x - x_t;
        model_t.p[ i ].y := model_t.p[ i ].y + y_t;
        model_t.p[ i ].z := model_t.p[ i ].z + z_t;
      end;
      MoveXYZ := model_t;
    end;

  begin
    Driver := D8bit;
    Mode := m800x600;
    InitGraph( Driver, Mode, '' );
    th := 6;
    area.g := 20;
    area.h := 20;
    area.gl := 20;
    area.gb := 40;
    if ( GraphResult <> GrOk ) then WriteLn( '800x600x256''s not supported' ) else
    begin
      ClearDevice;
      area.xc := ( GetMaxX div 2 ) + 1;
      area.zc := ( GetMaxY div 2 ) + 1;
      SetRGBPalette( 17, 55, 55, 55 );
      SetRGBPalette( 18, 30, 30, 30 );
      SetRGBPalette( 19, 10, 10, 10 );
      SetRGBPalette( 20, 44, 44, 44 );
      SetRGBPalette( 21, 88, 88, 88 );
      XYZCenter( area );

      model_1.l := 40; model_1.w := 40; model_1.h := 80; model_1.x := 0; model_1.y := 0; model_1.z := -60;

      model_2.l := 300; model_2.w := 40; model_2.h := 40; model_2.x := 0; model_2.y := 0; model_2.z := 0;

      model_a.x := 0; model_a.y := 0; model_a.z := 0;

      rx := 0; ry := 60; rz := -100;

      model_1.p[ 1 ].x := - model_1.l / 2; model_1.p[ 1 ].y := - model_1.w / 2; model_1.p[ 1 ].z := - model_1.h / 2;
      model_1.p[ 2 ].x := - model_1.l / 2; model_1.p[ 2 ].y :=   model_1.w / 2; model_1.p[ 2 ].z := - model_1.h / 2;
      model_1.p[ 3 ].x :=   model_1.l / 2; model_1.p[ 3 ].y :=   model_1.w / 2; model_1.p[ 3 ].z := - model_1.h / 2;
      model_1.p[ 4 ].x :=   model_1.l / 2; model_1.p[ 4 ].y := - model_1.w / 2; model_1.p[ 4 ].z := - model_1.h / 2;
      model_1.p[ 5 ].x := - model_1.l / 2; model_1.p[ 5 ].y := - model_1.w / 2; model_1.p[ 5 ].z :=   model_1.h / 2;
      model_1.p[ 6 ].x := - model_1.l / 2; model_1.p[ 6 ].y :=   model_1.w / 2; model_1.p[ 6 ].z :=   model_1.h / 2;
      model_1.p[ 7 ].x :=   model_1.l / 2; model_1.p[ 7 ].y :=   model_1.w / 2; model_1.p[ 7 ].z :=   model_1.h / 2;
      model_1.p[ 8 ].x :=   model_1.l / 2; model_1.p[ 8 ].y := - model_1.w / 2; model_1.p[ 8 ].z :=   model_1.h / 2;

      model_1.p[  9 ].x := - model_2.l / 2; model_1.p[  9 ].y := - model_2.w / 2; model_1.p[  9 ].z := - model_2.h / 2;
      model_1.p[ 10 ].x := - model_2.l / 2; model_1.p[ 10 ].y :=   model_2.w / 2; model_1.p[ 10 ].z := - model_2.h / 2;
      model_1.p[ 11 ].x :=   model_2.l / 2; model_1.p[ 11 ].y :=   model_2.w / 2; model_1.p[ 11 ].z := - model_2.h / 2;
      model_1.p[ 12 ].x :=   model_2.l / 2; model_1.p[ 12 ].y := - model_2.w / 2; model_1.p[ 12 ].z := - model_2.h / 2;
      model_1.p[ 13 ].x := - model_2.l / 2; model_1.p[ 13 ].y := - model_2.w / 2; model_1.p[ 13 ].z :=   model_2.h / 2;
      model_1.p[ 14 ].x := - model_2.l / 2; model_1.p[ 14 ].y :=   model_2.w / 2; model_1.p[ 14 ].z :=   model_2.h / 2;
      model_1.p[ 15 ].x :=   model_2.l / 2; model_1.p[ 15 ].y :=   model_2.w / 2; model_1.p[ 15 ].z :=   model_2.h / 2;
      model_1.p[ 16 ].x :=   model_2.l / 2; model_1.p[ 16 ].y := - model_2.w / 2; model_1.p[ 16 ].z :=   model_2.h / 2;

      model_1 := MoveXYZ( model_1, model_1.x, model_1.y, model_1.z, 1, 8 );

      model_1 := MoveXYZ( model_1, model_2.x, model_2.y, model_2.z, 9, 16 );

      for ii := 1 to 16 do
      begin
        model_a.p[ ii ].x := model_1.p[ ii ].x;
        model_a.p[ ii ].y := model_1.p[ ii ].y;
        model_a.p[ ii ].z := model_1.p[ ii ].z;
      end;

      SetColor( 14 ); DrawModel( model_a, area );

      model := MoveXYZ( model_a, model_a.x, model_a.y, model_a.z, 1, 16 );

      rz := 0;
      repeat Delay( 100 ) until KeyPressed; ReadKey;
      SetActivePage( 1 );
      SetVisualPage( 0 );
      repeat
        ClearDevice;
        XYZCenter( area );
        model := RotateXYZ( model, 0, 0, 1, 1, 16 );
        SetColor( 14 ); DrawModel( model, area );
        SetColor( 4 ); Circle( area.xc, area.zc, 2 );
        OutTextXY( area.xc + 3, area.zc + 3, '[ 0, 0 ]' );

        delay( 1 );

        SetColor( 4 );

        if ns = 0 then
        begin
          SetActivePage( 0 );
          SetVisualPage( 1 )
        end
        else
        begin
          SetActivePage( 1 );
          SetVisualPage( 0 )
        end;
        if ns = 0 then ns := 1 else ns := 0;
        until KeyPressed; ReadKey;
      repeat Delay( 100 ) until KeyPressed;
      CloseGraph;
    end;
  end.

```

The result of code:

If you want to change octant, just change **if** statements in **DrawFirstOctant** procedure like:

```
    procedure DrawOctant( model_t: TModel; sp_t, ep_t: integer; area_t: TArea );
var
  mxyz: TArray2;
  a, b, a2, b2: TPoint3D;
  dx, dy, dz: real;
begin
  indx := 0;

  a2.x := model_t.p[ sp_t ].x;
  a2.y := model_t.p[ sp_t ].y;
  a2.z := model_t.p[ sp_t ].z;

  b2.x := model_t.p[ ep_t ].x;
  b2.y := model_t.p[ ep_t ].y;
  b2.z := model_t.p[ ep_t ].z;

  dx := - a2.x / ( b2.x - a2.x );
  dy := - a2.y / ( b2.y - a2.y );
  dz := - a2.z / ( b2.z - a2.z );

  if ( dx >= 0 ) and ( dx <= 1 ) then
  begin
    a.x := 0;
    a.y := dx * ( b2.y - a2.y ) + a2.y;
    a.z := dx * ( b2.z - a2.z ) + a2.z;
    if (a.y >= 0) and (a.z >= 0) then
    begin
      SetColor( 1 );
      points[ indx ] := a;
      Inc( indx );
    end;
  end;

  if ( dy >= 0 ) and ( dy <= 1 ) then
  begin
    a.x := dy * (b2.x - a2.x) + a2.x;
    a.y := 0;
    a.z := dy * (b2.z - a2.z) + a2.z;

    // x >= 0 changed to x <= 0
    if (a.x <= 0) and (a.z >= 0) then
    begin
      SetColor( 2 );
      points[ indx ] := a;
      Inc( indx );
    end;
  end;

  if ( dz >= 0 ) and ( dz <= 1 ) then
  begin
    a.x := dz * (b2.x - a2.x) + a2.x;
    a.y := dz * (b2.y - a2.y) + a2.y;
    a.z := 0;

    // x >= 0 changed to x <= 0
    if (a.x <= 0) and (a.y >= 0) then
    begin
      SetColor( 3 );
      points[ indx ] := a;
      Inc( indx );
    end;
  end;

  // x >= 0 changed to x <= 0
  if ( a2.x <= 0 ) and ( a2.y >= 0 ) and ( a2.z >= 0 ) then
  begin
    SetColor( 4 );
    a.x := a2.x;
    a.y := a2.y;
    a.z := a2.z;
    points[ indx ] := a;
    Inc( indx );
  end;

  // x >= 0 changed to x <= 0
  if ( b2.x <= 0 ) and ( b2.y >= 0 ) and ( b2.z >= 0 ) then
  begin
    SetColor( 5 );
    b.x := b2.x;
    b.y := b2.y;
    b.z := b2.z;
    points[ indx ] := b;
    Inc( indx );
  end;

  if (indx >= 2) then LineXYZ( points[ 0 ], points[ 1 ], model_t, area_t );

end;

```

The result of these changes:
> 0 votes

---
Tags: 3d, graphics-programming, 3d-modeling, clipping, axis
---


# Question
Title: Programmatically creating a continuous scrolling background in Game Maker: Studio
I have 15 background images for a 2D horizontal scrolling shooter game and I have been wondering how to insert programmatically those background images in the first level room, as I want them to be displayed one after the other looking as they were one large background image, repeating the last four ones until the boss is defeated.

I have seen that in Game Maker: Studio only 8 background slots are available in each room, so how could I achieve doing what I need here?

# Answer
> 3 votes
To dynamically scroll through a very large background made up of smaller frames, there are many different solution; the main idea though is quite the same.

**The main idea**
Think of your fifteen background frames as sort of "panels", which you draw one along the other so that they fit the current `view` width: if your view is 1280 pixels wide, and each background is 960 pixels wide, then you need at least three backgrounds per time to fit the current `view`; this looks obvious if one of the "panels" fits within the current view:

**Cycling through panels**
With this setup, we expect background **1** in the image to disappear as soon as it lies completely out of our `view` borders; later, when background **3** find itself completely within the `view` borders, we need to draw the new background **4** following the number **3** seamlessly.

**Make it simpler**
We can tear down the global complexity of our solution by making some considerations:

* We can use a fixed number of scrolling panels (backgrounds) as long as they fit the `view` range, as showed ealier, in number equal to or greater that the minimum required;
* In GM:S, since we have a limited number of available backgrounds, instead of loosing past backgrounds and allocating new ones (not possible because background indices are fixed in GM:S), we can just shift the `background_index`es in a proper way to make the whole bigger background be drawn seamlessly.

All this realizes as follow. First, we draw the first *n* backgrounds; when the *n*-th background lies within the `view` borders, thus we now need to draw the *n+1*-th background, we shift the *n* backgrounds back (for example, along the positive direction of *x* axis) of value *n\*background\_width*; finally, we make the *n*-th background equal to the first - so that it will actually be drawn in the same previous position regarding the room `view` \- and then assign the new backgrounds to the indices to follow.

If we make *n = 5*, we reach the following:

* Starting cycle: backgrounds **1** to **5**;
* First iteration: backgrounds **5** to **9**;
* Second iteration: backgrounds **9** to **13**;
* Boss iterations: backgrounds **13**, **14**, **15**, **12**, **13**

The "boss iteration" will occur through the same backgrounds continuously and seamlessly, thanks to a useful choice of numbers.

**Implementation**
Have one object to control directly the background movement.

In its *Create Event*, you assign the backgrounds and their offsets:

```
// Assign background indices
background_index[0] = bgFrame0;
background_index[1] = bgFrame1;
background_index[2] = bgFrame2;
background_index[3] = bgFrame3;
background_index[4] = bgFrame4;

// Shift backgrounds (otherwise they will be overlapped)
for (var i=1; i<5; i++)               // bkgr0 starts at (0,0)
    background_x[i] += i*bk_width;    // bk_width is the width of single backgrounds

```

Then, in the *Step Event* (or similar):

```
// Update backgrounds' relative positions
for (var i=0; i<5; i++)
    background_x[i] -= 5;                 // an alternative to background_hspeed[]

// Change the backgrounds stack when needed
if (background_x[4]<=0)                   // if the last background lies within the view
{
    for (var i=0; i<5; i++)               // push back all five backgrounds
        background_x[i] += bk_width;      // (maintaining their relative offsets)
    background_index[0] = background_index[4]; // last panel becomes the first one

    // change other backgrounds here
}

```

**Final touch**
Where I commented `// change other backgrounds here`, you can implement a `switch` statement that changes `background_index[1]` to `background_index[4]` upon looking up a counter variable telling you which background cycle to draw (starting, first, second, or boss).

Important thing is, before changing these `background_index`es, you must always execute `background_index[0] = background_index[4]` to make the transition seamless.

# Answer
> 1 votes
I figured out a workaround. As i posted before, I don't know for sure if the code above works but if it doesn't you can try this one out.It is based on the one above but I also put variables in case you want to change the number of backgrounds. My workaround needs the duplication of the last bg.

```
Create Event:

bgNum = 6  //The total number of bgs plus 1(the duplicate)

background_index[0] = bg0 //the bg you want to appear LAST
background_index[1] = bg1 //The ACTUAL bg you want to see FIRST
background_index[2] = bg2
background_index[3] = bg3
background_index[4] = bg4

background_index[bgNum-1] = background_index[0] //the duplicate last bg

bk_width = 3840 //my width is double my view's width but you can try your         own

var i;           //fill array

i = bgNum-1;
repeat(bgNum)
   {
   background_x[i] = 0
   i -= 1;
   }

// Shift backgrounds (otherwise they will be overlapped)

for (var i=1; i<bgNum; i++)   // bkgr0 starts at (0,0)
{
background_x[i] += i*bk_width;
}

for (var i=0; i<bgNum; i++)
{
background_x[i] -= bk_width; //move to the one you want first
}

Step Event:

// Update backgrounds' relative positions

for (var i=0; i<bgNum; i++)
background_x[i] -= key;    // an alternative to background_hspeed[]

//when the last bg reaches 0
if (background_x[bgNum-1]<=-0)  // if the last background lies within the     view

{
for (var i=0; i<bgNum; i++)  //push back all backgrounds so that bg0 replaces
{                                //the last bg which has the same sprite
background_x[i] += bk_width*(bgNum-1); //so the transition is seamless
}
}

```

Big thanx to liggiorgio who posted the original code it was really helpful and sorry for the poor formating

---
Tags: game-maker, side-scroller, scrolling, shooter
---


# Question
Title: Moving a game object along a 2d vector by knowing the Rotation in degrees (Unity)
I am hoping one of you fine fellows can help me again. Basically I have been making a game like Asteroids in Unity. But its in a 3d world space (pretty much not relevant except I am using X and Z axes, and the rotation angle is on the Y axis).

When the user presses "W" this adds some power towards the thrust. It also records the objects current rotation in transform.eulerAngles. (i've verified that the angle of y is correct. So a value of 90 is showing when my ship is facing right).

I have used Mathf.Cos/Sin and that angle value to move the object along X,Z axes.

But for some reason it isnt moving in the same direction as it should. -I tried it with some offsets like thrustAngle - 45 (or 90 etc) and it doesnt adjust it as expected. (reducing it be 45 seems to have a bigger impact than expected for example).

Here is the lines of code, have I got the Cos Sin part incorrect?

```
    void HandleInput(){
    // activate weapon
    if (Input.GetKey(KeyCode.Space))
    {
        FireWeapon();
    }
    // Rotate left
    if (Input.GetKey(KeyCode.A))
    {
        transform.Rotate(0, -rotationSpeed * Time.deltaTime, 0);
    }
    // Rotate right
    if (Input.GetKey(KeyCode.D))
    {
        transform.Rotate(0, rotationSpeed * Time.deltaTime, 0);
    }
    // activate thrusters
    if (Input.GetKey(KeyCode.W))
    {
        thrustAngle = transform.eulerAngles.y -90;
        if (currentThrust < maxThrust)
        {
            currentThrust += accel;
        }
    }
    else
    {
        if (currentThrust > 0f)
        {
            currentThrust -= thrustDecay;
        }
    }
    if (Input.GetKey(KeyCode.S))
    {
        if (currentThrust > 0)
        {
            currentThrust -= decelThrust;
        }
    }

    transform.position += new Vector3(Mathf.Cos(thrustAngle), 0, Mathf.Sin(thrustAngle)) * currentThrust * Time.deltaTime;
    Debug.Log("angle: " + thrustAngle);

    if (currentThrust < 0f)
    {
        currentThrust = 0f;
    }

}

```

# Answer
Ok Ive fixed although I am puzzled as I thought that Cos was for the X axis. But I had two things incorrect: 1. I needed the angle to be in rads not degrees. 2. I had Cos and Sin the wrong way around.

Here is the code that got it working perfectly for me. (Sorry if I wasted anyones time)

```
        transform.position += new Vector3(Mathf.Sin(thrustAngle * Mathf.Deg2Rad), 0, Mathf.Cos(thrustAngle * Mathf.Deg2Rad)) * currentThrust * Time.deltaTime;

```
> 0 votes

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


title: Unity - Progress bar with sprites

text:
# Question
Title: Unity - Progress bar with sprites
I have 4 images that I made in photoshop that represent the progress the player is making in the game. When you finish the first level the image changes, when you finish the second level changes again, and so on.

But I have no idea how to make that work. So anything helps. Thank you

# Answer
To accomplish this we need to use what's called Image, which is a 2d sprite that we render for our ui:https://docs.unity3d.com/ScriptReference/UI.Image.html One way you coul make this work in a scrilt is by having a list of all the images that you created in photoshop, and then just switch the sprite of the object with one of the images from the list
> 1 votes

---
Tags: unity, sprites
---


# Question
Title: How to animate a bezier curve over a given duration
I have created a bezier curve by adding the following script to an empty game object in the inspector. This draws to complete curve at once when I run the code. How can I animate it over a given period of time, say 2 or 3 seconds?

```
public class BCurve : MonoBehaviour {

LineRenderer lineRenderer;
public Vector3 point0, point1, point2;
int numPoints = 50;
Vector3[] positions = new Vector3[50];

// Use this for initialization
void Start () {
    lineRenderer = gameObject.AddComponent<LineRenderer>();
    lineRenderer.material = new Material (Shader.Find ("Sprites/Default"));
    lineRenderer.startColor = lineRenderer.endColor = Color.white;
    lineRenderer.startWidth = lineRenderer.endWidth = 0.1f;
    lineRenderer.positionCount = numPoints;

    DrawQuadraticCurve ();

}

void DrawQuadraticCurve ()  {
    for (int i = 1; i < numPoints + 1; i++) {
        float t = i / (float)numPoints;
        positions [i - 1] = CalculateLinearBeziearPoint (t, point0, point1, point2);

     }
    lineRenderer.SetPositions(positions);
}

 Vector3 CalculateLinearBeziearPoint (float t, Vector3 p0, Vector3 p1,    Vector3 p2)   {

    float u = 1 - t;
    float tt = t * t;
    float uu = u * u;
    Vector3 p = uu * p0 + 2 * u * t * p1 + tt * p2;

    return p;
}

```

# Answer
You're doing all the work at once. You could do this in `Update()` and just render the points one by one, or you could reveal it slowly, by setting it to an image and then revealing it over a linear interpolation.

There's also one more method, you could just *not* draw the bezier curve from your calculations, but instead make a gameobject (preferably invisible) follow it. Attaching a trail renderer to the gameobject will give you a nice drawing effect, which you can adjust all sorts of ways.
> 2 votes

---
Tags: unity
---


# Question
Title: About making game development account for publishing Android-related games?
Registering as Google Play Developer requires a fee in order to publish games that have been invested in exchange for money. What about Steam? Is it required the same thing in registration or not?

Also, is it possible to publish Android games on Steam? If yes, how? My main game engine is Unity. Nothing else...and I'm gonna use it for making games before publishing. I have to check for possibilities before a quick conclusion that only Unreal engine is allowed to make games and published on Steam.

# Answer
> 2 votes
Steam is a lot more strict, than something like the play store. You either need a publisher, who has a contract with Valve or you need to submit you game to Steam Direct, which costs you $500 dollars, but you can get it back later if the game gets accepted.

And no, you can't publish android games on Steam, it's a PC game marketplace. Even if you could, the fee is much higher. You can either publish it on the play store or port it to PC.

---
Tags: unity, android, google-play, steam
---


# Question
Title: My cube goes through side walls on android device
I have a cube and it's on the ground and there are two walls (Plane) next to the ground.

Like in the image there is a ground and in side there is a wall. Here is my code:

```
    void Update() {

      transform.Translate(userDirection * speed * 14f * Time.deltaTime);
    transform.Translate(mSpeed * Input.GetAxis("Horizontal") * 2 *  Time.deltaTime, 0f, mSpeed * Input.GetAxis("Vertical") * 2 *  Time.deltaTime);

    if (Input.touchCount == 0)
        return;
    Touch touch = Input.GetTouch(0);
    float originalY = transform.position.y;
    float cameraZ = Camera.main.WorldToScreenPoint(transform.position).z;

    if (touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Began) {
        Vector3 screenPoint = new Vector3(touch.position.x, touch.position.y, cameraZ);
        Vector3 worldPoint = Camera.main.ScreenToWorldPoint(screenPoint);
        worldPoint.y = originalY;
        transform.position = worldPoint;
    }
}

```

My cube goes through the side walls, but on laptop it works perfectly, and on android device my cube goes through the side walls. Can anyone please tell why is my cube is going through side walls? Any help is appreciated!

# Answer
> 1 votes
Here is a simple example on how to make the movement a lot smoother and more natural(this also solves the problem of the cube passing through the walls): https://unity3d.com/learn/tutorials/projects/roll-ball-tutorial/moving-player

# Answer
> 0 votes
Your cube is probably going through walls because your `Update()` method doesn't get called as often as it does on a laptop. The android device will most likely have something near 30 FPS and that means 30 calls to the update method. If your cube can move behind the plane in that time, then it will be counted as behind the plane.

You could use a 3D object like a cube instead of a plane to offset this. You could also just change the plane's collider to a cube collider and make it thicker so that your cube can't go through it. See badly drawn example below:

Of course, using built in physics will handle most of the work instead if you choose to go that route. It will also use the `FixedUpdate()` method and will behave the same way in all systems (or at least try to do so).

---
Tags: unity, c#, 3d
---


title: Coroutine not working (Unity)

text:
# Question
Title: Coroutine not working (Unity)
I made this code because I needed an image to display a couple seconds after an enemy spawns, but for some reason I can't make it work.

There's no error in the console, but it doesn't display the image and I don't know what to do. Here's my script (it's attached to the enemy prefab)

```
 public class enemyAttack : MonoBehaviour {

 public float time = 5f;
 private IEnumerator coroutine;
 public Image image;
 private float t = 5f;

 void Start ()
 {
     //image.gameObject.SetActive (false);
     image.enabled = false;
     coroutine = nombredeCorutina (time, image);
     StartCoroutine (coroutine);
 }

 private IEnumerator nombredeCorutina (float t, Image im)
 {

     image.enabled = true;
     //im.gameObject.SetActive (true);
     yield return new WaitForSeconds (t);

     coroutine = nombredeCorutina (time, im);
     StartCoroutine (coroutine);
 }
}

```

# Answer
> 2 votes
You need to edit your code something like this:

```
public float time = 5f;
private IEnumerator coroutine;
public Image image;
private float t = 5f;

void Start() {
    image.enabled = false;
}

private IEnumerator nombredeCorutina(float t, Image im) {
    yield return new WaitForSeconds(t);
    image.enabled = true;
}

public void EnemySpawn() {
    //call enemey spawn whenver you want. it will register coroutine and you image will be displayed after given seconds
    //enemyspawn logic
    StartCoroutine(nombredeCorutina(t,image));
}

```

Now you have to identify that when should you disable your image and when you want to spawn enemy.

# Answer
> 0 votes
Some of your code is redundant or actively incorrect. For instance, why set the cooroutine in private and redeclare it over and over when you can just call it as is?

I've reordered your code to work correctly for the specific purposes you need it, if you wish to make your code reusable (which you should) then you'd have to structure it differently.

```
public class enemyAttack : MonoBehaviour {

    public float time = 5;
    public GameObject gameObjectHoldingImage; //Obviously too long a name, but helps explain.

    void Start (){
        gameObjectHoldingImage.SetActive (false);
        StartCoroutine(nombredeCorutina (time));
    }

    private IEnumerator nombredeCorutina (float t){
        gameObjectHoldingImage.SetActive(true);
        yield return new WaitForSeconds (t);
        //If you call this again (repeating) it is redundant as the game
        //object/image is not re-set to false.
        StartCoroutine (nombredeCorutina (t));
    }
}

```

---
Tags: unity, coroutines
---


# Question
Title: Using trademark or famous game characters for free (related to collaboration)?
Let's say, for example, I'm making an indie version of a *Batman* game using the signature DC character and my concept project of my own. It's like a fan base-project with some income earned. Then, added with some ads library, published in Google Play Store (via developer account) and leave a "disclaimer" note just in case.

Few days later, I got a hundred-thousand downloads with a lot of income I've earned. Some DC team notice this without permission even though it was a successful. Here's the catch: negotiate and agreed to split the earnings in order to support the project and became part of it without getting sued.

Can this work that way?

This method I believed is 50-50 and I need a confirmation if it is effective that way like what I've mentioned above example of this situation.

# Answer
Another reason why this is not a good plan: think about the people.

I doubt you have a lot of funds to make that game, and as @Philipp already pointed out, to make a game that DC would be ready to put their logo on, you need a *lot* of money. A lot of that money goes to paying people to make the game (salaries).

To make a game of that scale, you'll need people. *Where will you find them?* If you have no money, will you be able to convince developers, artists, support people, marketing people, managers, etc. that your plan is going to work, and that all the time that they spend making the game (one year and more of hard work) will be paid by DC a couple of days after the game launches? And if you manage to convince some, and your plan doesn't work and you get poorer than before, no one knows what they'll think about you.

If your plan is to borrow money to pay the salaries, you'll have to convince some investors. And I'm not sure you'll find any serious investor ready to get on with that plan.

---

If you want to make a deal with a bigger company and work on license games, I suggest you create your own game studio, make a few games with *your own IP*, get noticed for your skills, then bigger entertainment companies will know that you can make games, and it will be easier to make deals with some of them.

---

P.S.

Keep in mind that these companies want to *make money*, so working with them *can be very hard*.
> 4 votes

# Answer
Absolutely not. Do **not** do this.

A general rule of thumb, is that you should not use or reference any property that you do not exclusively own, e.g. you should not even be saying "This game is like a better Tetris!" or "This is a Super Mario Style Game!"

The reason being, say your project that is about the DC character Batman is a complete failure, and it is generally universally hated... Do you think DC would be happy to find out they lost fans, whose first experience with DC, was your hated game? Equally it doesn't have to be about a **first** experience, just a **consistent** one.

You might wonder, "I've seen games pop up online before using copyrighted materials, and they seem to be fine." - Well the answer to this is that they will either have been so unpopular that they have gone unnoticed, or the big difference (and this is the big one) is that the game did not make any money whatsoever.

If you do this, you will have no leg to stand on, and all your money can be taken at any time, you can be sued, and your game can be removed. Do not risk this if you consider yourself a respectable game developer.

Equally (I am only mentioning this to preemptively counter anyone who argues the following defence); consider that when someone suggests a particular copyright claim is protected by "Fair Use" - Fair Use is a court defence. Not a protection from a summon. Meaning that whether it does or does not come under fair use (this example 99% does not), you will still have to appear in court, pay legal fees, and most importantly spend inordinate amounts of time preparing and attending a case, that ultimately you will lose.
> 6 votes

# Answer
While it is *theoretically* possible to end up with such an agreement (they sue and you negotiate this as a settlement), you should not bet on it.

1. You obviously violated their copyright and their trademark. Why would they settle for a 50% split when they can sue for 100%, and then possibly damages and legal fees (beyond what you already have to pay for your own legal fees)? And there is not much you can do to defend your point, because they have a legal department stuffed with IP rights specialists and you don't (there is no right to a free attorney in a civil lawsuit). You have literally nothing you can offer them. They got you in a corner. A best deal you can realistically hope for is that they offer to buy the game rights from you for one symbolic dollar in exchange for covering your legal fees.
2. They *have* to make an example out of you. When they let you get away with that, others will too. When a company doesn't defend their trademark, they risk losing it. That's why most companies have a zero tolerance policy when it comes to trademark violations. Especially when it is about an immortal cash cow like the Batman character.
3. You just assume your game will be a huge success. But you can not bet on that. Most indie games thrown into the play store barely break even. When you don't have a million dollar budget and a team of experienced industry veterans at hand, it is extremely unlikely that you will live up to the standards of quality and success the DC Comics executives expect from one of their most valuable brands.

And all of that is not just theoretical. The list of fan projects smashed by the legal hammer is endless. Most projects which look slightly more ambitious than "school kid discovered Game Maker" don't even make it to release.

When you want to create a game based on someone's intellectual property, negotiate and sign a license deal **before** you start sinking serious work and money into the project. That's likely what happened in the *Abe's Oddysee* remake and what usually happens with any other game based on a license.

Looking at who DC Comics is working with usually, there is little chance that they would give the Batman license to a newcomer. But there are companies which are more cooperative. Games Workshop, for example, seems to sell their licenses to almost everyone nowadays (Even if you just want to make a chess game).
> 6 votes

---
Tags: copyright, business, trademark, intellectual-property
---


# Question
Title: What are good alternatives to microtransactions?
Recently, this question popped up on here, and it made me wonder if there was a better way to earn money from one's game without using microtransactions.

So, **What are good alternatives to microtransactions?**

# Answer
> 1 votes
First of all, the microtransaction model of monetization is based around a few premises. It lends itself to games that are long, or continuous in nature, where players will come back for multiple sessions over a period of time. Arena games where you enter and exit a match several times in one sitting, or games with many stages that unlock in succession. A short, linear, story-based game would be less suitable if the players are going to play through it once and then put it on their (virtual) shelf. Also, in practice, it often relies on a curved demographic, where a few players are the source of most of the revenue, and most of the players are the source of very little revenue.\*

Secondly, from the opposite perspective, microtransactions represent a certain type of revenue. With microtransactions, you are aiming for a smaller, more even stream of revenue over time, which lends itself to a continuous process of releasing small content updates over a longer period. You won't have a big pay-off from many players purchasing your game on launch after a long, draining development cycle like you could with a fixed price. And once you stop making new content to sell, the revenue may taper off.

With that context in mind, the alternative is going to depend on the type of experience you are monetizing.

Assuming that we want to consider *only the type of game for which microtransactions are a good match to begin with*, here are some different models:

**Advertising**: Instead of small amounts of money, the player exchanges small amounts of time spent interacting with a third-party ad, and you get your small amounts of money from that third party. This is often combined with the option for the player to swap their roles around by paying a fee to bypass all future ads. This model aims for a similar goal of steady revenue over time, so it lends itself to game types where players continue to play over a period. You also get a similar effect to microtransactions where some players will opt to pay the fee to remove ads, which should be a fee that exceeds the expected revenue from the ads that player would have interacted with.

**Subscription**: Less popular in today's mobile world, but works on the same premise of playing over a period of time in exchange for a fee over a period of time. The advantage and / or disadvantage of a subscription model is that revenue is more or less proportional to number of registered players. You won't earn any less if a player only plays occasionally while their subscription is running, but you also won't earn any more from enthusiastic big spenders (or whales\*) who log in every day.

* I wouldn't necessarily trust the specific numbers quoted, but here are some articles about the phenomenon:

Social game “whales” are big spenders

> The new report shows that about 10 percent of social game players actually spend money in Facebook games, according to a study of 2,000 people who were surveyed by Inside Network.

Only 0.15 percent of mobile gamers account for 50 percent of all in-game revenue

> The group of gamers responsible for half of all in-game revenue in mobile titles is frightening because it is so narrow, according to a survey by Swrve, an established analytics and app marketing firm. About 0.15 percent of mobile gamers contribute 50 percent of all of the in-app purchases generated in free-to-play games.

# Answer
> -1 votes
You can put ads in game or make the players pay full price out front. I have to say, though, that microtransactions are not a bad thing, if done correctly. I advise you to look at this video how to do so:

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

Basically, if you can finish the game without having to use cash, you can access all parts of gameplay and money buys the player cosmetic upgrades without giving them undue advantage over other players then you're good. Here's some more videos from the same authors on how it could be done badly:

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

Another two:

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

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

---
Tags: monetization, appstore, advertisements, in-app-purchase, microtransactions
---


# Question
Title: Unity - An unwanted Collider , far too big , being added to meshes without reason and I cannot remove it
so I have a game in progress that is very similar to Asteroids. I was using spheres as primitive game objects and it all works perfectly in this case, but I need to be able to rotate the ship's model, and move the sphere as seperate entities and so I decided to keep the sphere for the positioning (but with no mesh renderer on it, just the sphere collider). And then as a child of that sphere is my model of a spaceship. It all works fine, ie. the ship rotation is completely seperate to that of the position of its parent sphere.

My problem is when I added the OnTriggerEnter to test collision between Ship to Asteroid. It would trigger immediately.

So I looked further into it, I zoomed right out on the Unity editor and could see that there is a huge collider that appears to be part of the mesh. (Now the mesh i did download from Blend Swap, but I have tried 3 varied ships and they have all done it - not to mention that I pulled them into Blender first and editted them so that it was just the ship part that I wanted and when I exported the OBJ/FBX's I ticked the box "Selected Only", - In a nutshell - I'm 110% sure there wasnt some little camera/light/object floating around that would cause the model to have such a big collider)

Secondly , I think I mentioned already, that in Inspector THERE ISNT ANY COLLIDER supposed to be attached to the mesh/model.

Heres a screenshot which I hope shows what I mean.

alt text

I really hope there is a way to fix/remove this as its been stopping me progressing any further and if it cant be removed I will have to start the whole game from scratch again.

Really I am also asking, why is there a collider even there when as you can see in the screenshot it clearly doesnt have any collider added. The parent has a collider, but this is the correct size and I can adjust/deactivate it as I'd expect. In my mind this collider pictured shouldnt exist.

# Answer
> 4 votes
Well that collider might not even belong to the game object you are currently selecting, try to go through each game object that is a child object and you'd probably find it. And when you do you can remove it by right clicking the component and clicking "Remove Component". If it still doesn't work send me the project file cuz I can't make out what is what just from looking at the picture.

---
Tags: unity, mesh, importing, collider
---


# Question
Title: EventSystem first selected not highlighting
I'm trying to make a menu and encountered this problem.

```
protected static EventSystem eventSystem
{
    get { return GameObject.Find("EventSystem").GetComponent<EventSystem>(); }
}

public static void ButtonNavigation(List<GameObject> _listButton, int firstSelected)
{
    eventSystem.SetSelectedGameObject(_listButton[firstSelected]);
    print(eventSystem.currentSelectedGameObject);
}

```

But when I print out the currentSelectedGameobject it clearly says that "Status" is selected but how come it's not highlighted?

I've read some article on using Co-routines but is it really necessary?

# Answer
> 0 votes
Try setting `eventSystem.SetSelectedGameObject` to null first before setting it to anything.

---
Tags: unity, gui, bug
---


# Question
Title: How can I create and load models with additional information?
I want to create game similar to original DOOM in Unity (using 2017.2). I'd like to make it possible to load entire levels from file, but I don't really want to write my own level editor that would serialize and deserialize Unity objects.

I'd like to allow the player base to create new levels using blender, without them needing to use Unity: all the logic and shapes should come from that single blender file.

I'm wondering how it could be possible to create levels in blender with some additional data, that could be processed from the Unity game. Just simple markers, for example stepping on platform **A** will open door **B**.

# Answer
This is not going to be as easy as you think it would be, because only the Unity *Editor* can load Blender files. When you import a Blender file, it is converted to Unity's internal format. This is the only format which the actual game engine can read. The built game does not include any Editor-specific program code, including the code which imports assets from 3rd party formats. That means when you want to allow the built game to read .blend files at runtime, you need to include your own parser for the .blend file format. And if you go that far, then you can just load any meta-data from the Blender file you want, for example in form of a text datablock created with the text editor.

But note that there are games which built thriving modding communities of people who use the Unity Personal Edition to create asset bundles which the base game can then load as mods. Kerbal Space Program, for example. This makes modding a lot easier than using Blender, because you can release a pack of handy editor scripts and other assets which help your modders to perform common tasks.

Another positive aspect of using Unity is that the full power of the Unity scripting system is at their disposal for adding new game features. But that does of course also give great potential for abuse.
> 3 votes

# Answer
Well, I don't think blender can do logic, but it can do animating. You can animate a door opening and making it an animation in Unity as well. You can add a `Collider` and enabling the `Trigger` in front of the door to make it open. Making a map in blender isn't really efficient but it works. Just add a `Mesh Collider` to it without checking 'Convex' and it should automatically add colliders to it according to its shape.

> The thing is, I'd like to put all the level logic and shape in one file.

Thats what scenes are for.
> 0 votes

---
Tags: unity, models, blender, modding, data-driven
---


title: How to create a boomerang-a-like path?

text:
# Question
Title: How to create a boomerang-a-like path?
For the GitHub Game Off Jam, I plan to create a small game with a boomerang. But I don't know how to build the equation that will update the boomerang position.

I try to build a direction vector and rotate it a little to each update. But it generate each time a circle.

Is a bezier curve a good alternative? Or is it too complex?

# Answer
What about one side of a lemniscate (polar) or a rose curve (also polar)?

You can find a refresher on polar curves (and the equations of the curves described above) here (which is where I got the equation for the lemniscate. This was just one of the first sites that came up when I searched "polar curves"):

http://math.tutorvista.com/geometry/polar-graphs.html

How this would be implemented in C (the equation for a lemniscate is r^2 = a^2sin2(theta)):

Since `r^2 = a^2sin(2theta)`, then `r = +-sqrt(a^2sin(2theta))`, which can then be simplified to `r = +-asqrt(sin(2theta))`. We will only focus on the right side, which means that we can just assume the equation is positive instead of `+-`. a just alters the shape of the lemniscate slightly, so let's just set it to 1. We end up having `r = sqrt(sin(2theta))`.

```
float theta = .0F; // a global theta variable to store the position of the boomerang in each frame

void draw() { //or whatever function you are using for drawing each frame
    float r = sqrt(sin(2 * theta));
    //"Base Coords" refers to the boomerang's coordinates right before it is thrown
    float xTransformFromBaseCoords = r * sin(theta); // In order to turn a polar radius into an x Rectangular coordinate, multiply r by sin(theta). In order to obtain the y-coordinate, multiply r by cos(theta).
    float yTransformFromBaseCoords = r * cos(theta);
    glTranslate4f(xTransformFromBaseCoords, yTransformFromBaseCoords, .0f); // The ".0f" is the z-transform
    theta += .01F; //increase the value being added to theta in order to make the boomerang move faster
    //draw the shape
    glLoadIdentity();
}

```

If you don't need a perfect lemniscate curve, and want to improve performance, then you can approximate sine and cosine using taylor polynomials that have up to two parts (I tested that on my intel pc, and the native sine function ended up being faster than Taylor polynomials of degree three and higher. However, if your coordinates are normalized (from -1F to 1F), then your theta value will most likely be very close to 0, meaning that the error will be relatively small.
> 3 votes

# Answer
Regarding comments and answer:

I can create a path based on bezier curve or use a rose curve.

Because I want my path to be modified by the player strenght or some environmental behavious, I use a path based on bezier curves:

* the player strenght can scale the curve
* environmnental behavious just achange a local part of the curve

But because the rose curve will allways be the same shape, i now use bezier curve instead.

So I build a bezier curve by "hand". But environmental behavious will be able to move points from this bezier curve. And the player movement will update the strenght of the curve.

The next issue I got with Bezier curve is : how to move an objet allong at a constant speed the path? I use LibGdx and you can get a position regarding a percentage of the curve.

To achieve this, I compute the lenght of a displacement. Then I compute the percentage that this displacement represent for my bezier curve. Now I got the percentage of the curve from my displacement, so I can get the position of my objet of my bezier curve.

```
val dst = accumulatedDistance + (speed * delta)
val percent = curve..approxLength(500) / dst
val position = Vector2()
// will set in position the value at percent of the curve
myCurve.valueAt(position, percent)

```

This comment is inspired from this LibGDX source code (which manage several curves to create one path).
> 0 votes

# Answer
**tl;dr:** Do what you want. But sure, béziers are fine.

Realistically, a boomerang goes on a very weird, unnatural path which depends on the boomerang's individual form but is definitively not a circle, nor anything like circle-shaped, with its wings describing a hypocycloid around its center of mass. Which is, admittedly, a very pretty pattern, and sheer hell to simulate. You can easily hold an one-hour lecture on that topic if you want.

A game is a game, is a game, is a game.

Bézier curves are easy to implement and can be evaluated efficiently. So, if you want your boomerang to go on a somewhat bent path, do that.

In the easiest case, you can model the control points of your bézier curve in a SVG editor (so you see that the result will look approximately like what you want!) or in another tool (Blender will do, for example), then hardcode the control points in your game, and apply a simple rotation matrix to them depending on what direction your character faces. Then, just evaluate the polynomial for any desired *t*, and that's it.

You can do something much more complicated, but why. Modelling the curve once WYSIWYG and then rotating it is mighty fine, no user will complain about lacking realism. And it's easy...

If you think a boomerang goes in a straight line and then returns, then even that is mighty fine. Do that then. Whatever you like.

Really, there is no right and no wrong, but bézier curves most definitively are a good plan.
> 0 votes

---
Tags: mathematics, curves, path
---


# Question
Title: What is the Shannon rule/law when talking about game physics?
I've been reading some articles on game physics and came across subjects such as fixed timestep (article). Some of the articles I read mention the "*Shannon rule*" or "*Shannon law*" in relation to the length of the timestep. Example quote:

> Your timestep should be at least `1 / 120` seconds or smaller because of the Shannon rule \[...\]

Here's an answer here on Gamedev that mentions it. Some quick google searches for "Shannon's law" doesn't seem to yield much result except for this wikipedia article but I'm not sure if that's what is being talked about here.

So what is the **Shannon rule / Shannon law**?

# Answer
> 5 votes
In short, you cannot find it because it is incorrectly named.

The quote refers to the Nyquist sampling theorem (or rather the Nyquist rate), the former sometimes also being referred to as the Nyquist-Shannon sampling theorem, and also known under a couple of different names.

If you want no aliasing at 60Hz, you need a 120Hz sampling. Here, "sampling" is the frequency of your simulation.

Although Shannon's name appears in the Nyquist-Shannon theorem, his name is usually associated with entropy (whereas Nyquist is usually associated with the Nyquist rate).

# Answer
> 2 votes
When you have a fixed timestep, then your graphics framerate should be at most half your physics framerate.

When your graphics framerate is more than that, then sometimes there will be two logic updates between two rendered frames and sometimes just one. This leads to a perceived lack of smoothness which some players describe as "jitter", "stutter" or "microlag".

60 Fps is usually considered the highest framerate the human eye can perceive when looking at 3d graphics. It's also the highest framerate most consumer-grade monitors support\*, so there is little reason in rendering any faster. That's where the 120 Ticks per second number comes from.

*<sub>"Gaming monitors" with 120Hz and more are still a niche product, but they are becoming more popular lately. If they really have a point or are just a placebo is an ongoing debate.</sub>

---
Tags: physics
---


# Question
Title: 2D Parallax scrolling through GLSL shader
I currently switched from LWJGL to LibGDX. In LWJGL I had a shader to do parallax scrolling by simply adding an offset to the texture coordinates and it worked fine, the texture repeated itself when the coordinates where greater than 1 or smaller than 0. But in LibGDX the same shader won't work. Once the texture coordinates are greater than 1 or smaller than 0, the texture just "smears" all over the screen, it doesn't repeat itself.

Vertex shader:

```
#version 330 core

layout (location = 0) in vec4 a_position;
layout (location = 1) in vec4 a_color;
layout (location = 2) in vec2 a_texCoord0;

out vec4 v_color;
out vec2 v_texCoords;

uniform float x_offset;
uniform mat4 u_projTrans;

void main() {
    v_color = a_color;
    v_texCoords = vec2(a_texCoord0.x + x_offset, a_texCoord0.y);
    gl_Position = u_projTrans * a_position;
}

```

Fragment shader:

```
#version 330 core

in vec4 v_color;
in vec2 v_texCoords;

out vec4 frag_color;

uniform sampler2D u_texture;

void main() {
    frag_color = v_color * texture2D(u_texture, v_texCoords);;
}

```

# Answer
You need to set the texture parameters to change it from clamping to the edge of the texture to repeating the texture. You can do this with:

```
glTexParameteri(target, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(target, GL_TEXTURE_WRAP_T, GL_REPEAT);

```

after you've bound the texture to the appropriate texture target (which in your case is `GL_TEXTURE_2D`).
> 0 votes

# Answer
You can also achieve this with the `fract` function in GLSL, i.e.

```
frag_color = v_color * texture2D(u_texture, fract(v_texCoords));

```
> 0 votes

---
Tags: libgdx, shaders, glsl, parallax-scrolling
---


title: Inaccurate UI button unity

text:
# Question
Title: Inaccurate UI button unity
As you see in this screenshot I must hover the mouse on that that spot to click on button in overall you must hover the mouse upper than button to click on it, tried to change the Sprite but even with default Sprite I have this problem so I don't think there is problem with Sprites.

Let me explain more about this panel:
In this scene I have two canvas's one for Pause button only and another one for this panel that is disabled. When you click on Pause this panel will appear ( second canvas will be activated. Why is that? I tried to change some things in the canvas like change UI scale mode to scale with screen size but no luck.
I will be grateful for help I don't really know where problem is.

Update : I just now found very odd behavior when hit play if mouse be in game view that problem wont occur, after mouse leave the button issue will appear again.

# Answer
> 2 votes
Well I've finally solved my problem and issue was texts on buttons looks like i scaled them and made them bigger than buttons.

---
Tags: unity, gui
---


# Question
Title: Why is the velocity of my rigid body in OnCollisionEnter always zero?
My object must explode when the player touches it or when it collides at a low speed.

The problem I'm having is that its speed becomes zero when the floor collides for example and then the `OnCollisionEnter` event is called, it is already late and never fulfills the condition.

Someone knows what I'm doing wrong or what I should do to fix this?

```
void OnCollisionEnter(Collision other)
{
    Debug.Log(Mathf.Abs(rb.velocity.magnitude));
    if (Mathf.Abs(rb.velocity.magnitude) >= detonationImpactVelocity)
        Explosion(200);

    if (other.gameObject.tag == "Player")
        Explosion (600);

}

```

I came up with this but I guess there must be a better way to do it.

```
void Update()
{
    if (Mathf.Abs(rb.velocity.magnitude) >= detonationImpactVelocity)
        explosionSpeedAchieved = true;
    else
        explosionSpeedAchieved = false;
    Debug.Log(Mathf.Abs(rb.velocity.magnitude));
}

void OnCollisionEnter(Collision other)
{
    Debug.Log(Mathf.Abs(rb.velocity.magnitude));
    if (explosionSpeedAchieved)
        Explosion(200);

    if (other.gameObject.tag == "Player")
        Explosion (600);

}

```

# Answer
Check instead the collision's relative velocity:

```
void OnCollisionEnter(Collision collision)
{
    Debug.Log(collision.relativeVelocity.magnitude);
    if (collision.relativeVelocity.magnitude >= detonationImpactVelocity)
        Explosion(200);

    if (collision.gameObject.CompareTag("Player"))
        Explosion (600);
}

```

On a side note, it would be more efficient to check the `sqrMagnitude` against the square of `detonationImpactVelocity` to avoid an unnecessary sqrt calculation.
> 8 votes

# Answer
You could try the relative linear velocity from the Collision object itself:

```
if (Mathf.Abs(other.relativeVelocity.magnitude) >= detonationImpactVelocity)

```

See also: https://docs.unity3d.com/ScriptReference/Collision-relativeVelocity.html
> 3 votes

---
Tags: unity, c#, collision-detection
---