# Question
Title: Texture "Mapping" (Using just part of a texture sheet on a object face)? Unreal Engine
I've created a `Playing_Card` class which is of course for card games such as Blackjack. The class works fine, except until now I have not used graphics.

I have now started using Unreal Engine and have started getting to grips with the less advanced parts such as making my own GameModeBase and Player/Pawn class.

But until now, I have made-do with just starter content only.

So this is the first model I've ever imported to UE4. I created the model in Maya and have the UV-Mapping all in place. The rear of the card is of course the same for every card, so I have made that built-in to my exported fbx. But for the face, I am not sure how to deal with it.

What I'd like is to be able to create a "Texture Atlas" of sorts. Ie) a bunch of Vector2D values along with the single width/height values for the portion I need.

But Unreal is mindblowing to me with all the options and even the docs are mindblowing to me. I would really like to learn it though. I realise this might not something that can be easily written up as an answer.

I guess what I need to get started is just to know where in the documentation does it refers to all this stuff AND even better where in the UE4 UI can I find it (what do they call this stuff?).

ONE OTHER RELATED THING: I wondered if it would hurt the program/game if I made one long texture of the card faces. So the texture file would be something like 1300x150 or something (rather than the faces texture shown in my picture)?

Any help is greatly appreciated. Here are some images to help you understand what stage I am at:

(EDIT: Well I mapped the face side to be the size of just the Ace. So in theory if I want to make it a Two I just need to move the UV forward a little bit along U (or V? Lol). I found TexCoord node but that seems only for tiling, not positioning the UV. I have looked for hours but can't find the right node. One more picture I add below might help to explain what's happening)

\[

\[

# Answer
> 1 votes
Well I figured I'd have a go at answering my own question since there wasn't any responses yet and I made a little progress.

I really dislike using visual scripting/material editing but this was the only way I can get it to work. I still haven't managed to connect my Card.cpp script in so that I can adjust that value to which card, but in the Material Editor I have set it up so I can just increase the `Multiply` node to show the card I want.

I had to edit the texture so all cards are in a line, and I decided to remove any padding so that its easier to calculate.

So I use `TexCoord` node. The Y value is 1.0 showing all height of texture. The X is 1/13 (there's 13 types of card face).

Then I had to add those other nodes you will see in the picture. This took me absolutely hours to figure out. Also the `UV Map` in Maya had to be changed so that the card face UV just covered the entire texture.

The constant at the top-left is also '1/13' .

I would love to hear any suggestion of better way to handle this. I suppose I could easily have done the same with Y-Axis if I wanted to have a more square texture (for example to add the other suits below it). But ideally I would like to avoid all this node dragging stuff and find a way to code this stuff in C++.

I had hoped there would be a way to simply have two constants (UV\_WIDTH, UV\_HEIGHT) and then a constant array of points ((0,0) (130,0) etc etc) . Then simply use that array to move the UV via script. Is there a way to make it that simple?

---
Tags: textures, unreal-4, unreal, uv-mapping, texture-atlas
---


# Question
Title: How do I find the correct vectors perpendicular to a vector in between two vertices?
I'm trying to push the purple vertices inward by moving it with a vector perpendicular to the red vector shown in the picture.

Each directional vector created will move its respective vertex towards the center. How do I control what direction these perpendicular vectors are going?

Edit: Here's a more descriptive picture illustrating my problem:

So the yellow vertices do move in a direction perpendicular to the direction of the edge vertex (red).

However, they all move in the same direction. This is just a base case but I need to iterate through all of the yellow vertices and make each of the move towards the middle like this:

For each yellow vertex, I want to control them so they move inward towards the middle but no success with the dot product. Here's a snippet of my code:

```
for (int i = 0; i < yellowVertexArray.Length; i++)
{
    Vector2 originToRedVertDir = (redVertexPos - originOfTransform).normalized;
    Vector2 perpendicularDir = new Vector2(directionToInitial.y, -directionToInitial.x);

    Vector2 cornerToMiddleDir = (yellowVertexArray[i] - redVertexPos).normalized;

    if (Vector2.Dot(cornerToMiddleDir, originToRedVertDir) > 0)
    {
        yellowVertexArray[i].position += (Vector3)perpendicularDir * Time.deltaTime;
    }
    else if (Vector2.Dot(cornerToMiddleDir, originToRedVertDir) < 0)
    {
        yellowVertexArray[i].position += -(Vector3)perpendicularDir * Time.deltaTime;
    }
}

```

# Answer
> 0 votes
In 2D you can form a perpendicular with a very simple trick — exchange the x and y components, and negate one of them:

```
purple.x =  red.y
purple.y = -red.x

```

There are two ways to do this of course — we could have negated either x or y. That corresponds to the two different purple arrows in your diagram: one negated x and one negated y. (Or looking at it a different way, one purple vector is -1 times the other)

To make the purple vector point inward instead of outward, you can take the dot product of the purple vector with the vector from the corner vertex you're working on to the middle vertex:

```
dot = purple.x * (middle.x - corner.x)
    + purple.y * (middle.y - corner.y)

```

If the dot product is positive, then the purple arrow is pointing inward toward the middle. If it's negative, then it's pointing outward — multiply both components by -1 to fix that.

---
Tags: unity, c#, 2d, geometry, vertex
---


# Question
Title: Why addForce creating some small movement in my game object?
I'm working in a project with **Unity 2d** where player walks on a small planet. I try to use some code from youtube tutorial to apply gravity to my planet.This code consists of two parts, Attractable and Attractor. Attractables are used on objects that are drawn and Attractors placed on planets. When I try to play it it works, but when my player is idle, my player get pull toward the bottom of the planet.

in Attractor script, it just find all object inside Circle area with `Physics2D.OverlapCircleAll` and then call Attract function from object with Attractable script. The Attractor code look like this:

```
    void Update()
    {
        SetAttractedObjects();
    }

    void FixedUpdate()
    {
        AttractObjects();
    }

    void SetAttractedObjects()
    {
        AttractedObjects = Physics2D.OverlapCircleAll(planetTransform.position, effectionRadius, AttractionLayer).ToList();// can be optimized
    }

    void AttractObjects()
    {
        for (int i = 0; i < AttractedObjects.Count; i++)
        {
            AttractedObjects[i].GetComponent<Attractable>().Attract(this);
        }
    }

```

And inside the Attractable script, it has Attract function, that apply some force to object rigidbody. This is the function called from the previous Attractor script. This code apply force from rigidbody position to the position of the planet.

```
public void Attract(Attractor artgra)
    {
        Vector2 attractionDir = (Vector2)artgra.planetTransform.position - m_rigdibody.position;
        m_rigdibody.AddForce(attractionDir.normalized * -artgra.gravity * force * Time.fixedDeltaTime);
        if (currentAttractor == null)
        {
            currentAttractor = artgra;
        }

    }

```

This script also has, a RotateToCenter function which ensures the player is always facing the planet. This function is called from the Update function.

```
void RotateToCenter()
    {
        Vector2 distanceVector = (Vector2)currentAttractor.planetTransform.position - (Vector2)m_transform.position;

        float angle = Mathf.Atan2(distanceVector.y, distanceVector.x) * Mathf.Rad2Deg;
        m_transform.rotation = Quaternion.AngleAxis(angle + 90,Vector3.forward);
    }

```

I try to use `Debug.DrawLine` to see the AttractionDir variable from Attract function, and i get:

I think it's the correct force vector because it applies the force from my player position to the center of my planet the way I want it. But my player always move a bit to the bottom of the planet. I tried to remove my RotateToCenter function, and my player doesn't pull down anymore, but it also causes my player to not move as it should. I try to reduce the force, but my player still moved. So i try to increse the force and my player moves faster. I get confused, because i think the force direction is from my player rigidbody position to the planet center(it should only pull my player to the planet not moved it), so why my player moved by this force. I also set rigidbody gravity to 0 so it doesn't effect my player but i still get the small movement. Why is this happening? Anyone know how to solve it?

# Answer
> 2 votes
I suspect this happed because you apply constant force to the player every frame, and this force coming from the wrong direction. You may need to stop applying that force when the player is grounded and idle and turn it back on when the player is not grounded and/or is moving. Tiny floating point errors plus a box collider colliding with a spherical collider can cause things like this to happen. You can also try setting the rigidbody to kinematics if your player is idle.

```
if(!isMoving){
          rb.isKinematic=true;
     }else{
          rb.isKinematic=false;
     }

```

You can set the bool isMoving when your player move, example:

```
 if (Input.GetKey(KeyCode.A))
     {
          isMoving=true;
          // player movement code
     }
else if (Input.GetKey(KeyCode.D))
     {
          isMoving=true;
          // player movement code
     }
     else
     {
          isMoving=false;
     }

```

---
Tags: unity, physics, rigidbody, planet
---


title: Detecting Surrounding GameObjects

text:
# Question
Title: Detecting Surrounding GameObjects
**Some Background Context:**

So I have a 2D prototype in Unity I am working on that has enemy entities that have rigidbody2D component set as dynamic as I am using physics (`AddForce()`) for movement. I am using physics for movements as I want entities to have a physicsy feeling (slight accel / decel movement, knock back when hit / from explosions, etc.) and Unity physics system with support what I need and I would not really be able to create something myself anyways.

I want my enemies to be able to have knowledge about the entities around it (relatively large area, anywhere from 10 - 25 Unity units radius) and my initial implementation was a quick and simple trigger collider that called a script any time a GameObject in a matching layer entered or exited which worked at first. When I stress tested with a lot of entities in the same area, I noticed the performance when down exponentially with `Physics2D.FindNewContacts()` taking up a ton of time in the profile. Because the detection collider is on a game object under the enemy entity that has the dynamic rigidbody2D component, each new entities in the area exponentially adds more contacts (when I have 4 entities moving in range of each other that is 4 entities re-calculating contact points for 3 other entities and then I have 30 entities moving in range of each other that is 30 entities re-calculating contact points for 29 other entities and so on).

The only 2 options I can think of are:

* Use a kinematic Rigidbody2D and write custom code for handling "physics" interactions
* Remove the detection collider and do area scanning in a different way.

Option #1 seems like a lot of work especially since I don't really need anything outside of what unity physics support (it is really just the performance which I assume is more just because of how I am doing things) so I am thinking of how to handle Option #2.

What I am thinking of doing at a high level is:

* Remove the detection collider
* Add a queue for a detection area scanning (for lack of a better term) that game objects can add themselves to or remove themselves from
* I can process this queue in a co-routine or something (it does not need to check every frame for every entity that need detection scanning) so that each frame I do a scan for X entities
* This detection scanner would call something like `Physics2D.CircleCastAll()` and then process those hits (in the same way the detection script did when using the collider).

For content, this scanning is mainly for AI purposes. Right now it is just for enemies to be able to track the player when in range however it will be expanded upon later (like enemies keep track of nearby enemies to heal if possible as one example).

Does this seem like a sane way to handle this kind of problem? Is there "standard" way of handling something like this? Am I missing something with the core problem that could solve this issue easier?

# Answer
> 1 votes
I'm thinking of giving the detection method to the player and not the enemy.So instead of allowing 30 enemies to always detect 1 player, I'm thinking of letting one player find 30 enemies that are close to him and call a function to have the enemy chase them depending on the distance from the enemy to the player, i think of using:

```
void EnemyDetection()
    {
        AttractedEnemy = Physics2D.OverlapCircleAll(playerTransform.position, effectionRadius, EnemyLayer).ToList();// can be optimized
    }

```

and the use for loop to call nemy function

```
void AttractEnemy()
    {
        for (int i = 0; i < AttractedEnemy.Count; i++)
        {
            AttractedEnemy[i].GetComponent<Attractable>().Attract(transform.position);
        }
    }

```

And then in Attractable script in enemy, use Attract function:

public float radius;
    void Attract(Vector3 playerPos){
        float dis= Vector3.Distance(playerPos,this.transform.position);

        if(dis<=radius){
            //enemy chase player;
        }
    }
```

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


# Question
Title: All objects are destroyed when I click left mouse button. | Unity 2D C#
I'm currently working on a game strategy game and I just started working on it.

Here is the first script:

```
using UnityEngine;

public class Village : MonoBehaviour
{
    public int strength;
    private int x;

    private void Start()
    {
        StrengthValue();
        strength = x;

        print(gameObject.name + " ---- " + strength);
    }

    private void Update()
    {
        if (Input.GetMouseButton(0) && GameObject.Find("Game Manager").GetComponent<GameManager>().ArmySize > strength)
        {
            Destroy(gameObject);
        }
    }

    private void StrengthValue()
    {
       x = Random.Range(10, 500);
    }
}

```

here is the second script:

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

public class GameManager : MonoBehaviour
{
    public int ArmySize = 100;
}

```

All I want is for the game to detect when the player clicked a certain village. But I just can't figure it out since I'm pretty new to c# and unity. The scripts should be self-explanitory, but if you need more details please ask.

# Answer
Instead of putting this:

```
if (Input.GetMouseButton(0) && GameObject.Find("Game Manager").GetComponent<GameManager>().ArmySize > strength)
{
    Destroy(gameObject);
}

```

in the `Update` function, I put it into the `OnMouseDown` function. I also made sure to put colliders on my objects.

so this is the full script:

```
using UnityEngine;

public class Village : MonoBehaviour
{
    public int strength;
    private int x;

    private void Start()
    {
        StrengthValue();
        strength = x;

        print(gameObject.name + " ---- " + strength);
    }

    private void OnMouseDown()
    {
        if (Input.GetMouseButton(0) && GameObject.Find("Game Manager").GetComponent<GameManager>().ArmySize > strength)
        {
            Destroy(gameObject);
        }
    }

    private void StrengthValue()
    {
       x = Random.Range(10, 500);
    }
}

```
> 1 votes

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


# Question
Title: How to calculate the shadow bounding box with a directional light
I'm trying to implement a directional light in my C++ / OpenGL engine, but I struggle to calculate the shadow bounding box (i.e the shadow frustum). The bounding box has to encompass the main frustum and be aligned with the light rays, resulting in an orhographic frustum.

The problem is that as the light have no position, I don't know how to create the light view matrix, which is necessary to calculate the aligned bounding box.

Here's my current attempt:

* calculation of the main frustum 8 coordinates in world space
* conversion of these 8 coordinates in light view space, using the lightView matrix
* calculation of a bounding box around the main frustum, aligned with light rays since I'm in light view space
* calculation of the bounding box center, in light view space
* conversion of the bounding box center in world space (using the inverse of the lightView matrix)
* calculation of the bounding box projection matrix with glm::ortho
* calculation of the bounding box view matrix (the lightView matrix) with glm::lookAt. For this I need the bounding box center, which I calculated... using the lightView matrix.

This doesn't work, because I need the lightView matrix to calculate the bounding box center. But I need the bounding box center to calculate the lightView matrix.

I can't manage to get it right. What am I missing?

Here is the code:

```
void Shadows::updateFrustumBoundingBox()
{

  // Here we convert main camera frustum coordinates in light view space
  std::array<glm::vec3,8> points = {
    // Near plane points
    lightView * glm::vec4(cameraPtr->ntl, 1.0),
    lightView * glm::vec4(cameraPtr->ntr, 1.0),
    lightView * glm::vec4(cameraPtr->nbl, 1.0),
    lightView * glm::vec4(cameraPtr->nbr, 1.0),
    // Far plane points
    lightView * glm::vec4(cameraPtr->ftl, 1.0),
    lightView * glm::vec4(cameraPtr->ftr, 1.0),
    lightView * glm::vec4(cameraPtr->fbl, 1.0),
    lightView * glm::vec4(cameraPtr->fbr, 1.0)};

  // Here we find the shadow bounding box dimensions
  bool first = true;
  for (int i=0; i<7; ++i)
  {
    glm::vec3* point = &points[i];

    if (first)
    {
            minX = point->x;
            maxX = point->x;
            minY = point->y;
            maxY = point->y;
            minZ = point->z;
            maxZ = point->z;
      first = false;
    }

        if (point->x > maxX)
            maxX = point->x;
    else if (point->x < minX)
            minX = point->x;

        if (point->y > maxY)
            maxY = point->y;
    else if (point->y < minY)
            minY = point->y;

        if (point->z > maxZ)
            maxZ = point->z;
    else if (point->z < minZ)
            minZ = point->z;
  }

  frustumWidth = maxX - minX;
  frustumHeight = maxY - minY;
  frustumLength = maxZ - minZ;

  // Here we find the bounding box center, in light view space
  float x = (minX + maxX) / 2.0f;
  float y = (minY + maxY) / 2.0f;
  float z = (minZ + maxZ) / 2.0f;
  glm::vec4 frustumCenter = glm::vec4(x, y, z, 1.0f);

  // Here we convert the bounding box center in world space
  glm::mat4 invertedLight = glm::mat4(1.0f);
  invertedLight = glm::inverse(lightView);
  frustumCenter = invertedLight * frustumCenter;

  // Here we define the light projection matrix (shadow frustum dimensions)
  lightProjection = glm::ortho(
    -frustumWidth/2.0f, // left
    frustumWidth/2.0f, // right
    -frustumHeight/2.0f, // down
    frustumHeight/2.0f, // top
    0.01f, // near
    SHADOW_DISTANCE); // far

  // Here we define the light view matrix (shadow frustum position and orientation)
  lightDirection = glm::normalize(lightDirection);
  target = glm::vec3(frustumCenter) + lightDirection;

  lightView = glm::lookAt(
                  // Shadow box center
                  glm::vec3(frustumCenter),

                  // Light orientation
                  target,

                  // Up vector
                  glm::vec3( 0.0f, 1.0f,  0.0f));

  // Final matrix calculation
  lightSpaceMatrix = lightProjection * lightView;
}

```

# Answer
Well, probably not the best way but this works pretty well.

Before to process the shadow bounding box, calculate a lightView matrix based on the main frustum center, with the light view set to a position relative to this center.

```
  lightView = glm::lookAt(
            // Eye
            cameraPtr->adaptativeFrustumCenter + lightPosition,
            // Target
            cameraPtr->adaptativeFrustumCenter,
            // Up vector
            glm::vec3( 0.0f, 1.0f,  0.0f));

```

When the shadow bounding box is processed, we have access to its center in world space. So we can update the lightView matrix. This updated view matrix will be then used to render the depth map.

```
lightView = glm::lookAt(
            // Eye
            glm::vec3(shadowFrustumCenter) + lightPosition,
            // Target
            glm::vec3(shadowFrustumCenter),
            // Up vector
            glm::vec3( 0.0f, 1.0f,  0.0f));

```
> 2 votes

---
Tags: opengl, 3d, lighting, shadows, shadow-mapping
---


# Question
Title: How can I check if the scale of an object is bigger (or smaller) than.......?
When starting the game, I make the size of the object random. And when I start the game, how can I check if the object's size is smaller than x-1, y-1, and the z doesn't matter. When I try something I get this error: 'non-invocable member 'Vector3' cannot be used like a method.'

Here is the if statement that the error is in:

```
if(transform.localScale < Vector3(1, 1, 1))
{

}

```

I also forgot to mention that the `if` statement is at the end of the start method.

# Answer
> 0 votes
I used `if(transform.localScale.x < 1 && transform.localScale.y < 1)` instead of `transform.localScale < Vector3(1, 1, 1)` Which seemed to work perfectly.

# Answer
> 0 votes
Vectors can not be compared directly, but you can compare their `.magnitude`.

Or alternatively, if you always set the x and y component of those scales to the same, you can just compare one of those. This would be slightly faster, because you don't need to calculate the magnitudes.

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


title: DOTween capacity always increasing

text:
# Question
Title: DOTween capacity always increasing
I'm creating a sequence and adding a couple of tweens to it. If I call it a couple of times the tweens capacity gets increased exponentially till everything gets incredible laggy.

I've recorded this 30 seconds gif to showcase the issue:

https://thumbs.gfycat.com/CarefulAngelicBrahmanbull-mobile.mp4

My code for when the button is pressed consists of 2 simple functions:

```
    public void HideUI()
    {
        Sequence sequence = DOTween.Sequence();

        sequence.Append(PremiumButton.DOAnchorPos(new Vector2(0, 300), 0.5f));
        sequence.Join(SkinsButton.DOAnchorPos(new Vector2(0, 300), 0.5f));
        sequence.Join(RateButton.DOAnchorPos(new Vector2(0, 300), 0.5f));
        sequence.Join(HideShowUIButton.DOAnchorPos(new Vector2(1145, 0), 0.5f));
        sequence.Join(AchievementsButton.DOAnchorPos(new Vector2(0, 300), 0.5f));
        sequence.Join(CollectionsButton.DOAnchorPos(new Vector2(0, 300), 0.5f));
        sequence.Join(SettingsButton.DOAnchorPos(new Vector2(0, 300), 0.5f));
        sequence.Join(Up.DOAnchorPos(new Vector2(0, 400), 0.5f));
        sequence.Join(Down.DOAnchorPos(new Vector2(0, -400), 0.5f));
        sequence.Join(LevelsPanel.DOAnchorPos(new Vector2(2000, 0), 0.75f));

        HideUIImage.GetComponent<Image>().sprite = ShowUISprite;
        HideUIText.GetComponent<TMPro.TextMeshProUGUI>().text = "SHOW UI";

        HideShowUIButton.GetComponent<Button>().onClick.AddListener(() => ShowUI());
    }

    public void ShowUI()
    {
        Sequence sequence = DOTween.Sequence();

        sequence.Append(PremiumButton.DOAnchorPos(new Vector2(0, 0), 0.5f));
        sequence.Join(SkinsButton.DOAnchorPos(new Vector2(0, 0), 0.5f));
        sequence.Join(RateButton.DOAnchorPos(new Vector2(0, 0), 0.5f));
        sequence.Join(HideShowUIButton.DOAnchorPos(new Vector2(0, 0), 0.5f));
        sequence.Join(AchievementsButton.DOAnchorPos(new Vector2(0, 0), 0.5f));
        sequence.Join(CollectionsButton.DOAnchorPos(new Vector2(0, 0), 0.5f));
        sequence.Join(SettingsButton.DOAnchorPos(new Vector2(0, 0), 0.5f));
        sequence.Join(Up.DOAnchorPos(new Vector2(0, 0), 0.5f));
        sequence.Join(Down.DOAnchorPos(new Vector2(0, 0), 0.5f));
        sequence.Join(LevelsPanel.DOAnchorPos(new Vector2(0, 0), 0.75f));

        HideUIImage.GetComponent<Image>().sprite = HideUISprite;
        HideUIText.GetComponent<TMPro.TextMeshProUGUI>().text = "HIDE UI";

        HideShowUIButton.GetComponent<Button>().onClick.AddListener(() => HideUI());
    }

```

I don't understand what exactly is happening. Is there a memory leak? Why is DoTween increasing exponentially like that? The function suggested in the console has the prototype like static DOTween.SetTweensCapacity(int maxTweeners, int maxSequences). There's no way I'm reaching those numbers as the console shows.

# Answer
The issue as pointed out by @DMGregory was not actually with DoTween but with

```
    HideShowUIButton.GetComponent<Button>().onClick.AddListener(() => ShowUI());

```

On every click I kept adding listeners over listeners and not removing the previous ones. At some point pressing a button would call the same function maybe tens of times forcing DoTween to perform hundreds of transitions.

You can solve it by removing a specific listener before adding a new one or by simply removing all. In my case I decided to remove all listeners:

```
HideShowUIButton.GetComponent<Button>().onClick.RemoveAllListeners();
HideShowUIButton.GetComponent<Button>().onClick.AddListener(() => ShowUI());

```
> 1 votes

---
Tags: unity, c#, unity-ui, dotween
---


# Question
Title: Army does not always destroy village, even when it's larger than the village strength
Here is the army code:

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

public class Army : MonoBehaviour
{
    public int ArmySize = 100;

    private Vector2 lastClickedPos;
    private bool moving = false;
    public float speed;

    public SpriteRenderer sprite;

    private GameObject Village;

    private void Start()
    {
        Village = GameObject.FindGameObjectWithTag("Village");
    }

    private void Update()
    {
        if(Input.GetMouseButton(0))
        {
            sprite.enabled = true;
            lastClickedPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            moving = true;
        }

        if(moving && (Vector2)transform.position != lastClickedPos)
        {
            float step = speed * Time.deltaTime;
            transform.position = Vector2.MoveTowards(transform.position, lastClickedPos, step);
        }
        else
        {
            moving = false;
        }

        if(ArmySize < 0)
        {
            ArmySize = 0;
        }
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if(other.gameObject.CompareTag("Village"))
        {
            Debug.Log("Attack");

            if (ArmySize <= Village.GetComponent<Village>().strength)
            {
                Debug.Log("Lost");
                ArmySize -= 30 % Village.GetComponent<Village>().strength;
            }

            if (ArmySize > Village.GetComponent<Village>().strength)
            {
                Debug.Log("Won");
                ArmySize += 15% Village.GetComponent<Village>().strength;
                Destroy(other.gameObject);
            }
        }
    }
}

```

and here is the village code:

```
using UnityEngine;

public class Village : MonoBehaviour
{
    public int strength;
    private int x;

    private void Start()
    {
        StrengthValue();
        strength = x;

        Debug.Log(gameObject.name + " ---- " + strength);

        transform.localScale = new Vector3(strength / 100, strength / 100, 1);

        if(transform.localScale.x < 1 && transform.localScale.y < 1)
        {
            Debug.Log(gameObject.name +  "Is Destroyed");
            Destroy(gameObject);
        }
    }

    private void StrengthValue()
    {
       x = Random.Range(10, 500);
    }
}

```

the problem is that it sometimes doesn't destroy the village even though the army size is bigger than the village's strength. I also got an error but I can't seem to re-create it.

# Answer
> 2 votes
`if (ArmySize <= Village.GetComponent<Village>().strength)`

This code looks like it's trying to compare "this" army's size against the strength of the village it just collided with. But that's not what's happening.

Let's look at where you assign a value to the `Village` variable. It's nowhere inside the collision handler. It's way back in the `Start` method!

```
private void Start()
{
    Village = GameObject.FindGameObjectWithTag("Village");
}

```

So this army, when it comes into existence, selects the first village in the scene, and decides to do all future comparisons of army size vs village strength against *that one* village, no matter which village it's actually trying to attack.

This is obviously ridiculous. Compare against the village you're attacking.

```
private void OnTriggerEnter2D(Collider2D other)
{
    if(!other.TryGetComponent(out Village targetVillage))
        return;

    Debug.Log("Attack");

    if (ArmySize <= targetVillage.strength)
    {
        Debug.Log("Lost");
        ArmySize -= 30 % targetVillage.strength;
    } else {
        Debug.Log("Won");
        ArmySize += 15 % targetVillage.strength;
        Destroy(other.gameObject);
    }
}

```

Notice another strength of this approach is that you don't need to compare tags anymore. You know something is a village when it has a `Village` component.

You probably don't want those `%` modulo operators in there either. They're not computing percentages, but rather remainders when 30 or 15 is divided by the village's strength. It looks more like you want something along the lines of `Mathf.RoundToInt(0.30f * targetVillage.strength)` to get 30% of the village's strength rounded to an integer.

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


# Question
Title: how to download owned assets from unreal engine marketplace on linux?
From any browser, after you own an asset, clicking on download does nothing.

To me, as many suggest, installing windows is not ok, but that is just my opinion.

Is there any alternative that could let me download stuff I own from unreal engine marketplace?

# Answer
I first tried “ue4-mp-downloader” (as it was the first result on google) but it did not work. Things may have changed and it stopped working.

Then I found this unofficial UE4 Launcher on the Unreal Engine forums, and downloaded a few things w/o any problems!

I used a Google-linked account as a sign-in method (just in case you try something else, this method is working!).

The real problem is that I have already posted this answer on the Unreal Engine forums, but my posts are awaiting approval and I read that may take more than a month! So, as many Linux users are struggling to download even things they bought, I post here in the hope they reach here somehow when they google again about it!

I also wonder if there are any other alternatives? Also, helping to keep any of these projects updated (working) would help a lot!
> 1 votes

---
Tags: unreal-4, assets, unreal, asset-management
---


# Question
Title: Teleport character a fixed distance in the direction it is looking
Game : bird's eye view (2D)

1. When I touch the button, my character will teleport a fixed distance in the direction it is facing.
2. If there is an object at that distance (like a wall) it will not teleport (it can pass through the wall)

For example, the code below teleports the character, but only takes it to the position determined on the stage with the mouse. I also tried the "raycast" system, but the problem is that even if there is an object nearby, the character should be able to teleport from there, it does not provide me with raycast. (because of Raycasthit)

Actually what I think is very simple. Assigning the transform of the point in the direction my character is facing, for example 10 units away, to my character's transform. This way my character will be teleported. However, of course, if there is a collider 10 units away, it cannot teleport, but on the other hand, my character can teleport even if there is a collider object 6 units away. Although it seems simple, I could not do it.

```
void Update ()
{
   if( Input.GetMouseButtonDown( 0 ) )
   {
    transform.position = Camera.main.ScreenToWorldPoint( new Vector3( Input.mousePosition.x, Input.mousePosition.y, 10 ) );
   }
}

```

# Answer
It looks like you meant to write something like this:

```
void Update ()
{
   if (Input.GetMouseButtonDown(0))
   {
        var mousePosition = Input.mousePosition;
        mousePosition.z = 10f;

        var facing = Camera.main.ScreenToWorldPoint(mousePosition)- transform.position;
        facing.z = 0f;

        // Get a position a fixed distance in the mouse direction.
        var destination = transform.position + facing.normalized * teleportDistance;

        // Check if there are any obstacles blocking the character from spawning there.
        if (Physics2D.OverlapCircle(destination, characterRadius, obstacleLayers) != null)
        {
            // If not, perform the teleport.
            transform.position = destination;
        }
   }
}

```
> 1 votes

---
Tags: unity, c#, movement, raycasting
---


# Question
Title: Why do my bullets always go the wrong way when my player turns around?
So I tried to make a shooting mechanism for my game. My player can shoot in the direction pointed by the mouse. My player can also turn around, facing the other way as he walks. The firing mechanism is fine when my player is facing right, but when my player is facing left (I used `transform.localscale` and set my x scale to a negative value so my player sprite is flipped) the gun is also reversed, i solved the problem on the gun, but when i shoot the bullet, the first bullet fired after i turn around will go in the wrong direction. I set my weapon as child of an empty game object named gunHolder like this:

When it play, it looks like this, when i trun around and shots my first bullet, the bullet go in mirror direction:

My shooting code look like this:

```
void Update()
    {

        Vector3 difference=Camera.main.ScreenToWorldPoint(Input.mousePosition)-transform.position;
        float rotZ=Mathf.Atan2(difference.y,difference.x)*Mathf.Rad2Deg;

        if(player.transform.localScale.x==1)turnOffset=0;
        else turnOffset=180;

        transform.rotation=Quaternion.Euler(0f,0f,rotZ+offset+turnOffset);
        if(timeBtwShots<=0){
            if(Input.GetMouseButtonDown(0)){

            Instantiate(projectile,shotPoint.position,transform.rotation);

            float transX= (float)(player.transform.localScale.x*0.3);
            projectile.transform.localScale= new Vector3(transX,projectile.transform.localScale.y,projectile.transform.localScale.z);

            BulletBehaviour bulletBehaviour=projectile.GetComponent<BulletBehaviour>();
            if(player.transform.localScale.x==1){
                bulletBehaviour.flip=false;
            }
            else{
                bulletBehaviour.flip=true;
                Debug.Log("flip");
            }
            timeBtwShots=startTimeBtwShots;
        }
        }else{
            timeBtwShots-=Time.deltaTime;
        }

    }

```

So I flip my weapon based on where my player is facing. I handle my player animation when facing another direction by changing transform.localscale.x:

```
scale=transform.localScale;
if (Input.GetKey(KeyCode.A))
     {
          isMoving=true;
          Vector2 movement = transform.right.normalized * -moveSpeed;
          rb.AddForce(movement);
          scale.x=-1;
     }
     else if (Input.GetKey(KeyCode.D))
     {
          isMoving=true;
          Vector2 movement = transform.right.normalized * moveSpeed;
          rb.AddForce(movement);
          scale.x=1;
     }

```

And my bullet script look like this:

```
void Update()
    {
        if(!flip){
            transform.Translate(Vector2.right*speed*Time.deltaTime);

            }
        else {
            transform.Translate(Vector2.left*speed*Time.deltaTime);
            }
    }

```

Based on where my player facing, i change my bullet direction(I did this because before, my bullet went in the wrong direction if my player was facing left). Now my bullets are facing the right direction, it's just that the first bullet that is fired after my player turns around always goes in the wrong direction (the opposite direction to the direction it should be, even the sprites are reversed). Anyone know why this happening and how to solve this?

# Answer
So the problem is in instantiate. I instantiate the bullet before i set the condition. I try to move the instantiate function after the else statement and it works
> 1 votes

---
Tags: unity, c#, transformation, scale
---


# Question
Title: How do I add force in all directions on point of touch or mouse click?
I wanna add a force on the point of player touch. Basically when player touches a point it release force in all directions and all sprite in its range get effected and start moving.

What is the right way to go about it?

# Answer
I'm thinking of using Empty GameObject that spawns on mouse click but instantly destroy. That game object has a ForceOnClick script to detect every object in its range, and call function from a script named Force in that object.

```
public List<Collider2D> AffectedObjects = new List<Collider2D>();
public LayerMask EffectLayer;
public float magnitude = 10;

void SetAttractedObjects()
    {
        AffectedObjects = Physics2D.OverlapCircleAll(transform.position, effectionRadius, EffectLayer).ToList();// can be optimized
    }

    void AttractObjects()
    {
        for (int i = 0; i < AffectedObjects.Count; i++)
        {
            AffectedObjects[i].GetComponent<Force>().Push(this);
        }

    }

```

You need to put all the object that will affected by the gravity to a layer and set it to this script. These two functions will be called from update. You can also use gizmo to see how big the radius from editor, with:

```
void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.yellow;
        Gizmos.DrawWireSphere(transform.position, effectionRadius);
    }

```

On the affected object, you can make a Force script that push object away.

```
Transform m_transform;
Collider2D m_collider;
Rigidbody2D m_rigdibody;
ForceOnClick currentFoc;

public void Push(ForceOnClick foc)
    {
        Vector2 pushDir = (Vector2)foc.planetTransform.position - m_rigdibody.position;
        m_rigdibody.AddForce(pushDir.normalized * -foc.magnitude * force * Time.fixedDeltaTime);

        if (currentFoc == null)
        {
            currentFoc = foc;
        }
    }

```

After applying the force, you can destroy the game object
> 0 votes

---
Tags: unity
---


title: 3D AxisAngle spins at 180 degrees

text:
# Question
Title: 3D AxisAngle spins at 180 degrees
I am using the Axis Angle technique on objects so that they are oriented away from a planet surface like in Super Mario Galaxy. I am using two unit vectors \[0,1,0\] and a normal vector from the planet. Is there any way to stop the 3D objects from spinning when they go near 180 degrees and still orient correctly? Could I use gimbal lock to fix it? This is what I have so far for my game in JavaScript:

```
// Angles are in radians
angle = Math.acos(dotProductVec3([0,1,0], forceNormal));

// Using two unit vectors to find the axis and angle
if (angle > Math.PI / 2)
{
    forceRotation.angle = Math.acos(dotProductVec3([0,-1,0], forceNormal));
    forceRotation.axis = vec3Normalize(vec3CrossProduct([0,-1,0], forceNormal));
}
else
{
    forceRotation.angle = Math.acos(dotProductVec3([0,1,0], forceNormal));
    forceRotation.axis = vec3Normalize(vec3CrossProduct([0,1,0], forceNormal));
}

```

Above I am using a negative number on the y axis to stop the spin when 180 degrees has been reached. The problem is the objects point towards the planet rather than away. Also I have tried Quaternions but they seem to spin too.

Update:

I watched a video on the hairy ball theory and restarted my work on this project. I managed to get the spaceship to align with the velocity like you said but the ship's linear y axis does not always point away from the middle of the planet. Is there a way to get the ship to have a properly aligned orbit like Super Mario Galaxy? Note I am using \[0,0,1\] since I can't figure out how to orient the ship any other way. The new code is below:

```
    let angle = Math.acos(dotProductVec3(vec3Normalize([0,0,1]), vec3Normalize(velocity)));
    let axis = vec3Normalize(vec3CrossProduct([0,0,1], velocity));
    newAngle = vec3EulerFromAxisAngle(axis, angle);

```

Any help would be much appreciated.

# Answer
Below is some of the code I could get working. First I test for a collision with an object on the planet and use the \[0,1,0\] code. If there is no collision then I find the previous normal and use it to rotate. The forceAngle boolean orients the spaceship after it has had a collision and is only touching the planet. I am not sure why but I can't get the forceAngle to stop running.

```
if (collision > 1 || forceAngle === true)
{
    forceRotation.angle = Math.acos(dotProductVec3([0,1,0], forceNormal));
    forceRotation.axis = vec3Normalize(vec3CrossProduct([0,1,0], forceNormal));
    if (collision === 1)
    {
        forceAngle = false;
    }
}
else
{
    forceAngle = true;

    forceRotation.angle = Math.acos(dotProductVec3(oldForceNormal, forceNormal));
    forceRotation.axis = vec3Normalize(vec3CrossProduct(oldForceNormal, forceNormal));
}

```
> 0 votes

---
Tags: 3d, javascript, rotation, game-mechanics, vector
---


# Question
Title: How to access a Material Editor node from a script?
Is it possible to access a node from the Material Editor from a C++ script?

I'd like to be able to change the value of 'Mulitply' from a script.

# Answer
> 0 votes
In your Material, create a Scalar Parameter (hold 1 on the material grid and left click), name it and plug it in to your multiply node.

In your C++ header, create an instance variable and set it as a UPROPERTY so it doesn't get garbage collected.

```
UPROPERTY()
UMaterialInstanceDynamic* DynMat;

```

In your C++ constructor, set the dynamic material instance from the existing material on your mesh then set it to your mesh.

```
DynMat = UMaterialInstanceDynamic::Create(YOURMESHNAME->GetMaterial(0), this);
YOURMESHNAME->SetMaterial(0, DynMat)

```

The 0 in the get and set refer to which Element of the mesh the material is set to. If 0 is the back of the card and 1 is the front, change the code accordingly.

From here, you can use the DynMat reference to change your parameter values as follows.

```
MI->SetScalarParameterValue(TEXT("YourMultiplierName"), NewFloatValue);

```

YourMultiplierName must match exactly what you put in for the name of the parameter in the material grid, otherwise this won't work.

---
Tags: c++, unreal-4, unreal, materials, blueprints
---


title: Unity fade post-processing effect

text:
# Question
Title: Unity fade post-processing effect
I'm trying to build a game that uses the Pix2Pix post-processing effect for Unity, which is an image-to-image translation with deep neural networks. It works well but I want to fade this effect with the non-post-processing render. The post-processing effect allows only an off-on feature.

I'm trying to get an in-between that I could access via script in order to change the render

Here with the post processing :

Here without :

Is there a way to get an in-between?

EDIT:

I tried to follow Gabriele's idea of using color.lerp method to lerp the input and output (named as sourceRT and resultRT), It gives me a gray output, here is what I tried (in Postprocessing.cs) :

```
    // RenderTexture Source to Color[]
    Texture2D texSources = new Texture2D(256, 256, TextureFormat.RGB24, false);

    texSources.ReadPixels(new Rect(0, 0, 256, 256), 0, 0);

    Color[] sourcePixels = texSources.GetPixels(0, 0, 256, 256);

    // RenderTexture Result to Color[]

    Texture2D texResult = new Texture2D(256, 256, TextureFormat.RGB24, false);

    texResult.ReadPixels(new Rect(0, 0, 256, 256), 0, 0);

    Color[] resultPixels = texSources.GetPixels(0, 0, 256, 256);

    // Blend Pixel comporte un lerping de chaque pixel selon un float
    Color[] blendPixel = new Color[resultPixels.Length];

    Texture2D blendTexture = new Texture2D(256, 256, TextureFormat.RGB24, false);

    // Lerping via a loop in the array
    for (int i = 0; i < resultPixels.Length; i++)
    {
        Color c = Color.Lerp(sourcePixels[i], resultPixels[i], ratio);
        blendPixel[i] = c;
    }
    // tranformation of blendPixel to Texture2d
    blendTexture.SetPixels(blendPixel);

    // END LERP

    // blendpixel
    cmd.Blit(blendTexture, context.destination);

```

# Answer
> 2 votes
Even though i am not familiar with this library the first solution that comes to mind is to do a lerp from the input to the output by creating a new Texture2D and interpolate each pixel between the first image and the second one. If Pix2Pix does not provide any way to extract the output as an image you can renderer the output of the camera to a texture.

---
Tags: unity, post-processing, effect
---


title: Rectangle collision not working!

text:
# Question
Title: Rectangle collision not working!
I'm making a simple game in C# and i'm having some problems with rectangle collisions. What i'm doing is checking if two rectangles intersects, checking the side of collision and then moving the rectangles away from each other.

**What is working:**

* The rectangle intersection check is working.
* The left and right rectangle side collisions is working.

**What is not working:**

* When debugging, the collision check only prints "Touching Left/Right".
* When i move a rectangle to the top or bottom side of another, the first rectangle jumps to the other side.
* The second problem works correctly if the first rectangle is alligned perfectly to the top or bottom side.

Here is a snippet of the code that i currently have, i hope someone can help me solve these problems.

```
public RectangleF Bounds { get { return new RectangleF(position.x, position.y, scale.width, scale.height); } }

public void CheckCollisions(Transform first, Transform second)
{
    if(first.Bounds.IntersectsWith(second.Bounds) == false) return;

    bool touching_left =
    first.Bounds.Right > second.Bounds.Left &&
    first.Bounds.Left < second.Bounds.Left &&
    first.Bounds.Bottom > second.Bounds.Top &&
    first.Bounds.Top < second.Bounds.Bottom;

    bool touching_right =
    first.Bounds.Left < second.Bounds.Right &&
    first.Bounds.Right > second.Bounds.Right &&
    first.Bounds.Bottom > second.Bounds.Top &&
    first.Bounds.Top < second.Bounds.Bottom;

    bool touching_top =
    first.Bounds.Bottom > second.Bounds.Top &&
    first.Bounds.Top < second.Bounds.Top &&
    first.Bounds.Right > second.Bounds.Left &&
    first.Bounds.Left < second.Bounds.Right;

    bool touching_bottom =
    first.Bounds.Top < second.Bounds.Bottom &&
    first.Bounds.Bottom > second.Bounds.Bottom &&
    first.Bounds.Right > second.Bounds.Left &&
    first.Bounds.Left < second.Bounds.Right;

    if (touching_left)
    {
        float x = second.Bounds.Left - first.Bounds.Width;
        float y = first.Bounds.Y;

        first.SetPosition(new PointF(x, y));
        Debug.WriteLine("Touching LEFT");
    }

    else if (touching_right)
    {
        float x = second.Bounds.Right;
        float y = first.Bounds.Y;

        first.SetPosition(new PointF(x, y));
        Debug.WriteLine("Touching RIGHT");
    }

    else if (touching_top)
    {
        float x = first.Bounds.X;
        float y = second.Bounds.Top - first.Bounds.Height;

        first.SetPosition(new PointF(x, y));
        Debug.WriteLine("Touching TOP");
    }

    else if (touching_bottom)
    {
        float x = first.Bounds.X;
        float y = second.Bounds.Bottom;

        first.SetPosition(new PointF(x, y));
        Debug.WriteLine("Touching BOTTOM");
    }
}

```

Thanks in advance!

# Answer
We can make this a bit simpler using Minkowski addition. We can shrink one rectangle down to its center point, and enlarge the other rectangle from its center by the first's width and height, and get an equivalent situation: the two original rectangles overlap if and only if the shrunken point overlaps the new enlarged rectangle.

Then we can just pick a new place for that center point, and transform that back into a non-overlapping position for the original rectangle. This lets us resolve the collision in one pass, touching only x or y, and only once - rather than stacking a vertical collision resolution after a horizontal resolution using outdated info.

We call this the "minimum translation vector" - using the smallest adjustment possible to remove the overlap, whether that's horizontal or vertical.

```
if(first.Bounds.IntersectsWith(second.Bounds) == false) return;

// Compute the center of each rectangle:
var firstCenter = new PointF( first.Left  + first.Width  /2f,
                              first.Top   + first.Height /2f );

var secondCenter = new PointF(second.Left + second.Width /2f,
                              second.Top  + second.Height/2f);

// Compute the offset from the second's center to the first.
var offset = firstCenter - secondCenter;

// Compute how deeply we're overlapping, horizontally and vertically.
var penetration = new PointF((first.Width  + second.Width )/2f,
                             (first.Height - second.Height)/2f);
                - new PointF(Math.Abs(offset.x), Math.Abs(offset.y));

if (   penetration.y <= 0
   || (penetration.x  > 0 && penetration.x < penetration.y)) {
    // If we're only overlapping on the x,
    // or we're overlapping on the x less than on the y,
    // then correct our x position for the minimum safe correction.
    offset.x = Math.Sign(offset.x) * (first.Width  + second.Width )/2f;
} else {
    // Otherwise, our minimum safe correction is vertical.
    offset.y = Math.Sign(offset.y) * (first.Height + second.Height)/2f;
}

// Now form the top-left corner of the first rectangle at
// this new position.
var corner = new PointF(secondCenter.x + offset.x - first.Width /2f,
                        secondCenter.y + offset.y - first.Height/2f);

first.SetPosition(corner);

```
> 3 votes

# Answer
## Preface

The answer from @DMGregory has some wonderful math that will most likely solve most *if not all* of your problems. While I would recommend working towards an implementation like theirs, I thought it would also be helpful to answer some of your other questions about why your code behaves the way it does.

## Q&A

**Q:** When debugging, the collision check only prints "Touching Left/Right".

**A:** Your debug messages are wrapped inside of: `if ... else if ...` blocks. After the first `true` evaluation the remaining `else` statements are skipped over. The `else` is preventing more than one message from being written. Since you have the LEFT and RIGHT blocks before the TOP and BOTTOM blocks it will stop as soon as either LEFT or RIGHT evaluate to `true` and wont continue to the TOP or BOTTOM sections. Try removing the `else` so that it reads `if` instead of `else if`. When you have 4 independant `if` statments you should see both a LEFT/RIGHT message and a TOP/BOTTOM message.

**Q:** When i move a rectangle to the top or bottom side of another, the first rectangle jumps to the other side.

**A:** Your code now uses boolean logic. It is either `true` or `false`. This means that it is all or nothing, and there is no in between. If the first rectangle touches the second at all *even a little bit* then the bool is `true` and you move it all the way to the other side. The math from the other answer will find that "in between" amount and only move it as much as is necessary.

**Q:** The second problem works correctly if the first rectangle is aligned perfectly to the top or bottom side.

**A:** Your code checks to see if the sides are `>` or if they are `<` but it doesn't check to see if they are perfectly `=`. If your two rectangles are the same size then when the two sides are `=` is the only case where the LEFT/RIGHT `if ... else if ...` blocks evaluate to `false` and allow the code to continue into the TOP/BOTTOM sections.
> 3 votes

---
Tags: c#, collision-detection, collision-resolution, windows-forms
---


# Question
Title: Is there a game-design related reason why games with checkpoints don't implement "save on exit" as well?
*This seems like a common question but I couldn't find it anywhere. Please excuse me, if this is a duplicate.*

EDIT: After receiving the first answer I realized this is too broad of a question. It does make a lot of sense to always restart from the start of the level in genres I wasn't even thinking about when writing the question. My question specifically relates to open-world/metroidvania games. Examples of the games I played that relate to this problem would be Hollow Knight, Legend of Zelda games for 3DS (including remakes), Castlevania series, Metroid series, Ori games (in "The Blind Forest" you still get warped, but to a player-set checkpoint).

As an example of a game that does what I see as a better option, Shining Soul II allows the player to save at any point in a dungeon. After saving, the game automatically turns off and upon reentering, spawns the player character at the beginning of the level where they saved and that mid-dungeon save gets destroyed.

# The problem

In a game with checkpoints, after exiting and loading back a game one of two things can happen: either the player is warped back to the last checkpoint or the player is placed back more or less where they left with the same amount of health/mana/ammo/whatever as when they quit the game. Yet for some reason every game I played that implements checkpoints always implements the first and not the second option.

From the development standpoint, I can understand that the first option is easier to implement. But from game design standpoint this doesn't make sense to me for several reasons.

# Why I believe auto-save on exit is better

First, it's a hostile design. If I need to stop playing right this moment and cannot continue, all my progress is lost for a reason not related to the game itself. In theory, checkpoints are meant to create a pace for the game, the difficulty spikes between one checkpoint and another are carefully designed to create the best experience for the player. For that reason, in a well designed game, players would rarely stop playing mid-checkpoint even if their progress was saved, because they would lack the sense of completeness that comes from reaching the safe spot. Implementing auto-save will not ruin the pace but add player agency for those situations when they absolutely cannot continue or remove the need to continue under stress, because they are needed somewhere else ASAP. Personally, I find it less frustrating and unfulfilled to just turn off the game without completing an objective than rushing to the next checkpoint and dying in the process, getting even further behind.

Second, this grants a hidden ability in the game, that allows the player to warp to the last checkpoint at any moment in the game. While not obvious to most players and somewhat cheesy, once the player realize they can escape any situation, they will eventually start to abuse it. This can happen if the threat of dying is so much worse than inconvenience of restarting the game, for example in Hollow Knight, at first I considered bench warp to be an exploit but when I played Steel Soul and not exploiting this mechanic meant loosing 4 hours of progress, I too started abusing it.

There is a good reason, why the ability to warp to the last checkpoint without dying is important. It allows the player to quickly disengage from challenges they are not yet prepared for. It prevents soft locking if there are bugs in the game (either mechanical or in level design) and the player can get stuck because of them. But if this mechanic is so ubiquitous and important to this kind of games, it would be a much better design to make this an in-game ability of the character, not force the player to access that ability from the game menu. If the recall ability doesn't fit the game in-universe, I would still consider explicit menu option to go to the last checkpoint better than quitting the game and loading again.

Imagine if in League of Legend in order to teleport to the fountain the player would need to close the game and load it again instead of using the Recall ability that every player has. That would be absolutely ridiculous. Yet in single-player games for some reason this is a norm and I don't understand why.

Some games do have the "Restart from the last checkpoint" option in game menu but for those games the first reason still applies.

# The question

Considering the reasons above, why is it that warping on restart is so much more common than auto-saving on exit? Is there something I'm missing here that makes the more common approach better than what I believe makes more sense? Considering I have the technical abilities to easily implement the save system I prefer, is there any reason why should I follow the industry standards?

# Answer
> 7 votes
I think Tooster's answer covers most of the important points, but I do want to elaborate on a couple of details.

## Maintaining Flow

This builds on Tooster's references to "context" that can be lost between play sessions. When I quit a game, I might intend to come back to it in a minute or an hour. But in practice, sometimes it will be days or weeks in between. During that time, my memory of where I was and what I was doing, and even my skills in the game will atrophy.

In Metroidvania and Zelda games like Reverent Lapwing describes, sections of the map will often be designed around a theme. Introducing a new element (like a new enemy, obstacle, player ability, or strategy), then developing it over the course of several challenges/rooms/waves, twisting it by juxtaposing it against previously-introduced elements, and finally culminating at a boss fight or major test that lets the player show off their mastery of the new skill.

When played through in one session, this creates an enjoyable progression - your understanding and skill in dealing with the new ingredient grows, parallel to the escalation of the challenge. Designed well, this facilitates the player in finding a "flow state" that can be very engaging.

Dropping cold into the middle of this flow, however, can be quite painful. I've forgotten what trick I needed to navigate this area, or I've lost the particular timing that I'd practiced in the previous room due to the time spent away from the game. Instead of a feeling of flow, I find I'm bashing my head against the wall just trying to get back up to speed.

In a scenario like this, starting the player back at the checkpoint can be a mercy - giving them a chance to practice the early challenges again and pick back up the thread of what they were doing. This is even more true if the reason they ended the last session was because they got stuck - a chance to practice the early lesson again is often all they need to unstick themselves, but they won't get that if we spawn them back at the part that frustrated them into quitting.

Meanwhile, the impact on a player who did learn and retain the skill is (if the checkpoint frequency is well-designed) relatively mild. They can breeze through the early parts of the challenge with their already-developed skills, maybe finding it at worst dull for a couple minutes until they get back to the novel part. If you have great 3Cs, then even fighting your way back to where you were should still be pleasurable - if it's not, then you have deeper problems that skipping the replay only partly masks.

## Preventing Soft-Lock

Reverent Lapwing touches on this in the question: if you spawn the player at a checkpoint, you can guarantee the game is playable and winnable from every possible spawn point. Generally speaking, we cannot make this guarantee for every possible game state that can arise at runtime and get snapshotted by a background auto-save or save-on-exit feature. In a game of even modest size, there are enough possible interactions between mechanics that it basically reduces to the Halting Problem.

I recently worked on a AAA open world game, and the variety of navigational tools and explosive mechanics open to players meant there were plenty of opportunities to get hurled out of the ordinarily-navigable area and get stuck somewhere. If we spawned you back at the exact position where you quit, then these would become walkthrough breaks. Even though they were exceedingly rare, even a one in a million chance means it happens to tens of players if you sell tens of millions of copies. So instead, we always snapped the player to the closest "known good" spawn point, of which we had a reasonable number that we could exhaustively verify.

The chaos that can be introduced by an overly-faithful save system can be even worse during development of the game. Let's say I'm doing a test of "chapter 2", and I'm halfway through at the end of the day, so I save and log off, recording my exact position. The next time I get a chance to continue my test, I'm working with a slightly more updated build (which is good - fewer bugs, right?), not realizing that yesterday the level designer checked in a change that raised the floor 1 centimeter. Now my save file - which has recorded the exact position where I should be spawned - places me under the floor and I'm stuck or fall to my death.

These kinds of changes are happening *continuously* during development, and having to create new save files for each test scenario or redo the test from scratch anytime something changes can seriously slow down development.

(Yes, we could fix this particular example by having the load system scan for a valid place to stand *near* the saved position, but that fixes only the one case, not the general problem, and adds complexity - something we'll get to shortly)

This can happen in non-buggy ways too, like being on the wrong side of a damaging obstacle with 1 health left, or in a boss fight with your ammo exhausted. We can say "oh, that's the player's own fault" and yeah maybe it is, but it's not necessary for the game to rub your nose in your mistake and force you to struggle in vain or kill yourself when it could have spawned you in a state it knows is winnable instead. Especially in cases like Tooster's Portal example, where the fact that they're in a dead end might not be obvious to the player.

As Reverent Lapwing points out, a workaround for soft-lock issues is to offer a "return to last checkpoint" option as a menu item or in-game ability of some kind, and I do think those are valuable inclusions. However, from observing playtests, I can attest that even when these options are present, players frequently miss them or forget about them, because they're not part of their routine play. So ensuring the player always starts a fresh game session in a winnable state can still improve the player experience and reduce negative reviews or customer service calls from frustrated players.

## Complexity

A checkpoint save system can be dirt simple. Upon entering a trigger zone, you save the character's current progression state (like XP/items/etc), and the ID of the checkpoint they're at, and that's all the information that you need to reconstruct this game state reliably.

The checkpoint location will generally be designed such that it has no other complicated state in its immediate vicinity - no enemy spawners, etc - so everything else can just be spawned "from scratch" as the player approaches, and there will be no visible or game-altering discrepancies. (This also gives the resuming player a space to re-orient themselves with what's happening in the game before they're immediately tested on their recall)

A save that records you "in the moment" needs to contend with a lot more. Just about every feature you add to the game, the save system needs to be made aware of it in order to put that feature back into the right state on load.

Even simple things like moving platforms can be a can of worms. If you can save on a moving platform, then the position/phase of the moving platform (and other platforms you might need to jump to from there / hazards you might need to avoid) also need to be saved and synchronized with your load, so you don't spawn in mid air or in an unwinnable configuration. If you want to avoid this complexity by *disallowing* saves on moving platforms, then you need to save a bookmark anytime the player jumps or is knocked around just in case they might land on a moving platform and quit before returning to solid ground. Both ways have a cost. Multiply this by every other thing your player can do or have done to them. Alternate forms/movement modes, status effects, multi-stage enemy waves or boss battles, and especially any kind of exotic gameplay for a narrative beat or level design set piece.

These types of complexity can creep in unexpectedly. Say a level designer makes a room where you need to hit a series of switches in a particular order to open and shut doors, giving you access to other switches and other doors. You've probably played dozens of segments like this. The level designer doesn't know this needs special save handling - they don't know the guts of the save system, and other times they've used one switch-door pair at a time there were no issues. And the programmers working on the save system usually aren't playing every part of the map or attending every review, so they don't spot it either.

But a player who quits in the middle of the puzzle might come back to an unwinnable state - spawned somewhere in the middle, but with a door still in the initial state, so they can't reach the next switch. Worse, this kind of bug can go undetected, because any tester playing the puzzle through in one pass finds it works perfectly - it only shows up if the player quits at just the wrong moment.

This may seem like a contrived example, but at least one nasty issue like this has cropped up in every AAA game with an autosave system I've worked on, often being discovered months later, and always at the most inconvenient time to overhaul either the offending content or the underlying save system. We've had it arise from things as unassuming as loot containers or sidequest completion. The bigger the project, the more susceptible it is, because you have more cooks in the kitchen and it becomes infeasible for the save system programmer(s) to stay abreast of every change being made that might impact game saves.

Conceptually "snapshot the game on exit" sounds simple, but in practice it carries a heavier development cost.

## Priorities

You may object to the preceding sections, "but that's all solvable!" and yes, it is, given unlimited time to fix the problems or wisdom to avoid them all in the first place (and all the time needed to implement that wise robust solution).

Unfortunately, we work with finite time and finite wisdom. In practice, the more complexity there is in the save system, the more time and brain cycles your team will be spending on that complexity instead of other parts of your game.

Sadly, games don't get rave reviews about the quality of their save system. You could have the greatest feat of engineering under the hood, and players will only ever notice it when something goes wrong.

So sometimes, it makes more sense to make a simple, predictable save system that does one thing reliably (say, a simple contract with the player "when you load, you'll spawn at the last checkpoint you touched, with full health and ammo"), and spend the dev time and energy freed in this way on parts of the experience that get players more excited - like the 3Cs and combat mechanics, adding new bosses or new items and abilities, etc. (all of which become cheaper to create when you don't have to contend with every save contingency).

This is especially true if you're making a game that you expect will almost always be played in sessions that are one or more "checkpoint span" long. Respawning a player at the exact moment they left off might save an individual player some seconds or minutes of retracing their steps, but this will often have less impact on their appreciation of the game than say an extra hour of new gameplay.

## Wrapping Up

None of this is to say "Auto-save bad. Always use checkpoints." - both systems have their merits, but they also have drawbacks. If you were making a mobile game meant to be played in very short snippets that could be interrupted at any time and had very simple state considerations, then a background auto-save that puts you exactly where you left off might be a no-brainer.

For a designer, the challenge is to be aware of the trade-offs of each decision, and find the one that's right for the game they're making and the team/production practices making it. And then to design the feature and the features it intersects with in such a way as to capitalize on its strengths and minimize the frustration or risks introduced by its weaknesses.

# Answer
> 4 votes
I think this is a bit too shallow of a viewpoint focusing only on the player's perspective. It would be better If you posted more examples of games doing it first and the latter way. It's hard to say about games "in general" because many games are unique and must be considered separately. I'm just gonna post my own thoughts. First from player's POV, then from producers and developers.

# Puzzles

Consider puzzle games. They are often divided into units - be it a level, location or a world. The way they are usually meant to be played is finding a certain solution from many possibilities. Those solutions depend on all the actions you take in a specific order -- one wrong move and you may have to start again.

Assume now that you are in the middle of solving a puzzle, but you got bored/had to go and quit the game. You come back later - an hour, a day or a week. Now you most probably lost the context of what you were doing. What if you took a wrong step at the very beginning and now you are stuck with what you perceive as "unsolvable" puzzle? You would probably think that the game is broken. But when a game forces you to start a level from the beginning you can make your context from scratch and solve it. I experienced it once in Portal (or some other game) -- I thought I was stuck, but in reality I was just quick-loading in a moment that already led to a dead end. So there you have your first reason in favor of checkpoint-warp -- regaining context of actions. By reverting to a checkpoint you can discover a completely new perspective on the problem.

# Platformers

For a second example let's take a platformer: N++ game (you can play an original free flash version in the browser). Game is divided into episodes, each consisting of 5 levels: 0 to 4. You play episode as a whole - you can't start level 2 of episode 5, you always play from level 0 to 4. Why? Let's ask the creators!

So what's the answer? To make players feel time pressure and give them this sense of epicness when they complete a run! It's all about emotions and feelings of a player. I highly recommend you give this game a try to understand what I'm talking about. The feeling of mastery that you get from completing an episode with time rapidly running out -- you have so much adrenaline pumping in you that you just want to keep playing it. It also encourages you not to give up - you will lose your progress if you quit now! This indirectly translates to game's statistics (replayability, session length etc.), which in turn translate to more profits and better player reception.

# MMO

Now let's take a MMORPG PvE/PvP game -- Tera. You can exit the game whenever you want... buuuut you get a penalty if you exit outside of town (at least that was true when I played it several years ago, idk if anything changed). Why does it do that?

My first guess is to discourage "evasion of fast travel tax" -- i.e. you would be able to travel back to last town from dungeon simply by reloging, and that in turn would mean that you don't have to use teleportation scrolls etc. which... translates again to real profits of a game (you don't contribute to economy).

Second guess: to make players stay longer - when you have to go back to a town just to avoid XP-loss penalty you are forced to make a trip and spend more time in the game. You can eventually encounter some new mobs, some strange location or engage more with community -- LOOK, SOMEONE IS SELLING RED-ASSED MONKEY'S RING FOR ONLY 2KK GOLD!!! WHAT AN OPPORTUNITY! GOOD GOD I DIDN'T LEAVE!!! Basically the longer you stay logged in the more they earn and you commit more to the game.

# Rhythm games, Bullet hells, race games

Imagine quitting in the middle of a song or shooting. Those games rely heavily on the context of a game - speed of song, speed of objects and their movement. You load the rhythm game in the middle - what's the BPM? You can't tell without starting or going back a little. You load bullet hell - what's the direction and speed of projectiles? What phase of a boss I'm now in? You can't tell without sampling a little bit of the past.

# Why `FreezeTheWorld > Checkpoint`

Now this in fact is a separate category of games -- Nuclear Throne, Enter the Gungeon, Noita, Minecraft, Factorio, Strategies, Board games, Storytelling games, actionless games. Here quitting the game is the only way to save it and you don't have checkpoints. The lack of checkpoints gives those games a feeling of a "single adventure". You learn to cherish the moment. You learn that actions have consequences.

**@Edit** "Freeze The World" (short FTW) type of save is a very early design decision that basically determines the game's direction. I see them implemented in games that don't create this "sense of urgency", but rather want to be a "one time adventure" -- always different, always changing.

Writing this I came to a conclusion, that checkpoints are used in games that focus on goals -- complete a level, complete a quest, solve a puzzle, finish something in the fastest time. FTW on the other hand are used mainly in open-ended games, where it's not a goal that is important, but the journey: Noita, sandboxes, simulators -- anything where you want your player to be free. If there are no strict goals then there is no way that you can determine checkpoints.

# From Developer's POV

It's easy. You don't have to write a daemon that runs once every x minutes and saves a game. You prevent game freezes and performance issues, because you don't have to serialize the whole game state.

Let's say you are in the middle of an epic battle with lots of bots. Serializing all of that data would take a lot of time. Loading it back would take probably twice as much. Have you ever been stuck in a quick-load loop in the middle of a difficult encounter, just because you can't feel the rhythm of keypresses? Saving only in save-zones, with few entities, enemies etc. is simple, quick and doesn't irritate the player.

Saving only in safe-zones can also help when developer publishes a patch to the game - you could get glitched if you load a patched location, or a location that due to an event is now completely terraformed. You could by accident bypass content that was added to the game. And if developers have to force you either way to the location entrance to prevent bugs - it's only natural that you already have checkpoint system in the game.

Checkpoints are also often placed in strategic places, where difficulty starts to ramp up. I imagine them as valleys on a sawtooth graph -- you start from lower difficulty and progress to higher difficulty. It works like a warm-up and reduces your frustration when you are stuck in a quick-load loop of a difficult situation.

Finally, making reliable "save-anywhere" system is hard - it should be used together with checkpoints -- otherwise you could get locked. What's the good moment to save a game? How often to save a game? Does this system require player to manually manage his savefiles? Save-anywhere to a player is like manual checkpoint placement - you have to remember to create them, how often to make them and you can make poor decisions that you could regret later if you saved in a bad moment (Say your last save was 4h ago and the next one is 5 minutes ago -- I've been there, done that and I don't recommend...).

# Final thoughts

Checkpoints are like chapters in a book. They establish pacing, give reasonable points to stop, divide story into coherent units and encourage you to read "just 5 more pages".

TL;DR:

* In puzzles - you would loose context or could get locked
* In platformers - you would loose the sense of urgency and adrenaline
* In MMOs - you would play less and generate lesser profit
* rhythm, race, bullethells - you loose sense situational awareness and fall out of "the zone"
* `FreezeTheWorld` saves teach that actions have consequences and determine game's direction. They are crucial to open-ended games.
* as developer - it's easier to make checkpoints
* as story designer - it's good for pacing and splicing story later.

Things you can check out:

---
Tags: game-design, savegame, open-world
---


# Question
Title: How to orient a rectangular object, so when a sphere ( ball ) collision happens to redirect it towards a point?
I have a rectangular object and a ball ( sphere ) in 3D and would like to orient the rectangular object in such way that when a collision with the ball and the object happens, to redirect the ball towards a certain point

Here's an example of what I want to achieve

In short: How to rotate the black rectangle in order to redirect the blue ball towards the yellow.

Thanks in advance

# Answer
> 2 votes
This gets more complicated than it might appear on the surface, because as we rotate the box, we also change the position where the sphere comes into contact with it, and that then changes the outgoing velocity we'd need to achieve to hit our target, which then changes the angle we need to reach to rebound with that velocity, which then changes the position...

There is a 1:1 relationship between these, but trying to work out a closed-form equation I could solve led me into an absolute mess of trig. Someone else may have an insight that I'm missing, but I have a sneaking suspicion that iterative approximation might be our best bet here.

First though, we can reduce the dimensionality of the problem. Even though we're in 3D, the sphere's initial position, target position, and initial velocity give us a 2D plane. The normal vector pointing perpendicular from the "bouncing face" of our box has to lie in this plane too.

Now we need to figure out how much to rotate the box around that movement plane's normal to achieve our goal. So from here on in we can think of the problem almost entirely in that 2D plane.

We can think of our box's intersection with this plane as a rectangle, whose width is the thickness of the box from the bouncing face to the opposite face, and whose height is \\$2 \sqrt{ \left(\frac {\text{diagonal}} 2\right)^2 - \text{distance}^2}\\$, where \\$\text{diagonal}\\$ is the length of the diagonal of the bouncing face, and \\$\text{distance}\\$ is the distance of the sphere's motion plane from the origin of the box. Anything inside this rectangle, we can twist our box to hit, anything outside, we can't.

Let's impose a coordinate system on this plane, where the origin is the center of our rectangle, and the x axis points opposite the sphere's initial velocity. You can cross this direction with the plane normal to get your y axis. (There are two choices, but either one works)

We'll start with the rectangle rotated "0 degrees" relative to this coordinate frame, so that the bouncing face points directly against the sphere's incoming velocity. That gives us the best possible chance to catch the sphere. Compute where the sphere hits the line segment of the bouncing face in this orientation in the usual way.

If it misses even in this most favourable angle, then we give up - there's no way we can rotate the box to affect the sphere at all - it will always fly past us unless we translate the box in space, which was not part of the question.

If we do detect an intersection, then we reflect the ball's velocity in the usual way, and we check whether our target lies "above" or "below" this reflected trajectory (counter-clockwise or clockwise in our imposed 2D coordinate system).

Next, we turn the rectangle as far as we can in that direction while still intersecting the sphere's path, and we check the trajectory again.

If we get the same result both times ("above and above" or "below and below"), then again we give up. No matter how we rotate the box we'll always miss - though you can take the smallest miss of the two if you like.

If you get opposite results (your first bounce went "above" and your second bounce went "below" or vice versa), then we have a solution in sight, and we can find it by binary search between these two extremes.

You now have an upper and lower bound for the solution angle. Choose an angle halfway between those bounds, and check again. If the result is "above", replace your previous "above" bound. If the result is "below", replace the previous "below" bound. Rinse and repeat, halving your uncertainty with each iteration, until you close in to your desired precision around the solution.

Once you have a solution in this imposed coordinate space, you can transform that face normal back to your original world coordinates, and aim the box to face that vector.

# Answer
> 1 votes
Since the angle coming in is the same as going out - let us call it β - and you know the angle between your blue and yellow line - let us call it α - you can calculate β by 2\*β + α = 180°. The angle α can be determined if you know the coordinates of the blue circle and the yellow circle and the point of contact with your rectangle: α = arccos ( a.b / |a| . |b| )

You need to read DMGregory's answer for the big picture; this is just a *proof of concept* for the narrow constraints known to me by your question.

```
#include <stdio.h> // printf
#include <cmath> // acos, sqrtf

#define PI 3.14159265

struct vec2
{
    union
    {
        struct { float x, y; };
    };
    vec2() {}
    vec2(float x, float y) : x(x), y(y) {}
    float dot(const vec2 &o) const  { return x*o.x + y*o.y; }
    float squaredlen() const { return dot(*this); }
    float magnitude() const  { return sqrtf(squaredlen()); }
    vec2 &sub(const vec2 &o) { x -= o.x; y -= o.y; return *this; }
};

float rad2deg(float r){ return r*180.0/PI; }

void example(vec2 A, vec2 B, vec2 C) // pertains to https://gamedev.stackexchange.com/q/195488/93991
{
    vec2 v_a = vec2(A).sub(C); // a⃗: 0A - 0C (The vector a⃗ is Origin-to-PointA minus Origin-to-PointC)
    vec2 v_b = vec2(B).sub(C); // b⃗: 0B - 0C (see above)
    printf("a⃗ = (%+3.2f, %+3.2f) has |a⃗| = %3.2f\n", v_a.x, v_a.y, v_a.magnitude());
    printf("b⃗ = (%+3.2f, %+3.2f) has |b⃗| = %3.2f\n", v_b.x, v_b.y, v_b.magnitude());
    printf("a⃗∙b⃗ = a⃗.x*b⃗.x + a⃗.y*b⃗.y = %5.3f\n", v_a.dot(v_b)); // https://en.wikipedia.org/wiki/Dot_product
    float rad_alpha = acos(v_a.dot(v_b) / (v_a.magnitude() * v_b.magnitude())); // alpha in radians
    float deg_beta = (180.0f - rad2deg(rad_alpha)) / 2.0f; // beta in degrees
    printf("At C[%3.2f,%3.2f] the angle β must be %5.3f° (α = %5.3f^=%5.3f°) to reflect object from A[%3.2f, %3.2f] to reach B[%3.2f, %3.2f]\n", C.x, C.y, deg_beta, rad_alpha, rad2deg(rad_alpha), A.x, A.y, B.x, B.y);
}

int main()
{
    example( vec2( 7.5f,  4.5f), vec2( 7.5f, -4.5f), vec2( 3.0f,  0.0f) ); // α == 90°
    example( vec2( 3.2f,  1.0f), vec2( 9.9f, -4.2f), vec2( 1.1f,  0.3f) ); // α ~= 45°
    example( vec2( 1.0f,  1.0f), vec2( 5.0f, -1.0f), vec2( 0.0f,  0.0f) ); // α ~= 56°
    return 0;
}

```

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


title: How to blend a 2D terrain

text:
# Question
Title: How to blend a 2D terrain
Rimworld (shown above) has many different terrain types.

In order to achieve Rimworld styled terrain, I need to achieve two goals

A) How to render differently textured terrains

B) How to blend these terrains (which is what this question is about)

Demonstrated below as an example ( think each square as different terrain type)

I can easily solve A by rendering a mesh that, say, represent, stone terrain and render another mesh representing grass terrain.

However this is not enough because the sections in which two different terrain types meet must be blended

There are many ways I can think of to achieve this however all methods that I can think of are not fitting to render a giant 2d map (look at the first picture)

# Answer
Let's start with some basics: in this case linear interpolation (and its limitations), using pure colours. Once you're on the right track, you can figure things out from there.

First, try to recreate the below image using `Mathf.Lerp()`, to create a controlled 1D interpolation between two adjacent colours:

(expanded vertically so you can see it more clearly)

Next, try to `Lerp()` in 2D, also known as `bilerp()` to create an interpolation on a quadrilateral with 4 colours, one at each of the corners of the quad:

(You can see that bilinear interpolation specifically operates on quads.)

You can see here how the final result comes out between (grid-aligned) world tiles / chunks, with the 2D / bilerped example above, being the middle tile between 4 pure colour tiles:

The easiest way to create the above in Unity is to set up a textured quad facing the camera, then use `Texture2D.setPixel()` to build a texture according to the numbers you get out of your linear interpolation functions given above.

Once implemented on the CPU using Unity's `Lerp()` & custom `Bilerp()`, you can then shift this logic over to `lerp()` textures correctly on the GPU if desired.

**EDIT per comments** How your input map must look to be blended this way (grid-aligned cells):
> 1 votes

# Answer
I thought about a solution

If there was a terrain such as above example, dirt should be below grass.

I could render dirt terrain to overlap grass terrains a little (below)

Then render Grass mesh on top of dirt terrain, then have its edges be rendered with transparency

However I still need to solve needing to apply different transparent value at the edges.

I wonder if I were to select this method, should each vertices contain "transparency value"? so that vertex at the edge contains zero-or-low transparency value
> 0 votes

---
Tags: unity, 2d, terrain, blending, top-down
---


# Question
Title: Simulating a rocket out of control in Box2D
In the void of space, a spaceship releases a rectangle shaped space-torpedo. In half a second, it starts its rocket engine and goes straight until something get in its way, and then boom! The code looks something like this on `update()`:

```
if (Game::gameplay_timer_.milliseconds() - launch_time_ > thrust_time_) {
  body_->ApplyLinearImpulseToCenter(0.006f * body_>GetLinearVelocity(), true);
}

```

But, what if something disturbs the projectile before igniting the rocket, giving it some rotation? It should enter in an uncontrolled spiral (think KSP or tethered gas canisters in Just Cause 2).

How can I achieve this effect (spiraling uncontrollably)? I tried to apply the impulse in places other than the center using `ApplyLinearImpulse()`, but I can only make the projectile rotate on itself keeping the direction perfectly straight.

Edit: for visualization purposes, I mean something like this. But in 2D.

# Answer
> 0 votes
Improved the code thanks to @Sacha's clues.

```
if (Game::gameplay_timer_.milliseconds() - launch_time_ > thrust_time_) {
  delta_.x +=  SDL_sinf(body_->GetAngle()) * speed_ * delta_time;
  delta_.y += -SDL_cosf(body_->GetAngle()) * speed_ * delta_time;
  body_->ApplyLinearImpulseToCenter({delta_.x, delta_.y}, true);
}

```

Now the projectile rotates and it's trajectory is modified. See it here:

But still isn't perfect. It continues to follow a semi-straight direction and I'd like it to be more "chaotic". Any suggestion for improvement will be appreciated.

Edit: If you set the `angularDamping` value of the b2Body to 1, the effect is even more interesting.

# Answer
> 1 votes
Your update method accelerates the rocket along the direction of its velocity vector (as returned by `body_->GetLinearVelocity`) but it should accelerate it along the direction it's facing.
Currently, there's nothing in the update method that can change the rocket's velocity vector orientation.

Box2D allows you to get the current world angle of your body with the function `b2Body::GetAngle`, allowing you to apply the thrust in the desired direction by projecting it along the axis.
(Pasting OP's own answer using this projection for completness):

```
if (Game::gameplay_timer_.milliseconds() - launch_time_ > thrust_time_) {
  delta_.x +=  SDL_sinf(body_->GetAngle()) * speed_ * delta_time;
  delta_.y += -SDL_cosf(body_->GetAngle()) * speed_ * delta_time;
  body_->ApplyLinearImpulseToCenter({delta_.x, delta_.y}, true);
}

```

---
Tags: physics, rotation, box2d, projectile-physics
---


title: Pygame time.get_fps() value

text:
# Question
Title: Pygame time.get_fps() value
I was looking at the `pygame.time.Clock.get_fps()` method and after puting it inside of the `while` loop printing and checking it some times, i see that i starts to give its value after five frames (and not 10 as said in the documentation). I did put this inside the while loop (clock is the object of the `pygame.time.Clock()` class created inside my class):

```
 print "clock.tick:", self.clock.tick(self.fps)
 print "clock.get_fps", self.clock.get_fps()

```

and the result by having the `fps=60` was:

```
clock.tick: 48
clock.get_fps 0.0
clock.tick: 16
clock.get_fps 0.0
clock.tick: 16
clock.get_fps 0.0
clock.tick: 16
clock.get_fps 0.0
clock.tick: 16
clock.get_fps 0.0
clock.tick: 16
clock.get_fps 51.8134689331
clock.tick: 16
clock.get_fps 51.8134689331
clock.tick: 16
clock.get_fps 51.8134689331
clock.tick: 16
clock.get_fps 51.8134689331
clock.tick: 16
clock.get_fps 51.8134689331

```

As one can see the first `clock.get_fps` comes out after the first 5 calls, but it supposedly should calculate the average of the last 10 calls to `tick()`. What am i missing here? Can anyone help explain this?

# Answer
Looking at the implementation of clock.tick() and where in that module the FPS value is set (search for `_clock->fps =`), the documentation seems to be correct that it determines the FPS after 10 calls (which means at the 11th call) to `tick()`. Let's try with a more isolated example:

```
import pygame

clock = pygame.time.Clock()
fps = 60

for i in range(20):
    print '{}: tick={}, fps={}'.format(i+1, clock.tick(fps), clock.get_fps())

```

For me, this gives:

```
1: tick=17, fps=0.0
2: tick=17, fps=0.0
3: tick=18, fps=0.0
4: tick=16, fps=0.0
5: tick=19, fps=0.0
6: tick=17, fps=0.0
7: tick=18, fps=0.0
8: tick=17, fps=0.0
9: tick=17, fps=0.0
10: tick=17, fps=0.0
11: tick=19, fps=57.1428565979
12: tick=17, fps=57.1428565979
13: tick=18, fps=57.1428565979
14: tick=16, fps=57.1428565979
15: tick=19, fps=57.1428565979
16: tick=17, fps=57.1428565979
17: tick=18, fps=57.1428565979
18: tick=16, fps=57.1428565979
19: tick=18, fps=57.1428565979
20: tick=17, fps=57.1428565979

```

Given the fact that 5 is 10 divided by 2, I'd assume that you call `clock.tick()` (or `clock.tick_busy_loop()`, which both call `clock_tick_base()` internally) either directly or indirectly somewhere else in your game loop, so each iteration has two calls to `clock.tick()`, resulting in a FPS value already after 5 loop iterations.

This is using Python 2.7.11 on OS X and PyGame from Mercurial (`pip install --user hg+http://bitbucket.org/pygame/pygame`), which should be revision `d61ea8eab` at the time of writing, just in case you can't reproduce it on your installation.
> 3 votes

# Answer
What I figured out is you can do 1000 / clock.tick(60) and you would get an approcimation to the fps but it doesn't return 0 for the first 5 frames
> 0 votes

# Answer
try this: you type this in your code (anywhere in the code will work):

```
while True:
    print(clock.getfps())

```

and BOOM! it just prints the current fps in the console!
> -1 votes

---
Tags: python, pygame, frame-rate
---


title: Can't add script to gameObject

text:
# Question
Title: Can't add script to gameObject
New to Unity and got this issue. I was watching a Brackey's video about topdown shooting and copying code as we go along. So I am really stumped as to why I am having this issue.

At 4:58 seconds he adds this script to the player and starts moving. When I add my script I get the "Can't add script" error.

I have read other posts about this and Have copied and pasted my script name and even tried changing it too. No luck. I have restarted Unity as well thinking it could be some kind of bug. Not that either. I will post my code down below if somebody can help me out that be so great

# Answer
Wasn't anything to do with the script name or my code. In the project folder in unity I had another script that had a compile error and the Console would not allow me to add any scripts until that was resolved. By deleting that 2nd script I could add the script correctly and ran as one would expect it to. :)
> 1 votes

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


# Question
Title: Rendering order objects with transparency?
I do not know if this question might have been asked before, but which method for rendering transparency is more efficient in terms of less lag?:

1. Rendering the scene from front to back with respect to the camera
2. Rendering the all the opaque items then all the transparent items from least transparent to most transparent.

Also another question with method 2 above, would **disabling the `GL_BLEND` func** when **rendering the opaque items** reduce usage of memory, and inturn reduce lag, because the fragment shader would not have to run the blend operations, which saves memory, (right?) or have I got it wrong?

# Answer
The usual way is:

1. Render opaque objects first

* Blending *disabled* (this does not save memory — the render target still has just as many pixels with just as many bits of colour information — but it does save *time* spent doing the blending calculation)
    * Sorted *front to back* (so earlier objects tend to occlude later objects, and you can skip drawing some of the distant objects' pixels entirely thanks to early Z rejection)
2. Render transparent objects second

* Blending *enabled* (obviously)
    * Sorted *back to front* (so distant objects are already in the frame buffer when you draw a closer translucent object over them, allowing you to see the distant one through the near one, attenuated by the near object's translucency. Doing this front to back would end up layering some distant objects *on top* of nearer ones, making for strange-looking artifacts)
> 2 votes

---
Tags: opengl, lwjgl, transparency, alpha-blending
---