# Question
Title: How to use multiple UV maps with ShaderLab (Unity)
I want to layer one texture over top of another on the same mesh, but map the textures to different UV maps.

The example for Detail Maps in the Surface Shader Examples looks almost identical to what I want, but it seems that it uses the same UV map as the albedo texture, multiplied by 2.

I will admit I am very new to ShaderLab, but I am willing to put the work in and research: I just haven't seemed to be able to find the right documentation for what I want to do, or at least I do not understand how to use it.

I have achieved this result in blender this way, though I understand obviously there isn't a 1:1 conversion here.

I also have it working with ShaderGraph, which is neat, but I need it to work using the internal Unity shader for the project I am working on, so unfortunately ShaderGraph is out.

My understanding is that I would declare the UV maps under the Input struct like

```
struct Input {
    float2 uv_MainTex : TEXCOORD0;
    float2 uv2_Detail : TEXCOORD1;
};

```

and then grab the textures from the Properties input by doing

```
sampler2D _MainTex;
sampler2D _Detail;

```

and then use the inputs similarly to the `_MainTex` call which is

```
fixed4 c = tex2d(_MainTex, IN.uv_Detail).rgb * _Color;

```

I have also seen this answer but it doesn't really seem to solve the problem for me, it still doesn't seem to access my second UV map.

I do know that there is some confusion with how UV maps are used in HLSL vs. in Unity. Generally speaking I'm not concerned about overwriting UVs with lightmaps or stuff like that, and if that is an issue I can just add dummy maps when I export from blender to put my custom UV map as the 4th index.

My question is: how do I make one image map use a certain UV Channel and a second image use a second UV channel? Currently my setup is basically just a standard Lit Shader that I added the properties for the detail map to.

Right now it is only displaying the `_MainTex` on UV0.

Code in full here.

# Answer
> 1 votes
Reviewing the Surface Shader documentation:

> # Surface Shader input structure
>
> The input structure Input generally has any texture coordinates needed by the shader. Texture coordinates must be named “uv” followed by texture name **(or start it with “uv2” to use second texture coordinate set)**.

So:

```
struct Input{
    float2 uv_MainTex : TEXCOORD0;
    float2 uv2_Detail : TEXCOORD1;
};

```

---
Tags: unity, shaders, textures
---


title: Gamedev related magazines

text:
# Question
Title: Gamedev related magazines
Do you know any gamedev related magazines ? I only know http://www.gdmag.com/ and http://www.gamasutra.com/ .

I also know http://ffdmag.com/ ,there's texts about flash (sometimes related to games)

# Answer
Besides Game Developer Magazine from UBN TechWeb and Develop from Intent Media, you could find a game developer magazine in DEVMAG. This website is not frequently updated comparing with the first two but it provides free archived PDFs to read and you could reach issue 1 to 29.
> 3 votes

# Answer
Gamasutra is the online companion to Game Developer Magazine, both are UBM TechWeb publications but for whatever reason, the original online content and reprints go to Gamasutra.com, while the gdmag.com website basically just serves as an online table of contents for the current print issue.

As far as I know Game Developer Magazine is the only print magazine that targets game developers specifically, although there are a few additional online resources like GamesIndustry.biz and GameDev.net, which is a great site with a bit more of an indy/hobbyist bent but definitely a great resource with plenty of participants from industry.
> 2 votes

# Answer
There is also Develop, at develop-online.net .
> 2 votes

# Answer
AltDevBlogADay is also sometimes interesting.
> 2 votes

# Answer
There is indiegamemag as well
> 2 votes

# Answer
There's also Big Bytes and Small Nibbles

It contains a mix of reviews, design-focused interviews, and the occasional essay on an aspect of game design.
> 0 votes

---
Tags: education
---


# Question
Title: Trying to use an overlapping shader for 2D sprites but sprite wont show its shape
So Im trying to use this shader I had from a while ago to implement shadows in a 2D top down game. In order to show clouds on top of the game. At the moment, Sprites dont overlap which is good, but the shape of the sprite rendered by the sprite renderer is completely different to the one inserted in the sprite renderer, as the sprites in the sprite renderer are circles not squares. And it seems to cover any other sprite in the scenes which is not what a shade is supposed to be like.

How can I modify the shader so that it respects the sprite. Also I want it to react to lighting the same way as sprite diffuse does.

```
Shader "Custom/OverlappingDiffuse"
{
    Properties
    {
        [PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" { }
        _Color ("Tint", Color) = (1, 1, 1, 1)
        [MaterialToggle] PixelSnap ("Pixel snap", Float) = 0
    }

    SubShader
    {
        Tags { "Queue" = "Transparent" "IgnoreProjector" = "True" "RenderType" = "Transparent" "PreviewType" = "Plane" "CanUseSpriteAtlas" = "True" }

        Cull Off
        Lighting On
        ZWrite Off
        Blend One OneMinusSrcAlpha

        Stencil
        {
            Ref 1
            // Comp NotEqual
            Comp NotEqual
            Pass Replace
            Fail Keep
            ZFail Keep
            ReadMask 1
            WriteMask 1
        }

        CGPROGRAM

        #pragma surface surf Lambert vertex:vert nofog keepalpha
        #pragma multi_compile _ PIXELSNAP_ON
        #pragma multi_compile _ ETC1_EXTERNAL_ALPHA

        sampler2D _MainTex;
        fixed4 _Color;
        sampler2D _AlphaTex;

        struct Input
        {
            float2 uv_MainTex;
            fixed4 color;
        };

        void vert(inout appdata_full v, out Input o)
        {
            #if defined(PIXELSNAP_ON)
                v.vertex = UnityPixelSnap(v.vertex);
            #endif

            UNITY_INITIALIZE_OUTPUT(Input, o);
            o.color = v.color * _Color;
        }

        fixed4 SampleSpriteTexture(float2 uv)
        {
            fixed4 color = tex2D(_MainTex, uv);

            #if ETC1_EXTERNAL_ALPHA
                color.a = tex2D(_AlphaTex, uv).r;
            #endif //ETC1_EXTERNAL_ALPHA

            return color;
        }

        void surf(Input IN, inout SurfaceOutput o)
        {
            fixed4 c = SampleSpriteTexture(IN.uv_MainTex) * IN.color;
            o.Albedo = c.rgb * c.a;
            o.Alpha = c.a;
        }
        ENDCG

    }

    Fallback "Transparent/VertexLit"
}

```

This is how is showing up in the editor:

here is what I want , and want I am getting at the moment:

# Answer
Ok I found the solution here https://forum.unity.com/threads/2d-issue-with-overlapping-transparent-objects.355025/ :

```
Shader "multiply2D"
{
    Properties
    {
        [PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {}
        _Color ("Tint", Color) = (1,1,1,1)
        _MainTex ("Base (RGB), Alpha (A)", 2D) = "white" {}
        _Stencil ("Stencil ID", Float) = 0
        _ColorMask ("Color Mask", Float) = 15
        _ClipAlpha ("ClipAlpha", Float) = 0.2
    }

    SubShader
    {
        Tags
        {
            "Queue"="Transparent"
            "IgnoreProjector"="True"
            "RenderType"="Transparent"
            "PreviewType"="Plane"
            "CanUseSpriteAtlas"="True"
        }

        Stencil
        {
            Ref [_Stencil]
            Comp NotEqual
            Pass Replace
        }

        Cull Off
        Lighting Off
        ZWrite Off
        ZTest [unity_GUIZTestMode]
        Blend SrcAlpha OneMinusSrcAlpha
        ColorMask [_ColorMask]

        Pass
        {
        CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"
            #include "UnityUI.cginc"

            struct appdata_t
            {
                float4 vertex   : POSITION;
                float4 color    : COLOR;
                float2 texcoord : TEXCOORD0;
            };

            struct v2f
            {
                float4 vertex   : SV_POSITION;
                fixed4 color    : COLOR;
                half2 texcoord  : TEXCOORD0;
                float4 worldPosition : TEXCOORD1;
            };

            fixed4 _Color;
            fixed4 _TextureSampleAdd;
            fixed _ClipAlpha;

            v2f vert(appdata_t IN)
            {
                v2f OUT;
                OUT.worldPosition = IN.vertex;
                OUT.vertex = mul(UNITY_MATRIX_MVP, OUT.worldPosition);

                OUT.texcoord = IN.texcoord;

                #ifdef UNITY_HALF_TEXEL_OFFSET
                OUT.vertex.xy += (_ScreenParams.zw-1.0)*float2(-1,1);
                #endif

                OUT.color = IN.color * _Color;
                return OUT;
            }

            sampler2D _MainTex;

            fixed4 frag(v2f IN) : SV_Target
            {
                half4 color = (tex2D(_MainTex, IN.texcoord) );
                color.rgb=_Color.rgb;
                color.a*=_Color.a;
                clip (color.a - _ClipAlpha);
                return color;
            }
        ENDCG
        }
    }
}

```
> 0 votes

---
Tags: unity, 2d, shaders
---


# Question
Title: Does "Personal Use" mean I can earn from it?
I'm almost done with my personal game. One of the reasons I started this is because of monetization. I plan to monetize it using Google Admob. However, I need some icons - essential part of my game.

And these icons are free, released by a certain company, and they say in their download page:

> These icons are free for personal use or commercial testing purposes. Otherwise, you'll need a Premium or Enterprise license. :)

Question is, does "Personal Use" mean I can earn from it?

Also, this "personal game" is actually "under" a group named, say "XXX". The group "XXX" is merely a group name, not a company, not legal/registered, just literally a group name on Github. And this group is composed of 3 people and that includes me. Does this kind of setup go under the "personal use"?

# Answer
If you are earning money from the game, that is commerce, ie. commercial use.

You would need to ask for a licence for commercial use, or replace these assets with ones that permit commercial use.
> 3 votes

---
Tags: licensing
---


# Question
Title: Move an object with other objects connected (via joints) the right way
**What is the best way to move an object with other objects connected to it via joints?**

Let's assume we have the following setup:

* A player that can move on the x and the z axis
    + "Normally configured" RigidBody
    + Moving like this:

```
    void FixedUpdate() {
        Vector3 movement = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
        movement = movement.normalized * 2f * Time.deltaTime;

        // m_rb is the RigidBody of the player
        m_rb.MovePosition(transform.position + movement);
    }

```
* Another object that should be moving with the player as it were its child
    + Connected to the player via a fixed joint
    + "Normally configured" RigidBody

---

When moving the player without any object connected the movement looks as expected:

Now moving the player with the object connected results in some kind of dragging effect as seen here:

One way to solve this behaviour would be to also move the connected object:

```
// m_otherRb is the RigidBody of the connected object (m_other)
m_otherRb.MovePosition(m_other.transform.position + movement);

```

**Is there a better way to solve this?** Shouldn't the joint handle the movement of the other object? Moving the connected object like this results in many problems like **to high impulse forces when colliding with something** as both elements get pushed towards the collider. Also handling the rotation of the connected object isn't as easy as the position.

# Answer
As DMGregory pointed out the behaviour of the joint connected to the image is totaly right (See his first comment for an explanation).

The problem with the to high impulse force when colliding was solved by changing the velocity instead of using `MovePosition` like this:

```
void FixedUpdate() {
    Vector3 movement = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
    movement = movement.normalized * 150f * Time.deltaTime;

    // m_rb is the RigidBody of the player
    m_rb.velocity = movement;

    // m_otherRb is the RigidBody of the connected object
    m_otherRb.velocity = movement;
}

```

I've just had to turn up the speed multiplyer.
> 1 votes

---
Tags: unity, physics, collider, joints
---


# Question
Title: How to deal with players having too much money (or any large numbers)?
I'm working on a browser MMORPG in PHP and MySQL and today got a bug report about int32 overflow, due to the player having too much money. When I was designing the core system, I completely forgot about the integer 2,147,483,647 limit, so now I'm trying to come up with some way to fix this without breaking everything apart.

How to better handle in-game currency (or basically any number that's going to increase indefinitely)? I have couple of ideas, but would like to ask for help choosing as this is the first time I'm dealing with this kind of stuff (int overflow and large numbers.)

1. Fix the current mechanics so that players won't ever have that much money. Doesn't really address the integer problem, but it still needs to be done.
2. Use float instead of int. This seems like an easy option, but I'm not sure if there would be any potential side-effects. Also, I read somewhere that you shouldn't compare floats, so I'm not sure how I would handle basic `hasEnoughMoney?` type of conditions. Also, is float the same in PHP and MySQL?
3. Have some sort of higher currency, like bronze/silver/gold coins and automatically convert it at certain threshold (ie. 1,000,000 would become 1M or something like that.) The downside here is more apparent than with the floats - more complexity and more room for mistakes to happen.
4. Straight out cap the amount of money player can have few points below the overflow limit. Straight forward and effective, but I don't really like the idea of having a limit on money - though I just realized, GTA (and many more I'm sure) has it if I'm not mistaken, so maybe it could work?

Any help would be much appreciated. I searched for hours, but couldn't find much. I read this How do idle games handle such large numbers? among other things, but it doesn't really help as what I'm doing is multiplayer, so not every player will have either too much (and not need precision, so to use floats) or too little (and need precision), and it needs to be unified for all players.

Thanks!

# Answer
> 4 votes
> I read somewhere that you shouldn't compare floats

**Beware programming by hearsay.** This is a good way to make mistakes for reasons you don't understand. Instead, ask for clarification.

The full advice here is "*be careful* when comparing floats for *exact equality*." Code like `if (playerCoinBalance == 0)` is safe enough with integers, but with floats the player's coin balance could conceivably be `1.401298E-45`, which is a perfectly valid float that is *exceptionally close* to zero, but is not actually zero, so the `==` comparison will return `false`, even though the player can't buy anything with one quattuordecillionth of a coin, and if we printed the balance in their inventory it would likely round to "0".

But when you're comparing ranges, you're reasonably safe. `if (playerCoinBalance >= cost)` will pass for any balance exactly at, slightly over, or way over the cost, just as desired. So, the trick for float comparisons is to think about ranges of tolerance, rather than exact equality.

That said, **floats are not a good choice for solving the problem** of players getting too much money. For two reasons:

* They still have a maximum value, so you've just moved the problem, you haven't solved it. If you go past `3.40282347E+38` (a little shy of a duodecillion), you spill out to `infinity`, after which the player has unlimited money to spend.
* They lose precision as the number gets larger. Once you exceed about 33 million, you no longer have integer precision with a 32-bit float. So while you don't get an overflow error right away, you can get weird rounding artifacts: like I give you 5 coins, but your balance goes up by only 4 coins, because it got rounded to the closest representable value. Or you spend a coin without changing your balance, because `currentBalance - 1` isn't a representable number.

As you point out, **many games successfully solve this problem by enforcing a maximum cap** on your balance - often something like 99, 999, 9999, or 99 999. (These numbers tend to make more intuitive sense to your players than 2 147 483 646, and also neatly cap how many digits / how much text field width you need to display the balance in base 10 in your UI, while making maximum use of that available real estate).

A benefit you get from this is that it discourages stockpiling money, and encourages spending. The player risks losing value if they continue earning while close to their cap, so it's in their best interest to spend the money before it gets there. Just make sure the cap is clearly advertised to the player, so it doesn't bite them by surprise.

You can even make a game mechanic out of the cap, as Legend of Zelda games do by letting you earn bigger and bigger wallets with higher caps as part of your character progression. This helps ensure the player is aware of the cap and not surprised by it, gives them opportunities to set and achieve goals with a major impact on their purchasing power, and lets you gate certain purchases behind these progression milestones by setting their cost just over one of the lower caps.

We can't tell you what the right solution is for your game, but I don't see any particular reason not to enforce a cap like this, in tandem with the game mechanics changes you have in mind for point 1, to reduce the likelihood that players stockpile that much in the first place.

# Answer
> 1 votes
The GMP (GNU Multiple Precision) library for PHP offers you the class GMP which can represent integers of arbitrary length and perform arithmetic with them.

MySQL offers you the BIGINT type which represents 8-byte (64-bit) integers (up to 9 Quintillion). If that's not enough, the type DECIMAL supports up to 65 decimal digits. If that's *still* not enough, you might have to encode your numbers as BLOBs or strings.

# Answer
> 1 votes
You can straight up cap your players money. However, if this is a game where high numbers are going to be common, you are better of using a big integer solution, such as Philipp suggests.

Automatically converting to another currency is doing a poor man's big integer. However, there might be value in setting a cap, but letting player manually convert to a higher currency.

---

As per floats… It depends on the game if that is a good idea.

Once you go over the maximum safe integer that can be represented, you may start having items that are essentially free. That is, when you subtract the price from the float, you get the same float.

*For what I read in php.net the float size is platform depended, and thus the maximum safe integer is also platform depended.*

Are you OK with that? Many idle game designers are OK with that, but that does not sound like a good approach for a game with a player economy, it is essentially infinite money (if exploited appropriately).

---

As per the design of the economy, you probably want good reasons to use large amounts of money.

MMORPGs economies are often designed with built-in sinks. Such as buying from in-game shops, paying for crafting/repairing items, healing pets, and taxes to player transactions. These are meant to introduce a counter balance to the influx of money from drops (which are often endless).

I would like to encourage to study the economy of the game as a whole. I do not have the context to suggest a solution for players hoarding money without having a look at all the ways people gain and use money.

If you wish to not cause mechanic unbalance when tweaking the economy, one option is to offer expensive cosmetics (yes, paid with non-premium currency). And be wary of sticker shock. Avoid big jumps between the prices of items. Try to have a couple options to buy at any price range.

# Answer
> 1 votes
Instead of int32, use uint32, it doesn't hold negative numbers thus max value will be 4,294,967,295. (Not for PHP. Currently PHP supports int32 or int64 depending on the type of machine its running on)

Also, just make your money harder to gain! for example instead of giving N amount of money for a battle, give them N/100. Thats it. Now it will be 100 times harder to get this amount.

Next. Instead of saving players' money as `PlayerMoney = 4294967295`, do something like `PlayerMoney = array(4294967295, 4294967295, 4294967295, 150);`

If you'll want to display money as 1 value in UI, you will write a simple script that just adds the numbers in "column" as you add them on paper(You know, starting from last digit, and moving each time to the left). This will allow you to add very big numbers together.

Or you could display it in a list as a "PlayerBank", and each bank account or wallet has maximum of again this 4294967295.

But I think just making money 100 times harder to gain will be enough.

Oh and last. Why not use `uint64`? Its max value will be 18,446,744,073,709,551,615 (Again, not for PHP)

# Answer
> 0 votes
Another simple way to at least alleviate the problem is storing the amount by subtracting -2147483648 internally (assuming the amount doesn't go below 0). This allow you to use the full range of values (0 to 2^32 - 1). Not a long term solution, but it could work.

PHP allows for 64-bit signed integers, but only on 64-bit systems. The gives you a maximum of 9 * 10^18.

If not, there are libraries that allow for BigInt numbers. You would need an overhaul for some parts of your code, but it allows you to use arbitrary length integers.

# Answer
> 0 votes
What about moving to 64-bit server, with 64-bit standard PHP integers (much bigger!) and using BIGINT in MySQL?

---
Tags: browser-based-games, php, floating-point, economy, mysql
---


# Question
Title: How can I debug a GameObject's rotation?
I have a model of a dragon, with an animation of it flying. When I play the animation in the Animator's preview, the dragon flies in a straight line, but when I run it in-game, it flies around in circles about 10 units in diameter.

If the turning isn't coming from the animator, it has to be coming from somewhere else, but I have no idea where. There aren't any scripts on the dragon that would influence it like that. Is there any way to discover what's causing my dragon to turn? (It's times like this that I really miss the ability to set a memory breakpoint on an object when working in .NET. That would make this trivial!)

# Answer
After a bunch of poking around, I was finally able to get it to stop by disabling the `NavMeshAgent` on the dragon, which was used to make it take a running start before taking off and flying. Once I knew what to look for, a bit of Googling shows that `NavMeshAgent` making things circle the destination is a known issue that's been around for years.

The best solution appears to be to set `agent.isStopped = true` when taking off.
> 2 votes

# Answer
Here's the possible reasons, keep in mind this is speculation since I don't know what you are actually doing. These are things I would check if I was you.

Animation might have unwanted rotations.
Solution: Check your animation in 3D software or preview window in inspector.

There's an undesired physics pull from other objects.
Solution: Are there any scripts in the world that effects your dragon without you knowing? Maybe a layer specific effect or just using Find().

Your bones might have rigidbodies on them.
Solution: Maybe you added ragdoll then forgot about it. Check bones for rigidbodies.

Is your model centered correctly?
Solution: Go back to 3D software and apply all transforms as well as centering your mesh to world.

Is there a physics force applied in 3D software?
Solution: Maybe you exported a physics effect by mistake? Check if you used a physics simulator on your 3D software such as wind. This is very low probability but hey, people do win lottery.

Your model have orientation problems with it's parents.
Solution: Check the origin of your parents and try to fix it that way. Is your object properly centered with it's parent's origin?

Your animation has a problem you couldn't detect.
Solution: Disable said animation and check movement in-game.

It's something else. Welcome to Quaternion hell.
Solution: Setup breakpoints at rotations in code, set up Debug.Logs on your rotations and try to understand your rotations and where it gets bad.
I did use this one to fix bad rotation before. It ain't pretty.
> 1 votes

---
Tags: unity, debugging
---


# Question
Title: How to move my cube left or right using touch Inputs (C#) in unity
I am trying to create a 3d game in unity. I have a cube in unity and I want it to move left or right on swipe . It should move to a distance till where user swipe or take their finger off of a screen. I want it to move fast or the cube should move fast on swipe and cube should flow smooth. Like in the gif there is a circle and the user use their finger to move the circle till wherever the user swipe it and it should be instant and I want my cube to move like that at a distance till where user swipe their finger and it should be instant and fast. I don't know how to do it. Any help is appreciated!

# Answer
Here is an example script to answer your question:

```
 if (Input.touchCount > 0)
 {
 Touch touch = Input.GetTouch(0); // get first touch since touch count is greater than zero

 if (touch.phase == TouchPhase.Stationary || touch.phase == TouchPhase.Moved)
 {
     // get the touch position from the screen touch to world point
     Vector3 touchedPos = Camera.main.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, 10));
     // lerp and set the position of the current object to that of the touch, but smoothly over time.
     transform.position = Vector3.Lerp(transform.position, touchedPos, Time.deltaTime);
 }
}

```

Basically, when this is attached to the object you want to move (this is for 2d objects, though it can be tweaked for 3d), it gets the touch location and moves itself to that spot. Hope this helps!

EDIT:

You can tweak for 3d by changing the value of your object's Z axis. Example:

```
 Camera.main.WorldToScreenPoint(touch.position.x, touch.position.y,transform.position.z)

```
> 2 votes

# Answer
You can try the following script

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

public class SelectObject : MonoBehaviour {

    // Use this for initialization
    GameObject hitObj;
    RaycastHit hit;
    private float speed = 1;

    void Start () {

    }

    // Update is called once per frame
    void Update () {
        foreach (Touch touch in Input.touches) {
            switch (touch.phase) {
                case TouchPhase.Began:
                    Ray ray = Camera.main.ScreenPointToRay (touch.position);
                    if (Physics.Raycast (ray, out hit, 10)) {
                            hitObj = hit.collider.gameObject;
                    }
                    break;
            case TouchPhase.Moved:

                // If the finger is on the screen, move the object smoothly to the touch position
                float step = speed * Time.deltaTime; // calculate distance to move
                if(hitObj != null)
                    hitObj.transform.position = Camera.main.ScreenToWorldPoint(new Vector3 (touch.position.x, touch.position.y, hitObj.transform.position.z));
                break;
            }
        }
    }
}

```
> 0 votes

# Answer
I hope I can help in this matter,but for rotation:

```
public class TouchRotate : MonoBehaviour
{
    public GameObject obj;
    public float power;
    float posTouchBegan;

    private void Update()
    {
        if (Input.touchCount > 0)
        {
            if (Input.GetTouch(0).phase == TouchPhase.Began)
            {
                posTouchBegan = Input.GetTouch(0).position.x;
            }

            if (Input.GetTouch(0).phase == TouchPhase.Moved)
            {
                if (Input.GetTouch(0).position.x > posTouchBegan)
                {
                    obj.transform.Rotate(new Vector3(0, 1 * Time.deltaTime * power, 0));
                }
                if (Input.GetTouch(0).position.x < posTouchBegan)
                {
                    obj.transform.Rotate(new Vector3(0, -1 * Time.deltaTime * power, 0));
                }
                Debug.Log("touch position:  " + Input.GetTouch(0).position.x);
            }
            if (Input.GetTouch(0).phase == TouchPhase.Stationary)
            {
                posTouchBegan = Input.GetTouch(0).position.x;
            }
        }
    }
}

```
> 0 votes

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


# Question
Title: Unreal member variables reset between function calls
I'm trying to make a weapons switching mechanic in my game. My implementation is a data asset that contains an array of weapons with each weapon contatining the meshes, stats and a weapon actor component which has the fire function and trigger status. At runtime I have a pawn that loads the weapon, loads the meshes and create a new weapon component matching that of the one in the weapon data asset. My problem is that when I call the functions to change the state of the trigger member function as soon as the function is finished the variable seems to reset itself back to false leading to the tick function never firing.

Things I have tried: \- Checking that the input is being registered (it is) \- Stepping through the code to see if the tick function is being called (it is) \- Restarting Unreal (had no effect)

Weapon Data Asset

```
USTRUCT(BlueprintType)
struct FWeaponBlueprint
{
    GENERATED_BODY()

    UPROPERTY(EditAnywhere, Category=WeaponMeshes)
    UStaticMesh* WeaponBody = nullptr;
    UPROPERTY(EditAnywhere, Category=WeaponMeshes)
    UStaticMesh* WeaponBase = nullptr;
    UPROPERTY(EditAnywhere, Category=WeaponMeshes)
    UStaticMesh* WeaponGun = nullptr;
    UPROPERTY(EditAnywhere, Category=WeaponMeshes)
    UStaticMesh* WeaponBarrel = nullptr;

    UPROPERTY(EditAnywhere, Category=WeaponData)
    FVector EndOfBarrel;
    UPROPERTY(EditAnywhere, Category=WeaponData)
    TSubclassOf<UHonkWeaponComponent> FiringMechanism;

    UPROPERTY(EditAnywhere, Category=WeaponStats)
    float RPM;
    UPROPERTY(EditAnywhere, Category=WeaponStats)
    float TurnRate;
    UPROPERTY(EditAnywhere, Category=WeaponStats)
    float ProjectileSpeed;
    UPROPERTY(EditAnywhere, Category=WeaponStats)
    float Damage;
    UPROPERTY(EditAnywhere, Category=WeaponStats)
    float Range;
    UPROPERTY(EditAnywhere, Category=WeaponStats)
    float ChargeSpeed;
    UPROPERTY(EditAnywhere, Category=WeaponStats)
    float ExplosionRange;

};

UCLASS(BlueprintType)
class HONK_API UHonkWeaponAsset : public UDataAsset
{
    GENERATED_BODY()

public:
    UPROPERTY(EditAnywhere)
    TMap<FName, FWeaponBlueprint> Weapons;
};

```

Weapon Component

```
void UHonkWeaponComponent::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
    Super::TickComponent(DeltaTime, TickType, ThisTickFunction);

    if (Firing && LastFired <= 0.0f) // Firing is always false and never true
    {
        UE_LOG(LogTemp, Warning, TEXT("This function needs overriding"));
        LastFired = FireRate;
    }

    if(LastFired > 0.0f)
    {
        LastFired -= DeltaTime;
    }
}

void UHonkWeaponComponent::SetTriggerStatus(bool status)
{
    this->Firing = status; // This get's called no problem
}

```

Pawn Class

```
void AHonkPawn::SetWeapon(FName weapon, bool inConstructor)
{
    if(WeaponAsset != nullptr)
    {
        if(WeaponAsset->Weapons.Contains(weapon))
        {
            EndOfBarrel->SetRelativeLocation(WeaponAsset->Weapons[weapon].EndOfBarrel);

            if (!inConstructor)
            {
                WeaponComp = WeaponAsset->Weapons[weapon].FiringMechanism; //This is the weapon component within the data asset
                WeaponInstance = NewObject<UHonkWeaponComponent>(WeaponComp);
                UE_LOG(LogTemp, Display, TEXT("Weapon Instance: %s"), ((WeaponInstance != nullptr) ? TEXT("SUCCEEDED") : TEXT("FAILED")))
            }

            if(UStaticMesh* mesh = WeaponAsset->Weapons[weapon].WeaponBody)  { WeaponBodyMesh->SetStaticMesh(mesh);   }
            if(UStaticMesh* mesh = WeaponAsset->Weapons[weapon].WeaponBase)  { WeaponBaseMesh->SetStaticMesh(mesh);   }
            if(UStaticMesh* mesh = WeaponAsset->Weapons[weapon].WeaponGun)   { WeaponGunMesh->SetStaticMesh(mesh);    }
            if(UStaticMesh* mesh = WeaponAsset->Weapons[weapon].WeaponBarrel){ WeaponBarrelMesh->SetStaticMesh(mesh); }
        }
    }
}

```

Apologies if the answer is obvious, I'm still getting to grips with UE4 and a lot of the concepts escape me. Thanks in advanced

EDIT: I figured it out. I missed registering the compontent

Updated Code:

```
WeaponComp = WeaponAsset->Weapons[weapon].FiringMechanism;
WeaponInstance = NewObject<UHonkWeaponComponent>(this, WeaponComp, WeaponComp->GetFName());
WeaponInstance->RegisterComponent();

```

# Answer
I figured it out. I missed registering the compontent

Updated Code:

```
WeaponComp = WeaponAsset->Weapons[weapon].FiringMechanism;
WeaponInstance = NewObject<UHonkWeaponComponent>(this, WeaponComp, WeaponComp->GetFName());
WeaponInstance->RegisterComponent();

```
> 1 votes

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


# Question
Title: 2D player controller moves to the left, but not to the right
I wrote a C# script to control a 2D player, but the script is not fully working. When I press the right arrow/d key to move the player is not moving in the right direction, but I have done the same exact thing for left key which works fine.The script shows no errors too.Kindly help me to solve the issue.The code is:

```
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    [SerializeField] private Rigidbody2D _rb2d;
    [SerializeField] private float _speed;
    [SerializeField] private float _jump;
    private static float _tempspeed;
    private static float _tempjump;
    private bool _isRight;
    private bool _isLeft;
    private bool _isSpace;

    private void Start()
    {
        _isLeft = false;
        _isRight = false;
        _isSpace = false;
        _speed = 5f;
        _jump = 7f;
        _tempjump = _jump;
        _tempspeed = _speed;
    }

    private void Update()
    {
        ReadInput();
    }

    private void FixedUpdate()
    {
        Move();
    }

    private void ReadInput()
    {
        if (UnityEngine.Input.GetKey("d") || UnityEngine.Input.GetKey("right"))
        {
            _isRight = true;
        }else {
            _isRight = false;
        }
        if (UnityEngine.Input.GetKey("a") || UnityEngine.Input.GetKey("left"))
        {
            _isLeft = true;
        }else {
            _isLeft = false;
        }
        if (UnityEngine.Input.GetKey("w") || UnityEngine.Input.GetKey("up"))
        {
            _isSpace = true;
        }else {
            _isSpace = false;
        }
    }

    private void Move()
    {
        Vector2 speedVectorRight=new Vector2(_tempspeed,_rb2d.velocity.y);
        Vector2 speedVectorLeft=new Vector2(-_tempspeed,_rb2d.velocity.y);
        Vector2 jumpVector=new Vector2(_rb2d.velocity.x,_tempjump);

        if (_isRight)
        {
            _rb2d.velocity = speedVectorRight;
        }else {
            speedVectorRight.x=0f;
            _rb2d.velocity = speedVectorRight;
        }
        if (_isLeft)
        {
            _rb2d.velocity = speedVectorLeft;
        }else {
            speedVectorLeft.x=0f;
            _rb2d.velocity = speedVectorLeft;
        }
        if (_isSpace)
        {
            _rb2d.velocity=jumpVector;
        }
    }

```

When I tried to print debug statements in different parts of if statements, they work fine. The problem in my observation is in :

```
if (_isRight)
        {
            _rb2d.velocity = speedVectorRight;
        }else {
            speedVectorRight.x=0f;
            _rb2d.velocity = speedVectorRight;
        }

```

The \_rb2.velocity is not accepting speedVectorRight I guess.Thanks in advance!

# Answer
You can make this code much simpler.

First, you can use the Input Manager to read your multiple sets of input buttons as a single axis. Mapping the typical arrow keys/WASD `A`= / `D`= to a "Horizontal" axis is already handled by the default setup:

Similarly, you can edit the default "Jump" action to read both `W` and  as a single synonymous input.

Doing it this way also allows users to remap these controls if you show the input mapping dialog at the start of your game.

With this in hand, you can simplify your code to:

```
void FixedUpdate() {
    // This gives us -1 if A/← is pressed, 1 if D/→ is pressed, and 0 if both/neither.
    // It's OK to read this in FixedUpdate because it's a sustained input.
    float inputDirection = Input.GetAxisRaw("Horizontal");

    // Get the current velocity.
    var velocity = _rb2d.velocity;
    // Override the horizontal with our desired speed and direction.
    velocity.x = inputDirection * _speed;
    // Assign it back.
    _rb2d.velocity = velocity;
}

// Jumps are usually instantaneous, so it needs to be checked in Update,
// so we don't miss or double-up a jump on frames that get 0 or 2 FixedUpdates.
void Update() {
    // GetButtonDown returns true the first frame the control is pressed,
    // then not again until the button is released and pressed a second time.
    if(Input.GetButtonDown("Jump")) {
         _rb2d.velocity += Vector2.up * _jump;
    }
}

```
> 0 votes

---
Tags: unity, c#, 2d, platformer
---


# Question
Title: When key pressed rotate until lifted if key up smoothly revert to original position and if rotate too far die
I am trying to have a smooth rotation animation on this hover-car to make it seem more realistic.

I am trying to code it so that if the key `a` or `d` is pressed it will rotate to the **left** and **right** accordingly. If it rotates too far then it dies and the scene is reloaded. When the keys `a` or `d` are lifted then it will smoothly revert back to its original position. I want it to rotate on the `x axis` of its origin. If you see in the image the scenes axis is `z` and the axis of origin that points in the direction of that from the vehicle is its `x`.

Here is the scene with the axis's of the vehicle:

```
        public int speed = 100;
        public float maxrotation = 30f; //To Set Max Rotation

        void Start()
        {

        }

        // Update is called once per frame
        void Update()
        {
            if (transform.rotation.eulerAngles.x > 0)
            {

                transform.rotation.eulerAngles.x - 1; //there is an error on this line saying "Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement"

            }
            if (transform.rotation.eulerAngles.x < 0)
            {

                transform.rotation.eulerAngles.x + 1; //there is an error on this line saying "Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement"

            }
            if (Input.GetKey(KeyCode.A))
            {
                //Set a rate at which we should turn
                float turnSpeed = speed * Time.deltaTime;
                //Connect turning rate to horizonal motion for smooth transition
                float rotate = Input.GetAxis("Horizontal") * turnSpeed;
                //            //Get current rotation
                //            float currentRotation = gameObject.transform.rotation.z;
                //            //Add current rotation to rotation rate to get new rotation
                //            Quaternion rotation = Quaternion.Euler (0, 0, currentRotation + rotate);
                //            //Move object to new rotation
                //            gameObject.transform.rotation = rotation;
                gameObject.transform.Rotate(Vector3.left * rotate);
            }
            if (Input.GetKey(KeyCode.D))
            {
                //Set a rate at which we should turn
                float turnSpeed = speed * Time.deltaTime;
                //Connect turning rate to horizonal motion for smooth transition
                float rotate = Input.GetAxis("Horizontal") * turnSpeed;
                //            //Get current rotation
                //            float currentRotation = gameObject.transform.rotation.z;
                //            //Add current rotation to rotation rate to get new rotation
                //            Quaternion rotation = Quaternion.Euler (0, 0, currentRotation + rotate);
                //            //Move object to new rotation
                //            gameObject.transform.rotation = rotation;
                gameObject.transform.Rotate(Vector3.left * rotate);

            }
            if (transform.eulerAngles.x > maxrotation)
            {
                Application.LoadLevel(Application.loadedLevel); //kills player and reloads scene
                scorecript.scoreValue = 0; // sets score to zero
            }
            if (transform.eulerAngles.x < maxrotation - (maxrotation * 2))
            {
                Application.LoadLevel(Application.loadedLevel); //kills player and reloads scene
                scorecript.scoreValue = 0; //sets score to zero
            }

        }

<!-- end snippet -->

```

# Answer
> 0 votes
```
// Cache the rotation we had at start-up.
Quaternion originalRotation;

void Start()
{
    originalRotation = transform.rotation;
}

void Update() {
    float axis = Input.GetAxis("Horizontal");

    // If we're not pressing left or right, rotate back toward neutral.
    var targetRotation = originalRotation;

    // If we are pressing left/right, our target should be somewhere to the left/right.
    if(!Mathf.Approximately(axis, 0)) {
        var twist = Quaternion.Euler(0, 0, 90 * Mathf.Sign(axis));
        targetRotation = transform.rotation * twist;
    }

    // Smoothly rotate toward the current target, at turnSpeed degrees per second.
    transform.rotation = Quaternion.RotateTowards(
                             transform.rotation,
                             targetRotation,
                             turnSpeed * Time.deltaTime
                         );
}

```

This code uses a linear rate of change, but you could also add damping/easing in and out if you like.

---
Tags: unity, rotation
---


title: Touch goes through UI objects on mobile

text:
# Question
Title: Touch goes through UI objects on mobile
I know this question has been asked a lot of times, and I have tried the solutions that were provided and I still have no valuable result, so I thought...maybe a new set of eyes could help.

I have a game in which the player can navigate around the scene environment using a virtual joystick and look around the scene by scrolling through the screen(like it is seen in most mobile fps games).

The problem that I am having now is that my "look around" script allows touch inputs to pass through UI elements on mobile, but everything works fine on the editor.

Useful tips:

1) I am using Unity 2019.3.0f5

2) I setup the script to work with Cinemachine Free Look, and my script(seen below) is attached to it.

Here is my code:

```
using UnityEngine.EventSystems;
using UnityEngine;
using Cinemachine;

public class CinemachineCoreInputTouchAxis : MonoBehaviour
{
private readonly float TouchSensitivity_x = 10f;
private readonly float TouchSensitivity_y = 10f;

[SerializeField] private bool UseTouchControls = true;

private static int Index = 0;

void Start()
{
    if(UseTouchControls)
        CinemachineCore.GetInputAxis = HandleAxisInputDelegate;
}

private float HandleAxisInputDelegate(string axisName)
{
    switch (axisName)
    {
        case "Mouse X":
            if (Input.touchCount > 0 && !IsPointerOverUIObject())
                return Input.touches[Index].deltaPosition.x / TouchSensitivity_x;
            else
                return Input.GetAxis(axisName);
        case "Mouse Y":
            if (Input.touchCount > 0 && !IsPointerOverUIObject())
                return Input.touches[Index].deltaPosition.y / TouchSensitivity_y;
            else
                return Input.GetAxis(axisName);
        default:
            Debug.LogError("Input <" + axisName + "> not recognized.", this);
            break;
    }
    return 0f;
}

public static bool IsPointerOverUIObject()      //Called to check if the pointer is over a ui object
{
    bool value = false;
    for (int i = 0; i < Input.touches.Length; i++)
    {
        Index = i;
        value = EventSystem.current.IsPointerOverGameObject(Input.GetTouch(Index).fingerId);
        if (value)
            break;
    }
    return value;
}
}

```

Can anyone please let me know what I am failing to see and how to fix it?

# Answer
> 0 votes
Here is how I fixed this problem. I disabled my touch scripts and rebuilt and I was still getting touch movements so then I figured that every script I've tried work just fine. Cinemachine's free look camera naturally accepts inputs from both touch and mouse for it's ability to look around. So my code only checks if a touch is over a UI object before allowing touch movements from my script and not from Cinemachine's.

How I fixed this is:

```
private float InitSpeedX, InitSpeedY;
public CinemachineFreeLook cFL;

void Update ()
{
      if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(Index).fingerId))
      {
             cFL.m_YAxis.m_MaxSpeed = 0;
             cFL.m_XAxis.m_MaxSpeed = 0;
      }
      else
      {
             cFL.m_YAxis.m_MaxSpeed = InitSpeedX;
             cFL.m_XAxis.m_MaxSpeed = InitSpeedY;
      }
}

```

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


# Question
Title: Unity toggleable shader property misbehaves when set by code?
I've added a **toggle to my shader**:

```
[Toggle(ENABLE_COLOR_BLEND)] _EnableColorBlend ("Enable Color Blend", Int) = 0

```

In the **Subshader**:

```
#pragma shader_feature ENABLE_COLOR_BLEND

```

And in the **fragment shader**:

```
#ifdef ENABLE_COLOR_BLEND
    color = lerp(_DryColor, _WetColor, _ColorBlend);
#endif

```

And **there it is in the inspector**, and when I toggle it, color blending is turned on and the **material is rendered as it should be**. if I turn it off, it's off.

But if I try to **set it** like this **in code**:

```
Renderer.material.SetInt("_EnableColorBlend", 1);

```

The material is **rendered like if EnableColorBlend is off**.

In the **inspector it's ticked**, and as soon as I turn it off, it gets ticked again. (I set it in an Update) But for some reason, it's still rendered like color blending is off.

And if I **remove the SetInt** above, and set it **by hand**, **everything works fine**.

Why?

**Idea:** If I set it by hand, there is a smooth transition (don't know why) instead of an instant change in shade. Maybe by setting it constantly to 1, it always just starts the transition, but can't finish it?

**EDIT:** Just checked it with a guard, and it still behaves the same.

```
if (Renderer.material.GetInt("_EnableColorBlend") == 0) Renderer.material.SetInt("_EnableColorBlend", 1);

```

# Answer
By setting up your shader toggle like this, you've forced it to be a compile-time constant.

When Unity loads your material, it selects or compiles the appropriate version of the shader for its toggled settings.

That includes evaluating all the preprocessor directives like `#ifdef`: the code wrapped in those blocks is either compiled into your shader program, or it is not. You don't get a section of "ghost code" that's there-but-skipped. If the `#ifdef` is not satisfied, the code is simply omitted from the compiled program and the GPU never sees it. That's the whole point, to take unneeded complexity out of the shader when you don't plan to use a particular feature.

So changing the toggle variable anytime after that moment is "closing the barn door after the horses have left" — the code is already there or not there, the preprocessor directives have done their job and are no longer present in your compiled shader program, so you have nothing in the compiled program on the GPU that reads your toggle and uses it to change behaviour.

You need to do one of three things instead:

* Compile two materials, one with the toggle on, one off. When you want to swap the toggle, swap to the other material whose shader was compiled in the state you want.

This lets you keep the benefit of having no dynamic branching inside the shader, but coordinating the other material properties might be more juggling.
* Tell Unity that you're not just changing a variable, but changing a compiler directive, using `material.EnableKeyword("_EnableColorBlend")` or `DisableKeyword("_EnableColorBlend")`.

Rather than just changing a variable, this swaps out the whole shader program, for one compiled with the appropriate setting. Note that you'll need to have each variant present in the assets in your build (as in the point above) to ensure Unity has a matching variant to load when it looks for one.
* Don't use preprocessor directives for something you want to change dynamically. Just use a regular `if (toggleVariable > 0) { ... }`

This will be evaluated every time the shader executes, so you can change which path is taken from frame to frame without changing compiled shader programs, or even from one fragment to another. But correspondingly, it has a cost to do this check and potentially branch execution paths within a warp.
> 2 votes

---
Tags: unity, shaders
---


title: How can I standardize ping?

text:
# Question
Title: How can I standardize ping?
I hear pros playing Fortnite that have 20-50 ping complain that they cannot perform as well as pros with 0 ping due to wall taking, etc. It's easy to think that a 20ms ping difference is negligible but it is not in competitive situations.

It seems to me that it should be possible to standardize a lobby's ping to the current maximum player's ping at any given moment. Obviously in a competitive game like Fortnite, the worst ping a pro player can have is generally 50-60 ping.

This solution would involve psuedo latency. For example, in competitive Fortnite, if the worst ping among the players is 50, then all players will be forced to also have 50 ping by inducing an artificial server response delay. This would allow no single player to have an advantage based on internet connection.

How could I implement a feature like this, to provide a level playing field?

# Answer
> 2 votes
First of all, I commend you for thinking outside the box. Keep doing that.

Here are a couple problems off the top of my head with one potential implementation. (Only a partial answer.)

**It increases latency for all players, including the already highest ping player.**

How much pseudo ping do we add? We must first check which player has the highest ping. So the server pings each player to figure that out.

We are one tick behind now.

OK. We now have the player who has the highest ping. Let's let each other player know what their artificial ping should be.

We are two ticks behind now.

OK. Each player inserts an artificial delay, then reports to the server their input. (Let's assume the predicition is perfect for how long it takes to send this input to the server.)

So we balanced the latency across all players. But instead of being 50ms for the highest ping player, we now have 150ms for all players.

Also keep in mind each ping has a different latency and can have a wide range (for the same player). This adds a lot of complexity.

(There are probably better implementations than the one i showed above, but I cannot think of any off the top of my head, considering the ping varies every tick.)

**It punishes other players for being in the lobby with a lower ping player.**

I have 20ms ping. I pay a lot of money for it. It is worth it because I like high responsiveness in my games.

The other player has 50ms ping (or 150ms if the above is taken into account). So I get throttled? I am going to go play something else.

---
Tags: client-server, synchronization, latency
---


# Question
Title: Reduce emission of sphere object with HDRP material
I have a material which I have assigned to be used on a sphere game object which acts as stars.

This is what the settings are set to:

And this is what the Game View looks like:

I have also tried setting emission intensity to 0 nits and exposure weight to the minimum (0), but some stars still are far too bright, below is a screenshot of what it looks like with the altered emission intensity and exposure weight:

The bigger stars are far too emissive. I am trying to give each star a little glow. How do I reduce the emission?

# Answer
> 1 votes
Thanks to the helpful input from @DMGregory, I have managed to solve this problem.

I added the "Volume" component to the Camera, then I created a new profile. I then added the "Exposure" override, which resulted in the appearance of two shaded out options, Mode and Fixed Exposure. Clicking on the checkbox to the left activated the options allowing me to set the Mode to "Fixed" and Fixed Exposure to "0".

Changing the Fixed Exposure value any lower results in the stars becoming too bright, and any higher results in the stars becoming too dim. "0" seems to be the sweet spot for my application.

This is the result:

---
Tags: unity, c#, gameobject, glow
---


# Question
Title: How can I achieve simulated fluid surface deformation in a bottle?
I'd like to mimic this effect seen in Half Life: Alyx:

I can't figure out what is going on here, people say "it is just a shader effect it isn't simulating anything", but I don't think that is true at all, it *appears* to be doing some sort of surface only fluid dynamics, but I'd have no idea what technique is actually used underneath.

My best guess is that

* each object has a "origin" plane associated with each bottle that "exists" outside of the bottle and always fixed to some origin relative to the bottle
* then waves ala gerstener waves are generated via movement somehow
* the surface is raymarched only within bottle geometry
* when below the surface additional ray marching is done for bubbles which are generated via potentially 4D noise, or a set number of bubbles are generated then rendered as round sprites or independently of noise
* foam is generated based on a uniform value that is passed in that determines the "shakey" ness of the bottle, which makes values closer to the fluid surface more opaque and white.
* fluid volumetric opacity doesn't necessarily have to be raymarched, but would likely be with the rest of this stuff being raymarched. Using beers law to attenuate light based on distance and density through fluid.

But I'm really not understanding how the plausibly physically correct surface deformation is happening. How would I do something similar? I've seen some other posts that just have the surface wobble, but if you look in the video, it is more than just surface wobble, there is actual surface deformation.

# Answer
> 14 votes
I've been redirected here after posting this on twitter : https://twitter.com/Gaxil/status/1268165270541078529

I can give you some details of my implementation, even if I know that it's a quite different approach of the original one.

So, in the vertex shader, I access a compute buffer in read/write mode. That allows me to store the world position of the vertex from the previous frame and so to extract the local velocity afterward.

Concerning the physics, it's springs based and everything is stored in the compute buffer as well ... I have an offset and a speed, it's only a couple of float as it is on one axis only (perpendicular to liquid surface). Every frame I:

* Dampen the current velocity to avoid ever moving spring.
* I compute an acceleration depending on the local velocity dot the vertex position, modulated by a sine depending on the world pos (see explanation above).
* That acceleration is added to the velocity
* The velocity is added to the position.
* I also add to that velocity an acceleration that depends on the current offset, to bring it to a rest position, the further away from the rest position the stronger the acceleration.
* I add the velocity to the offset

And so, that offset is added to the plane position, horizontal, above the center of the object. Also, I had to cheat a bit to avoid having geometry projected outside of the volume ...

For the foam and bubbles, I store an 'activity' level also in the compute buffer and this is decreased every frames with a constant but it's also increased by the abs(velocity) of the spring. The foam is added to the y position to do an extra displacement ... and it is also used as mask to colorize the foam part and to display some 3D noise for the bubbles.

And that's roughly all I've done here ...

The glass is a separate shader rendered twice (back and front). It's certainly a bit overkill and I've gone also a bit wild on the geometry, but I wanted to push that as far as I can to have something quite realistic. This can certainly be simplified and optimized for real usages.

I hope this helps, cheers!

---
Tags: opengl, shaders, glsl, water, fluid-dynamics
---


# Question
Title: How to sample from six cubemap images for a skybox in Shader Graph?
I'm trying to update a skybox shader to URP and reimplement it in Shader Graph. The shader code itself is pretty straightforward, but I don't know enough about Shader Graph yet to set up the basic skybox.

It's a standard cubemap skybox made up of six textures for +x, -x, +y, -y, +z, and +z.

Trying to Google different variants of "unity shader graph cubemap skybox" turns up tons of noise and nothing actually useful that I can see.

Does anyone know what the basic node setup is I would need to input six images and output a skybox?

# Answer
In your Assets folder, right click and select `Create > Legacy > Cubemap`

Set the "Face Size" parameter to your desired resolution before you assign your textures - it won't re-import them automatically if you increase the size later.

Assign your six textures to the six face fields.

Now inside your shader graph, you can add a Cubemap property, and sample it like so:

Assign your custom-made cubemap to the material property.

Note that you can also pre-compose your six images into a single image in various layouts, and Unity will automatically convert this to a corresponding cubemap based on your import settings. This gives you additional options to filter the cubemap for use in reflections, and HDR support.
> 3 votes

---
Tags: unity, skybox, unity-shader-graph
---


# Question
Title: Is an iOS development license with Unity free?
I'm coding in Unity Personal and I'm going to try to put my game onto the App Store (through the Unity --\> XCode --\> App Store process). In the past, Unity has charged money to get a iOS license for this. The price was $400 I believe. I've certain articles that say that it has changed, and some that say it still costs money. So, I'm not sure which one is true. **Is creating and publishing a commercial game with Unity Personal now free? (meaning that there is no license required). If there is a price, how much is it, and is it a one-time fee or per month/year/game published etc.** Thanks! Also, can I legally make money with this game using the Unity Personal?

# Answer
You can use Unity personal tu publish a game on every platform for free but if you start making a revenue up to $100k per year you need to pay an annual plan, which starts at $40 per month. Here you have all the info for that in their site Info of Unity Plans On the other hand you should pay a developer license of each platform to publish. Every platform has their own fee, in the case of Apple is $99 per year. Here you can see more info about it Apple dev program
> 3 votes

---
Tags: unity, c#, ios, xcode
---


# Question
Title: Is it possible to work out rotate in degrees per second based on this rotate logic?
I have this code to rotate an object towards another at a given speed.

```
    /// <summary>
    /// Rotate towards the target.
    /// </summary>
    /// <param name="lookPosition"></param>
    private void RotateTowardsTarget(Vector3 lookPosition)
    {
        // Determine which direction to rotate towards
        Vector3 targetDirection = lookPosition - transform.position;

        // The step size is equal to speed times frame time.
        float singleStep = weaponRotationSpeed * Time.deltaTime;

        // Rotate the forward vector towards the target direction by one step
        Vector3 newDirection =
            Vector3.RotateTowards(turretYRotation.transform.forward, targetDirection, singleStep, 0.0f);

        // Draw a ray pointing at our target in
        //Debug.DrawRay(turretYRotation.transform.position, newDirection, Color.red, 3);

        newDirection.y = 0;
        // Calculate a rotation a step closer to the target and applies rotation to this object
        turretYRotation.transform.rotation = Quaternion.LookRotation(newDirection);
    }

```

And I'd like to convert this to a "Degrees per second" to give the user useful feedback on how quickly it rotates. Is there a formulae I can apply to work it out?

# Answer
Currently `weaponRotationSpeed` defines the rotation speed in radians per second, if what you're asking is to let this variable define rotation speed in degrees per second you should change

```
float singleStep = weaponRotationSpeed * Time.deltaTime;

```

to

```
float singleStep = (weaponRotationSpeed * (180/Math.PI)) * Time.deltaTime;

```
> 2 votes

---
Tags: c#, mathematics, rotation
---


# Question
Title: Rotating projectile in direction it is moving
I am using a parabola curve to launch my arrows:

```
public static Vector3 Parabola(Vector3 start, Vector3 end, float height, float t)
{
    Func<float, float> f = x => -4 * height * x * x + 4 * height * x;

    var mid = Vector3.Lerp(start, end, t);

    return new Vector3(mid.x, f(t) + Mathf.Lerp(start.y, end.y, t), mid.z);
}

```

I have a projectile that is a simple capsule scaled down to be long and thin like an arrow. I've tried every way to rotate it I could find online, but there is always something off. In order to follow the curve I need the direction between the last position and the new position, so I have been trying things like:

```
void ParabolaMovement() //Called in Update()
{
    parabolaAnim += Time.deltaTime;

    parabolaAnim = parabolaAnim % 5;

    Vector3 newPos = MathParabola.Parabola(start, target, 5f, parabolaAnim / 5);
    Vector3 dir = newPos - transform.position;
    transform.LookAt(dir);

    transform.position = newPos;
}

```

As for what is going wrong, it does not point AT the target, which I udnerstand it can't because nowhere do I specify target pos, which I should, but don't know where. I cannot simply tell it to lookat target, since I want it to lookat the direction it is currently going in the curve, but it also needs to face the target.

# Answer
> 1 votes
Changing

```
transform.LookAt(dir);

```

to

```
transform.LookAt(newPos);

```

should work, atleast under the assumption that the forward vector of the arrow is set up correctly.

---
Tags: unity, c#, 3d, mathematics, projectile-physics
---


# Question
Title: Calculating Directional Shadow Map using Camera Frustum
I'm trying to calculate the 8 corners of the view frustum so that I can use them to calculate the ortho projection and view matrix needed to calculate shadows based on the camera's position. Currently, I'm not sure how to convert the frustum corners from local space into world space. Currently, I have calculated the frustum corners in local space as follows (correct me if I'm wrong):

```
float tan = 2.0 * std::tan(m_Camera->FOV * 0.5);
float nearHeight = tan * m_Camera->Near;
float nearWidth = nearHeight * m_Camera->Aspect;
float farHeight = tan * m_Camera->Far;
float farWidth = farHeight * m_Camera->Aspect;

Vec3 nearCenter = m_Camera->Position + m_Camera->Forward * m_Camera->Near;
Vec3 farCenter = m_Camera->Position + m_Camera->Forward * m_Camera->Far;

Vec3 frustumCorners[8] = {
    nearCenter - m_Camera->Up * nearHeight - m_Camera->Right * nearWidth, // Near bottom left
    nearCenter + m_Camera->Up * nearHeight - m_Camera->Right * nearWidth, // Near top left
    nearCenter + m_Camera->Up * nearHeight + m_Camera->Right * nearWidth, // Near top right
    nearCenter - m_Camera->Up * nearHeight + m_Camera->Right * nearWidth, // Near bottom right

    farCenter - m_Camera->Up * farHeight - m_Camera->Right * nearWidth, // Far bottom left
    farCenter + m_Camera->Up * farHeight - m_Camera->Right * nearWidth, // Far top left
    farCenter + m_Camera->Up * farHeight + m_Camera->Right * nearWidth, // Far top right
    farCenter - m_Camera->Up * farHeight + m_Camera->Right * nearWidth, // Far bottom right
};

```

How do I move these corners into world space?

Update:

I'm still not sure if what I'm doing is right. I've also attempted to build the ortho projection by looping through the frustum corners and getting the min and max x,y,z coordinates. Then simply setting the values of the projection as:

```
left = minX
right = maxX
top = maxY
botton = minY
near = - maxZ
far = -minZ

```

I've searched on the internet but all the tutorials use hard coded values so the shadow maps aren't applicable to an open world but a restricted portion of the scene. Any help? Pseudocode is preferred as my linear algebra skills (and reading skills) aren't that great

# Answer
Not sure why you are doing this "by hand", but it should be pretty straight forward if you use matrices for that.

Assume your models are all already transformed to world space, then you usually do the following to get them to clip space:

$$ P\_c = M\_{vc} \cdot M\_{wv}\cdot P\_w $$

\\$P\_c\\$ is the projected point in **c**lip space. \\$M\_{vc}\\$ is the projection matrix that transforms from **v**iew space to **c**lip space, \\$M\_{wv}\\$ the **w**orld to **v**iew space transformation matrix and \\$P\_w\\$ is a point in world space. Now what you want to do is the opposite transformation which simply is:

$$ P\_w = M\_{wv}^{-1} \cdot M\_{vc}^{-1} \cdot P\_c $$

The 8 corners of your view frustum are just the edge points of a cube in clip space (the space after projection - also see this link and the learnOpenGL coordinate system tutorial). For OpenGL, the 8 points have x-,y- and z- values that are either -1 or 1.

So all you need are the inverse matrices and the 8 corner points of your clip space. In case you don't use an existing linear algebra library and don't know how to invert a 4x4 matrix, check this StackOverflow question. You can actually simplify this formula for the projection matrix \\$M\_{vc}\\$ since it contains a lot of zeros.

> **Important Update:** The points in clip space need to be 4d vectors with \\$w=1\\$ and after the application of the inverse projection, all points have to be divided by the resulting \\$w\\$ component

Additionally, you can avoid calculating the inverse with the general formula for the matrix \\$M\_{wv}\\$ since it **usually** is just a composition of a rotation and a subsequent translation:

$$M\_{wv} = T \cdot R$$

So

$$M\_{wv}^{-1} = R^{-1} \cdot T^{-1} $$

The inverse of a translation is just subtracting the translation from all points. Don't create the inverse matrix of \\$T\\$, just subtract the part that corresponds to the translations from your points. For a rotation, it's inverse is equal to its transposed matrix:

$$R^{-1} = R^T$$

**EDIT:**

Even though clip space ranges from -1 to 1 in all directions, you might need to use 0 as the lower or upper limit for the z-direction of the view frustum points in clip space since if I remember correctly, the actual "screen position" is at z=0.

---

**UPDATE**

As you asked for some code in the comments, I wrote a small Python script that shows you everything about the solution I proposed. The full script is at the end of this answer and includes basically all calculations. Only for the inverse and matrix multiplication, I used NumPy. Regarding the calculation of the inverse matrix, check the link in the previous part of my answer.

You can copy the script and play around with the different camera parameters at the beginning of the script to see how they affect the result. It should run in any Python 3 environment with NumPy.

Now let's go to the important substeps. It is actually not that much. First, we define the view frustum in clip space. As I said before, it is just a cube with coordinate ranges -1 to 1. The important part here is, that you use 4d coordinates, where the w component is 1:

```
points_clip = np.array(
    [
        [-1, -1, -1, 1],
        [ 1, -1, -1, 1],
        [-1,  1, -1, 1],
        [ 1,  1, -1, 1],
        [-1, -1,  1, 1],
        [ 1, -1,  1, 1],
        [-1,  1,  1, 1],
        [ 1,  1,  1, 1],
    ],
    dtype=float,
)

```

The corresponding plot looks like this:

Now we calculate the perspective matrix and the world to view space matrix:

```
M_wv = get_world_to_view_matrix(camera_pitch, camera_yaw, camera_position)
M_vc = get_perspective_mat(field_of_view, z_near_plane, z_far_plane, aspect_ratio)

```

If you use OpenGl 3.3 or higher, you should have them already, since you need them in your shaders. If not, look at the corresponding function definitions in the full script (further references: learnOpenGL - Transformations, OGLdev - Perspective Projection).

Now we calculate the inverse matrices that we will need. Optionally, we can multiply them to get a single transformation matrix:

```
M_vw = np.linalg.inv(M_wv)
M_cv = np.linalg.inv(M_vc)
# M_cw = np.matmul(M_vw, M_cv) # direct clip to world transformation

```

Note that the indices of the result matrices are switched since they transform in the opposite direction. Now, all we need to do is to multiply each point with the corresponding transformation matrix, **and very important**, divide by the resulting w component afterward. I forgot to mention it in my original answer (I just found that out myself while I wrote the script ;) ). I transformed the points to world space and also to view space so that you can see the intermediate results:

```
points_view = []
points_world = []
for i in range(8):
    points_view.append(np.matmul(M_cv, points_clip[i]))
    points_view[i] = points_view[i] / points_view[i][3]
    points_world.append(np.matmul(M_vw, points_view[i]))
    # alternative
    # points_world.append(np.matmul(M_cw, points_clip[i]))
    # points_world[i] = points_world[i] / points_world[i][3]

```

Here is a plot of the frustum after the transformation to view space:

The green dot is the actual camera position. Here is the final result in world space:

I hope that helps you to understand the approach. If not, copy the script and run it. There are also some alternative calculations included, that you can use (In case you get an error, you missed probably to include some other comment). If there remain any questions, don't hesitate to ask, but consider creating a new question referring to this one for more complex questions to avoid extensive chatting in the comments.

> How do I move these corners into world space?

In case you want to use your own calculated points and want to transform them from view space to world space, all you need to do is to multiply them with the inverse world-to-view matrix. This is the same as this part of the script:

```
for i in range(8):
    ...
    points_world.append(np.matmul(M_vw, points_view[i]))

```

Just use your own points as `points_view`.

**Some further remarks**

* If you run the script, don't be confused if some frustum plots look distorted. This is because the axes are distorted. Resize the window manually, until the axes are identically scaled.
* In case you look into the "render function" don't get confused, that the y and z-axis are swapped. This is just to get the z-axis into the horizontal plane.
* Be aware, that you might not be able to copy/translate the code directly to use it with your program. In case you defined some coordinate directions differently, you might need to add or modify some transformations.

**Full Python script**

```
import numpy as np
from mpl_toolkits.mplot3d import Axes3D  # noqa: F401 unused import
import matplotlib.pyplot as plt

# setup --------------------------------------------------------------------------------

camera_position = [3, 0, 1]
camera_yaw = 20
camera_pitch = 30

field_of_view = 70
z_near_plane = 0.5
z_far_plane = 3
aspect_ratio = 16 / 9

# functions ----------------------------------------------------------------------------

def render_frustum(points, camera_pos, ax):
    line_indices = [
        [0, 1],
        [0, 2],
        [0, 4],
        [1, 3],
        [1, 5],
        [2, 3],
        [2, 6],
        [3, 7],
        [4, 5],
        [4, 6],
        [5, 7],
        [6, 7],
    ]
    for idx_pair in line_indices:
        line = np.transpose([points[idx_pair[0]], points[idx_pair[1]]])
        ax.plot(line[0], line[2], line[1], "r")
    ax.set_xlim([-5, 5])
    ax.set_ylim([-5, 5])
    ax.set_zlim([-5, 5])
    ax.set_xlabel("x")
    ax.set_ylabel("z")
    ax.set_zlabel("y")
    ax.plot([-5, 5], [0, 0], [0, 0], "k")
    ax.plot([0, 0], [-5, 5], [0, 0], "k")
    ax.plot([0, 0], [0, 0], [-5, 5], "k")
    if camera_pos is not None:
        ax.scatter(
            camera_pos[0], camera_pos[2], camera_pos[1], marker="o", color="g", s=30
        )

def get_perspective_mat(fov_deg, z_near, z_far, aspect_ratio):
    fov_rad = fov_deg * np.pi / 180
    f = 1 / np.tan(fov_rad / 2)

    return np.array(
        [
            [f / aspect_ratio, 0, 0, 0],
            [0, f, 0, 0],
            [
                0,
                0,
                (z_far + z_near) / (z_near - z_far),
                2 * z_far * z_near / (z_near - z_far),
            ],
            [0, 0, -1, 0],
        ]
    )

def get_rotation_mat_x(angle_rad):
    s = np.sin(angle_rad)
    c = np.cos(angle_rad)
    return np.array(
        [[1, 0, 0, 0], [0, c, -s, 0], [0, s, c, 0], [0, 0, 0, 1]], dtype=float
    )

def get_rotation_mat_y(angle_rad):
    s = np.sin(angle_rad)
    c = np.cos(angle_rad)
    return np.array(
        [[c, 0, s, 0], [0, 1, 0, 0], [-s, 0, c, 0], [0, 0, 0, 1]], dtype=float
    )

def get_translation_mat(position):
    return np.array(
        [
            [1, 0, 0, position[0]],
            [0, 1, 0, position[1]],
            [0, 0, 1, position[2]],
            [0, 0, 0, 1],
        ],
        dtype=float,
    )

def get_world_to_view_matrix(pitch_deg, yaw_deg, position):
    pitch_rad = np.pi / 180 * pitch_deg
    yaw_rad = np.pi / 180 * yaw_deg

    orientation_mat = np.matmul(
        get_rotation_mat_x(-pitch_rad), get_rotation_mat_y(-yaw_rad)
    )
    translation_mat = get_translation_mat(-1 * np.array(position, dtype=float))
    return np.matmul(orientation_mat, translation_mat)

# script -------------------------------------------------------------------------------

points_clip = np.array(
    [
        [-1, -1, -1, 1],
        [ 1, -1, -1, 1],
        [-1,  1, -1, 1],
        [ 1,  1, -1, 1],
        [-1, -1,  1, 1],
        [ 1, -1,  1, 1],
        [-1,  1,  1, 1],
        [ 1,  1,  1, 1],
    ],
    dtype=float,
)

M_wv = get_world_to_view_matrix(camera_pitch, camera_yaw, camera_position)
M_vc = get_perspective_mat(field_of_view, z_near_plane, z_far_plane, aspect_ratio)

M_vw = np.linalg.inv(M_wv)
M_cv = np.linalg.inv(M_vc)
# M_cw = np.matmul(M_vw, M_cv) # direct clip to world transformation

# alternative:
# M_wc = np.matmul(M_vc, M_wv)
# M_cw = np.linalg.inv(M_wc)

points_view = []
points_world = []
for i in range(8):
    points_view.append(np.matmul(M_cv, points_clip[i]))
    points_view[i] = points_view[i] / points_view[i][3]
    points_world.append(np.matmul(M_vw, points_view[i]))
    # alternative
    # points_world.append(np.matmul(M_cw, points_clip[i]))
    # points_world[i] = points_world[i] / points_world[i][3]

# plot everything ----------------------------------------------------------------------

plt.figure()
ax_clip_space = plt.gca(projection="3d")
render_frustum(points=points_clip, camera_pos=None, ax=ax_clip_space)
ax_clip_space.set_title("view frustum in clip space")

plt.figure()
ax_view = plt.gca(projection="3d")
render_frustum(points=points_view, camera_pos=[0, 0, 0], ax=ax_view)
ax_view.set_title("view frustum in view space")

plt.figure()
ax_world = plt.gca(projection="3d")
render_frustum(points=points_world, camera_pos=camera_position, ax=ax_world)
ax_world.set_title("view frustum in world space")

plt.show()

```
> 2 votes

---
Tags: opengl, camera, graphics-programming, shadow-mapping
---


title: Unity UI Objects edges are not smooth

text:
# Question
Title: Unity UI Objects edges are not smooth
I have this Unity UI Image placeholder and here is the snapshot  As you can see its edges are not smooth. First I thought this is editor problem but after making the build it remains the same. What i am missing?

# Answer
Thanks to @DMGregory, the reason was

> looks like you have an object that's rotated ever so slightly relative to the screen grid.

My UI elements z rotation was slight rotated so I change it to zero and it solved the problem.
> 1 votes

---
Tags: unity, gui, image, unity-ui
---


# Question
Title: Finding equivalent axial coordinates for a wrapping hexagonal map of radius n
I'm creating a wrap around hexagonal map that will potentially render infinatly.

With the method I'm using, I have an x-y coordinate I use to find it's equivalent axial coordinate with the equations: Q = (sqrt(3)/3 * x - 1./3 * y) / hexSize; R = (2./3 * y) / hexSize; the problem is, my map is of radius n and it's possible for the Q R coordinate to be far outside that radius. How can I find the equivalent Q-R coordinate within the radius n? I know methods for a single radius outside, but I'm talking the potential of having a radius of 15 but a Q-R something like (9999999,99999999). What would that coordinate be in relation to the center of the 15 radius hex region it'd be in?

# Answer
> 2 votes
I figured it out. For anyone else in the future I followed the posts by Sander Evers that amitp suggested (thanks both of you), just the small\_to\_big and center\_of functions in combination will give you the relative coordinate. One thing to note is the functions will tile the map with the southern mirror shifted right (and other mirrors following suit). Previously I had been assuming it'd be shifted left so It meant I had to tweak a couple of things in the rest of my code. Here's my implementation in c++:

```
//returns center coordinate of a large hex region with given radius r at cube coordinate (i,j,k)
        int_triple center_of(int i, int j, int k, int r)
        {
            return int_triple{
                                (r + 1) * i - r * k,
                                (r + 1)* j - r * i,
                                (r + 1)* k - r * j
                            };
        }
    //returns the coordinate of the large hex region with given radius r containing cube coordinate (x,y,z)
        int_triple small_to_big(int x, int y, int z, int r)
        {
            int area = (3 * r * r) + (3 * r) + 1;
            int shift = (3 * r) + 2;

            int xh = divide_floor(y + shift * x, area);
            int yh = divide_floor(z + shift * y, area);
            int zh = divide_floor(x + shift * z, area);

            return int_triple{
                                divide_floor(1 + xh - yh,3),
                                divide_floor(1 + yh - zh,3),
                                divide_floor(1 + zh - xh,3)
                            };

        }
    //returns the realative coordinate to the center of the hex region of size r containint the coordinate
        int_triple rel_coords(int x, int y, int z, int r)
        {
            int_triple smallToBig = small_to_big(x,y,z,r);
            int_triple centerOf = center_of(smallToBig.x,smallToBig.y,smallToBig.z,r);
            return int_triple{
                                x - centerOf.x,
                                y - centerOf.y,
                                z - centerOf.z
                            };
        }

```

---
Tags: algorithm, geometry, tiled, hexagonal-grid
---


# Question
Title: XNA's SpriteBatch resizing is not sharp as i use it
I draw a TiledMap with TiledSharp and i've introduced a resize factor when drawing, that looks like this:

```
SpriteBatch.Draw(TileSet                                                   // The input Texture2D
                 , new Rectangle((int)x                                    // The tile rectangle
                                 , (int)y
                                 , tileWidth * ScaleFactor
                                 , tileHeight * ScaleFactor)
                 , tilesetRec                                              // The tile offset on tileset texture
                 , Color.White);                                           // just white

```

> (note: it's not formated on different lines in my code, it's just i'm making it such way that anyone can understand without having previous lines)

but when i start the game it end up really blured and has some Strange outline

Can someone help me getting really sharp tiles instead of this?

N.B: i Don't want to resize the tileset file, it's to complicated for later modifications regarding the 16x16 style i want for my game. also i'm using Tiled to generate the Tiled Map but i Don't think this last info is relevent.

# Answer
> 1 votes
Thanks to @DMGregory, i've Added the parametter samplerState on SpriteBatch.Begin that fixed everything

```
SpriteBatch.Begin(transformMatrix: DisplayOffsetMatrix, samplerState: SamplerState.PointClamp);

```

---
Tags: c#, tilemap, spritebatch, tilesets, monogame-extended
---


# Question
Title: Completely Pixelated Font in JavaScript Canvas?
I'm making a game with a canvas scaled up such that each pixel is pretty big. I want to display some pixelated text without anti-aliasing but I have idea how I would accomplish this.

Is there I way can do such a thing?

# Answer
> 7 votes
In the css, you need to disable font smoothing for canvas:

```
canvas{
    font-smooth: never;
    -webkit-font-smoothing : none;
}

```

---
Tags: javascript, html-canvas, text
---


# Question
Title: How to register multiple key presses at the same time in pygame
Every time I try to operate player one and two or try to use the pickup key it stops the players. here is my code:

```
import pygame, sys, math
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((700,700))
screen.fill((255,255,255))
pygame.key.set_repeat(5,5)
import random
p1="james_u"
p2="billy_u"
p1_face= "r"
p2_face= "r"
p1h="health p1 4 HP"
p2h="health p2 4 HP"
player = 1
BG=pygame.image.load("Bgg.png")
H1=4
H2=4
G1X=random.randint(10,500)
G1Y=random.randint(10,500)

x_collide=[]
y_collide=[]

class Dude:
    char_width = 0
    char_height = 0

    def __init__(self, newX, newY):
        self.x = newX
        self.y = newY
        self.img = pygame.image.load(p2+".png")
        myRec = self.img.get_rect()
        Dude.char_width = myRec[2]
        Dude.char_height = myRec[3]

    def draw(self, window):
        window.blit(self.img, (self.x,self.y))

    def moveLeft(self):
        self.x = self.x - 5
        p2_face = "l"

    def moveRight(self):
        self.x = self.x + 5
        p2_face = "r"

    def moveUp(self):
        self.y = self.y -5
        p2_face = "u"

    def moveDown(self):
        self.y = self.y +5
        p2_face = "d"

    def getRec(self):
        return (self.x, self.y, myRec[2], myRec[3])

class Broski:
    char_height= 0
    char_width= 0
    def __init__(self, newX, newY):
        self.x = newX
        self.y = newY
        self.x_spd = 0
        self.y_spd = 0
        self.img = pygame.image.load(p1+".png")
        myRec = self.img.get_rect()
        Broski.char_width = myRec[2]
        Broski.char_height = myRec[3]

    def draw(self, window):
        window.blit(self.img, (self.x,self.y))

    def move(self):
        self.x += self.x_spd
        self.y += self.y_spd
        self.x_spd = 0
        self.y_spd = 0

    def getRec(self):
        print(myRec)
        return (self.x, self.y, myRec[2], myRec[3])

class BG:
    def __init__(self, newX, newY):
        self.x = newX
        self.y = newY
        self.img = pygame.image.load("Bgg.png")

    def draw(self, window):
        window.blit(self.img, (self.x,self.y))

    def getRec(self):
        myRec = self.img.get_rect()
        print(myRec)
        return (self.x, self.y, myRec[2], myRec[3])

class Health:
    def __init__(self, newX, newY, newH):
        self.x = newX
        self.y = newY
        self.img = pygame.image.load(newH +".png")
    def draw(self, window):
        window.blit(self.img, (self.x,self.y))

class Weapon:
    gun_list=[]
    gun_list_A=[]
    gun_count=0
    Player = "None"
    def __init__(self, newX, newY, idle_Image, Speed, Damage, Arc_Angle, R_Speed, active_Image):
        self.x = newX
        self.y = newY
        self.active_Image = active_Image
        self.idle_Image = idle_Image
        self.img = pygame.image.load(idle_Image +".png")
        myRec = self.img.get_rect()
        Weapon.gun_count+=1
        Weapon.gun_list.append(Weapon.gun_count)
        Weapon.gun_list.append(newX)
        Weapon.gun_list.append(newY)
        Weapon.gun_list.append(myRec[2])
        Weapon.gun_list.append(myRec[3])
        Weapon.gun_list.append(Speed)
        Weapon.gun_list.append(Damage)
        Weapon.gun_list.append(Arc_Angle)
        Weapon.gun_list.append(R_Speed)
        Weapon.gun_list_A.append(Weapon.gun_list)
        Weapon.gun_list=[]
    def playerlock(self, player):#once picked up it locks onto the player
        if math.sqrt((player.x-self.x)**2 + (player.y-self.y)**2) <= 150:
            self.img=pygame.image.load(self.active_Image+".png")
            Weapon.Player = player
        #positianal argument for weapons placement on player

    def draw(self, window):
        if Weapon.Player == bro:
            self.active_Image = self.idle_Image + p1_face
            self.x = bro.x -10
            self.y = bro.y -10
        if Weapon.Player == person:
            self.active_Image = self.idle_Image + p2_face
            self.x = person.x - 10
            self.y = person.y - 10
        window.blit(self.img, (self.x,self.y))
        #idle image must be gun name and nothing else while active is directional
    def getRec(self):
        print(myRec)
        return (self.x, self.y, myRec[2], myRec[3])

class Bullet:
    bul_width=0
    bul_height=0
    x=0
    y=0
    def __init__(self, newX, newY, Image, Player):
        self.x = newX
        self.y = newY
        x=self.x
        y=self.y
        self.player = Player
        self.img = pygame.image.load(Image +".png")
        myRec = self.img.get_rect()
        Bullet.bul_width= myRec[2]
        Bullet.bulsd_height= myRec[3]
    def shoot():
        print("shoot")

    def draw(self, window):
        window.blit(self.img, (self.x,self.y))

    def getRec(self):
        print(myRec)
        return (self.x, self.y, myRec[2], myRec[3])

class Object:
    ob_count = 0
    ob_list=[]
    ob_list_alpha=[]
    def __init__(self, newX, newY, Image):
        self.x = newX
        self.y = newY
        self.img = pygame.image.load(Image)
        myRec = self.img.get_rect()
        Object.ob_count += 1
        Object.ob_list.append(Object.ob_count)
        Object.ob_list.append(newX)
        Object.ob_list.append(newY)
        Object.ob_list.append(myRec[2])
        Object.ob_list.append(myRec[3])
        Object.ob_list_alpha.append(Object.ob_list)
        Object.ob_list = []

    def draw(self, window):
        window.blit(self.img, (self.x,self.y))

    def getRec(self):
        print(myRec)
        return (self.x, self.y, myRec[2], myRec[3])

# class does_collide:
#     def __init__ (self, item):
#         self.it = item
#         x_collide.append((self.it.img.get_rect(1))+Object.ob_list_alpha[1])

crate_1=Object(200,200,"Yellow_Cargo_Closed.png")
crate_2=Object(500,200,"Red_Cargo_Closed_Horz.png")
col_l = False
col_r = False
col_u = False
col_d = False
col_l2 = False
col_r2 = False
col_u2 = False
col_d2 = False
bggt=BG(0,0)
bro=Broski(10,10)
none=Broski(50,10)
person=Dude(665,560)
p1health=Health(35,620,p1h)
p2health=Health(465,620,p2h)
Gun_1=Weapon(G1X,G1Y,"glock",10,2,60,3,"glocku")
B_P1_1=Bullet(20,20, "Bullet_P1_1", "P1")
PL = none
while(True):
    screen.fill((255,255,255))
    bggt.draw(screen)
    person.draw(screen)
    bro.draw(screen)
    B_P1_1.draw(screen)
    crate_1.draw(screen)
    crate_2.draw(screen)
    p1health.draw(screen)
    p2health.draw(screen)
    Gun_1.draw(screen)
    pygame.display.update()
    key=pygame.key.get_pressed()
    for event in pygame.event.get():
        if (event.type==QUIT):
            pygame.quit()
            sys.exit()
        if event.type == pygame.KEYDOWN:
            #DEBUG HELP
            if key[pygame.K_LCTRL] and [pygame.K_b]:
                print("deebug")
                print(Gun_1.idle_Image+p1_face)
            for i in range (Object.ob_count):
                if  (person.x + Dude.char_width) >= Object.ob_list_alpha[i][1] and person.x <= (Object.ob_list_alpha[i][1] + Object.ob_list_alpha[i][3]) and (person.y + Dude.char_height) >= Object.ob_list_alpha[i][2] and person.y <= (Object.ob_list_alpha[i][2] + Object.ob_list_alpha[i][4]):
                    if person.x < Object.ob_list_alpha[i][1] and (person.y + Dude.char_height) > Object.ob_list_alpha[i][2] and person.y < (Object.ob_list_alpha[i][2] + Object.ob_list_alpha[i][4]):
                        col_r = True
                        break
                    else:
                        col_r = False
                    if (person.x + person.char_width) > (Object.ob_list_alpha[i][1] + Object.ob_list_alpha[i][3]) and (person.y + Dude.char_height) > Object.ob_list_alpha[i][2] and person.y < (Object.ob_list_alpha[i][2] + Object.ob_list_alpha[i][4]):
                        col_l = True
                        break
                    else:
                        col_l = False
                    if person.y < Object.ob_list_alpha[i][2] and (person.x + Dude.char_width) > Object.ob_list_alpha[i][1] and person.x < (Object.ob_list_alpha[i][1] + Object.ob_list_alpha[i][3]):
                        col_d = True
                        break
                    else:
                        col_d = False
                    if (person.y + person.char_height) > (Object.ob_list_alpha[i][2] + Object.ob_list_alpha[i][4]) and (person.x + Dude.char_width) > Object.ob_list_alpha[i][1] and person.x < (Object.ob_list_alpha[i][1] + Object.ob_list_alpha[i][3]):
                        col_u = True
                        break
                    else:
                        col_u = False
                else:
                    col_l = False
                    col_r = False
                    col_u = False
                    col_d = False
            for i in range (Object.ob_count):
                if  (bro.x + Broski.char_width) >= Object.ob_list_alpha[i][1] and bro.x <= (Object.ob_list_alpha[i][1] + Object.ob_list_alpha[i][3]) and (bro.y + Broski.char_height) >= Object.ob_list_alpha[i][2] and bro.y <= (Object.ob_list_alpha[i][2] + Object.ob_list_alpha[i][4]):
                    if bro.x < Object.ob_list_alpha[i][1] and (bro.y + Broski.char_height) > Object.ob_list_alpha[i][2] and bro.y < (Object.ob_list_alpha[i][2] + Object.ob_list_alpha[i][4]):
                        col_r2 = True
                        break
                    else:
                        col_r2 = False
                    if (bro.x + bro.char_width) > (Object.ob_list_alpha[i][1] + Object.ob_list_alpha[i][3]) and (bro.y + bro.char_height) > Object.ob_list_alpha[i][2] and bro.y < (Object.ob_list_alpha[i][2] + Object.ob_list_alpha[i][4]):
                        col_l2 = True
                        break
                    else:
                        col_l2 = False
                    if bro.y < Object.ob_list_alpha[i][2] and (bro.x + bro.char_width) > Object.ob_list_alpha[i][1] and bro.x < (Object.ob_list_alpha[i][1] + Object.ob_list_alpha[i][3]):
                        col_d2 = True
                        break
                    else:
                        col_d2 = False
                    if (bro.y + bro.char_height) > (Object.ob_list_alpha[i][2] + Object.ob_list_alpha[i][4]) and (bro.x + bro.char_width) > Object.ob_list_alpha[i][1] and bro.x < (Object.ob_list_alpha[i][1] + Object.ob_list_alpha[i][3]):
                        col_u2 = True
                        break
                    else:
                        col_u2 = False
                else:
                    col_l2 = False
                    col_r2 = False
                    col_u2 = False
                    col_d2 = False

            if key[pygame.K_UP] and col_u == False or (key[pygame.K_UP] and col_d == False and key[pygame.K_o]):
                if person.y > 10:
                    person.moveUp()
                    p2="billy_u"
                    p2_face="u"
                    if key[pygame.K_o]:
                        PL = person

            if key[pygame.K_w]  and col_u2 == False or (key[pygame.K_w] and col_d == False and key[pygame.K_q]):
                if bro.y > 10:
                    bro.y_spd += -5
                    p1_face="u"
                    p1="james_u"
                    if key[pygame.K_q]:
                        PL = bro

            if key[pygame.K_DOWN] and col_d == False or (key[pygame.K_DOWN] and col_d == False and key[pygame.K_o]):
                if person.y < 560:
                    person.moveDown()
                    p2="billy_d"
                    p2_face="d"
                    if key[pygame.K_o]:
                        PL = person

            if key[pygame.K_s] and col_d2 == False or (key[pygame.K_s] and col_d == False and key[pygame.K_q]):
                if bro.y < 560:
                    bro.y_spd += 5
                    p1="james_d"
                    p1_face="d"
                    if key[pygame.K_q]:
                        PL = bro

            if key[pygame.K_LEFT] and col_l == False or (key[pygame.K_LEFT] and col_d == False and key[pygame.K_o]):
                if person.x > 10:
                    person.moveLeft()
                    p2="billy_l"
                    p2_face="l"
                    if key[pygame.K_o]:
                        PL = person

            if key[pygame.K_a] and col_l2 == False or (key[pygame.K_a] and col_d == False and key[pygame.K_q]):
                if bro.x > 10:
                    bro.x_spd += -5
                    p1="james_l"
                    p1_face="l"
                    if key[pygame.K_q]:
                        PL = bro

            if key[pygame.K_RIGHT] and col_r == False or (key[pygame.K_RIGHT] and col_d == False and key[pygame.K_o]):
                if person.x < 665:
                    person.moveRight()
                    p2="billy_r"
                    p2_face="r"
                    if key[pygame.K_o]:
                        PL = person

            if key[pygame.K_d] and col_r2 == False or (key[pygame.K_d] and col_d == False and key[pygame.K_q]):
                if bro.x < 665:
                    bro.x_spd +=5
                    p1="james_r"
                    p1_face="r"
                    if key[pygame.K_q]:
                        PL = bro

            if B_P1_1.x == person.x and B_P1_1.y == person.y:
                if H2 > 0:
                    H2 -= 1
                B_P1_1.x = bro.x +10
                B_P1_1.y = bro.y +10

#             p1h ="health p1 "+str(H1)+" HP"
#             p2h ="health p2 "+str(H2)+" HP"
            if H1 == 3:
                p1h="health p1 3 HP"
            if H1 == 2:
                p1h="health p1 2 HP"
            if H1 == 1:
                p1h="health p1 1 HP"
            if H1 == 0:
                p1h="health p1 0 HP"
            if H2 == 3:
                p2h="health p2 3 HP"
            if H2<3 and H1>1:
                p2h="health p2 2 HP"
            if H2<2 and H2>0:
                p2h="health p2 1 HP"
            if H2<1 and H2>-1:
                p2h="health p2 0 HP"

            if event.type == pygame.KEYUP:
                if key[pygame.K_UP]:
                    print("hurr")
                if key[pygame.K_w]:
                    print("hurr")
                if key[pygame.K_DOWN]:
                    print("hurr")
                if key[pygame.K_s]:
                    print("hurr")
                if key[pygame.K_LEFT]:
                    print("hurr")
                if key[pygame.K_a]:
                    print("hurr")
                if key[pygame.K_RIGHT]:
                    print("hurr")
                if key[pygame.K_d]:
                    print("hurr")
            Gun_1.playerlock(PL)
            bro.move()
            p2health.img=pygame.image.load(p2h+".png")
            p1health.img=pygame.image.load(p1h+".png")
            bro.img=pygame.image.load(p1+".png")
            person.img=pygame.image.load(p2+".png")
            Gun_1.img=pygame.image.load(Gun_1.active_Image + ".png")
#             Gun_1.draw(screen)

```

I thought it was stopping because it was using a class function, but I did some messing around and figured it was the keys and I couldnt find anything online.

I've thought about switching the if statements to detect when the key isn't pressed but if pygame only lets one key be pressed at a time then the same issue arises.

If anyone has any suggestions on how to get it to detect multiple keys at once please let me know.

# Answer
> 1 votes
I refer to the answer by wyattis in https://stackoverflow.com/a/37126399/13682048. The built-in `pygame.key.get_pressed()` returns a list and one can check multiple keys with

```
keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT] and keys[pygame.K_LEFT]:
    move_fullcube = left

```

---
Tags: pygame, keyboard
---