# Question
Title: Running a standalone Godot application on a Yocto 2.6 system with OpenGL3.0/ES2.0 hardware
I have an application that displays construction machines like excavators or snow groomers. The application is built on my company's custom engine, but I am trying to find out if I can port it to a game engine. I choose Godot because it seems it is more compact and compatible compared to some other popular engines.

The target hardware environment of the application is a relatively limited panel with an Intel atom chip Intel(R) Atom(TM) CPU E3827. The Intel documentation stats that it supports OpenGL 3.0 and GLES 2.0. We have our custom 32bit operating system based on yocto 2.6 as well.

I made a very compact project which runs quite well on my Ubuntu 22.04 system. Then I exported it using the 32 bit Linux template in Godot to make it a standalone application for my special panel environment.

When I try to run the binary on the panel hardware, I receive a couple of errors:

```
/usr/local/bin/NewExcaProject$ ./MCGodot.x86_32
Godot Engine v4.2.2.rc1.official.c7fb0645a - https://godotengine.org
ERROR: X11 Display is not available
   at: DisplayServerX11 (platform/linuxbsd/x11/display_server_x11.cpp:5836)
Your video card drivers seem not to support the required OpenGL 3.3 version.

If possible, consider updating your video card drivers.

If you recently updated your video card drivers, try rebooting.
ERROR: Unable to create DisplayServer, all display drivers failed.
   at: setup2 (main/main.cpp:2394)

```

But in my project settings in Godot I have "Fallback to Gles" option enabled:

Why I am receiving that error, even though that option is enabled? How can I resolve this? Would it help me if I used an older version of Godot?

# Answer
Based on this article from the Godot devs in 2021, you might be better off with Godot 3:

> # So, GLES2 support is effectively dead in Godot?
>
> Not necessarily. It will be kept alive in two ways:
>
> * Godot 3.x will be maintained for a long time so, if you require GLES2 you can use this version.
> * Godot 4.x may support GLES2, but not necessarily out of the box. Some contributors want to work on it, so we may still add limited support for those who need it (may be switched off by default, though to save binary space). Keep in mind this will most likely be focused on 2D and may only support rather simple 3D.

At the time it was written, it sounds like either GLES2 wasn't well supported on mainline Godot 4 or if it was, it was a low priority. Additionally, your target hardware might not be something they have available for testing.

I'm not actively developing on any combination of GLES2, Godot 4 & Atom. It's possible that things have progressed since the above article was posted. But I wasn't able to find anything that superseded it and several searches eventually point back to that information.

I suggest installing Godot 3 and checking to see if you can successfully build and run one of the demo projects. You may still need to go into the settings to manually enable the GLES2 fallback. But as far as I can tell, that *should* work. Please note though that there are some documented differences between GLES2 & GLES3 on Godot 3.x. Some are by design, some are not.
> 2 votes

---
Tags: opengl, godot, opengl-es2, linux, godot-4
---


# Question
Title: My CharacterBody3D Is getting blocked by ramps that act as walls
To summarize, my ramp is acting like a wall even if it is created to have a collision and mesh that fits its shape.

I have tried:

* Putting the max angle to 90
* using different ramps (CSG & mesh)
* I have stopped everything but the basics that impact movement.

... but still I get blocked by ramps as if they are a wall. I am using move and slide and in all the tutorials I have looked at to see why it doesn't work, there is no major difference between my code and the tutorial. So what can be the problem?

Here is my code:

```
public partial class MovementPlayer : CharacterBody3D
{
    #region Movement
    [Export]
    private int Maxspeed = 8;
    private Vector3 direction;
    [Export]
    private float jumpspeed = 5.0f;
    private float gravity;
    [Export]
    private float accelerationSpeed;
    [Export]
    private float decelerationSpeed;
    private Vector3 PositionBeforeMove { get; set; }

    private Vector3 TemporaryVelocity;
    #endregion
    Node3D Head;
    [Export]//moves objects variables etc to the editor
    NodePath HeadPath;
    Camera3D PlayerCamera;
    [Export]
    NodePath PCameraPath;
    [Export]
    private float mousesensitivity = 2.5f;
    [Export]
    RayCast3D raycast;
    [Export]
    Node3D RayCasst;
    [Export]
    private bool Thirdperson;
    [Export]
    private float interpolateweight;

    // Called when the node enters the scene tree for the first time.
    // Called every frame. 'delta' is the elapsed time since the previous frame.
    public override void _Ready()
    {
        GD.Print("Override");
        Head = GetNode<Node3D>(HeadPath);
        PlayerCamera = GetNode<Camera3D>(PCameraPath);
        gravity = (float)ProjectSettings.GetSetting("physics/3d/default_gravity") * -1;
        //Input.MouseMode = Input.MouseModeEnum.Captured;
        if (Thirdperson == true)
        {
            PlayerCamera.GlobalPosition = new Vector3(PlayerCamera.GlobalPosition.X, PlayerCamera.GlobalPosition.Y + 2, PlayerCamera.GlobalPosition.Z+4);
            PlayerCamera.RotateX(Mathf.DegToRad(-20));
        }
    }

    public override void _Process(double delta)
    {
        base._PhysicsProcess(delta);
        ProccesInput(delta);
        ProccesMovement((float)delta);
      //is on floor is working
        /*if (raycast.IsColliding())
        {
            //GD.Print("RayHitSomething");
            RaycastCollision(raycast.GetCollisionPoint(),raycast.GetCollisionNormal());

        }*/
    }
    #region Camera&Keys
    public void ProccesInput(double value)
    {
        direction = new Vector3();
        var InputMovementVector = new Vector2();

        if (Input.IsActionPressed("Move_Up") == true)
        {
            InputMovementVector.Y += 1;
            //GD.Print("Player Angle Is:" + RotationDegrees.Y);
            //GD.Print("Camera Angle Is:" + Head.RotationDegrees.X);
            //GD.Print("Head Z Rotation" + Head.RotationDegrees.Z);
            //GD.Print("MovingForward");

        }
        if (Input.IsActionPressed("Move_Down") == true)
        {
            InputMovementVector.Y += -1;
        }
        if (Input.IsActionPressed("Move_Left") == true)
        {
            InputMovementVector.X += -1;
        }
        if (Input.IsActionPressed("Move_Right") == true)
        {
            InputMovementVector.X += 1;
        }
        InputMovementVector = InputMovementVector.Normalized();
        direction -= GlobalTransform.Basis.Z * InputMovementVector.Y;
        direction += GlobalTransform.Basis.X * InputMovementVector.X;
       /* if(IsOnFloor() && Input.IsActionJustPressed("Move_Jump"))
        {
            direction.Y = jumpspeed;
        }*/
    }

    public void ProccesMovement(float value)
    {
        PositionBeforeMove = GlobalPosition;
        TemporaryVelocity = Velocity;
        /*if (direction.Y != 0)
        {
            TemporaryVelocity.Y += direction.Y;
        }*/
        //apply gravity
        TemporaryVelocity.Y += value * gravity;
        direction = direction.Normalized();
        //horizontalMovement
        var horizontalVelocity = TemporaryVelocity;
        horizontalVelocity.Y = 0;

        var target = direction;
        target *= Maxspeed;
        //Speed up or slow down
        float acceleration;
        if (direction.Dot(horizontalVelocity) > 0)
        {
            acceleration = accelerationSpeed;
        }
        else
        {
            acceleration = decelerationSpeed;
        }

        horizontalVelocity = horizontalVelocity.Lerp(target, acceleration * value);
        TemporaryVelocity.X = horizontalVelocity.X;
        TemporaryVelocity.Z = horizontalVelocity.Z;
        Velocity = TemporaryVelocity;
        PositionBeforeMove = GlobalPosition;
        MoveAndSlide();
        raycast.ForceRaycastUpdate();

    }
    public override void _Input(InputEvent @event)
    {
       // GD.Print("OverridingInputforMouse"); is working
        base._Input(@event);
        if (Input.MouseMode == Input.MouseModeEnum.Visible)
        {
            InputEventMouseMotion mouseMotion = @event as InputEventMouseMotion;
            if (mouseMotion!=null)
            {
                HandleCameraRotation(mouseMotion);

            }
        }
    }

    public void HandleCameraRotation(InputEventMouseMotion mouseMotion)
    {
        if (Thirdperson==false) {
             //rotates around the x axis to look down and up
            Head.RotateX(Mathf.DegToRad(-mouseMotion.Relative.Y * mousesensitivity));
            //set the degrees
            Head.RotationDegrees = new Vector3(Mathf.Clamp(Head.RotationDegrees.X, -70, 70), 0, 0);
        }
        //rotate around the y axis to turn left and right
        RotateY(Mathf.DegToRad(-mouseMotion.Relative.X * mousesensitivity));

        GD.Print("Player velocity" + Velocity);
    }

    #endregion
    public void RaycastCollision( Vector3 Globalpositionpoint,Vector3 Normal)
    {
        Vector3 Change=new Vector3(0,Globalpositionpoint.Y-PositionBeforeMove.Y,Globalpositionpoint.Z-PositionBeforeMove.Z);
        var xform =Align_With_Normal(GlobalTransform, Normal);
        GlobalTransform = GlobalTransform.InterpolateWith(xform,interpolateweight);
        GD.Print("Current Z Angle" + GlobalRotationDegrees.Z);
        GD.Print("Current Y Angle" + GlobalRotationDegrees.Y);
        GD.Print("Current X Angle" + GlobalRotationDegrees.X);
        // RotateX(-Angle);
        Velocity = new Vector3(TemporaryVelocity.X, Change.Y, Change.X);
        MoveAndSlide();
    }

    public Transform3D Align_With_Normal(Transform3D xform,Vector3 Normal)
    {
        xform.Basis.Y =Normal;
        xform.Basis.Z = -xform.Basis.Z.Cross(Normal);
        xform.Basis = xform.Basis.Orthonormalized();
        xform.Basis.Z = Basis.Z;
        return xform;
    }
}

```

If it is needed I'll try to film a video to show how it looks. Here is the pictures:  And here is the Video:Here is the video \[i dont know why i cant move right now,it wasnt like that when i opened the gamefile last time so for now just ignore it i will fix it in the future\]

# Answer
Answer: The fix to this problem was to redo the whole movement script and the character. The code is here:

    public partial class Movement2 : CharacterBody3D
{
    # region export
    [Export]
    NodePath Head;
    [Export]
    NodePath PCameraPath;
    [Export]
    RayCast3D Raycast;
    [Export]
    private bool Thirdperson;
    [Export]
    private float MaxSpeed;
    [Export]
    private float acceleration;
    [Export]
    private float deacceleration;
    [Export]
    private float Jumpspeed;
    [Export]
    private float mousesensitivity = 2.5f;
    [Export]
    private float interpolateweight;
    [Export]
    CollisionShape3D scale;
    [Export]
    RayCast3D GrabRay;
    #endregion
    private Vector3 PositionBeforeMove { get; set; }
    private Vector3 direction;
    private Vector3 TemporaryVelocity;
    Vector2 planemovement = new Vector2();
    PhysicsDirectSpaceState3D spacestate;
    #region bools
    private bool MovementClass;
    private bool Jumping;
    private bool launch;
    private bool Chrouch;
    private bool grabbool;
    #endregion

    Node3D HeadNode;
    Camera3D PlayerCamera;
    // Get the gravity from the project settings to be synced with RigidBody nodes.
    public float gravity = ProjectSettings.GetSetting("physics/3d/default_gravity").AsSingle();
    public override void _Ready()
    {
        GD.Print("Override");
        HeadNode = GetNode<Node3D>(Head);
        PlayerCamera = GetNode<Camera3D>(PCameraPath);
        gravity = (float)ProjectSettings.GetSetting("physics/3d/default_gravity") * -1;
        //Input.MouseMode = Input.MouseModeEnum.Captured;
        if (Thirdperson == true)
        {
            PlayerCamera.GlobalPosition = new Vector3(PlayerCamera.GlobalPosition.X, PlayerCamera.GlobalPosition.Y + 2, PlayerCamera.GlobalPosition.Z + 4);
            PlayerCamera.RotateX(Mathf.DegToRad(-20));
        }

    }
    public override void _PhysicsProcess(double delta)
    {
        if (Jumping == true && Input.IsActionJustPressed("Move_Jump") == true)
        {
            launch = true;
        }
        if (IsOnFloor() == true)
        {
            Jumping = false;
        }
        if (Raycast.IsColliding())
        {
            RaycastCollision(Raycast.GetCollisionPoint(), Raycast.GetCollisionNormal());

        }
        input((float)delta); //spitting into 2 classes dont impact movement above edges
    }
    public void Movement(float delta)
    {
        PositionBeforeMove = Raycast.GlobalPosition;
        TemporaryVelocity = Velocity;

        if (Jumping==true && IsOnFloor() == true)
        {
            TemporaryVelocity.Y = Jumpspeed;
        }
        if (IsOnFloor() == false )
        {
            TemporaryVelocity.Y += delta * gravity;
            Jumping = true;
            //works
        }
        if (Jumping == false || Chrouch == true||grabbool==true)
        {
            TemporaryVelocity.Y = 0;
        }
        if (launch == true)//works like butter hehheheheh
        {
            launch = false;
            Vector3 launchvector = new Vector3(TemporaryVelocity.X, 0, TemporaryVelocity.Z + 10);
            TemporaryVelocity -= launchvector * PlayerCamera.GlobalBasis.Z;
        }
        direction = direction.Normalized();
        //horizontalMovement
        var horizontalVelocity = TemporaryVelocity;
        horizontalVelocity.Y = 0;

        var target = direction;
        target *= MaxSpeed;
        //Speed up or slow down
        float accelerationn;
        if (direction.Dot(horizontalVelocity) > 0)
        {
            accelerationn = acceleration;
        }
        else
        {
            accelerationn = deacceleration;
        }

        horizontalVelocity = horizontalVelocity.Lerp(target, accelerationn * delta);
        TemporaryVelocity.X = horizontalVelocity.X;
        TemporaryVelocity.Z = horizontalVelocity.Z;
        Velocity = TemporaryVelocity;
        MoveAndSlide();

    }
    public void input(float delta)
    {
        direction = new Vector3();
        planemovement = new Vector2();
        if (Input.IsActionPressed("Move_Up") == true)//jumping while going forward
        {

            planemovement.Y -= 1;
            MovementClass = true;
        }
        if (Input.IsActionPressed("Move_Down") == true)//works
        {

            planemovement.Y += 1;
            MovementClass = true;
        }
        if (Input.IsActionPressed("Move_Left") == true)//jumping while going Left
        {

            planemovement.X += 1;
            MovementClass = true;
        }
        if (Input.IsActionPressed("Move_Right") == true)//works
        {

            planemovement.X -= 1;
            MovementClass = true;
        }
        if ( Input.IsActionJustPressed("Move_Jump") ==true)//working
        {
            Jumping = true;
            direction.Y += 1;
            MovementClass = true;
        }
        if (Input.IsActionPressed("Chrouch"))
        {
            scale.Scale=new Vector3(scale.Scale.X,Scale.Y/2,scale.Scale.Z);
            Chrouch = true;
        }
        else
        {
            scale.Scale = new Vector3(scale.Scale.X, Scale.Y, scale.Scale.Z);
            Chrouch = false;
        }
        if (Input.IsActionJustPressed("Grab") == true && GrabRay.IsColliding()==true)
        {
            Grab(GrabRay.GetCollisionPoint());
            GD.Print("Grab");
        }
        if(Input.IsActionPressed("Grab")==false)
        {
            grabbool = false;
        }
        if (MovementClass == true)
        {
            planemovement = planemovement.Normalized();
            direction += GlobalBasis.Z * planemovement.Y;
            direction -= GlobalBasis.X * planemovement.X;
            Movement(delta);

        }
    } //ignore works fine
    public override void _Input(InputEvent @event)
    {
        // GD.Print("OverridingInputforMouse"); is working
        base._Input(@event);
        if (Input.MouseMode == Input.MouseModeEnum.Visible)
        {
            InputEventMouseMotion mouseMotion = @event as InputEventMouseMotion;
            if (mouseMotion != null)
            {
                HandleCameraRotation(mouseMotion);

            }

        }

    }
    public void HandleCameraRotation(InputEventMouseMotion mouseMotion)
    {

        if (Thirdperson == false)
        {
            //rotates around the x axis to look down and up
            HeadNode.RotateX(Mathf.DegToRad(-mouseMotion.Relative.Y * mousesensitivity));
            //set the degrees
            HeadNode.RotationDegrees = new Vector3(Mathf.Clamp(HeadNode.RotationDegrees.X, -70, 70), 0, 0);
        }
        //rotate around the y axis to turn left and right
        RotateY(Mathf.DegToRad(-mouseMotion.Relative.X * mousesensitivity));

    }
    public void RaycastCollision(Vector3 Globalpositionpoint, Vector3 Normal)
    {
        Vector3 Change = new Vector3(0, Globalpositionpoint.Y - PositionBeforeMove.Y, Globalpositionpoint.Z - PositionBeforeMove.Z);
        if (Mathf.Floor(Globalpositionpoint.Y) == Mathf.Floor(PositionBeforeMove.Y) && Jumping == false)
        {
            Velocity = new Vector3(TemporaryVelocity.X, Change.Y, TemporaryVelocity.Z);
            MoveAndSlide();
        }
        var xform = Align_With_Normal(GlobalTransform, Normal);
        GlobalTransform = GlobalTransform.InterpolateWith(xform, interpolateweight);

    }

    public Transform3D Align_With_Normal(Transform3D xform, Vector3 Normal)
    {
        xform.Basis.Y = Normal;
        xform.Basis.Z = -xform.Basis.Z.Cross(Normal);
        xform.Basis = xform.Basis.Orthonormalized();
        xform.Basis.Z = Basis.Z;
        return xform;
    }

    public void Grab(Vector3 RayPoint)
    {
        GlobalPosition = GlobalPosition.Lerp(RayPoint, interpolateweight);
        grabbool = true;
    }//working
}
```

> 0 votes

---
Tags: c#, movement, godot, godot-4
---


# Question
Title: I've hit the limit of what ChatGPT can teach me about game development in GDScript — what strategies can I use to keep making progress?
I felt like I had gained a decent grasp on core coding concepts (variables, if statements, loops) and I familiarized myself with Godot, so I wanted to start making small games to learn more by actually putting the core concepts into practice.

I started making a small arcade style beat 'em up that's just 1 simple level with a boss at the end. I coded the movement and the idle and run animations and it was all good, but then I started to primarily rely on ChatGPT to teach me how to implement more features like simple attacking and enemy hurt boxes.

What I would do is ask it something like "I want to implement attacking, can you teach me how and explain to me what the code does?" and at the start it was cool because it would just straight up write me code for attacking and teach me the types of nodes I needed to use.

I still made sure that I actually understood what I was writing, but as time went on I started encountering a ton of problems. The code that ChatGPT would write me looked correct logically but it rarely worked as intended in Godot. It would always do something unexpected and wrong. I would try my best to explain to ChatGPT and made sure it actually understood what I wanted, but the logic would always have some kind of bug.

Then I would spend hours debugging the issue with ChatGPT. It knew how to write logical code for one feature, but it never worked as intended when put in with the other features.

I posted here about my coding issues twice and multiple people told me that my coding logic is strange and looked cluttered.

So I started realizing that using ChatGPT as a primary tool was a mistake. I could've just searched "how to implement attacks in Godot" on YouTube and I could've found a straightforward and simpler method for it. ChatGPT gave me strange and complex methods that never worked right.

Don't get me wrong, I know the coding basics, and I want to learn more by actually applying the things I learn in small basic games instead of just entering analysis hell where I would watch like 36 hours of tutorials and then never apply anything.

I just need to revamp my strategy and only use ChatGPT as more of a side tool for small logical issues and not having it build the whole game for me.

I'm going to watch more tutorials on YouTube for the specific things I'm gonna implement, but what other strategies can I use to overcome these problems?

# Answer
Practice, practice and again, practice. There is no shortcut as you found out with chatGPT. But instead of watching a lot of Youtube tutorials, you should try to implement the one you are watching, step by step.

While there are a lot and good tutorials out there, I would pick a series of multiple smaller episodes. The problem with a tutorial that covers a single aspect might produce the same problem you have right now with chatGPT. You managed to get a single piece working but it might not fit into the rest of your code. By picking a series of tutorials, they build on top of the other parts and you can be sure you have a working something at the end.

Instead of just watching the whole thing, break it down.

* Give the episode a watch first, don't try to copy anything at all. Just watch it.
* Try to reimplement it as good as you can first. If you are stuck, compare it with the video.
* Repeat step 2 until you can do it without the help of the video.
* Try to apply it to other things. Not everything will be possible to transfer, but even thinking about where else the knowledge could be used will help.
* Write down the topic once you feel confident about it and retry it after a week or two again. A single line instruction like character controller, jump controller, audio system, etc on the paper and just make that single part.

A game usually is just an accumulation of the basic building blocks that are repeated over and over again. By making sure you have the basics down, when you make the game yourself, you just need to pick the correct ones.

Another helpful advice is to start small. Finishing a full game as a beginner is a very hard. It is advised to not make your dream game as the first game (not even after you finished a few even). There are a few games that are simple and incorperate the essentials of what makes a game. They are as well a good fit to try out new engines in how well you can make them.

What are good games to "earn your wings" with?

Quoting DMGregory (to keep comments for the future)

> "Combat is a tar pit" is a mantra among some game developers, because what feels effortless to the player takes a huge amount of interacting features and fine tuning to make it feel good. Practicing the skills in simpler combinations like a Breakout or Space Invaders clone can be a good way to reduce the up-front complexity and see early successes to keep motivating you on your learning journey, rather getting stuck in development hell on a game that's a bit too ambitious. You can always work up from those tiny prototypes
> 9 votes

# Answer
Learning techniques have a floor and a ceiling. That is how much you need to know to start using them (the floor), and how much you can learn just using them (the ceiling). *ChatGPT - and other large language models - has both a low floor and low ceiling.*

Of course, you can follow tutorials, and you can ask questions.

Since we are talking about Godot, I want to point out that there is a short curated list of tutorials on the official documentation: Tutorials and resources. *And yes, you are going to hit a ceiling with them too.*

In general - not just with ChatGPT - it is easier to write code than to fix the code. For example, if you were to ask here or in stackoverflow, you might get code snippets written for you... If you copy and paste without understanding them, the moment you need to fix a bug involving them - or modify them because they no longer match your requirements - you are going to run into trouble.

Thus, reading and understanding is important. In fact, there is a lot to learn if you go to open source projects and start reading. *Howevever, that has a higher floor.*

You can also improve your understanding by experimenting. Take working code and make changes, see what happens, learn from that.

---

I strongly advise you to develop system analysis skills. That is, breaking your problems into smaller problems. Try thinking about the system you want to build in terms of smaller components interacting, and also try thinking about the path that information takes inside the system so you can break it into steps.

So your project gets broken down. Either into steps or into components, or both. And each one of those you can break further down. Eventually it gets to the size of writing a function, which is broken into lines of code.

It is a way of thinking and you get there with practice.

---

Of course, I agree with the advice of starting small.

If the project is too big you might not even know how to begin to break it down. However I want to add a few things:

* You don't need to have a full view of your project to begin.
* You might fail to complete a project and still learn.
* Having the motivation and grit to see the project to the end is big factor to its completion.

If a project is too big, complex, or hard, it might be daunting and make you feel frustrated. If a project is too small, simple, or easy, you might find it boring.

Since you are not starting but you have done some learning already... You need to figure out a project that is right for you, so you can stay motivated doing it. *A good floor, and a good ceiling, for where you are.*

You don't know what project to pick? It is by feeling. Do you feel motivated to do it? Do you feel you have a good grasp about how to go about it? Good, try it. Even if the project you pick is not the absolute best choice, or if you do not complete it, you would learn. *And you might even have code to reuse in later projects.* It is not wasted time.

And, of course, that is just one step in your journey. We are breaking the project of learning game development into smaller steps: projects. And we do not have a full grasp of the whole process, in fact we can argue that we never finish learning... Yet, that shouldn't stop you.

*In this answer, if you read between the lines, there is also a lesson about game desing, difficulty curves, and target audience.*
> 1 votes

---
Tags: godot, gdscript
---


# Question
Title: Add Item for OptionsButton is Gone from the editor
When i added in a optionbutton for my hud i couldnt find a way to add items manually,this was weird as when i looked for a way,a button on top of the editor should appear but its not there? I dont know why and it seems to be a problem all over my project,i am not sure if this happends in other projects as i havent checked. Here is a picture:

# Answer
> 1 votes
This option is currently (Godot 4) on the inspector.

Open "Items":

And there you will find an "Add Element" button:

Clicking it will create an empty item that you can then customize (add text, etc):

---
Tags: gui, godot, interface, hud, user-interface
---


# Question
Title: What is the correct way to stop a Godot dedicated server
So I'm trying to understand how multiplayer works in Godot and the docs are very clear when one application is the host and the other applications join the host.

Now i want to have a dedicated server and there's 2 ways of doing that: just run the executable in headless mode or export it as a dedicated server for a smaller executable that can only be run in headless mode.

I then run the executable from cmd or powershell but I don't get how I would stop the server without throwing any errors (and saving data before actually terminating)

Just closing the console results in the following errors (for a split second) and doesn't trigger the close request notification:  The result is the same if I use the provided \*.console.exe Godot produces. (Tried with 4.2 and 4.2.1)

This is independent from having actual network code and can be reproduced with an empty project.

So my question is: What is the correct way to stop a headless Godot application? (+is there a notification I can use to save game state?)

# Answer
---

## Close the server

In theory ideal way to close a server is for it to close itself, *if it is going to close at all*. And it should only be possible to trigger this locally. Since there is no Window, the standard way to do this is by reading from standard input.

*I'll try to do that for Godot...*

We will implement a custom `MainLoop`. Create a script like this:

```
class_name CustomMainLoop
extends SceneTree

```

And configure it in project settings under `application/run/main_loop_type`, you write the class name (`CustomMainLoop` inb this case), for example:

And yes, this will be the `SceneTree` (not the `root` of the `SceneTree`, but the `SceneTree` itself).

Next we will override the `_initialize` method, and we will detect if we are running in headless mode:

```
func _initialize() -> void:
    if DisplayServer.get_name() != "headless":
        return

```

And we will read standard input with `OS.read_string_from_stdin()`. However, we need to run this in another thread because otherwise we are blocking the actual game.

Thus, let us do this:

```
class_name CustomMainLoop
extends SceneTree

var _input_thread:Thread

func _initialize() -> void:
    if DisplayServer.get_name() != "headless":
        return

    _input_thread = Thread.new()
    _input_thread.start(_listen_to_standard_input)

func _listen_to_standard_input() -> void:
    while true:
        prints("Insert some text:")
        var line := OS.read_string_from_stdin().strip_edges()
        prints("You inserted:", line)
        match line:
            "quit":
                prints("Quitting")
                _input_thread.wait_to_finish.call_deferred()
                quit.call_deferred()
                return

```

By the way, you know that we usually use `get_tree().quit()`, well, we are running the code on the `SceneTree`, so we just need to call `quit`. But we do not want to call it from our secondary `Thread`. A deferred call solves that.

Similarly, we are having the main thread wait for our secondary `Thread` to finish, so we do not leak the `Thread`.

However, this is not perfect, I have run into a couple problems:

* In PowerShell I only get one character at a time. The naive workaround made it unusable.
* In CMD the console gets the input first. So I need to press Enter which has CMD reply with the prompt, and then what I type gets send into the game.

So, don't. Instead create a bat file, like this:

```
my_game.exe --headless

```

And use that to launch the game server instead of CMD or PowerShell.

---

## Your Error

This seems to be a regresion of these bug:

This might be related:

If you can make a minimum reproduction project, please report at https://github.com/godotengine/godot/issues

---

## Exit Notifications

> is there a notification I can use to save game state?

*I suppose you are aware of `NOTIFICATION_WM_CLOSE_REQUEST`, but these are Window Messages, so they won't work on headless mode.*

---

Your `Node`s will be removed from the scene tree. So their `_exit_tree` gets called, and they also get a `NOTIFICATION_EXIT_TREE` right away, followed by `NOTIFICATION_UNPARENTED` a little later.

If your cleanup needs to happen from an `Node` while inside the scene tree use `_exit_tree` or `NOTIFICATION_EXIT_TREE` in one of your Autoloads.

---

Futhermore, *many* `Object`s will get a `NOTIFICATION_PREDELETE`. Use this as your finalizer.

*And those `Object`s also get a final undocumented notification `3` which internally has the name `NOTIFICATION_PREDELETE_CLEANUP`... Which is not intended for you to use.*

---

But your static variables are not attached to an `Object`, let alone to a `Node`. Let us say you must clean them manually when you know the executable is losing.

Well, let us go back to our custom `MainLoop`, and override the `_finalize` method:

```
func _finalize() -> void:
    prints("_finalize")

```

After everything else is said and done, your `_finalize` will be called. And yes, you can access your `static var`s in `_finalize`. As far as I know it is your last chance.

*Oh, but we would have an instance `CustomMainLoop`, does it also get notifications? Yes. Does it get `NOTIFICATION_PREDELETE` or `NOTIFICATION_PREDELETE_CLEANUP`? No, it does not.*

---

**Addendum**: The `@static_unload` has come to my attention. You should be able to annotate a script with it, for example:

```
@static_unload()
class_name MyClassWithStaticMembers

static var _something:Resource

```

And this would tell Godot that it can free the static variables early.

---

## Leaked Objects

Ah, but let me tell you something: your `Script`s are `Object`s, and they do not get to be freed in the above process. Also you might have `preload` some `Resource`s that would not have been freed yet - unless you freed them manually (and I'm not suggesting you do that). And there might be other Godot internal `Object`s lingering around.

If you run your executable with `--verbose` you will get everything that is being leaked printed after `_finalize` is called. Of course they get freed when the executable exits nontheless.

These do not cause the error you are seeing. The error you are seeing is caused by a bug. If you can make a minimum reproduction project, please report at https://github.com/godotengine/godot/issues
> 3 votes

---
Tags: godot, server
---


# Question
Title: How can I gradually increase the speed of my game?
I recently made a replica of (Dino run) game in Unity2d.

But I'm stuck on how can I speed up my game gradually.
Should the game speed be increased or should I increase the speed of the camera.

Here is my *spawn obstacles* script.

```
public class SpawnObstacles : Monobehaviour

{
    public GameObject [] obstacles;
    private GameObject obj;
    private float XPos = 0;
    private int number = 0;

    private float randomPosition = 0;

    // Start is called before the first frame update
    void Start()
    {
        InvokeRepeating("Spawn", 1.5f, 1.6f);
    }

   private void Spawn()
    {
        if (GameObject.Find ("Cube").GetComponent<Cube> ().isDead == false)
        {
            number = Random.Range(0, 12);
            randomPosition = Random.Range(19, 29);

            XPos = transform.position.x + randomPosition;
            obj = obstacles[number] as GameObject;

            Instantiate(obj, new Vector2(XPos, obj.transform.position.y), Quaternion.identity);

        }
    }
}

```

# Answer
> 2 votes
A very simple way to control the speed of a Unity game is by changing the value of `Time.timeScale`. The default value is 1, and higher values mean higher speed. 2 means twice as fast, 0.5 means half as fast, etc.. But keep in mind that this speeds up everything in your game. Often there are various things you do not want to speed up while the game progresses.

Often you want to control the speed of specific game features separately, and some not at all. In that case you have to find different solutions for different kinds of features. You posted the script which spawns objects, so I assume that one thing you might want to increase is the spawn frequency of objects. If that's your goal, then `InvokeRepeating` is the wrong tool to use, because you can't change the repetition frequency retroactively. Use an update-method instead. Here is a simple script which spawns objects in regular intervals based on Update.

```
public class RepeatingSpawner : MonoBehaviour {

     public float spawnsPerSecond;
     public GameObject prefab;

     private float nextSpawn;

     void OnEnable() {
         nextSpawn = Time.time;
     }

     void Update() {
         while (nextSpawn < Time.time) {
             nextSpawn += 1.0f / spawnsPerSecond;
             Instantiate(prefab, transform.position, transform.rotation);
         }
     }
}

```

You can now control the speed by changing the value of "Spawns Per Second". You could do this with an InvokeRepeating coroutine, but there are better ways to do that.

You likely want to change more things than just the speed of this spawner over the course of the game. So it is a good idea to control all of these from one central location. You could create a script with a name like `ProgressionController` which references everything in the game with a public variable which is supposed to change over the course of the game. But an even more elegant way to handle this could be to use a Timeline asset. It allows you to control the change of multiple values over time using a visual curve editor.

# Answer
> 0 votes
On a language independent level, you can often get this effect by controlling speed of change (change per frame). Pseudo-code being something like:

```
def time_dialation = 1.0
time_dialation = get_new_time_dialation()
change_in_property = change_in_property * time_dialation
property += change_in_property

```

For all changes in properties influenced by time (position, rotation, whatever).

---
Tags: unity
---


# Question
Title: Is there any reason not to use classes in C++?
I'm a bit conflicted when it comes to the use of classes currently, I use them all the time, but I realized through the KISS and YAGNI principles I can simplify things by not using them, but is there any reason to not use a class? They seem to bring a lot to the table even if you don't utilize everything you at least have the ability to do so later.

For example, I made this class which is responsible for imgui stuff and calling registered callback functions, but it doesn't really benefit from being class at the moment.

```
class GUI {
public:
    GUI(SDL_Window* window, SDL_GLContext context);
    ~GUI();
    void Draw();
private:
    void start();
    void end();
};

```

So I could do something like this instead which I suppose is simpler.

```
namespace GUI {
    void init(SDL_Window* window, SDL_GLContext context);
    void shutdown();
    void start();
    void draw();
    void end();
}

```

But is this any better than just using a class in the first place? I feel like it just limits what I could do later down the road.

# Answer
Good question.

First what role do classes serve?

No seriously, why do we use classes? Some might say thtat it is to bundle related bits of data together... Such as a rectangle has a location, a width, and a height... But structs allow us to bundle related data... So why do we use them?

We use classes because of **polymorphism**, and **encapsulation**.

## Polymorphism

Polymorphism allows us to treat apples, oranges, and strawberries as fruit. We can eat them, they all have weight, etc... Without having to perform checks outside of the orange/apple/strawberry to determine how they should be proccessed... All of the related information is self contained...

Your GUI? probably not going to need polymorphism there.

## Encapsulation

Encapsulation is all about reducing cognitive load. By limiting what you/ future users can see.

Encapsulation is all about limiting how people can interact with data. Limited access makes interacting with a component easier to do in the way that was intended... And harder to do in unintended manners.

For example not allowing future users to call `GUI::start`/`GUI::end` or to touch any of private data that GUI needs to keep track of for more complicated functionality..

## Getting into the specifics

I disagree with your assessment that your class as written doesn't benefit from being a class.

1. Globals are bad, with globals `x = use_globals(5, 1)` might not have the same result as `x = use_globals(5, 1)` does.. despite having the same parameters... `draw()` your GUI should probably contain some private variables so that `Draw()` doesn't rely on globals.
2. RAII is a wonderful concept... Whereas having a dependency between an `init()` and `deinit()` causes all sorts of problematic behavior. func OpenGUI(args...) { GUI my\_gui(window, context); while(my\_gui.not\_canceled()) { my\_gui.Draw(); if (something) { return some\_value; } return something\_else; } //my\_gui automatically shutsdown no matter how I exit...

vs:

```
func OpenGUI(args...) {
    GUI::init(window, context);
    while(??) {
       draw(); // is draw relying on global variables to determine what it is drawing?
       if (something) {
          return some_value; //early exit
       }
    }
    shutdown();
    return something_else;
}
//Whoops I won't always call shutdown() like I should.

```
> 2 votes

# Answer
The other answers here are great, but I wanted to add my two cents.

Classes in `C++` offer quite a few conveniences, other answers here mentioned `Encapsulation`, `Polymorphism` but there's also `Inheritance`. Overall you can emulate all this functionality in `C` using a `struct`, but is it worth it?

The simple answer is, this is all there for convenience and to make the code more **maintainable**. When you have a small project, it might be easy to just use global variables for everything, not use a `Class` at all, and still make something that works.

The problem comes when you **add features**, and suddenly your code has hundreds of variables in scope, even though they are not relevant/needed. It suddenly becomes a problem of, can you keep working on this project? Or is it that complex that it feels too much effort?

From experience, I've seen more projects being abandoned for being unmaintainable, than from not being performant enough. Just because your project feels maintainable in its early steps, that doesn't mean it will remain that way as you work on it.
> 2 votes

# Answer
C++ is a huge language, and there can be reasons not to use particular feature, and lots of argument about which features should be used.

For instance, if you use polymorphism, you are paying a small speed penalty for the indirectness of virtual method calls, and a memory penalty (on 64 bit platforms, 8 bytes to store a pointer to the virtual method table). If your class is in a very tight loop or you have *lots* of objects, this could matter.

The only reason I can think of not to use encapsulation is quick prototyping, and that will mess you up as you scale.

The game I'm working on has no virtual methods at all (yet, that might change), but I use encapsulation extensively.
> 1 votes

---
Tags: architecture, oop
---


title: Usage of 'World rotation quaternion'?

text:
# Question
Title: Usage of 'World rotation quaternion'?
While debugging the code that decomposes the world matrix, I found that the decomposed world rotation value is different from the world rotation value stored in Transform.

Simply, World Rotation is accumulated 'only' rotational data from root Transform, and I think it will have different results than World Matrix, which accumulates size and location values as well.

If my assumption is correct, is this rotation value not used to "make" the world matrix, but stored to obtain your relative rotation value by comparing it with the world quaternion value of the parent transform? Or if I'm wrong, where is this world quaternion value used?

# Answer
> 0 votes
World `rotation` and world `matrix` differ; world `rotation` is for relative rotations, world `matrix` contains full transform info, both used in transform hierarchies and specific calculations.

---
Tags: rotation, transformation, quaternion
---


# Question
Title: How to add samples with dependencies to Asset Store?
I want to add a sample to an asset published on the `Asset Store` in `Unity`. Sample has a dependency on the `netcode` package. This causes users to get an error when they download it from the `Asset Store`. Actually, I write what needs to be done in the document, but those who try to use it without reading it encounter errors and make negative comments. How can I provide a solution for this issue?

# Answer
> 0 votes
You can use the Package Manager Scripting API to install a package.

You might want to prompt the user for this. For example:

```
const string PACKAGE_ID = "com.unity.netcode";
static ListRequest Request;
static void CheckForNetcodePackage() {
    Request = Client.List();    // Get a list of installed packages for this project.
    EditorApplication.update += Progress;
}

static void Progress() {
    if (Request.IsCompleted) {
        if (Request.Status == StatusCode.Success)
            // Check if the package is installed.
            bool found = false;
            foreach (var package in Request.Result) {
                if (package.packageId == PACKAGE_ID) {
                    found = true;
                    break;
                }
            }
            // If the package wasn't found, prompt the user to install it.
            if (!found) {
                string title = "Missing Netcode package";
                string message = $"The demo scene requires {PACKAGE_ID}. Install it?";
                if (EditorUtility.DisplayDialog(title, message, "Ok", "Cancel") {
                    Client.Add(PACKAGE_ID);
                }
            }

            EditorApplication.update -= Progress;
        }
    }
}

```

I haven't tested this code, so it may have typos or other mistakes, but it should be enough to get you most of the way there.

---
Tags: unity, assets
---


# Question
Title: How to get difference in rotation between 2 objects, but only on one axis
Say I have 2 cubes that start with the same rotation. I wish to track the rotation difference between the 2 about the z (forward) axis. Such that if cube A remains stationary and cube B rotates 30 degrees Z, I get 30 degrees. But if it then rotates an additional 30 degrees Y, I get the summation of those 2 rotations (which should be around 42 degrees) on that one axis. But if I only rotate Y or Z, the result is 0.

I'm working within unity and have tried

```
Quaternion.Angle(boxA.transform.rotation, boxB.transform.rotation, Vector3.forward);

Quaternion.AngleAxis(Quaternion.Angle(boxA.transform.rotation, boxB.transform.rotation), Vector3.forward));

```

and a custom solution I found online

```
float angle = 0f;
Vector3 angleAxis = Vector3.zero;
(boxB.transform.rotation * Quaternion.Inverse(boxA.transform.rotation)).ToAngleAxis(out angle, out angleAxis);
return Mathf.DeltaAngle(0f, angle);

```

All of which will give correct results when only Z is rotated, but gives the angle when any other axis is rotated as well (eg if I only rotate X 45, it spits out 45 despite it not being on the axis plane I'm interested in).

If you need the practical reason I need this info, I'm comparing the rotation between a knob and a hand. Say the knob and hand start with the same rotation, I want to track how far a hand turns and apply it to a knob (under special conditions, so I can't just copy the rotation straight up), I only care about the Z rotation ("forward" into the knob panel); if the hand "rotates" in towards the knob panel, I don't care about that rotation.

# Answer
> 0 votes
You can use \_object1.transform.rotation.eulerAngles.z and \_object2.transform.rotation.eulerAngles.z and then you can use transform.rotation = Quaternion.EulerRotation(new Vector3(x,y,z));

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


# Question
Title: Apple Watch Intermediary Script with Unity or Remake Game in Xcode?
there. I had a question that I keep finding dead ends to. Is it possible to create a Unity iOS project that has the ability to talk to a WatchOS app? I know that there's no current way to build it directly with unity but theoretically could it work if there was an intermediary script that allowed the two to talk to each other when the code is transferred it to Xcode? I'm building a game that I want to have a watch app for but I've started building it in Unity and would like to keep it there just in case for other distributions.

Otherwise I'm thinking I might have to remake the game in XCode to have that functionality. What is the best course of action here? Try to make an intermediary script (is that's possible) or switch completely over to Xcode. I'm thankfully not too far in development that I can't switch over. Lemme know!

# Answer
> 2 votes
On many platforms, you can integrate native functionality that isn't built into Unity with native plugins. This includes iOS. In this case, you would need a native iOS plugin that uses the Watch Connectivity Framework to communicate with your watch app.

While you can sometimes find unofficial native plugins online, these are often outdated. You may need to create your own native plugin.

To be clear, a native plugin could allow your iPhone/iPad game to *communicate* with your WatchOS app. You would not be able to create the WatchOS app itself in Unity.

A tip: don't try to create and integrate a native plugin for Watch Connectivity until you've actually developed your WatchOS app. A connectivity plugin doesn't do you any good if you don't have anything to connect to.

---
Tags: unity, ios, xcode, hardware
---


# Question
Title: How to instantiate Capsule to always be facing another GameObject regardless of Capsule's world position?
I have the following line of code:

`Instantiate(capsulePrefab, GameObject.Find("BlueCube(Clone)").transform.position + transform.right * 1f - transform.up * 1f - transform.forward * 1f, (Quaternion.Euler(0f, 135, 0f)));`

Basically, I am instantiating a capsule `capsulePrefab` at the location of another prefab `BlueCube(Clone)` but 1 unit to the right, behind, and down.

That much works fine (it does spawn in the correct position). But on top of this, I am trying to make it so that `capsulePrefab` spawns facing towards `BlueCube(Clone)` prefab.

Instead, what happens is that `capsulePrefab` only spawns facing `BlueCube(Clone)` if `BlueCube(Clone)` is in certain world positions, like so:

Therefore, how can it be coded that when `capsulePrefab` spawns, it always spawns facing `BlueCube(Clone)`?

# Answer
In Unity, you can make an object look at an object or point in space with the `transform.LookAt()` function, for example:

`capsule.transform.LookAt(blueCube.transform.position);` or `capsule.transform.LookAt(blueCube.transform);`

If you want the capsule to *always* face the cube, even if the cube or capsule moves around, you can use a Look At constraint.

Basic questions like this can be answered with a simple web search.

**EDIT:** As to DMGregory's comment, if you only want to yaw (rotate on the global Y axis) without any pitch or roll, do this:

```
var position = blueCube.transform.position;
position.y = capsule.y; // Prevent looking up or down
capsule.transform.LookAt(position);

```
> 2 votes

---
Tags: unity
---


# Question
Title: How to check if an AABB is colliding or the mesh itself
I have the following problem. I would like to check in bullet whether only the AABB collides or the mesh collider itself. Unfortunately I can't find out how to do this

Within the screenshot you can see that there is a very big aabb between the houses and the car with tree. So its impossible for the player to move through this area.

So i try to approach that the collision from the manifold only rise the the even when the player shape collides with an real triangle within this ConvexTriangleMesh.

# Answer
I don't have a lot of experience with Bullet, but based on the limited information you've provided:

You've said that you're using a Convex Mesh. A Convex collision mesh can't have any voids or empty spaces. It looks like you are combining multiple triangles into one composite collider. If this is the case, in this specific circumstance your AABB and collision mesh are the same. Bullet will not have any information about whether there are triangles inside the collider.

If you want to be able to walk into the gap between the house on the right and the van on the far right, you should not be combining all of these objects into one convex mesh. You should probably do something like this, where each red box is its own convex collision mesh.

There is technically a higher performance cost for having more colliders, but a handful of static box colliders like this should be a non-issue on any modern device.
> 0 votes

# Answer
Ah ok, i created an CompoundShape and all all the tiles into this shape. It get debuged wrong but behaves like it should

This is my code atm

```
public void CreateRigidBody(float mass, PhysicHandler handler)
{
    if (this.Parent.GetType() == typeof(BufferedSprite))
    {
        var bufferedSprite = (BufferedSprite)this.Parent;
        //var Childshape = new ConvexHullShape(bufferedSprite.Verticies.ToArray());
        //var shape = new Convex2DShape(Childshape);

        var mesh = new TriangleMesh();

        CompoundShape compoundShape = new CompoundShape(true);

        foreach(var deffinition in bufferedSprite.ShapeDeffinitions)
        {
            Box2DShape box2DShape = new Box2DShape(new Vector3(deffinition.sizeX, deffinition.sizeY, 0f) / 2);
            BulletSharp.Math.Matrix boxtransform = BulletSharp.Math.Matrix.Translation(new Vector3(deffinition.locX, deffinition.locY, 0f));
            compoundShape.AddChildShape(boxtransform, box2DShape);

            //Vector3 v1 = new Vector3(deffinition.verticies[0], deffinition.verticies[1], deffinition.verticies[2]);
            //Vector3 v2 = new Vector3(deffinition.verticies[3], deffinition.verticies[4], deffinition.verticies[5]);
            //Vector3 v3 = new Vector3(deffinition.verticies[6], deffinition.verticies[7], deffinition.verticies[8]);
            //mesh.AddTriangle(v1, v2, v3, true);

            //v1 = new Vector3(deffinition.verticies[0], deffinition.verticies[1], deffinition.verticies[2]);
            //v2 = new Vector3(deffinition.verticies[3], deffinition.verticies[4], deffinition.verticies[5]);
            //v3 = new Vector3(deffinition.verticies[6], deffinition.verticies[7], deffinition.verticies[8]);
            //mesh.AddTriangle(v1, v2, v3, true);
        }
        //ConvexTriangleMeshShape shape = new ConvexTriangleMeshShape(mesh, true);
        //var shape = new Convex2DShape(meshShape);

        RigidBodyConstructionInfo info = new RigidBodyConstructionInfo(mass, null, compoundShape, compoundShape.CalculateLocalInertia(mass));
        BulletSharp.Math.Matrix transform = BulletSharp.Math.Matrix.Translation(bufferedSprite.Location.ToBulletVec3());
        Matrix startTransform = transform;
        info.MotionState = new DefaultMotionState(startTransform);

        RigidBody = new BulletSharp.RigidBody(info);
        RigidBody.UserObject = this.Parent;
        RigidBody.LinearFactor = this.LinearFactor.ToBulletVec3();
        RigidBody.AngularFactor = this.AngularFactor.ToBulletVec3();
        RigidBody.CollisionFlags = CollisionFlags.StaticObject;

        handler.ManageElement(this);
    }
    else
    {
        throw new InvalidOperationException("Invalid element for this Behavior");
    }
}

```
> 0 votes

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


# Question
Title: Set FBX creator while exporting using FBX SDK
I am using **FBX SDK 2018.1.1** to write a simple utility application on windows that will export existing FBX file (this file is exported from Blender 2.79).

I need to set the creator of the final FBX file to "My custom FBX exporter". As per documentation of FBX SDK, it can be done using

http://help.autodesk.com/cloudhelp/2018/ENU/FBX-Developer-Help/cpp\_ref/class\_fbx\_i\_o\_file\_header\_info.html

here is the code snippet used to export the FBX:

```
FbxExporter* pExporter = FbxExporter::Create(m_pSdkManager, "");

pExporter->SetFileExportVersion(FBX_2012_00_COMPATIBLE);

FbxIOFileHeaderInfo *infoExporter = pExporter->GetFileHeaderInfo();
infoExporter->mCreator = "My custom FBX exporter";

pExporter->Export(m_pScene);
pExporter->Destroy();

```

But when I read this newly exported FBX file it shows "**FBX SDK/FBX Plugins version 2018.1.1**" in the mCreator field. This is the snippet when I import the file (*just to check if mCreator property is properly set*)

```
lImportStatus = lImporter->Import(m_pScene);

info = lImporter->GetFileHeaderInfo();

```

How do I properly set the mCreator in FBX file header so that it is set in final exported file?

# Answer
> 1 votes
Try this code as your baseline, which is from Unreal Engine in the file of `UnrealEngine\Engine\Source\Editor\UnrealEd\Private\Fbx\FbxMainExport.cpp`

void FFbxExporter::CreateDocument()
{
    Scene = FbxScene::Create(SdkManager,"");

    // create scene info
    FbxDocumentInfo* SceneInfo = FbxDocumentInfo::Create(SdkManager,"SceneInfo");
    SceneInfo->mTitle = "Unreal FBX Exporter";
    SceneInfo->mSubject = "Export FBX meshes from Unreal";
    SceneInfo->Original_ApplicationVendor.Set( "Epic Games" );
    SceneInfo->Original_ApplicationName.Set( "Unreal Engine" );
    SceneInfo->Original_ApplicationVersion.Set( TCHAR_TO_UTF8(*FEngineVersion::Current().ToString()) );
    SceneInfo->LastSaved_ApplicationVendor.Set( "Epic Games" );
    SceneInfo->LastSaved_ApplicationName.Set( "Unreal Engine" );
    SceneInfo->LastSaved_ApplicationVersion.Set( TCHAR_TO_UTF8(*FEngineVersion::Current().ToString()) );

    Scene->SetSceneInfo(SceneInfo);

    //FbxScene->GetGlobalSettings().SetOriginalUpAxis(KFbxAxisSystem::Max);
    FbxAxisSystem::EFrontVector FrontVector = (FbxAxisSystem::EFrontVector)-FbxAxisSystem::eParityOdd;
    if (GetExportOptions()->bForceFrontXAxis)
        FrontVector = FbxAxisSystem::eParityEven;

    const FbxAxisSystem UnrealZUp(FbxAxisSystem::eZAxis, FrontVector, FbxAxisSystem::eRightHanded);
    Scene->GetGlobalSettings().SetAxisSystem(UnrealZUp);
    Scene->GetGlobalSettings().SetOriginalUpAxis(UnrealZUp);
    // Maya use cm by default
    Scene->GetGlobalSettings().SetSystemUnit(FbxSystemUnit::cm);
    //FbxScene->GetGlobalSettings().SetOriginalSystemUnit( KFbxSystemUnit::m );

    bSceneGlobalTimeLineSet = false;
    Scene->GetGlobalSettings().SetTimeMode(FbxTime::eDefaultMode);

    // setup anim stack
    AnimStack = FbxAnimStack::Create(Scene, "Unreal Take");
    //KFbxSet<KTime>(AnimStack->LocalStart, KTIME_ONE_SECOND);
    AnimStack->Description.Set("Animation Take for Unreal.");

    // this take contains one base layer. In fact having at least one layer is mandatory.
    AnimLayer = FbxAnimLayer::Create(Scene, "Base Layer");
    AnimStack->AddMember(AnimLayer);
}
```

---
Tags: c++, fbx
---


# Question
Title: Why is my spring exploding? And how to fix it?
Let's say I have a 1-dimensional spring, and I want to simulate it by applying a force that may vary with time. We can skip friction and dampeners for now.

From what I learned many years ago in high school physics, one can apply Hooke's law and calculate the resulting force, which can be applied to calculate the resulting displacement.

Here's a trivial snippet that in principle does just that:

```
float spring = stiffness * displacement;
float totalForce = force - spring;
displacement += (velocity * deltaTime) + (totalForce * deltaTime * deltaTime / 2.0f);
velocity += totalForce * deltaTime;

```

I'm over simplifying some things, like the mass of the spring, and this is by design. I'd rather have a simple system than a complex one that is perfectly physically accurate.

With a non-zero initial displacement, and zero force, this should oscillate in place. However, when I actually go and simulate it, the oscillation magnitude grows and grows infinitely.

I tried plotting this, and this is the result:

I'm reading some stuff online, and it seems like this method is infamous for being unstable, although it's not really clear to me why.

I'll continue researching, but is there a way to fix my method so it's more stable, or alternatively, is there a known simple, stable method to simulate something that looks like a spring? Once again, simplicity is more important than perfect accuracy.

# Answer
# Your problem: using a Discrete Feedback Model

What this means is that your future spring's state depends on its current state. The force actively changes depending on what position it is right now.

Now, normally that's not a problem. In theory. Regular springs in the real world can be demonstrated to have this property. However, your issues is that you're simulating it discretely - meaning you're using time steps.

A normal spring is continuous, which means the laws of physics apply at every moment in time. Your spring, however, has its physics calculated every time step. This means that you miss all of the physics that happens between the time steps, and that introduces bias into your forces. Bias, in turn, will amplify instability in an unstable model, which is just what your spring happens to be.

Just to demonstrate this, try changing your time step. It should change the pattern of instability of your plot, though it will still be inherently unstable.

An easy fix would be to introduce a dampening term. With a sufficiently small time step, this means that the spring would stabilize, though it would eventually stop over time. You want a spring that keeps going forever, though, so let's talk how to get that.

# Your solution: using a Mathematical Model

For a spring without dampening, the position-vs-time graph you want matches the equation for harmonic motion:

x(t)=Acos(ωt+ϕ)

Now you can calculate the A, ω, and ϕ terms using your spring equation and information you already know. For your case, it's pretty easy:

A = starting displacement

ϕ = 0 (because you're starting at maximal displacement)

ω can then be calculated with your spring equation:

Whenever you want to know the position, you can just query this equation using the time since the spring started springing. You can of course add more terms onto this, depending on what you want.

Of course, there are also issues with how this will interact with other things in your simulation. If you want a spring, that, say, reacts when you hit it with something, then you'll just have to recalculate the equation at the point that you hit it. This is very doable, but it can make the math a little more complex.

This text is really useful to figure out how to do further calculations.
> 1 votes

---
Tags: physics, spring
---


# Question
Title: Camera movement automatically tracking a tool over a surface
I need to create camera movement tracking the clipper hair like this:

I already have a script for the movement of the tool.

* I'm using Snapping Player to the Surface of an Object of this pos How could I constrain player movement to the surface of a 3D object using Unity?

```
  private void UpdatePlayerTransform(Vector3 movementDirection){
  if (GetRaycastDownAtNewPosition(movementDirection, out hitInfo)){
      Quaternion targetRotation = Quaternion.FromToRotation(Vector3.up, hitInfo.normal);
      finalRotation = Quaternion.RotateTowards(transform.rotation, targetRotation, float.PositiveInfinity);
      transform.rotation = Quaternion.Lerp(transform.rotation, finalRotation, Time.deltaTime * smoothTime);
      transform.position = Vector3.Lerp(transform.position, hitInfo.point + hitInfo.normal * .08f, Time.deltaTime * smoothTime);
      }
  }

  private bool GetRaycastDownAtNewPosition(Vector3 movementDirection, out RaycastHit hitInfo)
  {
      Vector3 newPosition = transform.position;
      Ray ray = new Ray(transform.position + movementDirection * Speed, -transform.up);

      if (Physics.Raycast(ray, out hitInfo, 1f, WorldLayerMask))
          return true;

      return false;

```

}

* I'm find move director

```
  void FindMovementDirVector(){
  try
  {
      float angle = Vector3.Angle(hitInfo.normal, Vector3.up);
      float angleWithForward = Vector3.Angle(hitInfo.normal, Vector3.forward);
      if (angleWithForward < 90 && angle < 60)
      {
          caseName = "Case 1";

          if (angleWithForward > 30)
              localForwardDir = Vector3.Lerp(localForwardDir, Vector3.Cross(hitInfo.normal, -Camera.main.transform.right), Time.deltaTime * smoothTime);
          else
              localForwardDir = Vector3.Lerp(localForwardDir, Vector3.Cross(hitInfo.normal, LocalRightDir), Time.deltaTime * smoothTime);

          LocalRightDir = Vector3.Lerp(LocalRightDir, Vector3.Cross(-localForwardDir, hitInfo.normal), Time.deltaTime * smoothTime);
      }
      else
      {
          caseName = "Case 2";
          Vector3 to = new Vector3(hitInfo.normal.x + hitInfo.point.x, hitInfo.point.y, hitInfo.normal.z + hitInfo.point.z);
          if (angleWithForward > 35)
              LocalRightDir = Vector3.Lerp(LocalRightDir, Vector3.Cross(to, Vector3.up), Time.deltaTime * smoothTime);
          else
              LocalRightDir = Vector3.Lerp(LocalRightDir, -Vector3.Cross(to, Vector3.up), Time.deltaTime * smoothTime);
          localForwardDir = Vector3.Lerp(localForwardDir, -Vector3.Cross(hitInfo.normal, LocalRightDir), Time.deltaTime * smoothTime);
      }
  }
  catch { }
  }

```

+ Input script

    ```
      private void TouchInput(){
      if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
      {
          pointer_x = Input.touches[0].deltaPosition.x;
          pointer_y = Input.touches[0].deltaPosition.y;

          if (pointer_x > 0)
              movementDirection += LocalRightDir * pointer_x;
          else if (pointer_x < 0)
              movementDirection -= LocalRightDir * Mathf.Abs(pointer_x);

          if (pointer_y > 0)
              movementDirection += localForwardDir * pointer_y;
          else if (pointer_y < 0)
              movementDirection -= localForwardDir * Mathf.Abs(pointer_y);
      }}

    ```

# Answer
> -2 votes
Personally, I would add an empty game object in the middle of the head and have the camera always LookAt() it. Then place another empty game object, as a child of the clippers, and have your camera always move towards it, probably using Vector3.SmoothDamp() (as it will give a bit of easing to the camera movement).

Danny

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


# Question
Title: How to pause player motion during an air attack animation in Godot 4?
So I am very new to Game Dev, and I am running into a problem that seems like it should have a simple answer. Unfortunately, I have not been able to figure it out.

I am creating a 2d side scroller. I have incorporated a quick and heavy attack the player can execute on the ground, and a set of attacks when the player is jumping. However, when the air attacks animate, the player continues falling to the ground - often landing before the attack animation finishes. I would like to lock the players position in the air until the animation finishes, and then allow the player to fall it is complete. I haven't figured out how to stop and make the player hover in place during the animation. I've searched around for a solution, but haven't been able to find an explanation.

This doesn't seem like a particularly unique concept, and I am hoping somebody has some sort of similar experience. I would be happy to provide any extra information needed. Thank you for any help you can provide.

# Answer
> 0 votes
Assuming your player character is a `CharacterBody2D`, you are in charge of moving it.

For example, you might be adding gravity to the velocity, something like this would suffice:

```
velocity += gravity * delta

```

---

So temporarly disabling gravity is a matter of setting a flag and checking it before doing the gravity computation. For example, we can declare:

```
bool _attacking := false

```

On your attack code you set:

```
_attacking = true

```

And you might want to connect a method to the `finished` signal of your animation player, so you can there reset the flag:

```
_attacking = false

```

And then we can check:

```
if not _attacking:
    velocity += gravity * delta

```

As alternative, you might check which is the current animation of the animation player, and use that to know if the player is attacking.

---
Tags: animation, godot, godot-4, gravity
---


title: How is this smoke effect made?

text:
# Question
Title: How is this smoke effect made?
In the game `Sheepy`, first (actually second) boss is a crazy cat that generates a very cool kind of light/smoke effect, as it is visible in this video at 12'00:

https://youtu.be/BKBfftWn5Zo?t=720

It looks like some particle effect with additive blend (+ pixelization) mixed with manual animation of the cat in pixel art. The engine seems to be Construct3 if that helps.

Is this how it's done? Else what could be the techniques used?

**EDIT**

* The cat is animated frame by frame.
* It *looks like* that the smoke is a solid surface with a flower-shaped sprite particle that keeps being generated from the particle emitter but I am still not sure that this is how it is made.

# Answer
> 0 votes
The smoke effect might simply be an elaborate frame-by-frame animation parented to the cat, rather than a procedural effect. I haven't played Sheepy, but given the very fluid frame animation of the cat when it jumps on and climbs around the elevator, it seems safe to assume that a similar technique was used for the smoke.

If this is indeed a frame animation, it may be composed of multiple layers, and possibly broken into tiles.

Eventually, someone will probably rip the art assets from the game, and then you'll have a concrete answer.

# Answer
> -1 votes
**Note for the downvoters: of course I mean realtime and in shaders, not in Photoshop - thats just a 3 minute mockup to make it visual**. If thats not the reason for the downvote please explain yourself.

I think my attempt would be a like a 2D particle metaballs in a secondary buffer.

Gradients from white to black, set to additive and animate that:

After that in a post process effect on that layer put a "levels / range":

And between maybe add some edge noise. Like throw a blocky noise map over the whole image before you set the levels.

After levels/range:

Then take this as a mask, and draw it once purple/lighten for the highlight and once dark/black for the main sligthly offset.

There also seems to be a general glow posteffect on their screen that really blends it together.

Of course this needs a lot of tweaking, but I would roughly take this approach.

---
Tags: particles, pixel-art
---


# Question
Title: How to rotate a game object automatically based on the angle?
I need someone to help me think about how this works so I can implement this behavior in my game. Below is a video from a game that does exactly what I am trying to accomplish. An airplane that only moves forward and automatically flips depending on the angle.

Here is a working sample of what I want to accomplish: https://youtu.be/VchXH0DvB-4

Here is my game in its current state: https://youtu.be/S1kDiF9wA7Y?si=599jcxnK4oA8ofGr&t=20

Currenlty the only code I have for my airplane is the forward translation and the right rotation depending on the vertical input.

```
void Update()
{
    transform.Translate(Vector3.forward * Time.deltaTime * forwardSpeed, Space.Self);
    transform.Rotate(Vector3.forward, -Input.GetAxis("Vertical") * rotationSpeed * Time.deltaTime, Space.World);
}

```

Quick explanation. The reason why I currently have the `Rotate` function rotating in the world space is so it would not interfere with airplane movement as I believe it needs to rotate around its own Z axis to accomplish what I am trying to do.

# Answer
> 0 votes
I think you are looking for `Quaternion.LookRotation(Vector3 direction, Vector3 up)`. This very useful method allows you to generate a new rotation that represents a tilt up and down, a yaw left and right, but no roll relative to the horizon (as defined by the `up` vector). So when you pass through the -90° or +90° vertical angle, it will flip the object around by 180° around the roll axis, so it doesn't end up upside-down.

If you don't want that rotation to be immediate but only happen in increments, then `Quaternion.RotateTowards(Quaternion currentRotation, Quaternion desiredRotation, float maximumChange)` could be what you are looking for. This generates a quaternion that changes the rotation from one to another, but limited by an amount of degrees.

Or in a more complete code snippet:

```
float turnRate = /* turn rate in degrees per second */
Vector3 direction = /* read input to get the direction you want to fly into */
Quaternion desiredRotation = Quaternion.LookRotation(direction, Vector3.up);
transform.rotation = Quaternion.RotateTowards(transform.rotation, desiredRotation, turnRate * Time.deltaTime);

```

---
Tags: unity
---


# Question
Title: Is there any performance penalty to unsigned integer underflow?
Is there any performance penalty to unsigned integer underflow?

Suppose I have a computation subtracting two unsigned integers (so underflow can happen if `b > a`), but still gives the correct result for my application logic because I want it to wrap anyway:

```
// Note: a and b are uint32_t
uint32_t c = (a - b) & mask; // mask is doing the equivalent of modulo

```

Performance-wise, is it better to intentionally let the underflow happen, or am I better off taking measures to avoid underflow, such having an if statement to handle the case `b > a` differently?

# Answer
You didn't specify the processor or the compiler you are using.

On any of the x86 family and any compiler I'm aware of, the answer would be that overflow has no impact on performance whatsoever. This is probably true for other processors as well.

If you want to be sure, look at the assembly code that is produced (-S in clang or gcc, make sure there is a -g or -ggdb3 so it includes the source code line numbers), and you will probably find it translates to something like (produced with gcc on x86-64):

```
    subl    %esi, %edi
    andl    %edx, %edi

```

If you do the same thing with signed,

```
    subl    %esi, %edi
    andl    %edx, %edi

```

So there is no difference, and if you want to be complete about it, look up the instruction timing for your processor (https://www.agner.org/optimize/instruction\_tables.pdf is great for this for x86) to check that there is no timing penalty for setting the overflow carry flag (I've never seen a processor for which this is the case). Under the hood, the difference between signed and unsigned usually only matters when doing something like inequality, multiplication, division or converting to and from strings.

Adding in a specific test will either make it slower, or the compiler will optimize the test out if it sees that both sides do the same thing.

Having said that, you risk running into undefined behavior when you try this sort of thing (even if this particular case is not undefined) and should at the very least add a comment about what you are doing so this doesn't trip you up later.
> 11 votes

# Answer
## No performance penalty

Generally the overflow / underflow (carry flag) is automatically set and does not have a performance penalty.

## Avoid branching code

You suggest *"having an if statement to handle the case b \> a differently?"*

That would introduce a performance penalty. CPUs look ahead and load instructions ahead of the current program counter (address) so that instructions can be processed optimally. Branches have two paths, and thus the CPU must guess which path will be taken. If the guess is incorrect then the CPU must wind back the cached instructions. This is a significant performance penalty.

Fast code avoids branching when it can.

## Use addition?

Using a modulo you don't need to subtract, you can add. Example the same calculation using subtraction and addition.

`10 - 2 & 0xFF == 8`

`10 + 254 & 0xFF == 8; // no overflow`

Using unsigned 32bit int and mask has all bits from top most to bottom set, eg `0x1ff == 511`. The following lines are equivalent .

`c = (a - b) & mask;`

`c = a - b & mask; // - has precedence over bitwise And &`

`c = a + mask + 1 - b & mask;`

This may be a better option if calculating `mask + 1 - b` is trivial or if `b` is a constant value (meaning `mask + 1 - b` is constant as well).

Trust the compiler and just use `c = a - b & mask;`
> 7 votes

# Answer
Unsigned integer overflow (and underflow) shouldn't have any noticeable impact on performance.

On top of that, based on Wikipedia - Integer Overflow, unsigned integer overflow is defined to wrap around, **but signed integer overflow is undefined behaviour**. It mentions `C` but the same should be true for `C++`:

> In C, unsigned integer overflow is defined to wrap around, while signed integer overflow causes undefined behavior.

When you're asking about performance, it starts to sound like Premature Optimisation. My advice would be, don't focus on micro-optimising every line of code, but when your project starts using more performance than you want it to, profile it and focus on the areas that use the most performance.

### Should you depend on unsigned integer overflow behaviour?

Part of me feels like it might be a better idea not to. The code might be harder to read if a new person is looking at it. There's also the human error element, if your code depends too much into unsigned integer overflow, someone might accidentally decide to switch to signed integer, which will cause undefined behaviour in your project.
> 3 votes

# Answer
> Is there any performance penalty to unsigned integer underflow?

No.

There is no cost to the wrapping (modulo) behavior of arithmetic with unsigned integral types. Processors use same instructions for integer subtraction regardless of whether the values are considered signed or unsigned. So there's no performance difference of that subtraction based on the signedness of the operands.

(For some bitshift operations, different instructions are used for signed and unsigned types, but I'd be surprised if they ran at different speeds.)

Both C and C++ agree that unsigned integer arithmetic is well-defined for overflow and underflow. When the programmer chooses to use unsigned integral types for the operands, they are choosing the wraparound behavior. Neither the processor nor the compiler has to do any extra work to produce the correct result.

With *signed* integers, however, the *C and C++ standards* say the behavior of subtraction is undefined if an underflow occurs (even though we know what the processor will do!). Declaring it undefined frees the compiler to apply certain optimizations and/or to help catch bugs.

At first glance, the expression `x - 42 < x` (where `x` and `42` are signed integral types) seems like it should always be true. But it's not because `x - 42` will underflow for certain values of `x`. Maybe the programmer knows it'll never happen because `x` will always be larger than 42. Or maybe they forgot to consider the possibility of underflow.

If the standard defined what the program's behavior must be in that case, the compiler would have to generate the instructions to do the subtraction and the comparison and possibly more to get the behavior aligned with what the standard required. And since the programmer's intent is unclear, what behavior should the standard require here?

Instead, the standard leaves it undefined. Any program where that subtraction can underflow is invalid. The compiler doesn't have any obligation to invalid programs, so it can assume that the underflow will never ever happen. And thus it can optimize away the entire expression.

Being able to detect whether an operation would over- or underflow could be useful. (Ironically, it's tricky to do correctly without over- or underflowing.) And a correct test could be costly in terms of performance.

It might be relatively inexpensive to have the compiler, when targeting certain processors, insert instructions to test for overflow and underflow immediately after it occurs. (Remember, the behavior is well-defined for the processor, just not the language.) Thus the compiler could make your code trap when the problem occurs. Like dereferencing an invalid pointer, a crash is likely better than the program proceeding in a bad state. I believe clang's undefined behavior sanitizer (UBSan) does that.
> 1 votes

# Answer
While the CPU can deal with undeflow without any performance hit, there are some cases where the undefined behaviour of signed integer underflow/overflow can actually help the compiler optimize code.

This probably isn't the case for the code mentioned above, but it can have an influence in some cases. This is discussed in some detail at: http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html

> For example, knowing that INT\_MAX+1 is undefined allows optimizing "X+1 \> X" to "true". Knowing the multiplication "cannot" overflow (because doing so would be undefined) allows optimizing "X\*2/2" to "X". While these may seem trivial, these sorts of things are commonly exposed by inlining and macro expansion.
> 0 votes

---
Tags: c++, performance
---


# Question
Title: How to record high quality footage for a game trailer?
I'm trying to record a trailer for my game using OBS, but the recordings are coming out in very poor quality. I've tried increasing the video bitrate, but that just makes the game lag during recording. How can I improve the recording quality without causing lag?

System Specs:

CPU: i7 9th gen GPU: GTX 1650 RAM: 16 GB

# Answer
> 2 votes
If the workload of both running the game and encoding the video is straining your system, you may want to invest in a separate capture device.

This is an external device that either acts as a monitor or as a pass-through between your PC and your existing monitor, and handles recording the video (and audio signals) passing through that connection.

Because it handles this workload external to your PC, your computer's resources can remain 100% devoted to keeping the game's framerate up at a high resolution, and load spikes won't cause video quality to suffer or add stutters.

A quick search for "game capture device" will turn up a number of options you can evaluate.

---
Tags: unreal, unreal-5, marketing, video, trailer
---


title: How do i get key input using c#

text:
# Question
Title: How do i get key input using c#
To change key configuration i need to get the key input but after looking around i havent found any way of doing that using c#.The other way is using the Gd programming language.but i cant do that as my whole script(works) is using c# including the object that has the key detection script so changing the language will couse me a lot of problem:(

# Answer
> 0 votes
This is the code for getting the key input:

```
      public override void _Input(InputEvent @event)
  {
      base._Input(@event);
      if (@event is InputEventKey inputKey && isRemapping==true)
      {
          Key c = inputKey.Keycode;
          GD.Print(c);
          Pressed = inputKey;
          GetViewport().SetInputAsHandled();
          isRemapping = false;
      }
  }

```

# Answer
> 0 votes
---

## Awaiting a key

I believe we can create a custom signal for this:

```
[Signal]
public delegate void KeyPressedEventHandler();

public override void _Input(InputEvent @event)
{
    base._Input(@event);
    if (@event is InputEventKey inputKey)
    {
          EmitSignal(SignalName.KeyPressed);
    }
}

```

And then we should be able to await it:

```
await ToSignal(this, SignalName.KeyPressed);

```

---

## General Input

Although I believe you already know how to check if an action is pressed, let us look at it again. You can, for example, do this:

```
Input.IsActionPressed("Move_Up")

```

Or this for analog input:

```
Input.GetActionStrength("Move_Up")

```

Now that `String` must match an action configured in project settings. So we are talking about reading and writing project settings.

However, input is handled a bit different than the rest. There are a couple things to know:

* The `InputMap` gives you access to the input settings. So we will be using that.
* What is getting stored in project settings are `InputEvent`s. Yes, the class of objects you get in `_Input`. They are `Resource`s, so they can be saved. And what Godot is doing is matching the input it gets to the stored ones.

---

Before we go on, I need to point out that manipulating `InputMap` on the editor (i.e. `tool` scripts) will give you access to the editor settings instead. And yes, you can end up messing them up.

---

First, to find out if a action is configured we can do this:

```
if (InputMap.has_action("Action_Name"))
{
    GD.Print("The action exists");
}

```

Second, if you want to find the names of all the actions that are configured do:

```
foreach (var action_name in InputMap.GetActions())
{
    GD.Print(action_name);
}

```

Third, to get the `InputEvent`s associated with an action, you do this:

```
foreach (var @event in InputMap.ActionGetEvents("My_ActioN"))
{
    GD.Print(@event);
}

```

Fourth, this is what I do to change them:

```
InputMap.ActionEraseEvents("My_Action");
foreach (var new_event in my_events)
{
    InputMap.ActionAddEvent("My_Action", new_event);
}

```

And I remind you that those events are `InputEvent`, so you can get them from `_Input` and add them to `InputMap`. *You probably want to filter them to the device the player is using (e.g. which controller). And remember leaving a way to cancel or restore the original settings.*

---

You, of course, will also want to be able to save these, and for that I remind you that they are `Resource`s. So you can use `ResourceSaver` and `ResourceLoader`.

However, if you rather not...

* For keyboard: From `InputEventKey` you can use either `keycode` or `physical_keycode`. And you might also want to store `alt_pressed`, `ctrl_pressed`, `shift_pressed` and `meta_pressed`.
* For mouse:

+ From `InputEventMouseButton` you use `button_index`.
    + From `InputEventMouseMotion`... I don't have code for this per-se. Instead I have sensitivity and invert axis.
* For joystick:

+ From `InputEventJoypadButton` you use `button_index`.
    + From `InputEventJoypadMotion` you use `axis` and `axis_value` (probably just the sign).

**Addendumm**: In both cases you identify the device by the `device` property.

**Note**: I'm looking on my GDScript code for the property names. I presume the capitalization is different on C#.

---

**Bonus**: if you want to mimic input, there is `Input.ActionPress` and `Input.ActionRelease`. There is also `Input.ParseInputEvent` which requires an `InputEvent`. There have been some bugs around these in Godot 4+ (either not doing anything or input getting stuck), so test if `ParseInputEvent` works better than `ActionPress` and `ActionRelease` on your version.

---
Tags: c#, input, godot
---


# Question
Title: How to stop moving a sprite if the user is holding down the opposing moving key at the same time?
I am new to creating games with graphics, and I want to make a very hard game. I have the movement down, but it has a weird bug where it if the user presses down the opposing movement key (i.e. `A` is to go left and `D` is to go right), it goes in the opposite direction and when the user stops pressing the opposing key in question, they stop moving in either direction.

I have did research to try to solve this problem myself, and found this question on Stack Overflow, and it made sense, but when I tried it, just made it even worse.

How can I stop the player from moving if the opposing key is pressed at the same time?

# Code

## Original Code

```
while True:
    if player.canMove:
                if e.type == KEYDOWN:
                    if pressed[K_w] and not pressed[K_s]:
                        dy = -player.speed
                    if pressed[K_a] and not pressed[K_d]:
                        dx = -player.speed
                    if pressed[K_s] and not pressed[K_w]:
                        dy = player.speed
                    if pressed[K_d] and not pressed[K_a]:
                        dx = player.speed
                elif e.type == KEYUP:
                    if e.key == K_c or e.type == QUIT:
                        close()
                    if e.key == K_a:
                        dx = 0
                    elif e.key == K_d:
                        dx = 0
                    elif e.key == K_w:
                        dy = 0
                    elif e.key == K_s:
                        dy = 0

```

## Modified Code

while True:

    up = None
    left = None
    down = None
    right = None

    if player.canMove:
                if e.type == KEYDOWN:
                    up = pressed[K_w]
                    left = pressed[K_a]
                    down = pressed[K_s]
                    right = pressed[K_d]

                    dx += (right - left) * player.speed
                    dy += (down - up) * player.speed
                elif e.type == KEYUP:
                    if e.key == K_c or e.type == QUIT:
                        close()
                    if e.key == K_a:
                        dx = 0
                    elif e.key == K_d:
                        dx = 0
                    elif e.key == K_w:
                        dy = 0
                    elif e.key == K_s:
                        dy = 0
```
</code></pre>

# Answer
> 1 votes
The simplest option would simply be to change your "else" condition to subtract instead of setting to zero....

```
            elif e.type == KEYUP:
                if e.key == K_c or e.type == QUIT:
                    close()
                if e.key == K_a:
                    dx += player.speed
                elif e.key == K_d:
                    dx -= player.speed
                elif e.key == K_w:
                    dy += player.speed
                elif e.key == K_s:
                    dy -= player.speed

```

That way, moving both ways cancels out and when one key is released you get the correct movement again.

# Answer
> 1 votes
**Depending on how you're interpreting dx/dy from between frames, you may want to skip the dx/dy += statements**

Focusing on this code block:

```
if e.type == KEYDOWN:
                    up = pressed[K_w]
                    left = pressed[K_a]
                    down = pressed[K_s]
                    right = pressed[K_d]

                    dx += (right - left) * player.speed
                    dy += (down - up) * player.speed

```

It looks like you're usually just increasing dx and dy every time a key is down, but with the key's information about which key is pressed, you can check against if a past key was pressed and you're processing one key being lifted up while still processing the keydown for another key.

For example:

If you're pressing down the "w" key, and then you press down the "S" key at the same time that you lift up the "w" key, it's possible that you're "Skipping" the event of registering that "W" got lifted, and "S" is being registered as being placed down.

One way to make this more robust is to check if dx or dy are positive or negative, and compare that to the opposing key.

If you turned the above into:

```
if e.type == KEYDOWN:
                    up = pressed[K_w]
                    left = pressed[K_a]
                    down = pressed[K_s]
                    right = pressed[K_d]

                    if (not (left and (dx >= 0))) and (not (right and (dx <= 0))):
                        # If we get here, we're not holding the "A" key down when we went right in a previous frame, or the "D" key when we're going left in a previous frame.
                        dx += (right - left) * player.speed
                    else:
                        dx = 0
                    if (not (up and (dy >= 0))) and (not (down and (dy >= 0))):
                        # If we get here, we're not holding the "W" key down when we went down in a previous frame, or the "S" key when we're going up in a previous frame.
                        dy += (down - up) * player.speed
                    else:
                        dy = 0
                    # ...etc.

```

The above presumes that you want dx and dy to be accelerating every while loop where the key in the same direction is pressed, and not the opposite direction key being pressed (As dx and dy are being added to, not assigned to the movement value of `(right -left) * player.speed` \- that might mean that the value could be kept constant instead of zeroing it out otherwise, and by removing the else statements, you can keep their momentum going until they drop the key they were holding and they then get to the "Key up" event and get zeroed out there as well.

As a note:

I suspect that the reason the linked code didn't work here, is that lines like `dx += (right - left) * player.speed` are about changing the delta to the player.x value, not the player.x value being added to itself (That is, after calculating `dx` here, you later went to `player.x += dx`.). So when `(right-left) * player.speed` was negative, but `dx` was already positive, you were decelerating by player.speed delta in the opposite direction - and every frame it was accelerating the deceleration. This might be the case if you were seeing the player character slow down moving in the positive direction once the opposing key is pressed, then and speed up in the negative direction. It may have been that `dx` was 0 for a single frame, and then the next frame immediately applied the reversed `dx` value.

---
Tags: python, pygame, keyboard
---


# Question
Title: How to rotate spaceship quaternion to face target direction with constant angular speed?
I have an enemy spaceship, and I want to make it turn to face the player with (for now) a constant angular speed. The ship's orientation is a quaternion. How do I do this?

Since this is totally free rotating space, I feel there should be no preferred up direction in the calculation except one based on the current enemy orientation quaternion... (perhaps the up vector of my coordinate system rotated by the enemy's orientation...?)

(I will eventually also want to make it angularly accelerate and decelerate, but I might be able to figure it out if I understand the solution for constant speed well enough.)

# Answer
> 1 votes
I got it. I was nearly there for ages, and flipping the multiplication on the final statement (rotationToApply * orientation, not orientation * rotationToApply) fixed it. Apparently whether you are working in an absolute frame of reference (like here) you put the second rotation to apply on the left side of the multiplication, but in an object's own frame of reference (like when applying angular velocity) you put it on the right. I don't understand any more than that yet.

I have some Lua code that does everything here (`~=` is "not equal to", and `condition and a or b` is Lua's equivalent to the ternary operator):

```
if state.player.position ~= entity.position then
    local entityToTargetDirection = vec3.normalise(state.player.position - entity.position)
    local curDirection = vec3.rotate(consts.forwardVector, entity.orientation)

    local crossResult = vec3.cross(curDirection, entityToTargetDirection)
    local rotationRequiredAxis = vec3.normalise(
        crossResult == vec3() -- This means the two vectors are parallel, so...
        and vec3.rotate(vec3(0, 1, 0), entity.orientation) -- ...pick an arbitrary direction (yaw right in this case)
        or crossResult
    )

    local dotClamped = math.max(-1, math.min(1, -- Clamping because it would sometimes be outside of [-1, 1] and therefore cause acos to return nan
        vec3.dot(curDirection, entityToTargetDirection)
    ))
    local rotationRequiredAngle = math.acos(dotClamped)

    local maxAngle = entity.maxAngularSpeed * dt
    local cappedAngle = math.min(maxAngle, math.max(-maxAngle, rotationRequiredAngle))

    local rotationAxisAngle = rotationRequiredAxis * cappedAngle

    -- if math.abs(getShortestAngleDifference(0, rotationRequiredAngle)) > consts.targettingAngleDistanceThreshold then
        entity.orientation = quat.normalise(quat.fromAxisAngle(rotationAxisAngle) * entity.orientation) -- Normalised to prevent numeric drift
    -- end
end

```

Convert to your use case as required. I'm going to refactor it to face arbitrary target points.

The `rotate` function's source code from my maths library (`new` creates a vec3 in this context):

```
local function rotate(v, q)
    local qxyz = new(q.x, q.y, q.z)
    local uv = cross(qxyz, v)
    local uuv = cross(qxyz, uv)
    return v + ((uv * q.w) + uuv) * 2
end

```

And `getShortestAngleDifference`, if you choose to make the entity stop rotating when within a threshold (I'm sure the maths can be simplified considering how it is used in the code above):

```
local function getShortestAngleDifference(a, b)
    -- a to b is b - a
    return (b - a + consts.tau / 2) % consts.tau - consts.tau / 2
end

```

Also `fromAxisAngle` from my maths library (`#` is length, `rawnew` creates a quaternion (in order x, y, z, w)):

```
local function fromAxisAngle(v)
    local angle = #v
    if angle == 0 then return rawnew(0, 0, 0, 1) end
    local axis = v / angle
    local s, c = sin(angle / 2), cos(angle / 2)
    return normalise(new(axis.x * s, axis.y * s, axis.z * s, c))
end

```

# Answer
> 0 votes
There's many approaches, but since you're not worried about final orientation, the easiest approach is just to use a cross product. If you take the cross product between the enemy's current LOS and the desired LOS (towards you), you get a vector which is perpendicular to both. If you rotate your enemy's orientation around this vector, it will move towards your character.

Just use the formula for constructing a rotation quaternion, rotating theta radians about a vector v: cos(theta/2) + v\*sin(theta/2)

---
Tags: 3d, mathematics, rotation, ai, quaternion
---