# Question
Title: After the player collides with the enemy, it keeps moving backwards until it falls down a cliff
My player will basically be pushed back forever after colliding with an enemy. I have tried changing the mass of the player to like 100, but it still does the same thing. The force that pushes the player is already 1f, so there must be something wrong with the code. Code:

```
[SerializeField] private LayerMask platformsLayerMask;

[SerializeField] private Rigidbody2D rb;

public float MovementSpeed = 100f;

public float JumpingHeight = 100f;

[SerializeField] private BoxCollider2D bc;

public float fallMultiplier = 2.5f;
public float lowJumpMultiplier = 2f;

[SerializeField] private Animator anim;

private enum State {idle, running, jumping, falling, hurt}
private State state = State.idle;

private Collider2D coll;

[SerializeField] private int cherries = 0;
[SerializeField] private Text cherryText;

[SerializeField] private float hurtForce = 10f;

void Awake()
{
    rb = transform.GetComponent<Rigidbody2D>();
    bc = transform.GetComponent<BoxCollider2D>();
    coll = transform.GetComponent<Collider2D>();
    anim = transform.GetComponent<Animator>();
}

void Update()
{
    if(state != State.hurt)
    {
        Movement();
    }
    VelocityState(); //referencing the void VelocityState
    anim.SetInteger("state", (int)state);
}

void Movement()
{
    float vDirection = Input.GetAxis("Vertical");
    if (coll.IsTouchingLayers(platformsLayerMask) &&  vDirection > 0)//the player is only able to jump if it is on the ground
    {
        rb.velocity = new Vector2(rb.velocity.x, JumpingHeight);
        Debug.Log("Jumping");
        state = State.jumping;
    }

    float hDirection = Input.GetAxis("Horizontal");

    if (hDirection < 0)
    {
        rb.velocity = new Vector2(-MovementSpeed, rb.velocity.y);
        Debug.Log("Going Left");
        transform.localScale = new Vector2(-1, 1); //flips sprite
    }
    else
    {
        if (hDirection > 0)
        {
            rb.velocity = new Vector2(+MovementSpeed, rb.velocity.y);
            Debug.Log("Going Right");
            transform.localScale = new Vector2(1, 1); //flips sprite
        }
        else
        {
            //no keys pressed
            rb.velocity = new Vector2(0, rb.velocity.y);
            Debug.Log("No key pressed");
        }
    }
    if (rb.velocity.y < 0) //reponsive jumping and falling
    {
        rb.velocity += Vector2.up * Physics2D.gravity.y * (fallMultiplier - 1) * Time.deltaTime;
    }
    else if (rb.velocity.y > 0 && vDirection > 0)
    {
        rb.velocity += Vector2.up * Physics2D.gravity.y * (lowJumpMultiplier - 1) * Time.deltaTime;
    }

}

private void VelocityState() //for switching states for animations
{
    if(state == State.jumping) //when jumping, if the player starts falling, switch to falling animation.
    {
        if(rb.velocity.y < 0.1f)
        {
            state = State.falling;
        }
    }
    else if(state == State.falling) //when falling, if the player touches the platform, switch to idle.
    {
        if (coll.IsTouchingLayers(platformsLayerMask))
        {
            state = State.idle;
        }
    }
    else if (state == State.hurt)
    {
        if (Mathf.Abs(rb.velocity.x) < .1f)
        {
            state = State.idle;
        }
    }
    else if (Mathf.Abs(rb.velocity.x) > Mathf.Epsilon) //if running, switch to running animation.
    {
        //moving
        state = State.running;
    }
    else //if it is not everything above, idle
    {
        state = State.idle;
    }
}

private void OnTriggerEnter2D(Collider2D collision) //cherries
{
    if (collision.tag == "Collectible")
    {
        Destroy(collision.gameObject);
        cherries += 1;
        cherryText.text = cherries.ToString();
    }
}

private void OnCollisionEnter2D(Collision2D other) //enemies
{
    if (other.gameObject.tag == "Enemy")
    {
        if (state == State.falling)
        {
            Destroy(other.gameObject);
        }
        else
        {
            state = State.hurt;
            if(other.gameObject.transform.position.x > transform.position.x)
            {
                //enemy is on my right therefore I should be damaged and moved left
                rb.velocity = new Vector2(-hurtForce, rb.velocity.y);
            }
            else
            {
                //enemy is on my left therefore I should be damaged and moved right
                rb.velocity = new Vector2(+hurtForce, rb.velocity.y);
            }
        }
    }
}

```

# Answer
You should not change the velocity of the RigidBody directly.

Try using `AddForce` instead.

```
if(other.gameObject.transform.position.x > transform.position.x)
{
    rb.AddForce(-hurtForce,rb.velocity.y,0,ForceMode.Acceleration);
}

```
> 1 votes

# Answer
Your problem is here:

```
if(state != State.hurt)
{
    Movement();
}

```

`Movement` is the only code that modifies your object's velocity. Without that, your object will coast up to the whims of physics.

For a knockback, we want a bit of sliding, but not an unlimited amount. So let's add some drag.

```
if(state != State.hurt)
{
    Movement();
} else {  // You could also add a time condition here to put the brakes on after a delay.
    var velocity = rb.velocity;
    velocity.x *= 0.9f; // Quick and dirty deceleration.
    rb.velocity = velocity;
}

```

Remember to put this in `FixedUpdate` to ensure you get consistent behaviour regardless of the framerate.
> 0 votes

---
Tags: unity, 2d, movement
---


# Question
Title: How do I properly use Unreal's Lens Distortion plugin?
I am trying to use UE's LensDistortion plugin (seems like it's bundled with the engine but only put to use in the Compositing sample project), and following the same workflow as the sample. Essentially, the idea is to create a camera model using the standard distortion parameters (radial, tangential etc.). The plugin then 'draws' a UV displacement map according to these params, and the original image is then distorted by adding these displacements to the corresponding pixels.

The level blueprint creates the displacement map and a material uses this to distort a given image (the distortion values are written only on the R and G channels, hence the mask in the material). Both are shown in these images:

I don't understand the output I am getting. Seems to me the material function somehow ends up addressing invalid pixel values (less than 0 or greater than 1, assuming UV range is 0-1), so I see a strange 'repeating' of the image, as below:

The way the whole canvas is distorted makes sense spatially: but the pixel values corresponding to those locations are wrong. Am I doing something wrong in my material? How do I properly use this distortion plugin?

# Answer
Firstly, you can run your Blueprint logic on EventBeginPlay, as I assume you won't be changing lens settings during game play.

Secondly set your Undistort Overscan Factor to 0.0 If you're going for a GoPro effect you won't need overscan area for undistorting down the road.

I have just tested this in 4.24, but my images are having issues uploading unfortunately.
> 1 votes

---
Tags: camera, unreal, materials
---


title: How to properly space train bogies

text:
# Question
Title: How to properly space train bogies
I have a small project with a train that follows a track, composed of discrete pieces. For each piece I calculate the location based on distance traveled, and each carriage gets a fixed offset.

I would like to improve on this with proper bogies, but the distance between the two bogies of a carriage is not the length along the track, it is always fixed distance. How do I best confine my bogies to a track, while kepping the distance between them fixed, regardless of the track curvature?

# Answer
there are 2 options:

1. cheat, just make the distance along the track constant and use the fact that the difference is minimal to hide it. Then you can use the straight line between the bogies to position each carriage on the center between them and aligned to them.
2. start doing geometry. For a constant curve with radius `r` the angle `theta` between bogies with a constant straight line distance `d` between them when viewed from the center of the curve is `theta = 2 * asin(d/2 / r)` the length along the track is then `r*theta` (with theta in radians). You can prove that when `r` gets larger (a more gentle curve) this gets closer and closer to `d`.
> 0 votes

---
Tags: unity, geometry
---


# Question
Title: UE4. How to create a reference to the physical material asset (which I create in editor) in C++
Oftenly, when we want to assign asset to the particular component in C++ we write code like that:

```
.h

UPROPERTY(BlueprintReadWrite)
UStaticMeshComponent* Body = nullptr;

.cpp

Body = CreateDefaultSubobject<UStaticMeshComponent>("Mesh Component");
// find mesh asset
auto MeshForBody = ConstructorHelpers::FObjectFinder<UStaticMesh>(TEXT
                        ("StaticMesh'/Game/StarterContent/Shapes/Shape_Sphere.Shape_Sphere'"));
if (MeshForBody.Object != nullptr)
{// if asset is finded -> set to the component
    Body->SetStaticMesh(MeshForBody.Object);
}

```

Question: how can I set the PhysicalMaterial in C++ through the reference to the asset in editor? Is it possible?

```
.h
    UPROPERTY(EditDefaultsOnly)
    UPhysicalMaterial* MyPhysicalMaterial = nullptr;

.cpp

    ???

```

Find this, but still waiting maybe the best solution without casting exists:

```
auto PhysicalMaterialAsset = ConstructorHelpers::FObjectFinder<UObject>(TEXT(
         "PhysicalMaterial'/Game/PhysicsMaterials/MyPhysicsMaterial.MyPhysicsMaterial'"));

if (PhysicalMaterialAsset.Object)
{
    Sphere->BodyInstance.SetPhysMaterialOverride((UPhysicalMaterial*)PhysicalMaterialAsset.Object);
}

```

THNX for any tips in advance ;)

# Answer
The easiest way is what you've done, then set the material in the Blueprint of whatever the material is attached to. Back in your .cpp file, you can then access the material.

A word of warning though, if you're trying to change any settings and you haven't assigned anything in the Blueprint, Unreal will return the nullptr and crash the editor. To avoid this, always start with:

```
if (MyPhysicalMaterial) {

```

This will check if there is something assigned to the material reference before attempting any changes.
> 2 votes

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


# Question
Title: How do I initialise levels sequentially?
I have been learning opengl and I have made good progress over past few months. However I still struggle to understand game logic in C++, I am new to C++ too.

Say I have this program.

```
#include <headers>

int main()
{
    #Step 1
    VAO_VBO_EBO_inits();

    while(!glfwWindowShouldClose(window))
    {
        glClearColor(.2f, .2f, .3f, 1.f);
        glClear(GL_COLOR_BUFFER_BIT);

        #Step 2
        DrawCalss();

        glfwPollEvents();
        glfwSwapBuffers(window);
    };
    return 0;
};

```

For OpenGL programmers this should be clear. With this structure, I have to load all levels and then draw part of them like so.

# Step 1 feeds the gpu the vertex data and its attributes.

# Step 2 binds shader programs and draws the vertices

Say I have A, B, C, D levels, within  `VAO_VBO_EBO_inits();` function I have to load all A, B, C, D levels then within `DrawCalss();` function will draw only related levels.

`DrawCalss();` function is dynamic but  `VAO_VBO_EBO_inits();` invoked only once.

What I want to do is create separate game loops for each levels and be able to switch between levels, and as I switch levels preceding level should be unloaded and next level reloaded.

*Since I am new to C++ I don't know what way would be the most efficient, that's why I have not tried anything.* **How do I achieve it? what is the best practice for such scenarios?**

# Answer
> 1 votes
What I would probably do is using the inheritance mechanism of C++ and have a level superclass which level subclasses inherits from. The superclass contains virtual functions for creating, destroying, updating and rendering a level. You can then have a pointer to the current level so that only a single level is updated and rendered at a time.

If each level should be created and handled differently, the inheritance mechanism will work good but if they work exactly the same and every level is created/handled the same, you might not need to use inheritance and instead just have a level class that is instantiated multiple times, one for each level in your game.

Below I've added a simple code example showing how such classes can be constructed/structured and a simple state machine to switch between game states (menu, game, end credits etc).

First we have the level superclass:

```
class ILevel
{
public:

             ILevel                     (void)                  {}
    virtual ~ILevel                     (void)                  {}

    virtual void    Create              (void)                  = 0;
    virtual void    Destroy             (void)                  = 0;
    virtual void    Update              (const float DeltaTime) = 0;
    virtual void    Render              (void)                  = 0;

public:

    ILevel*         GetPreviousLevel    (void)  const               {return m_pPreviousLevel;}
    void            SetPreviousLevel    (ILevel* pPreviousLevel)    {m_pPreviousLevel = pPreviousLevel;}

    ILevel*         GetNextLevel        (void)  const               {return m_pNextLevel;}
    void            SetNextLevel        (ILevel* pNextLevel)        {m_pNextLevel = pNextLevel;}

    unsigned int    GetID               (void)  const               {return m_ID;}
    void            SetID               (const unsigned int ID)     {m_ID = ID;}

    std::string&    GetName             (void)  const               {return (std::string&)m_Name;}
    void            SetName             (const std::string& rName)  {m_Name = rName;}

    bool            GetIsFinished       (void)  const               {return m_IsFinished;}

protected:

    // A pointer to the previous level - might wanna be able to return to the previous level etc
    ILevel*         m_pPreviousLevel;

    // A pointer to the next level for easy transition between the current level and the next
    ILevel*         m_pNextLevel;

    unsigned int    m_VBO;
    unsigned int    m_IBO;
    unsigned int    m_VAO;

    // A numerical ID of the level (1 for level 1, 2 for level 2 etc) might be needed
    unsigned int    m_ID;

    // A string for naming the level might also be needed
    std::string     m_Name;

    bool            m_IsFinished;

};

```

Then we have the class(es) that inherits from this superclass:

```
class CLevel1 : public ILevel
{
public:

             CLevel1        (void);
    virtual ~CLevel1        (void);

    virtual void Create     (void) override;
    virtual void Destroy    (void) override;
    virtual void Update     (const float DeltaTime) override;
    virtual void Render     (void) override;

};

class CLevel2 : public ILevel
{
public:

             CLevel2        (void);
    virtual ~CLevel2        (void);

    virtual void Create     (void) override;
    virtual void Destroy    (void) override;
    virtual void Update     (const float DeltaTime) override;
    virtual void Render     (void) override;

};

```

As you can see above, they looks identical, but you might wanna handle them in different ways and have unique data in each.

Then we have the actual entry point and its mainloop:

```
enum EGameState
{
    MENU = 0,
    GAME,
    END_CREDITS,
};

ILevel* pCurrentLevel = nullptr;

EGameState GameState;

void Update(void)
{
    if(GameState == EGameState::MENU)
    {
        UpdateMenu();
    }

    else if(GameState == EGameState::GAME)
    {
        pCurrentLevel->Update(Time.DeltaTime);

        if(pCurrentLevel->GetIsFinished())
        {
            ILevel* pNextLevel = pCurrentLevel->GetNextLevel();

            // Destroy the current level
            pCurrentLevel->Destroy();

            if(pNextLevel)
            {
                // Set the new current level (i.e, the next level)
                pCurrentLevel = pNextLevel;

                // And create it
                pCurrentLevel->Create();
            }

            // If pNextLevel is not valid (i.e it's a nullptr), the current level is the last level
            else
                GameState = EGameState::END_CREDITS;
        }
    }

    else if(GameState == EGameState::END_CREDITS)
    {
        UpdateEndCredits();
    }

    glfwPollEvents();
}

void Render(void)
{
    glClearColor(0.2f, 0.2f, 0.3f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    if(GameState == EGameState::MENU)
    {
        RenderMenu();
    }

    else if(GameState == EGameState::GAME)
    {
        pCurrentLevel->Render();
    }

    else if(GameState == EGameState::END_CREDITS)
    {
        RenderEndCredits();
    }

    glfwSwapBuffers(window);
}

int main(int argc, char* argv[])
{
    InitializeGLFW();

    GameState = EGameState::GAME;

    ILevel* pLevel1 = new ILevel;
    ILevel* pLevel2 = new ILevel;

    // Create the actual level, create the VBO, IBO, VAO etc
    pLevel1->Create();
    pLevel1->SetPreviousLevel(nullptr);
    pLevel1->SetNextLevel(pLevel2);
    pLevel1->SetID(1);
    pLevel1->SetName("Level 1");

    pLevel2->SetPreviousLevel(pLevel1);
    pLevel2->SetNextLevel(nullptr);
    pLevel2->SetID(2);
    pLevel2->SetName("Level 2");

    // Set the current level
    pCurrentLevel = pLevel1;

    while(!glfwWindowShouldClose(window))
    {
        Update();
        Render();
    };

    return 0;
}

```

This is just an example on how the game can be constructed/structured and you might need to adapt it to work for you and what's working for your specific game.

One think you can also ask yourself is whether you want to have all the levels loaded in memory or if you only want to have the current level in memory. In the end, it depends on your game and if it's a small one, with only a few levels, it might be okay to have them all in memory.

---
Tags: opengl, c++, level-design, logic
---


# Question
Title: Help needed in getting the correct hit position a raycast hits a sphere in Unity
I'm trying to get the actual position a raycast from a controller hit's a sphere gameobject.

The raycast is cast from the controller (gear vr controller) out in the forward direction when the trigger is pressed, but when I test the value of the hit.point, I get varying values depending on what sphere I hit.

Shouldn't the hit point be roughly the same if I say always hit the sphere's more or less dead center?

Here's the code I use to cast the ray, this runs when I click the trigger of the controller:

```
if (OVRInput.GetDown(LaserInputModule.instance.trigger) && triggerdown == false)
    {
        triggerdown = true;
        RaycastHit hit;
        if (Physics.Raycast(LaserInputModule.instance.helperCamera.transform.position, LaserInputModule.instance.helperCamera.transform.forward, out hit))
        {
            Debug.Log(hit.transform.name + " got hit at: " + transform.InverseTransformPoint(hit.point) );
        }
        else
        {
            Debug.Log("PlayerMissed");
        }
    }

```

LaserInputModule.instance.helperCamera is basically the controller the player has in their hand.

When I test the values in logcat, for the first picture, I get back what I assume to be correct values  Sphere(Clone) got hit at: (-0.2, 0.1, -0.5) (so x,y are roughly in the center of the sphere)

But when I do the same for another sphere (2nd Pic)enter image description here, I get back some spurious values Sphere(Clone) got hit at: (-7.2, 2.0, -0.4)

# Answer
Ahh face palm moment, you were right, I had it running on the update method for every sphere. So it was giving me values for every one of the 12 spheres, I just didn't see it in the logcat as it was spamming it.

I've moved this logic off the sphere's into it's own gameobject and works great. thanks for your help.
> 1 votes

# Answer
It looks like you're trying to output the position in the sphere's local coordinate system, but you have a typo, so you're using the raycaster script's local coordinate system instead.

```
if (Physics.Raycast(LaserInputModule.instance.helperCamera.transform.position, LaserInputModule.instance.helperCamera.transform.forward, out hit))
{
    //                 ↓ This is the transform of the sphere you hit.
    Debug.Log(hit.transform.name + " got hit at: " + transform.InverseTransformPoint(hit.point) );
    //                                                 ↑  This is the transform of the object
    //                                                    that this script is running on.
}

```

If you want to use the hit object's local coordinates, make sure to use `hit.transform`, not just `transform`.
> 0 votes

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


# Question
Title: What does the "DXGI Flip Model Swapchain" setting in Unity do exactly?
I'm preparing a Standalone Unity game for Windows and Mac.

There is a checkbox in Player Settings called "Use DXGI Flip Model Swapchain for D3D11", which seems disabled by default.

Needless to say, I don't understand this setting at all. The Unity documentation has this:

> Flip model ensures the best performance. Disable this to fallback to Windows 7-style BltBlt model. This setting affects only D3D11 graphics API on Windows 8.1 or greater.
>
> Note that even if the flip model is enabled, the BltBlt model will be used in exclusive fullscreen mode to reduce input latency.

It doesn't exactly tell me what this is (I literally don't know what most of that means) - but it almost seems like there is no reason *not* to have it enabled.

Can someone explain the pros and cons of this setting? Under what scenarios would I want to enable/disable it?

Since disabling it fallbacks to the Windows-7 style, it almost gives the impression that enabling this might make the game less compatible on Windows 7?

# Answer
The only reason this would conceivably not be enabled-by-default is because the swapchain image format has specific requirements for flip model. You may not do MSAA resolve as part of the buffer swap, you must also adhere to the desktop's colorspace.

It is a performance enhancement for rendering in windowed mode that allows you to draw directly into the DWM's backbuffer instead of causing the DWM to copy your application's frontbuffer when it repaints all windows.

Windows 7 technically introduced the feature, but only for D3D9Ex and the modern DXGI-based APIs (D3D10/11/12, DWrite, D2D) saw flip model introduced in Windows 8. Always enable this, it makes a big difference for framepacing and Unity needs all the help it can get in that department.
> 1 votes

# Answer
This option enables the use of `DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL` or `DXGI_SWAP_EFFECT_FLIP_DISCARD` as compared to `DXGI_SWAP_EFFECT_DISCARD` or `DXGI_SWAP_EFFECT_SEQUENTIAL`. On Windows 7, it's always going to use the older BitBlt style. This only impacts which one it uses on Windows 8.1 or Windows 10. See Microsoft Docs

Generally, it's recommended you use `DXGI_SWAP_EFFECT_FLIP_*` when possible because it's better behavior all around. See this blog post for a detailed discussion.

> For DirectX 12 on Windows 10, you have to use `DXGI_SWAP_EFFECT_FLIP_*`. This is also required to use `DXGI_FEATURE_PRESENT_ALLOW_TEARING`.

**UPDATE**: See this blog post series as well for more guidance on swapchains.
> 0 votes

---
Tags: unity, windows
---


# Question
Title: Calculating Hit Accuracy score in a game
I'm currently in the process of making a scoreboard for my game. One of things I would like to display is the players accuracy in the amount of hits they had in game. However, I have never done this before and I've no idea how to go about doing this.

Is there a commonly used algorithm out there that can help me calculate this, or has someone found a way to calculate this fairly easily?

Any help with this would be appreciated.

# Answer
> 2 votes
As I already mentioned in the comments, it's simply just:

```
float hitAccuracy = ShotsHit / ShotsFired * 100;

```

Basically just every time the player fires a shot, increment ShotsFired by one and if the shot hits the target, increment ShotsHit by one.

Of course, there's one problem with this. If Player A fires 100 shots of which 99 hits the target, he would lose to someone who has shot only one shot which hitted the target. This is not necessary a problem, but if it is, could you give us more details about your game?

# Answer
> -1 votes
it depends on how much of each hit the timing is, if it shows marvelous or perfect on all of the shots, it is 100% accuracy, there is usually 5 or 6 ratings, from most timed to least timed, the least would be a miss, and the more of a certain timing the less the accuracy would be, all greats, would not be the same accuracy as like an all perfect or an all marvelous.

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


title: Third person and LineTracing C++

text:
# Question
Title: Third person and LineTracing C++
**Problem**

I have a crosshair in the middle of the screen.

I need to create a `lineTrace` that passes straight through this crosshair.

As this is a third person game, I need the line trace to cast through the crosshair

---

**Question**

How do I do this

---

**Code sample**

    #include "GameFramework/PlayerController.h"
    #include "Engine/World.h"
    #include "DrawDebugHelpers.h"
    #include "Camera/PlayerCameraManager.h"
    #include "GrabObjects.h"
    #include "CollisionQueryParams.h"

    #define OUT

    //...

    // Called every frame
    void UGrabObjects::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
    {
        //...

        FVector PlayerViewPointLocation;
        FRotator PlayerViewPointRotation;

        // Get player viewport
        GetWorld()->GetFirstPlayerController()->GetPlayerViewPoint(
            OUT PlayerViewPointLocation,
            OUT PlayerViewPointRotation
            );

        // Draw a line from player showing reach
        // PlayerViewPointRotation.Vector() is the unit vector
        FVector LineTraceEnd = PlayerViewPointLocation + PlayerViewPointRotation.Vector() * Reach;

        DrawDebugLine(
            GetWorld(),
            PlayerViewPointLocation,
            LineTraceEnd,
            FColor(0, 255, 0),
            0.f,
            0,
            5.f
        );

        //...
    }

```
</code></pre>

# Answer
You can try doing what you are now, but take the distance from the camera to the player, multiplied by the Camera forward vector to make it begin at the player. This should achieve what you want.

Example, may not be correct or work but hopefully conveys the idea:

```
float dist = FVector::Distance(PlayerViewPointLocation , GetWorld()->GetFirstPlayerController()->GetPawn()->GetActorLocation());
FVector StartPos = PlayerViewPointLocation + (GetWorld()->GetFirstPlayerController()->PlayerCameraManager->GetForwardVector() * dist);

```

Note: If you are familiar with Matrix transformations you can just use the Cameras Transform (inverse as you want to go from World to Local) to transform the players world space location into the cameras local. Then you can just use the X of the new vector.
> 0 votes

# Answer
Instead of using the predefined GetPlayerViewPoint() to set your location and rotation, you'll need to use this:

```
PlayerViewportLocation = GetWorld()->GetFirstPlayerController()->GetPawn()->GetActorLocation();
PlayerViewportRotation = GetWorld()->GetFirstPlayerController()->GetPawn()->GetActorRotation();

```

This will set your parameters from the location of the pawn itself and not the camera.
> 0 votes

---
Tags: c++, unreal-4, debugging
---


# Question
Title: Why the cube is getting to the other cube instead stopping when both colliders hit?
I don't want to use a script with OnTriggerEnter or something like that but to simulate the red cube as a wall and when the blue cube collider hit the red cube collider it should stop. Both cubes have a box collider and on both the Is Trigger is checked true I also tried one of them or both when not checked true. And both colliders size on Z set to 3.

But the blue cube is getting to the red one and not stop when colliding :

The blue cube is getting inside the red one :

I tried to add a rigidbody to the moving cube the blue cube but if using Is Kinematic same behaviour if not using Is Kinematic the blue cube is falling down.

This is the script attached to the blue cube to move it to the target red cube :

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

public class MoveObject : MonoBehaviour
{
    public GameObject target;
    public float speed;

    // Update is called once per frame
    void Update()
    {
        transform.position = Vector3.MoveTowards(transform.position, target.transform.position, Time.deltaTime * speed);
    }
}

```

I want that the blue cube will stop when colliding the red cube collider that's why I set them on Z to 3. I don't need physics for now.

Do I need must using OnTriggerEnter in my script for that ?

I thought I tried it too but this seems to be working : Both box colliders on the cubes unchecked set false the is trigger and I added a rigidbody to the moving cube the blue one and unchecked the use gravity and now it seems to be working.

So I need a rigidbody even if I'm not using physics. I wonder why.

# Answer
> 1 votes
The cube wont stop as you are moving by changing the transform. That will just override physics.

You need to move the cube ONLY with physics to avoid this issue. If you don't then you need the moving cube to have a collider (non trigger) and the "wall" to have a trigger collider that will, when this cube is detected, tell it to stop moving. Both may then require a rigidbody set to "Is Kinematic"

To summarise. Move the cube with physics by using something like the Rididbody.MovePosition method. If you want to move without physics you need to use triggers correctly to simulate this.

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


# Question
Title: Show Camera field of view in minimap but without y axis rotation
Here is the function to draw a triangle that represents the camera field of view in a minimap. The problem with this code snippet is that when I rotate up and down (Change the pitch of camera) the viewport triangle also rotates up/down.

```
void makeViewPortCube()
{
    if (player.GetComponent<Camera>() == null)
    {
        // Debug.LogError("Please assing a Main Camera to Follow");
        return;
    }

    if (viewPortMesh == null)
    {
        viewPortGameobject = new GameObject();
        viewPortGameobject.AddComponent<MeshFilter>().mesh = makeStartingMeshForViewPort(2.0f, 2.0f);
        viewPortGameobject.AddComponent<MeshRenderer>().material = materiaForViewPortGameobject();
        viewPortGameobject.name = "View Port Object";
        viewPortMesh = viewPortGameobject.GetComponent<MeshFilter>().mesh;
        viewPortGameobject.layer = LayerMask.NameToLayer("MiniMap");
        viewPortGameobject.transform.position = new Vector3(viewPortGameobject.transform.position.x, /*transform.position.y-*/100, viewPortGameobject.transform.position.z);
    }

    // change vertices of the viewport
    Vector3[] aVertexList = viewPortMesh.vertices;

    if (stopRotation == false)
    {
        //Orignial
        aVertexList[1] = player.GetComponent<Camera>().ScreenToWorldPoint(new Vector3(Screen.width, 0, 10f));
        aVertexList[2] = player.GetComponent<Camera>().ScreenToWorldPoint(new Vector3(Screen.width, 0, player.GetComponent<Camera>().nearClipPlane));
        aVertexList[3] = player.GetComponent<Camera>().ScreenToWorldPoint(new Vector3(0, Screen.height / 4, player.GetComponent<Camera>().nearClipPlane));

        aVertexList[0] = player.GetComponent<Camera>().ScreenToWorldPoint(new Vector3(0, Screen.height / 4, 10f));

        for (int i = 0; i < 4; i++)
        {
            aVertexList[i].y = 3;
        }
    }

    viewPortMesh.vertices = aVertexList;
    viewPortMesh.RecalculateBounds();
}

```

# Answer
> 1 votes
Instead of using `ScreenToWorldPoint`, I would do something like the following:

```
// Get the camera once. GetComponent is an expensive call, so cache the result whenever
// you can instead of calling it repeatedly.
Camera theCamera = player.GetComponent<Camera>();

// The camera's far plane gives the view distance
float viewDistance = theCamera.farClipPlane;

// The camera's current orientation (defined by its "forward" direction) gives the view
// direction. Project onto the ground plane to ignore the up/down part.
Vector3 viewDirection = Vector3.ProjectOnPlane(theCamera.forward, Vector3.up).normalized;

// Get the view width from the camera's field of view
float verticalFoV = theCamera.fieldOfView;
float horizFoV = Camera.VerticalToHorizontalFieldOfView(verticalFoV, theCamera.aspect);

// Get the left and right sides of the view
Quaternion q = Quaternion.AngleAxis(horizFoV / 2f, Vector3.up);
Vector3 rightDir = q * viewDirection;
Vector3 leftDir = -q * viewDirection;

// And finally, to get all three vertices
// (Not sure why you have four in your question...)
Vector3 start = theCamera.transform.position;
Vector3 rightEnd = start + rightDir * viewDistance;
Vector3 leftEnd = start + leftDir * viewDistance;

```

If you are not comfortable with Quaternions, then you could replace that part with:

```
float rightAngle = (theCamera.transform.eulerAngles.y + horizFoV_rad/2f) * Mathf.Deg2Rad;
float leftAngle = (theCamera.transform.eulerAngles.y - horizFoV_rad/2f) * Mathf.Deg2Rad;

Vector3 rightDir = new Vector3(Mathf.Sin(rightAngle), 0, Mathf.Cos(rightAngle));
Vector3 leftDir = new Vector3(Mathf.Sin(leftAngle), 0, Mathf.Cos(leftAngle));
// Note that I might have the Sin & Cos backwards, none of this has been tested

```

By the way, Sebastian Lague made a great tutorial series on field of view visualization, available on Youtube. It's not quite what you are doing, but it should be similar enough to be helpful.

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


# Question
Title: How do open world game engines allocate memory?
# My troubles

I've been trying to create a game engine but since I am not well experienced in C++ I am having trouble deciding on how to load new scenes efficiently level by level or just an open world.

# Example

Recent games are heavy, **Most populat games are about 40 to 100 gigabytes** but neither RAM nor GPU have that much memory at least Normal PC or Consoles.

So obviously most game engines pre-allocate enough memory to fit the scene and sometimes just tolerate some wasted memory but how would you decide how much is enough?

# Possible solution

I was planning to create **separate game loops**, before entering the game loop I would load each level, then start the loop, thus I would be able to deallocate preceding level and then reallocate new memory for a next level.

Since I am new to the world of games and memory management my solution may sound rather stupid, But I need to know how to handle such situations efficiently.

# Answer
> 4 votes
Creating a seamless open world without loading bars is not an easy task. There are lots of small and large problems which need to be solved. This is not a beginners project!

The basic approach is usually to divide the world into sections and only load those sections which are around the player. When the player moves around the world, new sections and their assets get loaded from hard drive into memory and further away sections get deleted.

When you want a high view distance which would require you to load lots and lots of sections, then you usually load the further away sections in a lower level of detail. Simplified geometry, lower resolution textures and no simulation of any moving objects. When the player comes closer, those low-detail sections get replaced with high-detail sections. This requires that you have multiple levels of detail for every section.

The radius in which you load full-detail, mid-detail and low-detail sections is a question of memory budgetting. You should nail down early how much RAM you expect the end-user devices to have at least and how much of that RAM you can budget for the environment. Do a back-of-the-envelope calculation how much RAM a section will take in each detail level. After you implemented the first sections, confirm those assumptions through profiling. This should tell you how many sections you can afford to load at once.

When you target the PC or Phone market, then the capabilities of end-users devices can differ by a lot. So you might choose to make the quality level ranges configurable for the end-user. You could also try to detect how much RAM the users device has and adjust view ranges dynamically.

It can be a good idea to move this constant loading, replacing and unloading of sections to a separate thread, so it doesn't slow down the main game. But now you need to deal with what happens if the player moves very quickly and manages to enter a section which isn't fully loaded yet. You could put the player in the low-detail environment, but this is going to result in a very poor game experience and game-breaking bugs. Showing a loading bar after all might be the better solution for this situation.

---
Tags: opengl, c++, game-loop, memory-efficiency, memory
---


# Question
Title: How can I play an animation only using C#, without animation controller, or create an animation controller at runtime entirely from script?
I've been looking around for a while trying to figure out how to play simple animations with Unity via ONLY C# script, with no drag-and-drop involved. So far I've found various tutorials explaining how to manually set up a animation controller for each object, then manually select each animation state and manually create a transition then manually set the transition length to the most minimum possible etc...

I was wondering if there's a simple way to just do something like...

```
gameObject.playAnimation(
    "stand still /* which would be the name of the action state created in blender or other animation software*/",
    "loop");

```

...WITHOUT creating an animation controller manually at all, I haven't been able to find any resource to do this simple thing yet.

# Answer
> 6 votes
Have a look at different approach on Animation using "SimpleAnimation" via new Unity's Playable system.

Introducing the Simple Animation Component (Unity Blog)

Under the hood it hacks the way using animator to play animation while controlling clip and state name from Playables, using new API set `UnityEngine.Playables.AnimationPlayableUtilities`

But now you can add states easier by script since you are dealing with playables not RuntimeAnimatorController and their messy state system. This is how it looks like when you use it on your end:

```
// Assumes following variables
SimpleAnimation m_CustomAnimationPlayable; // Via inspector or added on runtime
AnimationClip clip, clip2; // Via inspector or other mean

// Example on creating
m_CustomAnimationPlayable.AddState( clip, "run" );
m_CustomAnimationPlayable.AddState( clip2, "attack" );

// Example on playing
m_CustomAnimationPlayable.Play( "run" );
m_CustomAnimationPlayable.PlayQueued( "run", QueueMode );
m_CustomAnimationPlayable.CrossFade( "run", 1.0f ); // crossfade length

```

It need quite a bit of initial setup but this official github will provide most boilerplate code for you:

Official Unity Git Hub for SimpleAnimation

## Here is outline of setting up

* You still need pre-constructed Animator in Unity editor but it could be almost blank or most simple one. This allows you to set other useful field in Animator such as avatar setup.
* Add "SimpleAnimation" component to the game object that has animator installed.
* Call SimpleAnimation.AddState( clip, name ) to add your own state. You don't have to even define transition. **Of course, you need your own way to provide list of AnimationClip to use,** it could be drag n drop field in your component or ScriptableObject contains animation database of some kind. Or if you want **totally "no-drag-drop"**, your solution would limit to `Resources` API and alike. (Refer to @Phillips answer)
* Play any state or crossfade using SimpleAnimationPlay( statename );

## Key point VS legacy Animation component

* ⌾ Not require marking AnimationClip as Legacy.
* ⌾ You can use Animator (Mechanim) important features such as Avatar (bone re-targetting), and possibly (I'm not sure) root motion.
* △ Code amount to setup is around the same as using Legacy Animation.

## Be discreet on Resources folder (!!)

* `Resources` API has been a good accessible way for loading thing on runtime.
* **BUT** Resource folder incurs memory and build performance. For best practice, use it with discreet. Do not dump everything there.
* Further in-depth read: Asset Bundles vs. Resources: A Memory Showdown
* Further in-depth read: Assets, Resources and AssetBundles
* What is worse than Unity's own best practice explicitly said `Don't use it.`?

---

## There is also AnimatorOverrideController

Keep in mind that there is also another approach AnimatorOverrideController, which is also possible to do on script runtime level. But this is leaning more toward scenario such as having several actors with exactly **same state machine but with different AnimationClip override for each state**.

# Answer
> 3 votes
Without using the Animation Controller, you can use Animation Type to Legacy.

Then All you need to attach the script to animation object.

```
 public Animation animates;

    void Start()
    {
       animates = GetComponenet<Animation>();
    }

    public void Plays()
    {
        animates["ClipName"].normalizedTime = 0.0f;
        animates["ClipName"].speed = 1.0f;
        animates.Play();
    }

```

# Answer
> 1 votes
I would recommend using an animation controller if you will ever need to blend animations or do any kind of complicated state. If you don't want transitions, you don't have to add them, just call Animator.Play("state\_name").

But, if you just want a simple way to play single animation clips, you might be interested in this blog. Unity created that exact component, and you can grab it from GitHub.

# Answer
> 1 votes
Although it is considered obsolete in favor of the much more powerful AnimationController, the good old Animation component still exists.

It provides you with a very simple way to play an animation clip: `GetComponent<Animation>().Play(clipName, mode);`

However, before you can play an animation clip by name, you first have to add the animation clip asset to the animator via inspector or using `GetComponent<Animation>().AddClip(animationClipAsset, clipName);`.

That means you will still need a way to get a reference to the animation clip asset. The easiest way would be to assign it to some inspector variable. But you specifically said "no drag and drop involved", so you might want to get them through Resources (also no longer recommended) or through the new Addressable Asset System.

# Answer
> 0 votes
To play animation during runtime you need to following things:

1. Animator component (on runtime)
2. Avatar of Character
3. Animator Controller

public class SM : MonoBehaviour
{
    [MenuItem("MyMenu/Create Controller")]
    static void CreateController()
    {
        // Creates the controller
        var controller = UnityEditor.Animations.AnimatorController.CreateAnimatorControllerAtPath("Assets/Mecanim/StateMachineTransitions.controller");

        // Add parameters
        controller.AddParameter("TransitionNow", AnimatorControllerParameterType.Trigger);
        controller.AddParameter("Reset", AnimatorControllerParameterType.Trigger);
        controller.AddParameter("GotoB1", AnimatorControllerParameterType.Trigger);
        controller.AddParameter("GotoC", AnimatorControllerParameterType.Trigger);

        // Add StateMachines
        var rootStateMachine = controller.layers[0].stateMachine;
        var stateMachineA = rootStateMachine.AddStateMachine("smA");
        var stateMachineB = rootStateMachine.AddStateMachine("smB");
        var stateMachineC = stateMachineB.AddStateMachine("smC");

        // Add States
        var stateA1 = stateMachineA.AddState("stateA1");
        var stateB1 = stateMachineB.AddState("stateB1");
        var stateB2 = stateMachineB.AddState("stateB2");
        stateMachineC.AddState("stateC1");
        var stateC2 = stateMachineC.AddState("stateC2"); // don’t add an entry transition, should entry to state by default

        // Add Transitions
        var exitTransition = stateA1.AddExitTransition();
        exitTransition.AddCondition(UnityEditor.Animations.AnimatorConditionMode.If, 0, "TransitionNow");
        exitTransition.duration = 0;

        var resetTransition = rootStateMachine.AddAnyStateTransition(stateA1);
        resetTransition.AddCondition(UnityEditor.Animations.AnimatorConditionMode.If, 0, "Reset");
        resetTransition.duration = 0;

        var transitionB1 = stateMachineB.AddEntryTransition(stateB1);
        transitionB1.AddCondition(UnityEditor.Animations.AnimatorConditionMode.If, 0, "GotoB1");
        stateMachineB.AddEntryTransition(stateB2);
        stateMachineC.defaultState = stateC2;
        var exitTransitionC2 = stateC2.AddExitTransition();
        exitTransitionC2.AddCondition(UnityEditor.Animations.AnimatorConditionMode.If, 0, "TransitionNow");
        exitTransitionC2.duration = 0;

        var stateMachineTransition = rootStateMachine.AddStateMachineTransition(stateMachineA, stateMachineC);
        stateMachineTransition.AddCondition(UnityEditor.Animations.AnimatorConditionMode.If, 0, "GotoC");
        rootStateMachine.AddStateMachineTransition(stateMachineA, stateMachineB);
    }
}
```

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


title: Unity raycast equivalent in Unreal

text:
# Question
Title: Unity raycast equivalent in Unreal
I've been moving from Unity to Unreal and I'm finding it difficult to grasp the Raycast (Trace) logic of Unreal.

The use case I'm trying to implement at the moment is to trace a ray and check if I hit a specific set of objects or if there are other objects blocking the line of sight.

In Unity, I would use Raycast, define a new specific Layer, set the object layer to it, create a LayerMask with that Layer and Raycast. I consider this method to be performant as the use of layer masks provide a form of optimization and most importantly I'm guaranteed that if the ray hits an object than it's because its layer is part of the layer mask and if I'm using multiple layers I could simply check which layer the hit object has.

In Unreal it's been harder to understand what are the solutions that offer better performance and are easier to use. The C++ documentation for Line Trace (channel or object type) is very poor when comparing to Unity's.

Can anyone shed some light on how to move from the Unity logic to Unreal using the above use case as an example?

# Answer
To do this in C++ / Unreal, you need to do the following either in (or called by) EventTick or on a timer:

```
// Set up parameters for getting the player viewport
    FVector PlayerViewPointLocation;
    FRotator PlayerViewPointRotation;

// Get player viewport and set these parameters
    GetWorld()->GetFirstPlayerController()->GetPlayerViewPoint(
    OUT PlayerViewPointLocation,
    OUT PlayerViewPointRotation
    );

// Parameter for how far out the the line trace reaches
    float Reach = 100.f;
    FVector LineTraceEnd = PlayerViewPointLocation + PlayerViewPointRotation.Vector() * Reach;

// Set parameters to use line tracing
    FHitResult Hit;
    FCollisionQueryParams TraceParams(FName(TEXT("")), false, GetOwner());  // false to ignore complex collisions and GetOwner() to ignore self

// Raycast out to this distance
    GetWorld()->LineTraceSingleByObjectType(
        OUT Hit,
        PlayerViewPointLocation,
        LineTraceEnd,
        FCollisionObjectQueryParams(ECollisionChannel::ECC_PhysicsBody),
        TraceParams
    );

// See what if anything has been hit and return what
    AActor* ActorHit = Hit.GetActor();

    if (ActorHit) {
        UE_LOG(LogTemp, Error, TEXT("Line trace has hit: %s"), *(ActorHit->GetName()))
    }

```

This will return the first actor that has been hit. If you want to find a specific actor, you can say:

```
if (ActorHit == Cast<AYourCustomActorClass>(YourCustomClass))

```

Which will only return true if the first item hit is the specific class you're looking for.
> 1 votes

---
Tags: unity, physics, unreal-4, raycasting
---


# Question
Title: What alternatives are there to using state machines to implement a board game?
I started a 2D Boardgame project and my partner decided to go with state pattern for the entire project so basically we sat down and thought about the states we need and we implemented like each scene in Unity has some states a state manager and state factory we are also using zenject. the problem is that i don't really like this approach because of the amount of code for a single scene and its kind of limited for example if i needed to add a new gamemode that needs more state or less whatever... i simply cant use this system and if the 2 modes are alike somehow the codes inside each state becomes huge so many nested if's for scene navigation or applying different logic for different modes. and i'm on a hunt for a good pattern to tackle this issue but i'm also afraid of over engineering. So i came here for help. I also thought about an event system for passing data between classes on the same scene and talking to each other via events but i don't know if it's good to for the enitre project or how i should handle scene navigation properly. so if events are the way to go tell me how can i use them.

Exmaple

so the game im working on is yahtzee and here are couple of the states some have controllers but others have the logic and states together and i know its a bad habit but i didnt have time :)

```
public class IdleState : IStateEntity
{
    [Inject] private InGameHandler _inGameHandler;

    public void Initialize()
    {
        LogController.Log("+Initialize State: InGame.Idle");
        if (_inGameHandler.GameModel.gameType != GameType.TutorialGame)
        {
            _inGameHandler.RollDiceButtonActive.SetValueAndForceNotify(true);
        }
    }
    public void Dispose()
    {
        LogController.Log("-Dispose State: InGame.Idle");
    }
    public class Factory : PlaceholderFactory<IdleState>
    {
    }
}

```

and IStateEntity

```
public interface IStateEntity
{
    void Initialize();
    void Dispose();
}

```

so as you can see thats how my states look like and here is a state manager

```
public class InGameStateManager : IInitializable
{
    [Inject] private GameStateManager _gameStateManager;
    public InGameStateEntity _currentState = InGameStateEntity.WaitForStart;
    public InGameStateEntity _previousState;
    private readonly InGameStateFactory _inGameStateFactory;
    private IStateEntity _inGameStateEntity;

    public InGameStateManager(InGameStateFactory inGameStateFactory)
    {
        _inGameStateFactory = inGameStateFactory;
    }

    public void Initialize()
    {
        if(_gameStateManager.CurrentState.Value !=GameStateEntity.Tutorial )
            ChangeState(InGameStateEntity.Intro);

    }

    public void ChangeState(InGameStateEntity stateEntity)
    {
        //if we're in already in stateEntity dont change it
        if (stateEntity == _currentState)
        {
            LogController.Log("Already in State: " + _currentState);
            return;
        }

        //if we're in some state and this not the first time we're entering this phase then dispose current state and make it null
        if (_inGameStateEntity != null)
        {
            _inGameStateEntity.Dispose();
            _inGameStateEntity = null;
        }

        _previousState = _currentState;
        _currentState = stateEntity;

        //initializing stateEntity and assigning it to _InGameStateEntity which represents the current state.
        Debug.Log("from state " + _previousState + " to " + stateEntity);
        _inGameStateEntity = _inGameStateFactory.CreateState(stateEntity);
    }
}

```

and InGameStateEntity is an enum which is all the states for my gameplay

```
public enum InGameStateEntity
{
    WaitForStart,
    Intro,
    OpponentMove,
    Idle,
    RollDice,
    BonusRoll,
    Yahtzee,
    PrimarySubmission,
    CheckItem,
    FinalSubmission,
    CheckSectionBonus,
    SaveProgress,
    GameList,
    Outro,
    GetMoreDice,
    ResetTurn
}

```

I didn't want to send it but whatever i really need help i'm kind of a newbie so don't judge me this is my first real project and the code for intro is so messed up lemme show you...

```
public class IntroState : IStateEntity
{
    [Inject] private InGameIntroCanvasController.Factory _introCanvasControllerFactory;
    [Inject] private InGameStateManager _inGameStateManager;
    [Inject] private InGameHandler _inGameHandler;
    [Inject] private DicePlaceHolderManager _dicePlaceHolderManager;
    private InGameIntroCanvasController _controller;
    [Inject] private PlayerPrefsManager _playerPrefsManager;
    [Inject] private DiceRollController _diceRollController;
    [Inject] private GlobalVariables _globalVariables;
    [Inject] private SFXManager _sfxManager;
    [Inject] private InGameSprites _inGameSprites;

    public void Initialize()
    {
        LogController.Log("+Initialize State: InGame.Intro");
        _dicePlaceHolderManager.Initialize();

        if (_inGameHandler.IsDiceWorld.Value)
        {
            if (!_inGameHandler.GameModel.hasIntroShown)
            {
                ShowIntro();
                Observable.FromCoroutine(() => IntroCountDown(3.5f)).Subscribe();
            }
            else
                DiceWorldIntroWithoutEnumerator();
            return;
        }
        if (_inGameHandler.GameModel.gameType == GameType.TutorialGame)
        {
            if (!_inGameHandler.GameModel.hasIntroShown)
            {
                ShowIntro();
                Observable.FromCoroutine(() => IntroCountDown(3.5f)).Subscribe();
            }
            else
                DiceWorldIntroWithoutEnumerator();
            return;
        }
        if (!_inGameHandler.GameModel.hasIntroShown && _inGameHandler.IsPlayerTurn.Value)
        {
           ShowIntro();
            Observable.FromCoroutine(() => IntroCountDown(4)).Subscribe();
        }
        else
            IntroWithoutEnumerator();
    }

    private void ShowIntro()
    {
        _inGameHandler.GameModel.hasIntroShown = true;
        _playerPrefsManager.GameModelData.GameModel = _inGameHandler.GameModel;
        _inGameHandler.RollDiceButtonActive.SetValueAndForceNotify(false);
        _controller = _introCanvasControllerFactory.Create();
        string nickname = _globalVariables.UserProfile.Nickname;
        int level = _globalVariables.UserProfile.Level;
        _controller.playerProfile.nickName.text = nickname;
        _controller.playerProfile.level.text = level.ToString();

        if (_inGameHandler.IsDiceWorld.Value)
        {
            SetBossAvatar(_globalVariables.CurrentRegion);
        }
        else if (_inGameHandler.GameModel.gameType == GameType.TutorialGame)
        {
            SetPlayerAvatar(_inGameSprites.DogAvatar);
            SetOpponentAvatar(_inGameSprites.CatAvatar);
        }
        nickname = _inGameHandler.GameModel.opponent.nickname;
        level = _inGameHandler.GameModel.opponent.level;
        _controller.opponentProfile.nickName.text = nickname == null || nickname.Equals("") ? "در حال جستجو" : nickname;
        _controller.opponentProfile.level.text = (level == 0  ? 1 : level).ToString();

        _controller.playerProfile.SelectedDice
            .DoIntroMoveIn()
            .Join(_controller.opponentProfile.SelectedDice
                .DoIntroMoveIn())
            .OnStart(() =>
            {
                Observable.FromCoroutine(() => _controller.PlayParticle(.8f)).Subscribe();
                _controller.PrizePlaceholderUp(.5f);
                _sfxManager.PlayInGameIntro(.5f);
            });

        // _controller.playerProfile.SelectedDice.ProfileMoveIn()
        //     .Join(_controller.opponentProfile.ProfileMoveIn())
        //     .OnStart(() =>
        //     {
        //
        //     });
    }

    private void SetBossAvatar(RegionData region)
    {

        if(region.boss.avatar == null)
            return;
        _controller.opponentProfile.avatar.sprite = region.boss.avatar;
    }

    private void SetOpponentAvatar(Sprite sprite)
    {
        _controller.opponentProfile.avatar.sprite = sprite;
    }
    private void SetPlayerAvatar(Sprite sprite)
    {
        _controller.playerProfile.avatar.sprite = sprite;
    }

    void DiceWorldIntroWithoutEnumerator()
    {
        _diceRollController.ShowLastRolledDice();
        _inGameStateManager.ChangeState(_inGameHandler.PlayerTurn() == false
            ? InGameStateEntity.OpponentMove
            : InGameStateEntity.Idle);
    }

    void IntroWithoutEnumerator()
    {
        if (_inGameHandler.IsPlayerTurn.Value)
        {
            if (_inGameHandler.GameModel.lastUpdatedCell != null && !_inGameHandler.GameModel.hasOpponentMoveShown)
                _inGameStateManager.ChangeState(InGameStateEntity.OpponentMove);
            else
            {
                _diceRollController.ShowLastRolledDice();
                _inGameStateManager.ChangeState(_inGameHandler.GameModel.isWaiting
                    ? InGameStateEntity.GameList
                    : InGameStateEntity.Idle);
            }
        }
        else
        {
            if (!_inGameHandler.HasOpponentMoved())
            {
                _inGameHandler.RollDiceButtonActive.SetValueAndForceNotify(false);
                _inGameHandler.PlayButtonActive.SetValueAndForceNotify(false);
                // _inGameHandler.OpponentAvailablePlaceHolders[_inGameHandler.GameModelData.lastUpdatedCell.cellId].opponentPlaceHolder.GetComponentInChildren<RTLTextMeshPro>().text = _inGameHandler.GameModelData.lastUpdatedCell.score + "";
                _inGameStateManager.ChangeState(InGameStateEntity.GameList);
            }
            else if(_inGameHandler.GameModel.hasOpponentMoveShown)
            {
                _inGameHandler.RollDiceButtonActive.SetValueAndForceNotify(false);
                _inGameHandler.PlayButtonActive.SetValueAndForceNotify(false);
                _inGameStateManager.ChangeState(InGameStateEntity.OpponentMove);
            }
        }
    }
    IEnumerator IntroCountDown(float delay)
    {
        yield return new WaitForSeconds(delay);
        _diceRollController.ShowLastRolledDice();
        if (_inGameHandler.IsDiceWorld.Value)
        {
            _inGameStateManager.ChangeState(_inGameHandler.IsPlayerTurn.Value
                ? InGameStateEntity.Idle
                : InGameStateEntity.OpponentMove);
        }
        else if (_inGameHandler.IsPlayerTurn.Value)
        {
            _inGameStateManager.ChangeState(_inGameHandler.GameModel.lastUpdatedCell != null
                ? InGameStateEntity.OpponentMove
                : InGameStateEntity.Idle);
        }
        else
        {
            if (!_inGameHandler.HasOpponentMoved())
            {
                _inGameHandler.RollDiceButtonActive.SetValueAndForceNotify(false);
                _inGameHandler.PlayButtonActive.SetValueAndForceNotify(false);
                _inGameHandler.OpponentAvailablePlaceHolders[_inGameHandler.GameModel.lastUpdatedCell.cellId].opponentPlaceHolder.GetComponentInChildren<RTLTextMeshPro>().text = _inGameHandler.GameModel.lastUpdatedCell.score + "";
                _inGameStateManager.ChangeState(InGameStateEntity.GameList);
            }
            else
            {
                _inGameHandler.RollDiceButtonActive.SetValueAndForceNotify(false);
                _inGameHandler.PlayButtonActive.SetValueAndForceNotify(false);
                _inGameStateManager.ChangeState(InGameStateEntity.OpponentMove);
            }

        }
    }

    public void Dispose()
    {
        if(_controller != null)
            _controller.Destroy();
        LogController.Log("-Dispose State: InGame.Intro");
    }
    public class Factory : PlaceholderFactory<IntroState>
    {
    }
}

```

I know that part of it is my fault for not separating the controllers from states but i really dont like states or if this is ok what is the best approach for making it reusable. just think about adding new intro i need to add bunch of if statements if based on the game type

BTW InGameHandler is a gameobject in the ingame scene and all the data i need for the game is inside that kinda silly and if you know a better way lemme know and dont be hard on me ok ? :))))

InGameStateFactory:

```
public class InGameStateFactory
{
    [Inject] private IntroState.Factory _introStateFactory;
    [Inject] private OpponentMoveState.Factory _opponentMoveStateFactory;
    [Inject] private IdleState.Factory _idleStateFactory;
    [Inject] private RollDiceState.Factory _rollDiceStateFactory;
    [Inject] private BonusRollState.Factory _bonusRollStateFactory;
    [Inject] private DicerState.Factory _yahtzeeStateFactory;
    [Inject] private PrimarySubmissionState.Factory _primarySubmissionStateFactory;
    [Inject] private CheckItemState.Factory _checkItemStateFactory;
    [Inject] private FinalSubmissionState.Factory _finalSubmissionStateFactory;
    [Inject] private CheckSectionBonusState.Factory _checkSectionBonusStateFactory;
    [Inject] private SaveProgressState.Factory _saveProgressStateFactory;
    [Inject] private GameListState.Factory _gameListStateFactory;
    [Inject] private OutroState.Factory _outroStateFactory;
    [Inject] private ResetTurnState.Factory _resetTurnFactory;
    [Inject] private GetMoreDiceState.Factory _getMoreDiceFactory;

    public IStateEntity CreateState(InGameStateEntity inGameStateEntity)
    {
        IStateEntity stateEntity = null;
        switch (inGameStateEntity)
        {
            case InGameStateEntity.Intro:
                stateEntity = _introStateFactory.Create();
                break;
            case InGameStateEntity.OpponentMove:
                stateEntity = _opponentMoveStateFactory.Create();
                break;
            case InGameStateEntity.Idle:
                stateEntity = _idleStateFactory.Create();
                break;
            case InGameStateEntity.RollDice:
                stateEntity = _rollDiceStateFactory.Create();
                break;
            case InGameStateEntity.BonusRoll:
                stateEntity = _bonusRollStateFactory.Create();
                break;
            case InGameStateEntity.Dicer:
                stateEntity = _yahtzeeStateFactory.Create();
                break;
            case InGameStateEntity.PrimarySubmission:
                stateEntity = _primarySubmissionStateFactory.Create();
                break;
            case InGameStateEntity.CheckItem:
                stateEntity = _checkItemStateFactory.Create();
                break;
            case InGameStateEntity.FinalSubmission:
                stateEntity = _finalSubmissionStateFactory.Create();
                break;
            case InGameStateEntity.CheckSectionBonus:
                stateEntity = _checkSectionBonusStateFactory.Create();
                break;
            case InGameStateEntity.SaveProgress:
                stateEntity = _saveProgressStateFactory.Create();
                break;
            case InGameStateEntity.GameList:
                stateEntity = _gameListStateFactory.Create();
                break;
            case InGameStateEntity.Outro:
                stateEntity = _outroStateFactory.Create();
                break;
            case InGameStateEntity.ResetTurn:
                stateEntity = _resetTurnFactory.Create();
                break;
            case InGameStateEntity.GetMoreDice:
                stateEntity = _getMoreDiceFactory.Create();
                break;
            default:
                throw new ArgumentOutOfRangeException(nameof(inGameStateEntity), inGameStateEntity, null);
        }
        if (stateEntity == null)
                throw Assert.CreateException("InGameState Not Found And This Code Should Not Be Reached There :/ !");
        stateEntity.Initialize();
        return stateEntity;
    }

```

PS: i'm using zenject , unirx and the game is connected to a server.

# Answer
> 0 votes
> Here is an idea: 1. extract methods to reduce code duplication (instead of having the same code in two places, make a method and call it in two places). 2. configure your game state factory to consider the game type. Then you can have a base game state entity for each game state, and derive (read: inherit) from it to make specialized game state entities for each game type. I'm assuming game type changes less often than game state. 3. Those methods you extracted? Yeah, make them virtual, so the derived types can override them. I hope that is enough to get rid of most nested if statements.

Theraot had a good point the first part helped me to figure out how make the code cleaner by extracting different logic into new files and adding a controller for the state so state should only calls the controller and nothing more. then the controller decides what to do with view, models and most importantly the FSM. so based on this states cant change FSM's current. and after that i creted.

**Intro:**

So i ended up changing the state factory and add more files that derive from IntroState as the base class and made the Initialize and Dispose methods virtual so my Factory looks something like this now

```
public class InGameStateFactory
{
    [Inject] private GlobalVariables _globalVariables;

    //intro
    [Inject] private IntroState.Factory _introStateFactory;
    [Inject] private NoIntroState.Factory _noIntroStateFactory;
    [Inject] private CampaignIntroState.Factory _campaignIntroStateFactory;
    [Inject] private TutorialIntroState.Factory _tutorialStateFactory;

    [Inject] private OpponentMoveState.Factory _opponentMoveStateFactory;
    [Inject] private IdleState.Factory _idleStateFactory;
    [Inject] private RollDiceState.Factory _rollDiceStateFactory;
    [Inject] private BonusRollState.Factory _bonusRollStateFactory;
    [Inject] private DicerState.Factory _yahtzeeStateFactory;
    [Inject] private PrimarySubmissionState.Factory _primarySubmissionStateFactory;
    [Inject] private CheckItemState.Factory _checkItemStateFactory;
    [Inject] private FinalSubmissionState.Factory _finalSubmissionStateFactory;
    [Inject] private CheckSectionBonusState.Factory _checkSectionBonusStateFactory;
    [Inject] private SaveProgressState.Factory _saveProgressStateFactory;
    [Inject] private GameListState.Factory _gameListStateFactory;
    [Inject] private OutroState.Factory _outroStateFactory;
    [Inject] private ResetTurnState.Factory _resetTurnFactory;
    [Inject] private GetMoreDiceState.Factory _getMoreDiceFactory;

    public IStateEntity CreateState(InGameStateEntity inGameStateEntity)
    {
        IStateEntity stateEntity = null;
        switch (inGameStateEntity)
        {
            case InGameStateEntity.Intro:
                stateEntity = ChooseIntroState();
                break;
            case InGameStateEntity.OpponentMove:
                stateEntity = _opponentMoveStateFactory.Create();
                break;
            case InGameStateEntity.Idle:
                stateEntity = _idleStateFactory.Create();
                break;
            case InGameStateEntity.RollDice:
                stateEntity = _rollDiceStateFactory.Create();
                break;
            case InGameStateEntity.BonusRoll:
                stateEntity = _bonusRollStateFactory.Create();
                break;
            case InGameStateEntity.Dicer:
                stateEntity = _yahtzeeStateFactory.Create();
                break;
            case InGameStateEntity.PrimarySubmission:
                stateEntity = _primarySubmissionStateFactory.Create();
                break;
            case InGameStateEntity.CheckItem:
                stateEntity = _checkItemStateFactory.Create();
                break;
            case InGameStateEntity.FinalSubmission:
                stateEntity = _finalSubmissionStateFactory.Create();
                break;
            case InGameStateEntity.CheckSectionBonus:
                stateEntity = _checkSectionBonusStateFactory.Create();
                break;
            case InGameStateEntity.SaveProgress:
                stateEntity = _saveProgressStateFactory.Create();
                break;
            case InGameStateEntity.GameList:
                stateEntity = _gameListStateFactory.Create();
                break;
            case InGameStateEntity.Outro:
                stateEntity = _outroStateFactory.Create();
                break;
            case InGameStateEntity.ResetTurn:
                stateEntity = _resetTurnFactory.Create();
                break;
            case InGameStateEntity.GetMoreDice:
                stateEntity = _getMoreDiceFactory.Create();
                break;
            default:
                throw new ArgumentOutOfRangeException(nameof(inGameStateEntity), inGameStateEntity, null);
        }
        if (stateEntity == null)
                throw Assert.CreateException("InGameState Not Found And This Code Should Not Be Reached There :/ !");
        stateEntity.Initialize();
        return stateEntity;
    }

    private IntroState ChooseIntroState()
    {
        var type = _globalVariables.CurrentPvPGameData.gameType;

        var hasShownIntro = _globalVariables.CurrentPvPGameData.hasIntroShown;
        if (hasShownIntro)
            return _noIntroStateFactory.Create();

        switch (type)
        {
            case GameType.Campaing:
                return _diceWorldIntroStateFactory.Create();
            case GameType.PvP:
                return _introStateFactory.Create();
            case GameType.Tutorial:
                return _tutorialStateFactory.Create();
            default:
                throw new ArgumentOutOfRangeException();
        }
    }

```

This with extracting code and move them to different files cleaned states like a boss. My next problem however was complicated models and static. i had only one model for all of the modes so for example i didn't have a model for creating a one-player-only game like tutorial and my approach was to set the opponent as null and preform null checks left and right. First of all **don't do that!** Create a base model that contains the minimum data you need the create classes deriving this model with additional data. This however works if your models have some similarity if every thing is different you need a new model for sure.

**Thank You.**

# Answer
> 1 votes
I think the problem could be that your `IStateEntity` classes are god objects for their respective states. They know too much, do too much and get too far into details about how these things happen. You could make them a lot more lightweight and modular by delegating most of their responsibilities to other MonoBehaviours.

When I use the state-machine pattern in Unity, then my states are not so much concerned with what happens in the states, but rather with what that state does and does not have compared to other states. So my states usually don't do much more than call `.SetActive(true)` and `.SetActive(false)` on a couple game objects. These objects then take care of what actually happens in the states while they are active.

Taking the intro scene, for example: The "boss avatar" logic should really be an own script. The state would just enable the "boss avatar" gameObject. That gameObject would then have a script with an `OnEnable` function which decides what sprite to pick. This has the advantage that you can easily reuse this gameObject for another state. It contains its own logic, so you don't need to duplicate its logic over all the states which use it.

Same with the separate sub-state-machine in `IntroWithoutEnumerator` which handles the logic for the intro. I would really put that in a separate script. The intro-state would enable the "introController" gameObject and the `IntroController` MonoBehaviour on that object would then manage the intro logic. That script would also decide when to transition to the next state. So no `IntroCountDown`. That logic belongs in the IntroController.

It also appears to me that this intro logic duplicates a lot of the logic which might also be used by the actual game. In that case it might make sense to move the duplicate logic into an own gameObject which exists in both states. The logic which is specific to the intro and the logic which is specific to the actual game would go into two separate objects.

And why do you have a `InGameIntroCanvasController` which apparently doesn't have control over anything?

```
    string nickname = _globalVariables.UserProfile.Nickname;
    int level = _globalVariables.UserProfile.Level;
    _controller.playerProfile.nickName.text = nickname;
    _controller.playerProfile.level.text = level.ToString();
    _controller.opponentProfile.nickName.text = nickname == null || nickname.Equals("") ? "در حال جستجو" : nickname;
    _controller.opponentProfile.level.text = (level == 0  ? 1 : level).ToString();

```

These all appear to be very tightly coupled calls which require that the state knows a lot of details about the internal workings of the canvas controller. The purpose of the controller pattern is that you only need to tell the controller object very high-level information about what's going on and then the controller decides on its own what to do with that information. So these lines should be moved into the controller. All this controller seems to need to execute these lines is `_globalVariables.UserProfile`. You could just pass to it when you create it and then let the controller decide internally what to do with that information. Or considering that it's a dependency which you can inject anywhere, you could also have the controller obtain that dependency itself.

---
Tags: unity, design-patterns, scalability
---


# Question
Title: Handling of Slopes for a Character Controller
I recently moved from Bullet to PhysX to see if it would be a better solution for my game engine, and so far it is. The only problem that I'm having, which is part of the reason that I switched is with the character controller. The build in one is pretty good, but I've run into an issue when I walk down a slope (although up is fine). Because the player walks faster than gravity pulls him down (I set it to 0 when he is on the ground), he detaches from the slope, which obviously is not desirable.

I've considered and tested several ways to fix this. One idea that I had was to check if there was ground below the character once he moved in the xz-direction, with a distance less than or equal to to the magnitude of that vector because I decided that a 45º slope was what the character could not walk up. That had a huge amount of problems and resulted in a lot of teleporting.

Then I tried to make it so when the player was on the ground that a really high gravity would be applied to keep him on the slope. This also didn't work because if the character was on the ground and then moved over a cliff, he was on the ground before he walked over the cliff he would be teleported down.

I'm really not sure how to progress here because logically the problem has stumped me. I took a look at some of the behavior of the Unreal character and it doesn't seem to suffer from any of these problems and it uses PhysX, so obviously they found a solution.

If anyone has any ideas, I would appreciate it.

Thanks

# Answer
For anyone who hits this problem in the future, a possible solution is to implement a "**surface follower**". It's one of those special-case movement things that will save you a lot of heartache to know about.

Instead of relying on physics to handle slopes, you branch into your surface following code, which uses e.g. a PhysX world collision raycast to find the ground directly beneath the mover. It then snaps the follower's position to the ground it hits, if the hit point is within a set threshold. If the surface is too far below the character, put them into "falling mode", and let them fall until their capsule hits the ground (i.e. don't snap to surface as soon as it gets to the threshold).

The length of the raycast should be long enough such that stairs and slopes within desired steepness should not be detected as causing "falling mode".

By having this special-case code, your game is now much more tuneable, because you can pick hard numbers for how steep slopes can be, and reliably see following on those slopes.

Surface followers are useful even in 2D, where small boundaries between collision objects can cause hitching.
> 3 votes

---
Tags: character, physx
---


# Question
Title: How do you refer to the objects covering the ground?
Newbye here. In the industry lingo, what is the best way to indicate the objects covering the ground (trees, rocks, ...)? Is `props` OK?

# Answer
> 0 votes
I would say `game assets` is definitely not specific enough. Everything in your game is an asset — the terrain itself, the shaders and textures it uses, every JSON or XML data file.

Similarly, I'd argue `props` is also too broad. A chair or a sword could reasonably be called "props" too, but they're not scattered terrain items like you're describing.

(Though to be fair, maybe your game has no chairs or swords or any other variety of prop, and so in this case it's OK to use a broad term)

If your game has different biomes that need to scatter a different mix of grass and trees and rocks, I'd be tempted to call these "biome objects" — but that might be needlessly complex if you don't have multiple biomes.

Some other options: (none of these are particularly standard, just looking for phrases that describe your use case)

* Terrain Dressing
* Scatterables
* Debris
* Ground Cover

---
Tags: terminology, tree
---


# Question
Title: Unreal modular character tutorial errors
I'm trying to follow the modular character tutorial for Unreal from this link Specifically the mesh merge portion. How ever the code that is provided seems to not be working.

For example when I add this piece of code :

```
USTRUCT(BlueprintType)
struct VR_API FSkelMeshMergeSectionMapping_BP
{
    GENERATED_BODY()
        UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Mesh Merge Params")
        TArray<type> SectionIDs;
};

```

I get the following error : `Unrecognized type 'type' - type must be a UCLASS, USTRUCT or UENUM`

I;m guessing I should provide a certain type in the \<\> but I have no idea what it should be. I've been using unreal only for 2 days now so if anyone can help me figure this tutorial out and get it working I would be thankful.

# Answer
> 1 votes
`TArray` is a template type in Unreal, which means you need to give it template parameters (within the angle brackets) when declaring one. In the case of `TArray`, you need *at a minimum* to indicate the type of data stored in the array. What you've written in your example is "a `TArray` of instances of `type`" and the error is telling you that there is no type named `type`.

"Section IDs" sound like they'd be integers, so you should probably write `TArray<int>` to create an array of `int`s. Or whichever other integer type is appropriate.

(Other than `TArray` itself, which is an Unreal type, this is a general C++ problem regarding templates, so if you are looking for more background you don't need to look for Unreal-specific information... although the specific error you are seeing is an Unreal-specific one arising from how it parses your code and applies extra validation to `UPROPERTY` members, in this case putting additional constraints on the type parameter. `TArray` is roughly analogous in intent to the C++ standard library type `std::vector`.)

---

Reading through that tutorial link in more detail, much of the code samples seem to suffer from errors like this, including several declarations of `TArray` with no template parameters at all (which won't compile) as well as some stray characters at the end of some of the snippets.

# Answer
> 3 votes
Not sure if you got this, but I worked it out pretty sure...

The goal is they're trying to make the existing ones in *SkeletalMeshMerge.h* editable on the blueprint side, so basically going into that file I could see what the arrays were.

So you want the **FSkelMeshMergeSectionMapping\_BP** to contain *int32*'s:

```
USTRUCT(BlueprintType)
struct MULTIPLAYERARENA_API FSkelMeshMergeSectionMapping_BP
{
    GENERATED_BODY()
        /** Indices to final section entries of the merged skeletal mesh */
        UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Mesh Merge Params")
        TArray<int32> SectionIDs;
};

```

and the **FSkelMeshMergeSectionMapping\_BP** to contain *FTransform*'s:

```
USTRUCT(BlueprintType)
struct MULTIPLAYERARENA_API FSkelMeshMergeUVTransform
{
    GENERATED_BODY()
        /** A list of how UVs should be transformed on a given mesh, where index represents a specific UV channel. */
        UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Mesh Merge Params")
        TArray<FTransform> UVTransforms;
};

```

and the **FSkelMeshMergeUVTransformMapping** to contain *FSkelMeshMergeUVTransform*'s:

```
USTRUCT(BlueprintType)
struct MULTIPLAYERARENA_API FSkelMeshMergeUVTransformMapping
{
    GENERATED_BODY()
        /** For each UV channel on each mesh, how the UVS should be transformed. */
        UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Mesh Merge Params")
        TArray<FSkelMeshMergeUVTransform> UVTransformsPerMesh;
};

```

finally in the struct params themselves, like so:

```
USTRUCT(BlueprintType)
struct MULTIPLAYERARENA_API FSkeletalMeshMergeParams
{
    GENERATED_BODY()
        FSkeletalMeshMergeParams()
    {
        MeshSectionMappings = TArray<FSkelMeshMergeSectionMapping_BP>();
        UVTransformsPerMesh = TArray<FSkelMeshMergeUVTransformMapping>();
        StripTopLODS = 0;
        bNeedsCpuAccess = false;
        bSkeletonBefore = false;
        Skeleton = nullptr;
    }
    // An optional array to map sections from the source meshes to merged section entries
    UPROPERTY(EditAnywhere, BlueprintReadWrite)
        TArray<FSkelMeshMergeSectionMapping_BP> MeshSectionMappings;
    // An optional array to transform the UVs in each mesh
    UPROPERTY(EditAnywhere, BlueprintReadWrite)
        TArray<FSkelMeshMergeUVTransformMapping> UVTransformsPerMesh;
    // The list of skeletal meshes to merge.
    UPROPERTY(EditAnywhere, BlueprintReadWrite)
        TArray<class USkeletalMesh*> MeshesToMerge;
    // The number of high LODs to remove from input meshes
    UPROPERTY(EditAnywhere, BlueprintReadWrite)
        int32 StripTopLODS;
    // Whether or not the resulting mesh needs to be accessed by the CPU for any reason (e.g. for spawning particle effects).
    UPROPERTY(EditAnywhere, BlueprintReadWrite)
        uint32 bNeedsCpuAccess : 1;
    // Update skeleton before merge. Otherwise, update after.
    // Skeleton must also be provided.
    UPROPERTY(EditAnywhere, BlueprintReadWrite)
        uint32 bSkeletonBefore : 1;
    // Skeleton that will be used for the merged mesh.
    // Leave empty if the generated skeleton is OK.
    UPROPERTY(EditAnywhere, BlueprintReadOnly)
        class USkeleton* Skeleton;
};

```

It compiles and it works with meshes, but I haven't used these optional parameters so don't know if they actually work

# Answer
> 1 votes
To add to Alex Coultas's solution, the final UProperty in the **FSkeletalMeshMergeParams** struct has to be *BlueprintReadWrite* like the others, otherwise you get yellow warnings in the output box.

```
// Skeleton that will be used for the merged mesh.
// Leave empty if the generated skeleton is OK.
UPROPERTY(EditAnywhere, BlueprintReadWrite)
    class USkeleton* Skeleton;

```

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


title: Making an enemy follow player (Unity)

text:
# Question
Title: Making an enemy follow player (Unity)
I'm working on coding enemy ai for a star fox-esqe shooter and I need the enemy to approach the player, stay a certain distance away and stay in front of them until destroyed. I can get the enemy to approach the player and I can get the enemy to stay a certain distance from the player but I'm not sure how to get the enemy to actually stay in front of the player. For a bit of extra information, the player makes a number of sharp turns and the like throughout the level. Also, as a stand in I tried simply causing the enemy to parent to the player within a certain radius but that causes clipping issues with buildings and the ground.

```
public class EnemyCar: MonoBehaviour
{
    public float safeDistance = 20f; // How close the enemy can get to the player

    // ...

    // Update is called once per frame
    void Update()
    {
        transform.LookAt(player.transform);

        Vector3 targertLocation = player.transform.position - transform.position;
        float distance = targertLocation.magnitude;

        // Decrease our speed as we get closer
        rb.AddRelativeForce(Vector3.forward * Mathf.Clamp((distance - 30) / 50, 0f, 1f) * thrust);
    }
}

```

# Answer
> 0 votes
You can do this by keeping track of a desired position relative to the player's view, or current frame of reference:

```
Vector3 desiredOffsetFromPlayer;

```

You can update this variable to make it approach the player or follow any arbitrary curve in its holding pattern in front of the player.

Then you can transform this into an actual world position like so:

```
Vector3 desiredPosition = player.transform.TransformPoint(desiredOffsetFromPlayer);

```

Now you can apply your navigation forces to seek toward that point (in FixedUpdate, for consistency regardless of framerate), or use physics queries to find the closest you can get to that point without clipping an obstacle.

Here's one potential way to do it:

```
void FixedUpdate() {
    // If you want to animate the holding position, update desired offset here.

    Vector3 desiredPosition = player.transform.TransformPoint(desiredOffsetFromPlayer);

    // How do we need to move to reach our target in this physics step?
    // You can also add the player velocity here to match course with them.
    Vector3 desiredVelocity = (desiredPosition - rb.position)/Time.deltaTime;

    // Clamp this within what our vessel is physically allowed to do.
    // (Here I assume we can thrust in any direction without turning around first)
    float maxDeltaV = maxThrust * Time.deltaTime;
    Vector3 deltaV = Vector3.ClampMagnitude(desiredVelocity - rb.velocity, maxDeltaV);

    // Accelerate to apply the needed correction.
    rb.AddForce(deltaV, ForceMode.VelocityChange);
}

```

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


# Question
Title: Calculate gravity between two intersecting bodies
I've been working on a 2D gravity simulator for some time and I'd like to add some surrealism to it by creating planets that can't collide with other planets (passing right through them).

The problem is, as distance between two bodies approaches zero, gravity goes to infinity - causing planets to slingshot when they're intersecting. Stopping gravity from being applied for a pair of bodies as soon as they touch looks odd as their velocity will suddenly go from accelerating to constant until they get to the other side.

Is there a function that gives me the best of both worlds or should I just leave the planets not being affected by gravity while intersecting other bodies?

# Answer
> 1 votes
Consider doing what you're currently doing and disable the "real" gravity simulation once the two bodies overlap in 2D. **But** rather than set the velocity to a constant, keep applying whatever the most-recently computed acceleration of each body was. I'd guess that cheating the formula in this way would be less noticeable to a player?

# Answer
> 1 votes
Make your simulation "2 and a half" dimensional by giving each body a Z depth. Z is ignored for draw location (only X and Y apply there), but is used for calculating distance between objects for gravity.

Having depth adds an actual separation between overlapping bodies, thus avoiding the zero distance / infinite gravity situation. Different Z values will give you different amounts of interaction. It also lets you detect actual collisions of items if they share the same Z depth.

This Z depth also allows you to choose rendering order, and even apply scaling based on Z distance.

# Answer
> 0 votes
Almost two years later, I noticed there's a better and more realistic way of calculating the gravity being applied for two intersecting bodies.

Note that this is more unstable than previous answers, and will usually require a high iteration count to maintain energy conservation.

If one picks a point inside a hollow planet, it's known that no gravity will be applied to this point. With that in mind we can safely assume that, for any given point `p1` of planet A that is intersecting with planet B, any given point of planet B `p2` that is further away from its center than `p1` is, isn't going to exert any gravity on `p1`.

`Point A` refers to any point in the pink planet's surface that is in the intersection with the blue planet

What this means for our calculation is that we can first calculate the point of collision between the two masses, then calculate the gravity as if their radii were only big enough so to touch the point of collision (so their radii is the distance between the planet's center and the point of collision). This will make it so the mass never high enough to push gravity to infinity, no matter the distance between the centers.

*"Corrected masses"* are only used when solving for gravity

---
Tags: 2d, game-design, simulations
---


# Question
Title: How to make child object a member of two parents in unity?
So I have an parent game object that has multiple objects.

This format is desirable:

```
-GameObject
    -object1 (abstract)
        -subobject1

    -object2 (abstract)
        -subobject2

    -object3 (abstract)
        -subobject1
        -subobject2
// There are two objects in the scene, subobject1 and subobject2

```

The problem is when i drag and drop one subobject from an object it removes it from the other object. When i copy the subobjects to another object, there are now two.

I hope this makes sense.

# Answer
You can't do that. The object scene graph is a tree. Each object can have exactly one parent.

But what you can do is reference the same game object from multiple MonoBehaviours.

When a script has a `public GameObject something`, then multiple instances of that script can reference the same object.

If you want to simulate a rubic's cube, then you could do that by making both the 9 slices and the 26 cubes direct children of the cube game object. The script of the slices would then have a `public GameObject[] cubes` referencing the cubes which are currently part of that slice. The initial assignment of cubes to slices can be done in the inspector. After rotating a slice, you would have the script look at the four other slices which are also affected by that rotation and change which cubes are now part of which slice.
> 2 votes

---
Tags: unity, heirarchy
---


# Question
Title: Using transform.position on an instantiated prefab in an array one by one
So I've been trying to make an already instantiated prefab to fall one by one in my scene. First they instantiate hidden in the camera and that works so far. But when I apply transform.position on them they don't seem to move. Here's the code

```
   public GameObject[] enemySpawn;

void Start()
{
    for (int i = 0; i < enemySpawn.Length; i++)
    {
        Instantiate<GameObject>(enemySpawn[i], new Vector2(-4,6),Quaternion.identity);

    }

    StartCoroutine(spawnBlades());
}

void Update()
{

}
IEnumerator spawnBlades() {
for(int i = 0; i<6; i++ )
        enemySpawn[i].transform.position = new Vector3(Random.Range(-3, 3), 6);
    yield return new WaitForSeconds(0.5f);

}

```

# Answer
Nevermind i got it. You have to assign it to another gameobject array like so

```
public GameObject[] enemySpawn;
public GameObject[] enemy;
for (int i = 0; i < enemySpawn.Length; i++)
{
   enemy[i] = Instantiate<GameObject>(enemySpawn[i], new Vector2(-4,6),Quaternion.identity);

}

```
> 0 votes

---
Tags: unity, 2d, movement
---


title: How to draw with OnPreviewGUI?

text:
# Question
Title: How to draw with OnPreviewGUI?
I want to implement custom preview for GraphViz files.

I created CustomEditor stub for that based on this beautiful gist: https://gist.github.com/prodigga/53ab658e1a818cd4ddfd#file-meshfilterpreview-part2-cs

```
using UnityEditor;
using UnityEngine;

/// <summary>
/// Inspector for .SVG assets
/// </summary>
[CustomEditor(typeof(DefaultAsset))]
public class GraphVizEditor : Editor
{
    public override bool HasPreviewGUI()
    {
        return true;
    }

    public override void OnPreviewGUI(Rect r, GUIStyle background)
    {
        var path = AssetDatabase.GetAssetPath(target);
        if (path.EndsWith(".gv"))
        {
            var texture = new Texture2D(1, 1);
            texture.SetPixel(1, 1, Color.green);
            GUI.DrawTexture(r, texture, ScaleMode.StretchToFill, false);
        }
    }
}

```

I expect to see green preview area, but preview keeps having gray background:

How to fix this and actually draw custom texture to a preview area?

# Answer
> 0 votes
Forgot to call Texture.Apply():

```
using UnityEditor;
using UnityEngine;

/// <summary>
/// Inspector for .SVG assets
/// </summary>
[CustomEditor(typeof(DefaultAsset))]
public class GraphVizEditor : Editor
{
    public override bool HasPreviewGUI()
    {
        return true;
    }

    public override void OnPreviewGUI(Rect r, GUIStyle background)
    {
        var path = AssetDatabase.GetAssetPath(target);
        if (path.EndsWith(".gv"))
        {
            var texture = new Texture2D(1, 1);
            texture.SetPixel(1, 1, Color.green);
            texture.Apply();
            GUI.DrawTexture(r, texture, ScaleMode.StretchToFill, false);
        }
    }
}

```

---
Tags: unity
---


# Question
Title: Unity 2d circle collider not stopping after collision with box collider 2d
I'm using unity circle collider 2d and rigid body 2d but when it hits the box it doesn't stop there but instead just pass through and fall. Can someone help?

## Circle Collider and rigid body 2d setting

## Box Collider Settings

## Game output

As you can see in game output my circle instead of stopping at collision it is getting passed by box. **I want the circle to fall in square rather than free fall.**

# Answer
> 1 votes
Your box collider has "Is Trigger" checked.

This box means "Please do not apply physics restitution when you detect collisions with this box. Treat it as a ghost that object can pass through unaffected"

Triggers are used to detect overlaps/collisions without automatically modifying the object's movement. We use them to create things like activation zones, or intangible things like energy weapons that should deal damage on impact without imparting momentum.

If you want the box to behave as a solid obstacle, uncheck the "Is Trigger" box.

Also, be sure any motion of the objects is being applied via their Rigidbody2D. If you move an object with its Transform, that bypasses physics and can lead to tunneling through solid colliders.

---
Tags: unity, rigidbody
---


# Question
Title: Cannot implicitly convert type "void" to "bool"
I have a problem with pressing UI button while cursor is locked. I tried to write in the script so that the cursor unlocks when a button appears on the screen, but the error "Cannot implicitly convert type "void" to "bool"" appeared. I searched for a solution on the Internet, but none of the solutions I found helped me.

```
public GameObject button;

// Use this for initialization
void Start () {
    LockCursor();
}

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

    if(Input.GetMouseButton(0))
    {
        LockCursor();
    }

    if(button.SetActive(true))
    {
        UnlockCursor();
    }
}

private void LockCursor()
{
    Cursor.lockState = CursorLockMode.Locked;
    Cursor.visible = false;
}

private void UnlockCursor()
{
    Cursor.lockState = CursorLockMode.None;
    Cursor.visible = true;
}

```

What can I do to solve this issue? Thanks for any help!

# Answer
> 1 votes
I have found a solution. In this case, the ".activeSelf" function is required. This function checks if the object is active or not and returns local active state of the GameObject.

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


# Question
Title: How can i write automated tests for some SDL2 objects?
For eg having a class that is rendering something on the screen, could be even a point or a line if not an image or whatever.

How is possible to write some tests for that class only?

or just a small program rendering a line, would it be possible to write an automated test for it?

# Answer
> 3 votes
There are a few approaches you could take for testing rendering output.

First, you could create a test mock version of your renderer, that instead of plotting things on the screen, would instead perhaps store some kind of representation of the rendering output, such as lists of renderer elements that you could assert against. This sort of approach is often used in webdev testing, where the output of components is tested using DOM elements instead of directly checking the output.

Your tests could then look something like this:

```
MyMockRenderer renderer;
MyObject object;
object.render(&renderer);
TEST_ASSERT(renderer.contains(Line(expectedStart, expectedEnd)));
TEST_ASSERT(renderer.contains(Image(playerImage, expectedPosition)));

```

Alternatively, you could first manually visually verify a rendered output that looks good, and implement code for storing screenshots of the output. Then, your automated testing procedure could launch the game, perform the rendering, capture the framebuffer contents, and compare those to the previously verified output images. This could be beneficial to find regression bugs for an example. I believe the term for this is "snapshot testing".

---
Tags: c++, sdl2, testing, unit-testing, automated-testing
---