title: How to use OnDrop on non-UI elements?

text:
# Question
Title: How to use OnDrop on non-UI elements?
I'm new to Unity and coding (C#), so sorry if this is a novice question.

Is the `OnDrop` function only usable for UI elements? I am currently making an ARPG Card game and I draw a hand of cards and can play these cards on enemies.

I currently have it working if I drag and drop a card onto other UI elements, but if I want to drag and drop the card onto an enemy (which then theoretically calls a function) it doesn't seem to work. BUT, if I drop the card onto its health bar (which is in the canvas and rendered into worldspace) it does seem to call the `OnDrop` function.

This is a 2D project and the enemies are set up with mesh renderers and 2D colliders.

How can I make `OnDrop` work if I just wanted to drop the card onto the enemy itself, and NOT its health bar?

# Answer
> 0 votes
To use Event System events with non-UI objects, you need to do the following:

1. Add a Physics Raycaster component the camera whose view you want to "click through" or "drop through". (Or a Physics 2D Raycaster if you're using 2D physics)

Optionally, you can set an Event Mask to control which physics layers should be clickable/drop-onto-able this way and which should be ignored / treated as transparent to clicks.
2. Add a physics collider to the 3D object you want to click/drop onto. (Or a 2D collider to the 2D object you want to click). This collider defines the volume of space that "counts" as a click/drop on this object. You can make it larger or a simpler shape than the object itself to make it easier to target with your mouse/finger.
3. Add an Event Trigger component to the object you want to receive the clicks / drops, or a script that implements the `IDropHandler` interface.

The reason why UI objects work with this automatically is because a newly-created UI canvas already has a Graphic Raycaster component on it by default. This does the same job as the Physics Raycaster in step 1 - mapping the pointer position on the screen to objects "under" that point - but for UI objects instead. UI objects also serve as their own collider shapes for picking purposes, as long as their "Raycast Target" checkbox is ticked.

---
Tags: unity, c#, input, unity-ui, card-game
---


# Question
Title: Do we need an ackowledgment packet in deterministic TCP multiplayer game?
I am trying to implement a deterministic game after having read 1500 archers on a 28.8. The simulation uses fixed-point math and the client only sends commands to the server which sends back the commands to all clients. The server sends also a `MessageTick` to autorize the clients to advance one step in the simulation. I have a few questions regarding this.

First of all, I don't know if I need an acknowledgment packet (even in TCP, not UDP) to guarantee that all the clients are synchronized before the server advances one step further. I know TCP has guarantees, but if I've understood correctly not the the one that the client has read the packet. We often see numbers like 15+ ticks per second. But I don't understand how it is possible, since a ping may be 100ms, how can it be more than 10 ticks per second? (1s/100ms=10). I could see that if the server sends continuously the `MessageTick` packets and do not wait an aknowledgment. In this case, we could run as much ticks per seconds we want with a delay dependening on the ping (and the bandwidth). However, this would make debugging difficult since we could not recover a network error (the server can't "go back in time" when an error is encountered). So do we need an ackowledgment packet or not? Is there a preferred method, or another that I didn't mentioned?

# Answer
No, you don't need to generate your own acknowledgement packet. TCP already guarantees the receipt and sequence order of messages below your application layer in the network stack. The protocol layer handles generating the required acknowledgements, invisible to your application.

If the server sends you "Action X happened in Tick 42" and then sends you "Action Y happened in Tick 42" and then "Now it's time to advance to Tick 43", your application will receive message X before message Y before the message for tick 43.

If the packet with message Y gets dropped, it will be re-transmitted until it's received before your application processes the Tick 43 message. So, it can delay the game and cause a noticeable stall or hiccup, but won't interfere with the correctness or determinism of the simulation.

> We often see numbers like 15+ ticks per second. But I don't understand how it is possible, since a ping may be 100ms, how can it be more than 10 ticks per second? (1s/100ms=10).

The next packet can be travelling down the pipe before the previous packet is received. That means the server may have already sent you messages 5, 6, 7, 8, before it knows whether you received message 4. If you didn't, the later messages you *did* receive are held in a buffer on your side of the connection until the missing packet (or a re-transmission of it) eventually arrives, after which the messages are delivered to your application layer in order.

However, this does not mean you will reliably receive messages 15 times per second. It can be bursty, with delays waiting for a key packet followed by rapid processing of buffered messages. So you'll hit your tick rate only on average, and if your game updates in realtime, you might need to use interpolation/prediction tricks to mask this and present the illusion of a history evolving continuously at a steady rate.
> 1 votes

---
Tags: networking, rts, fixed-timestep
---


# Question
Title: How to manually Simulate Physics properly on Unity?
I'm trying to simulate physics manualy in a Unity 3D game. I've turned off Physics "Auto Simulation" in Project Settings and wrote this piece of code (it is more or less the unity doc sample)

```
private void Update()
{
    this.timer += Time.deltaTime;
    while (this.timer >= Time.fixedDeltaTime)
    {
        this.timer -= Time.fixedDeltaTime;

        controller.ApplyForces(controls);
        Physics.Simulate(Time.fixedDeltaTime);
    }
}

```

But when I play the game, movements are lagging a lot.
In fact, I can explain it: my game runs at 120 fps. The `Time.fixedDeltaTime` is set to 0.01667 (60fps). So 1 out of 2 frames are not simulating physics! In other words, half of my Update calls don't enter the `while` loop, which produce the jump effect.

I'm sure i'm missing something... what is the recommended way to do this? Should I call `Physics.Simulate` in `FixedUpdate`?

EDIT:

As someone asked me in the comments (then deleted the comment), I'm simulating Physics manually for networking reason. With manual physics, I can do predictions and corrections. Here's a link that describes the problem

EDIT2:

Thanks to @DMGregory and his excellent answer, I figured out that the problem comes from the lack of interpolation of my player rigidbody:
InterpolationMode seems to be handled by Unity when autosimulation is set to ON, which is not my case.

So now I'm looking how to handle this myself.

# Answer
After a lot of research, I have a better understanding of this.

1. the problem I describe is a very common problem due to unsync between frame rendering timestep and physics fixed timestep. Unity solves this automatically with the `interpolationMode = interpolate` of rigidbodies.
2. when simulating physics manually, Unity do not interpolate thoses rigidbodies for us anymore. We have to do it manually, as @DMGregory suggests
3. another option is lower fixedDeltaTime a lot to minimize desyncs, as @shingo suggests. But rendering timestep is not constant! And if the game runs at 120fps, the fixedTimestep whould be very small and CPU instensive.
4. I highly recommand to read this article, which suggests to use `Application.targetFrameRate` and `fixedDeltaTime` to synchronise those timesteps to the same framerate.

Finally, I set the framerate to 60Hz whith those two properties: this is ok for rendering and not too intensive for CPU physics. And the game seems fluid again.
> 2 votes

# Answer
You are right, you need a small `fixedDeltaTime` value (eg. 0.01).

You can simulate physics in Update, but you'd better drag this script to the front row in Script Execution Order settings.
> 1 votes

---
Tags: unity, physics, networking
---


# Question
Title: Why do I still get values from _CameraDepthTexture even if I didn't set depthTextureMode?
I forgot to write this C# code to enable depth from my camera:

```
private void OnEnable()
{
    GetComponent<Camera>().depthTextureMode = DepthTextureMode.Depth;
}

```

Also, I specified camera render path is `Forward`. However, my shader below still works and the depth from `_CameraDepthTexture` is correct. All of this I tested in PC, I'm confused why it's working.

```
Properties
{
    _TopColor("TopColor",Color) = (1,1,1,1)
    _BottomColor("BottomColor",Color) = (1,1,1,1)

    _NoiseTex("NoiseTex", 2D) = "white" {}
    _NoiseScale("Noise Scale", Range(0.01,2)) = 1
    _Height("Height",float) = 1
    _Speed("Speed",float) = 1
    _DepthBiasFactor("DepthBiasFactor",float) =1
    _DcurvatureRadius("DcurvatureRadius",float) = 30
}
SubShader
{
    Tags { "RenderType"="Transparent" "Queue" = "Transparent" "IgnoreProjector" = "True"}
    LOD 100

    ZWrite On
    ZTest On
    Blend SrcAlpha OneMinusSrcAlpha

    Pass
    {
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        // make fog work
        #pragma multi_compile_fog

        #include "UnityCG.cginc"
        #include "Lighting.cginc"

        struct appdata
        {
            float4 vertex : POSITION;
            float2 uv : TEXCOORD0;
            float3 normal : NORMAL;

        };

        struct v2f
        {
            float2 uv : TEXCOORD0;
            float2 CloudUV01 : TEXCOORD2;
            float2 CloudUV02 : TEXCOORD3;
            float4 worldPos : TEXCOORD4;
            float2 noisePos:TEXCOORD5;
            float4 screenPos : TEXCOORD6;
            float3 worldNormal : TEXCOORD7;
            UNITY_FOG_COORDS(1)
            float4 vertex : SV_POSITION;
        };

        float4 _TopColor;
        float4 _BottomColor;
        sampler2D _NoiseTex;
        float _Height;
        float _Speed;
        float _DepthBiasFactor;
        sampler2D _CameraDepthTexture;
        float _DcurvatureRadius;
        float _NoiseScale;

        v2f vert (appdata v)
        {
            v2f o;
            o.vertex = UnityObjectToClipPos(v.vertex);

            o.CloudUV01 = v.uv + _Time.x * _Speed;
            o.CloudUV02 = v.uv - _Time.x *_Speed;
            o.noisePos.x = tex2Dlod(_NoiseTex, float4(o.CloudUV01,0,0)).r * _NoiseScale;
            o.noisePos.y = tex2Dlod(_NoiseTex, float4(o.CloudUV02,0,0)).r * _NoiseScale;
            o.worldPos = mul(unity_ObjectToWorld, v.vertex);
            o.worldNormal = mul(v.normal,(float3x3)unity_WorldToObject);

            o.vertex.y += o.noisePos.x * o.noisePos.y * _Height;

            o.vertex.y -= pow(distance(float2(0,0), o.worldPos.xz) / _DcurvatureRadius, 3);

            o.screenPos = ComputeScreenPos(o.vertex);

            UNITY_TRANSFER_FOG(o,o.vertex);
            return o;
        }

        fixed4 frag (v2f i) : SV_Target
        {
            float3 worldNormal = normalize(i.worldNormal);
            float3 worldLight = normalize(_WorldSpaceLightPos0.xyz);

            float4 depthSample = SAMPLE_DEPTH_TEXTURE_PROJ(_CameraDepthTexture, i.screenPos);
            float depth = LinearEyeDepth(depthSample);
            float borderLine = saturate((depth - i.screenPos.w) / 2 - _DepthBiasFactor);

            float mask = saturate(i.noisePos.x * i.noisePos.y);

            float4 col = _TopColor * mask + _BottomColor * (1 - mask);

            col.a = borderLine;

            float3 diffuse = _LightColor0.rgb * col.rgb * (dot(worldNormal,worldLight) * 0.5 + 0.5);

            // apply fog
            UNITY_APPLY_FOG(i.fogCoord, diffuse);
            return float4(diffuse,col.a);
            // return float4(borderLine,borderLine,borderLine,1);
        }
        ENDCG
    }
}

```

# Answer
I changed the platform to Android and the `_CameraDepthTexture` can't be fetched anymore if I failed to specify the camera's depth mode by code.

So, on the PC platform, no matter what render path, it seems there is no need to specify the camera's depth mode, but on other platforms, depending on the render path, the C# code might be needed.
> 0 votes

---
Tags: unity, shaders, rendering, depth-buffer
---


title: ECS : Can systems have sub-systems?

text:
# Question
Title: ECS : Can systems have sub-systems?
I am searching about "sub-systems" in ECS but I don't find any article speaking on that. Considers this simple example:

```
struct Engine
{
    MoveSystem move_system;
    CollisionSystem collision_system;
    RenderSystem render_system;

    void PhysicsSystem::update()
    {
        move_system.update();
        collision_system.update();
        render_system.update();
    }
}

```

We can make a `physics_system` which will be the aggregation of the `physics_system` and the `collision_system`.

```
void Engine::update()
{
    physics_system.update();
    render_system.update(); // No change
}

struct PhysicsSystem
{
    MoveSystem move_system;
    CollisionSystem collision_system;

    void PhysicsSystem::update()
    {
        move_system.update();
        collision_system.update();
    }
}

```

Is it a bad practice? I could not see any drawback since it looks like just a pure change-big-class-into-many-smalls refactoring without logical changes.

# Answer
> 2 votes
1. Yes, you can. ECS is just like a "guiding methodology",There is no mandatory rule. You can make your own implementation as needed.
2. Is it a bad practice? Maybe. `PhysicsSystem` is not characterized as a system. It does not focus on entities with certain properties. It is only used to organize some other systems. So maybe `PhysicsSystem` is a **System Group** instead of system. System Group is a common concept in ecs system, usually used to organize the update order. You can search it with "system groups" as key-word instead of "sub-systems".

---
Tags: entity-component-system
---


# Question
Title: Isometric Tilemap is blocking UI elements
I'm using Unity 2019.4.6f1, and I'm working on Isometric Tilemaps.

The hierarchy is like this:

The VillageScreen is a `Canvas`, `img-bg` is an UI Image, the two `Panel`s are UI Panels, and the `Grid` and two `Tilemap`s are the isometric tilemaps. The problem is, the Grid & Tilemap is blocking all other UI elements, and it seems to be always on top, no matter how I set the Z value.

The Grid setting is:

And the Panel setting is:

My question is: How do I put the UI elements **ABOVE** the Tilemap?

p.s. the UI button is clickable, it just cannot be displayed properly.

--

**UPDATE:** Added a mockup screen - Black circles are buttons, while Red texts are UI texts for displaying scores.

# Answer
I think the problem is that your Grid transform position is to `-100` on the Z-axis. Perhaps not using the UI sorting layer for the Grid might help as well.

I'm a relative newbie in Unity so I may be wrong, but I'm doing something similar with a project I'm working on and don't have the same problem.
> 1 votes

---
Tags: unity, tilemap, isometric
---


title: Game Data Files security in unity

text:
# Question
Title: Game Data Files security in unity
I have some game data files in PDF, excel, and video format. Is there any way to make it secure? Through encryption? I have almost encrypted my all files in .aes encryption format but there is a huge problem i have to decrypt it each time when i have to show it to the user ! Therefore I have to place it inside file explorer and anyone can access it. How do I prevent it?

# Answer
> 2 votes
First things first: if the data is in the user's hands (stored on their device or even just displayed), they have access to it and it should be treated as such. That means regardless of what kind of encryption you employ, if they spent enough time, they can / will always be able to get it. All you can do is make it harder for them.

Now you noticed it yourself already that encrypting is already a performance issue for you. But is that really needed? Since we know that if they really want that they can get the data, we actually just need to prevent first 99% of the users to casually read the data. Storing it in a format that is easy to read (for your application) but hard for the user (file manager) is rather trivial. Instead of saving it as a common type (like .xsl, .xml, .pdf) just store it as a byte stream.

Now the harder part: what are you trying to prevent? In case you want to prevent manipulation of fixed assets (like values for stats, scores, saves), in addition to storing the file you can store a hash. On load you compare the hash of it to the file (you would rehash the file) to make sure they are equal. This does not prevent manipulation totally since if the hash is local, it can be manipulated as well. Just another layer of making it harder.

If you want to prevent theft of assets, this is even harder. The easiest way would be probably to not use any common format but have a custom developed one. If you are the only one that uses the format, it reduces the chance that others are willing to spent the effort trying to find out how to use them. Again just making it harder.

If you want to prevent the loss of sensitive data, do not store it locally at all. Keep it on your own server to make a data mining of it harder.

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


# Question
Title: What are the implications of releasing without a trademark?
I've been working on a video game for almost a year now and with release looming I'm starting to panic cause I don't have a trademark (but I do have a company).

I really don't want to have to push release back a year to wait for the trademark process... Can I get around this and just release (safely) somehow?

# Answer
**You should release.**

A trademark allows you to protect a name. You're more likely worried about your game, its concepts and art assets. You likely haven't spent a lot of time building up a brand, getting lots of following for your game, so people know it by name. If you had, you likely wouldn't be so worried about releasing without a trademark.

However, don't think that releasing without a trademark hurts you. In fact, it's likely to be beneficial:

> Assuming your name doesn’t violate any existing trademarks, you gain “common law” trademark rights the minute you use it in commerce, regardless of whether it has been registered by the USPTO. Furthermore, registering a trademark with the USPTO requires you to prove that you’ve used the name in commerce – which will be hard to do if you’ve been keeping it under wraps.

Releasing your game and using its name grants you protections you don't have if you keep your game unreleased.
> 46 votes

# Answer
There are different kinds of trademark, normal (™) and registered (®). Registering a trademark is overkill for most cases. Even huge studio's don't always do it.

A normal trademark does not need a registration with an authority. So, just put a ™ after the name and you should (as far as I know) be fine.
> 14 votes

# Answer
As someone who has been through this with my own software, I would strongly recommend that you register your trademark ASAP with the USPTO.

Our product has been out for 20+ years, and just recently a large 'industry disrupter' came out with a product that used our name. This immediately put us in league with them, in our prospective clients' eyes, and basically killed our goodwill to a large chunk of our industry.

Over the years, we have also contested (and lost) to other groups using our name.

At the end of the day, your main asset is your name & reputation. Software gets upgraded, replaced, dumped... But your product name is how the world knows you, and what will hopefully get your bought out down the road (if that is your goal).
> 2 votes

# Answer
first off, IANAL so be aware. That said...

"Safely" is a relative term. I mean, the main thing a registered trademark protects against is someone scooping up your game's name, and even then you're only "protected" in the sense that you could win a lawsuit; someone could still try to steal your game's name, and then you'd have to sue them.

That's not super likely to happen as long as you've done your due diligence to make sure nobody else is already using that name. For example you can lookup existing trademarks here. But whether "not super likely" is safe enough for you is, well, relative. I mean, it certainly *does* happen occasionally.

Either way I would apply for a trademark right away. That's whether or not you release the game before the registration process is finished. The name isn't really valuable yet, but could become so if your game is successful, so you'll want a registered trademark by then.

Also, this related question has more information you should read.
> 1 votes

# Answer
Of course, you can launch a new brand without first getting trademark registrations, but securing the essential rights afterward may need a large sum of money.
> 0 votes

---
Tags: trademark
---


# Question
Title: How can I discourage players from attacking everything they encounter?
### Setting

A game I'm currently developing is in a dark, hostile setting full of otherworldly creatures. The world is set in an unusual series of castles, towers, and other enormous types of medieval construction that are floating in a foggy void. The player character awakens with no memory of who they are or how they got there.

### Plot

The driving forces of the game are:

1. Finding food and water in a setting where such would be scarce, encouraging exploration
2. Looking for other people, if there even are any
3. Looking for a safe place to stay when the monsters inevitably find the home base you have set up

### Gameplay and why players may try to kill everything

The central gameplay loop involves searching out food and water sources in a bizarre location where both are scarce (the player has a very generous amount of time before starving or becoming dehydrated, as well as gaining buffs from being full/hydrated), and battling with the horrific creatures you encounter on your travels. Being constantly on the move is a necessity, as staying in one place for too long is a good way for the more predatory creatures to have you as a late night snack. I intend for finding a secluded hiding place to be very satisfying, allowing for respite and giving an opportunity to safely take inventory of all the things you've picked up. You can fight anything that you encounter, but it's often a better idea to carefully plan your attack rather than running in mashing attack buttons.

The combat is reminiscent of games like *Dark Souls* and *Monster Hunter*, focusing on strategic combat and caution, as well as planning ahead. Items, tactics, and the environment itself can be used to give the player the edge in a fight where they would otherwise be outmatched. There are many ways to approach fights, and they can often be avoided outright if the player feels the need to do so. Most enemies are monstrous, inhuman, and much stronger than the player. A good portion will also attack or become aggressive on sight. Some are even very intelligent and will use stealth or deception to catch you off guard.

Now, not all creatures are like the ones here. Many will attempt to kill and eat you but will give up and flee if you prove to not be worth the risk. Some will simply run and hide immediately. Some are territorial and just want you to leave, and will rely more on intimidation than actually engaging in combat.

You may even encounter small nomadic groups of humanoid creatures with similar intelligence to humans. This is where this problem comes in. They will generally not attack the player on sight, and will even be willing to cooperate with the player if you show you aren't hostile, may that be by putting away your weapons or giving them items as an act of peace. The creatures are visibly non human. If they see the player they will not immediately attack, and instead will display cautious curiosity or fear. They do not speak any human language, so interactions are done through body language or simple gestures. They will even do things like trade with the player or lead them to locations with abundant treasure. But this requires you to not immediately try to kill them.

Just because of the way the game works, players are conditioned to be paranoid and overly cautious, and a player just encountering them may just think to stealthily pick them off instead of attempting to interact or just see what they're up to. How can I give the players any hints that they shouldn't just murder them? Or for that matter, a way for players to learn that not everything they see should be killed. Preferably I would want to do it in a way that doesn't involve an immersion destroying tutorial screen or something similar.

# Answer
> 43 votes
The reason why players tend to kill anything that moves in most games is because those games reward them for doing so. Whenever the player kills an enemy, they gain something which makes up for the investment in resources, time and risk: Money, score, experience, resources, progression, you name it.

If you want to train your players to only fight when strictly necessary, then don't do that. When they defeat an enemy, don't give them anything at all. If fighting always means to spend resources and take risks with no hope of getting anything in return, then players will soon develop a habit of avoiding confrontation.

If you have both hostile and non-hostile entities in your game and want the player to find out which is which, then a good way to do so is to introduce non-hostile entities very early in the game and in a context where the player can't fight them. Like right in the beginning before the player obtained the ability to fight or during a non-interactive cutscene. This teaches the player that not everything that moves is a threat.

One game which does both of these very well is *Subnautica*. I would really recommend you to check it out, because it seems like a game with a very similar premise to yours. The major difference is perhaps that *Subnautica* also avoids making combat interesting by not giving the player any good weapons or cool combat maneuvers, which removes another incentive for the player to seek combat.

# Answer
> 8 votes
We can try to frame it as a balance between gain and loss (we are excluding risks and applied costs, for simplicity):

Typical monsters:
Attack Gain - when player attacks a monster, they gain experience and loot.
Attack Loss - none (cos we exclude the risk factor of being hurt/killed and applied costs for simplicity).
NoAttack Gain - none.
NoAttack Loss - none.
Conclusion - attacking monsters is always a good idea.

Now we can already see where this can be going, we need to apply similar rules but "invert" them to discourage the attacking of NPCs. Attacking should be discouraged and Not-Attacking encouraged.

For example, neutral or friendly NPCs:
AttackGain - when player attacks an NPC, they should gain little/nothing. No experience and little/no loot.
AttackLoss - when player attacks an NPC, they could lose reputation, ability to trade, etc.
NoAttackGain - if player does not attack an NPC they gain a lot from being able to interact, trade, get quests, etc.
NoAttackLoss - none.
Conclusion - attacking NPCs should be costly/undesireable.

---

Another aspect of it - player usually gets visual/audio feedback from their actions. If attacking NPCs looks/sounds unpleasant - player will do that less.

---

Now what about "attacks by mistake"? Many times a player can mis-click or attack by instinct/reflex. For such cases the games usually make the NPCs tolerant to some damage and/or completely invulnerable and/or standing in "no offence" zones.

# Answer
> 4 votes
There are a few ways to get players to try to interact with creatures instead of attacking them.

You can decide what makes the most sense for your game and the mechanics you have and whether players even having the option of attacking these creatures is ultimately something you want.

I mention human NPCs in some of the below solutions. This would obviously only apply if you actually have human (or other clearly friendly) NPCs.

### Tell players to interact with the creatures

You can have some human NPCs casually mention that some creatures can be interacted with. Although this could be fairly easy to miss.

You can have loading screens tell the player this.

You can have info messages pop up occasionally when players approach these creatures.

### Force interaction once

#### Tutorialise interaction

This is probably the most in-your-face solution that still allows players to do their own thing.

The first time they encounter such a creature, you could pause the game and prompt them to put away their weapon or interact with the creature. Or you could prevent them from attacking and only allow them to interact with it.

After they've interacted with one of the creatures, they can freely choose to instead murder the next ones they run into.

Tutorials are common in games, but I don't think I've seen any for this specific purpose. Then again, most games tend to clearly differentiate friendlies and enemies in various obvious ways (some of which are listed in this answer).

#### Make interaction an (optional or required) quest

Give them a quest to interact with one of the creatures (either a specific one, or just any of them).

This makes it fairly clear that these creatures can be interacted with.

#### Introduce the creatures in the beginning of the game

You can have the player be awoken by one such creature or in a dwelling of the creatures.

The player might not have any weapons yet or you may simply prevent them from attacking until they get away from the creature or leave the settlement.

This makes it clear that the creatures are non-hostile, but it may make sense to also tutorialise interacting with them in case players miss the fact that they can do this.

### Force interaction always

If you don't want players to attack the creatures, make them unable to attack the creatures.

It's fairly simple, and it's an approach many games go with.

Some games allow you to attack friendlies while they will just idly stand there staring at you boggle-eyed while you try to murder them, until you give up eventually when you realise you don't seem to be having much of an effect on them.

### Present the creatures as NPCs

This is what almost all games I've played do.

Either something is an NPC or it's an enemy. Players can't non-violently interact with enemies. Players may or may not be able to attack and kill NPCs.

Skyrim (and other Elder Scrolls games) are probably a decent example of this. In towns attacking people is not going to go well (you'll have a bunch of guards to deal with soon enough). But there are also more remote settlements where you're free to kill NPCs, but it's still obvious that they're NPCs.

There are a few ways to present creatures as NPCs:

* Their dwelling uses a "town" as a marker on the map (which is possibly usually used for humans in your game)
* The UI shows them as neutral / ally.

+ They don't show up as enemies on the minimap.
    + You see an "interact" crosshair when looking at them (or something similar that's easy to differentiate from what they see when looking at an enemy).
    + The crosshair doesn't change to an "attacking" crosshair until after you've attacked them for the first time.
* They live in what's basically a town. The creatures could have various trades and they do things that humans would typically do. Overall, such a town might look a whole lot like a palette-swapped human town.
* Some of the creatures live with human NPCs inside a friendly town.
* Some or all of them run away when you attack them.
* Even when fighting, they generally try to keep their distance from the player. They may draw a sword and just stand there, waiting for you to engage (like someone who doesn't actually want to fight would do).
* They have "guards". After you attack one of them, that one may run away and a bunch of others might engage in combat instead. Guards will engage in combat, most others will just run away (even after all the guards are dead). Some others may defend themselves if attacked.

Building on the Skyrim example, you can have some dwellings be large with plenty of guards (meaning it's really, really difficult to fight your way through that, which may make it clear that fighting probably isn't the best option), while other dwellings are small and fairly easy to wipe out. Think large city versus a few adventurers in a tent or two (with plenty in between).
* They may stop attacking when you put your weapon away (but they may still be "on guard").

# Answer
> 2 votes
An example that fits the bill are Minecraft Piglins. They are humanoid, but clearly not human. Don't have verbal communication (only gestures and grunts). You can trade with them. They are not hostile unless provoked.

When you attack them (or provoke them), you are marked. You may get away from them, but they remember you attacked them and stay hostile. Also other piglins will come to help hunt you. Which means that if you stay and fight, they will become overwhelming by numbers.

It is important to note that you provoke them by picking up gold items. So you pick up a gold item in front of them, and they attack you. And that is likely to happen because there is gold available for mining in the enviroment where they are.

As a result, the player learns to not attack them and not pick up gold items near them. Which will give the player enough pause to observe that the piglin picks the gold items, and drops something else in exchange. This is how you trade with them. Drop gold items, they pick them and give you something in exchange.

---

You can take the same concept and apply it to your game:

1. Fighting them is hard. It could be they heal fast, or resit a lot of damage, or it could be they keep summoning help, or whatever. Depending on your death mechanic, you may want to give the player the opportunity to escape the combat, even have them disengage easily. In fact, it could be that they push the player away, so the player can't melee them.
2. They give you a trade opportunity. I don't suppose you mine gold, or trade by dropping items. Instead, make it obvious that there is trade opportunity with them, and trust that once the player learned to not attack them, the player will notice. I suppose that having them approach the player will trigger fight or flight. So, instead, I suggest some sort of sign that the player can see from reasonable distance, which also promts the interactions when the player approaches.

Note: I agree with the other answers that not giving a reward for killing them is a good idea. However, I want to note that there is reward for killing Piglins in Minecraft. And that works in Minecraft because you lose your inventory upon death. If that is the case in your game too, then that might work.

# Answer
> 2 votes
Why not put a corpse of one of those humanoid creatures near the spawn point? The player will be able to find a note (book) on them with some facts about trading with those tribes =\> to not be too obvious but still give the player some hint that those humanoids are another intelligent life form.

# Answer
> 1 votes
I can think of a few ideas.

1. Resources are scarce; fighting causes your character to dehydrate and starve at a faster rate as they consume the (really valuable) energy he regains once he finally encounters something to eat and drink. This way the character feels the urge to choose his fights better, and if something doesn't attack the player at first sight, the player will fell free to get close and interact without attacking.
2. Make these creatures change their behaviour according to the player's actions. If the player doesn't attack them, they won't attack the player. If the player attacks them, they will run away. If the player keeps attacking them, they will fight back, and the next time the player gets close to them, this time they will attack first. You could also make that the next group the player encounters also attacks the player immediatly.
3. Use visual cues, e.g. a colored glowing aura around all the creatures roaming this place. Aggresive creatures glow in red; scaredy creatures glow in yellow; non-aggressive creatures glow in blue or green. This can be some kind of in-universe mechanic, a special hability the main character has, that is somehow tied to his past and origins.

# Answer
> 0 votes
Try to look at the problem with a different perspective. In such a dilemma providing a solid background for your NPCs hostiles or not will help you foresee and feel why players would not fight everything that moves.

* Lets start by figuring why those other creatures are non-hostile to players?
* And why hostile creatures are hostiles to player?
* Then lets define if there are various degrees between full hostility and total friendliness; and if this can change during a journey/session or is engraved in rules and cannot change.

When you have answered those 3 questions above, you have a better picture on why player may not be hostile toward all creatures.

# Answer
> 0 votes
Make sure your players respect the world they are in. Much like in the real world there are large consequences of making stupid choices.

Make the enemies passive dangerous. I am reminded of the giants in skyrim. You can also remove many rewards from them, but making them more hostile is a good step.

If there are NPCs or guards, make them very capable and respectable. Look at morrowind for example, you learn the laws in that game and there is a respectful sense of fear for even small things like sleeping in someone's bed . Or Alma Alexia's right hands.... Those guys are not easy and starting a fight or stealing around them is a death sentence.

Here are some funny videos talking about this.

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

https://www.youtube.com/watch?v=gvNb3jts-Qs

https://www.youtube.com/watch?v=09t\_ZuA\__6U

# Answer
> 0 votes
I would simply add very negative Voice Actor lines and strict sanctions of the game, for once you can make things harder if you act aggressively, and twice, you can have a karma-like system that opens options only for players who behave cooperatively and careful.

# Answer
> -1 votes
My first idea was outlines. When you hover your mouse/crosshair/whatever over an enemy, it gets a red outline. But friendly creatures get a green outline.

Even when a player has been initially conditioned to attack anything and everything, the sudden green outline (which is unlike all the red outlines they've seen so far) should give them a pause for thinking. And in most cultures (but not all! Beware!) red==bad, green==good.

I think this should be a strong enough nonverbal cue to the players that "you should try to interact with this creature peacefully". To give them extra safety, if your game relies on savepoints, place one such a savepoint just before the first few friendly encounters, so that the player feels safer to try a risky approach. (A few, because they might miss the first one)

Alternatively, if outlines aren't your thing, I've seen games give other kinds of visual cues. For example in Hollow Knight most enemies have some orange about them, while friendly creatures rarely do. You could do similarly with glowing red eyes or whatever. But that of course depends on your chosen art style, so it may or may not be an option.

---
Tags: game-design, game-mechanics
---


# Question
Title: How do I create this windblown snow effect?
How do I create this snowy wind kind of effect, where wisps of snow appear to blow through the air close to the ground?

I have seen this in several games like Skyrim, the new God of War, but I don't know what name to call it by.

I found this God of war gameplay https://youtu.be/b7u59Iutb0c

# Answer
> 3 votes
Note: I have not used Unity yet, so here's my very high-level/conceptual answer:

Aside from simply spawning particles in a particular area/direction, it looks like Skyrim is using another technique where a semi-transparent "blown snow" texture is quickly scrolling across a flat mesh coming off the ground.

The mesh would be completely stationary, but the texture on it would be scrolling quickly in the direction of the wind. To make a texture scroll across a mesh without moving the mesh itself, just translate the vertices' UV coordinates over time. To make the effect repeat correctly, you'll have to set edge sampling of the texture to 'repeat' or the equivalent (if this is not already the default).

Also, since the mesh you'd be using would be 'paper thin' you may want to disable backface culling on the object in order to see the gust effect from both sides.

Final note: You may want to fade the effect out as it gets closer to the edges of the mesh, otherwise it may look like a cutout. This can be done via the mesh itself. Add extra vertices and triangles near the edges of the mesh, then set the color attributes on the outermost vertices to completely transparent.

# Answer
> 0 votes
I think that image space modifiers (imod objects in the object window) could be used as well. A weather comes with its own ambient directional lighting and imod. The weather is also flagged as "severe" for Frosftall, survival mode etc. So I would investigate the solution starting at the weather. Imods are "just" changes "on-screen" of the player, and not really alter the environment ("in 3D").

---
Tags: unity, particles, graphic-effects
---


# Question
Title: Fatal Python error: (pygame parachute) Segmentation Fault when using PyGame and cx_Freeze
I'm using cx\_Freeze to package my PyGame game. I'm running Ubuntu Linux, so I used the source package. However, I got the following error when I run `cxfreeze game.py`:

```
Fatal Python error: (pygame parachute) Segmentation Fault
Aborted

```

How can I fix this? I have seen other similar questions but no good answers.

# Answer
> 1 votes
You can fix this by finding out what exactly causes the "pygame parachute".

Your first step to find this out is to add detailed logging to your code. Start off with poor man's `print()` logging:

```
print("importing pygame")
import pygame
print("initialising pygame")
pygame.init()
...

```

With that sort of code you might get an error message like

```
initialising pygame
Fatal Python error: (pygame parachute) Segmentation Fault
Aborted

```

which helps you to isolate where the problem happened.

Second, cx\_freeze is rather tricky. `cxfreeze game.py` might not be enough to get a working executable. It is a far better practice to set up a `setup.py` file. See the source code of the Fabula setup file as an example:

http://code.ohloh.net/file?fid=pqI6bOZhHyHchm4NLxcwxsSxVdA&cid=S\_RYKZr4PdY

# Answer
> 1 votes
I don't know about `cxfreeze` but your problem might not be specific to it. In my case running under gdb provided a hint:

```
root@beczulka:/# gdb python3
[...]
(gdb) r -c 'import pygame;pygame.init()'
Starting program: /usr/bin/python3 -c 'import pygame;pygame.init()'
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
pygame 1.9.4.post1
Hello from the pygame community. https://www.pygame.org/contribute.html
[New Thread 0x7fffef819700 (LWP 32726)]
No protocol specified
No protocol specified
No protocol specified

Thread 1 "python3" received signal SIGSEGV, Segmentation fault.
0x00007ffff70427b4 in caca_free_display () from /usr/lib/x86_64-linux-gnu/libcaca.so.0
(gdb) bt
#0  0x00007ffff70427b4 in caca_free_display () from /usr/lib/x86_64-linux-gnu/libcaca.so.0
#1  0x00007ffff7043460 in __caca0_end () from /usr/lib/x86_64-linux-gnu/libcaca.so.0
#2  0x00007ffff7803c0c in ?? () from /usr/lib/x86_64-linux-gnu/libSDL-1.2.so.0
#3  0x00007ffff77e173e in SDL_VideoQuit () from /usr/lib/x86_64-linux-gnu/libSDL-1.2.so.0
#4  0x00007ffff77e1b03 in SDL_VideoInit () from /usr/lib/x86_64-linux-gnu/libSDL-1.2.so.0
#5  0x00007ffff77bad84 in SDL_InitSubSystem () from /usr/lib/x86_64-linux-gnu/libSDL-1.2.so.0
#6  0x00007ffff784d41a in ?? () from /usr/lib/python3/dist-packages/pygame/base.cpython-37m-x86_64-linux-gnu.so
#7  0x00007ffff784d4b0 in ?? () from /usr/lib/python3/dist-packages/pygame/base.cpython-37m-x86_64-linux-gnu.so
#8  0x00000000005d6e51 in _PyMethodDef_RawFastCallKeywords ()
#9  0x000000000054b620 in ?? ()
#10 0x0000000000552a01 in _PyEval_EvalFrameDefault ()
#11 0x000000000054bfa2 in _PyEval_EvalCodeWithName ()
#12 0x000000000052e2ff in PyRun_StringFlags ()
#13 0x000000000062fc5d in PyRun_SimpleStringFlags ()
#14 0x0000000000652a08 in ?? ()
#15 0x0000000000652b3e in _Py_UnixMain ()
#16 0x00007ffff7a2009b in __libc_start_main () from /lib/x86_64-linux-gnu/libc.so.6
#17 0x00000000005e026a in _start ()
(gdb)

```

The name `caca_free_display` made me realize I was trying to run without a display. Running in an X session, with a DISPLAY set made it work.

# Answer
> 0 votes
It should be an error related to C implementation. Please see if the following command works:

```
apt-get install -y xserver-xorg

```

# Answer
> -2 votes
import pygame I just did this and it works.

---
Tags: python, pygame
---


# Question
Title: Color glitch with tilemap.SetColor() in Unity
I've been experimenting with Tilemap to display tiles (with random colors) in script with SetColor() and other methods:

```
x = tilemap.WorldToCell(cur);

tilemap.SetTile(x, tile);
tilemap.SetTileFlags(x, TileFlags.None);
tilemap.SetColor(x, UtilityFunc.GetRandColor());

```

But as the number of tiles increased to a certain point, the colors just glitched out (this is a 200x400 hexagon, pointed-top grid):

Full code:

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

public class TEST : MonoBehaviour
{
    [SerializeField] Tilemap tilemap;
    [SerializeField] Tile tile;

    [Space(15)]
    [SerializeField] private float hexSize = 0.1f;

    [Space(15)]
    [SerializeField] private int hexLevel = 20;
    [SerializeField] private int perLevel = 20;

    private float hexWidth, hexHeight;
    [SerializeField] private float delay = 0.2f;

    Vector3Int x;

    private void Start()
    {
        StartCoroutine(CreatBoard());
    }

    IEnumerator CreatBoard()
    {
        tilemap.transform.localScale = new Vector3(hexSize, hexSize, 1f);
        hexHeight = hexSize; hexWidth = hexHeight/2f * Mathf.Sqrt(3f);

        bool goLeft = true; Vector2 original = new Vector2(0f, 0f);
        original += new Vector2(-hexWidth*perLevel/2f, hexLevel*hexHeight*0.75f/2f);

        //create board
        for (int i = 0; i < hexLevel; i++)
        {
            yield return new WaitForSeconds(delay);
            original = (goLeft) ? GetBottomLeftPos(original) : GetBottomRightPos(original); goLeft = !goLeft; Vector2 cur = original;
            for (int j = 0; j < perLevel; j++)
            {
                x = tilemap.WorldToCell(cur);

                tilemap.SetTile(x, tile);
                tilemap.SetTileFlags(x, TileFlags.None);
                tilemap.SetColor(x, UtilityFunc.GetRandColor());

                cur = GetRightPos(cur);
            }
        }
    }

    private Vector2 GetTopRightPos(Vector2 pos) { return new Vector2(pos.x + hexWidth/2, pos.y + hexHeight*0.75f); }
    private Vector2 GetTopLeftPos(Vector2 pos) { return new Vector2(pos.x - hexWidth/2, pos.y + hexHeight*0.75f); }

    private Vector2 GetLeftPos(Vector2 pos) { return new Vector2(pos.x - hexWidth, pos.y); }
    private Vector2 GetRightPos(Vector2 pos) { return new Vector2(pos.x + hexWidth, pos.y); }

    private Vector2 GetBottomRightPos(Vector2 pos) { return new Vector2(pos.x + hexWidth/2, pos.y - hexHeight*0.75f); }
    private Vector2 GetBottomLeftPos(Vector2 pos) { return new Vector2(pos.x - hexWidth/2, pos.y - hexHeight*0.75f); }
}

```

And random color function:

```
public static Color GetRandColor()
{
    return new Color(UnityEngine.Random.Range(0f, 1f),
        UnityEngine.Random.Range(0f, 1f),
        UnityEngine.Random.Range(0f, 1f),
    1f);
}

```

Why is the Tilemap system behaving like this?

Additional info: Video

# Answer
> 2 votes
\*Since the C++ source code of Unity is not public, what I am talking about here is **speculation**

From the video, the wrong part of the tile color changes together. There must be some kind of resource limit. To save memory, tilemap has some flyweight-like design. This means that instead of each tile having its own complete resource, there is something like a resource index. Such as sprites and colors.

Just like:

```
HashTable<int,Color> _colorTable;
void SetTileColor(Vector3Int position, Color color){
    int colorKey = GetColorKey(color);
    Tile tile = GetTile(position);
    tile.colorIndex = colorKey;
}
int GetColorKey(Color color){
    int colorKey = some_hash_strategy(color);
    if(_colorTable.CoutainsKey(colorKey)){
        return colorKey;
    }
    if(_colorTable.Count >= COLOR_NUM_MAX){
        //ooops! color run out, I'll just give you the last one, what ever
        colorKey = lastColorKey;
    }
    _colorTable[colorKey]=color;
    return colorKey;
}

```

Proof: Compare the memory addresses of the colors returned by `tilemap.GetColor`. The color passed in when `tilemap.SetColor` is called is all new object, but `tilemap.GetColor` returned some duplicate addresses.:-)

Fix: Limit the number of colors so that color resources do not run out.

```
private Color GetRandColor()
{
    return new Color(randFloat(), randFloat(), randFloat(), 1f);
}
private float randFloat()
{
    return Random.Range(0, 16) / 16f;
}

```

---
Tags: unity, c#, tilemap, tiles
---


# Question
Title: Placing rectangular outlines on a hexagonal grid
I'm prototyping a base-building game that uses a hex grid as the basic structure. Hex grids have benefits, but when humans want to build buildings or divide up space, they usually use square/rectangular shapes. How can I allow players to lay out spaces that look or feel right, while playing nicely on the hex grid?

One option I think I could use is to align rectangles with the centers of hexes. This allows for some hexes to clearly fall "inside" or "outside" the region, but also introduces three new hex/rect intersection types: an edge-to-edge half, a vertex-to-vertex half, and a corner.

Another option would simply be to make buildings and regions hex-based as well - they could be drawn in any arbitrary fashion on the grid and would have clean boundaries, but would probably feel strange to someone who just wants to build a square building.

Or is this just a sign that I should be using a square grid?

# Answer
> 1 votes
Don't know if this can help but you can design rectangle overlapping several hex.

---
Tags: game-design, hexagonal-grid
---


title: How to make animals Playable in Skyrim

text:
# Question
Title: How to make animals Playable in Skyrim
I have some experience with the Skyrim Creation Kit, and have made some small mods. I am really interested in creating new races, and have already made a mod that allows the player to create an old person, a child or a dremora. To accomplish this, I simply found their IDs in the editor and checked the "playable" box (and unchecked "child"). When I attempt this with some of the non-human races, such as wolf, horse or dragon, the game crashes as soon as I select that race in the character creation screen.

My question is this: Why does the game crash instantly, and is there a way to make animal/monster races playable fairly easily (I don't have much knowledge with scripting or creating meshes). Thanks.

# Answer
> 1 votes
Probably reason in different classes that handled them.

For example, humans, elves, dremora are humanoid races that have method `equipArmor`, but animals don't have such method. As the engine don't handle this situation, it will be a fatal error.

It is very hard to find exact reason so probably you will not be able to make it work. Or maybe you can change some of the "animal types" to a humanoid race? For example use same id, but change his type to human.

# Answer
> 1 votes
I think the animations are the reason. We have been modding Skyrim for 7+ years now, and the only real limitation we have is the old workflow for rigging with legacy tools (which we made new tools for) and the hardcoded batch of animations "vanilla" in the game. All new workarounds have to add new animations via SKSE by replacing vanilla ones.

The hkx files (Havoc animation files) of each actor depend on their skeleton, which is a connection of bones and joints in the mesh. If the animations and the body skeleton do not match, you run into severe issues.

I would expect that the game loads all the player / rigged on human animations, and that you try to force an animal mesh as "player body", where you run into these conflicts.

Race menu mods where new races become controllable usually just paste this new "body" over the old actor's player/humanoid animations as far as I know.

HOWEVER, it appears to me that this mod made it possible and found your fix: https://www.nexusmods.com/skyrim/mods/87316

Best of success!

---
Tags: skyrim-modding, modding
---


# Question
Title: Detect if a chain of tiles form an enclosed shape/contour
I'm looking to determine if in a tilemap if a set of tiles of same color in a chain (either right next to cardinally, or diagonal) is forming a closed shape and to detect the tiles inside the said shape.

To clarify further, a player will step on a tile to give it color, if the player walks around the tilemap forming a shape with the same color of tiles, I'll need to know if that chain is enclosed, and the tiles inside of it.

I have read the previous similar question to mine, but it focuses more on sides of the edge and filling the tiles inside the shape, whereas I want to detect if any enclosed shape is formed from a chain of same colored tiles.

# Answer
> 0 votes
Once the player steps on a new tile and colours it, examine the neighbourhood (8 tiles around it). Find the tiles that are of the player's colour, sort out early rejections (if there are 2 or fewer, you cannot possibly have anything enclosed yet), any tiles that are not of that colour are potential inside/outside candidates.

Create a copy of your tilemap, that only stores two types of tile - "player colour" tile and "any other" tile and try flood filling from any of the candidate tiles (there might be a heuristic for this) If after the flood fill, all candidate tiles got flood filled, you do not have an enclosed area (there's a leak). Otherwise you have now a set of tiles that got flood filled, that's one area, and another set of tiles that didn't get flood filled.

Good news is that one of these is exactly the set of the tiles inside of your shape, bad news I am not sure how to distinguish between the two. I know that size cannot be used as you could have enclosed a huge area taking up most of the field. Maybe somehow check the edges of the field and see whether they are flood filled or not, and whatever touches the edges is the "outside"?

I hope this will get you a bit of the way there.

---
Tags: algorithm
---


# Question
Title: Can you use common Datastructures in UE?
I just saw that you normally use Unreal engines own data structures when you code scripts.

Why is this are those better ? Can you also use the common c++ datastructures ( vector... ) or are you forced to use the UE ones ?

# Answer
> 2 votes
You can use other data structures, but there may be tradeoffs.

The most immediate difference is that the API is going to favor their structures. Even if the engine developers haven't tunes data structures for their engine, the API uses them "as is". You can use other structures, but then it's on you to do any conversions (for instance converting some other vector into a format that can be passed into an API rotation function). Even if the compiler optimizes this, there's still a mental complexity cost when you have extra steps to get data from on form to another.

Secondly, their data structures were built with the intent to use them with their framework. General purpose data structures are built for general use. By using their structures, you typically remove the need to question whether or not the structure you're using is implemented in a way that favors your usage.

If you can use other structures, you're potentially adding friction to your development process. Any time, energy & money that you expend replicating work already done by framework amounts to resources that could have been spent working on other the parts of your project. Ultimately only you can decide if that's a good exchange.

---
Tags: unreal
---


# Question
Title: How to change skeletal mesh with multiple .uc files in runtime
My plan for this is kind of complicated. I want to create a world where you can find things and place them around the map. But I don't want it to be too complicated. If my character had the ability to shoot cars, for example, I'd imagine the cars natural collision in the editor would still work and I wouldn’t have to specify it in the code. I also want to be able to make movie sequences using two code files running instantaneously, for example.

Apparently there is a timer function in UDK but it looks really complicated. I'm hoping not to use it. I'm not really a developer but with just being able to change the skeletal mesh using timers on the fly I can create an entire game out of it without much experience. What I'm also hoping to do though is by having these objects in the room. In other words: they're not abstracts. They essentially act like variables that change other things in the code.

**I want to figure out how to change skeletal mesh with a variable in the code with multiple .uc files extending the file where the skeletal mesh is changed in Unreal Engine 3.**

Basically, in Unreal Engine you can extend files.

This is in `UT_Weap_CustomWeapon_Content`

```
Begin Object name=PickupMesh
SkeletalMesh=SkeletalMesh'A.okay'
PhysicsAsset=PhysicsAsset'A.okay_Physics'
CollideActors=true
BlockActors=true
BlockRigidBody=true
End Object
Components.Add(PickupMesh)
CollisionComponent=PickupMesh
Mesh=PickupMesh

```

I want to overwrite this file when another object is added to the room. the problem is, I don't know how to update that object even within the same Unreal class or uc file.

I tried to copy and paste the object again but this causes the system to hang.

I've tried creating an object with the same vars as `PickupMesh` in `PickupFactory` and `UtWeapon` then I tried setting `PickupMesh=Replace` after creating an object with a different skeletal mesh.

```
Begin Object name=Replace
SkeletalMesh=SkeletalMesh'A.b'
PhysicsAsset=PhysicsAsset'A.b_Physics'
CollideActors=true
BlockActors=true
BlockRigidBody=true
End Object
Components.Add(Replace)
CollisionComponent=Replace
Mesh=Replace

PickupMesh=Replace

```

# Answer
Still don't know really. With Kactors and kismet you can easily change a kactor to a different static mesh and you can also spawn actors with a static mesh. these can be created without lighting using a fbx file in 3ds. these will show up pitch black if you try to import them normally. however spawning them through create actor in kismet will allow them to show up. Kismet is fairly easy but here are some things that tripped me up. ctrl left click allows you to move kismet objects. this is very helpful as without it kismet never really places your kismet objects where youd like them. another thing thats helpful is the instigator class. go to variables create object and youll see three ? marks attach that to any class marked instigator. instigator is used by unreal to mean the object that initiated the action. changing things to skeletal meshes using uc code is cumbersome. for the most part kismet works for a far amount of things.

However im sure there are things it can't do. Currently im working on getting 2 players to work with local multiplayer so the game can be played through Parsec. this has to be done through uc code.
> 0 votes

---
Tags: unreal, udk
---


# Question
Title: Detect if actors are inside another actor with custom shape
I have few actors with custom, non convex geometry (mesh) created using `PxRigidActorExt::createExclusiveShape` and a lot of actors with `PxSphereGeometry` geometry. Now I want to check if these spheres are colliding or are inside my custom geometries. I have created `PxSimulationEventCallback` with `onContact` method, but it only gives me info about collisions.

How can I get info if my spheres are inside my custom geometry?

Edit: It doesn't have to work in "real-time", it can be much slower.

# Answer
> 1 votes
I was able to achieve what I wanted.

To check if the sphere is inside my triangle mesh, I've used raycasting from the center point into (0.0f, 1.0f, 0.0f) direction (which can be random). The point is inside if the hit count is \> 0 and is odd.

Finding if a point is inside of a mesh (Point-in-polyhedron)

---
Tags: c++, collision-detection, physx
---


# Question
Title: What causes the error "Code not loaded" when editing a quest?
In my *quest object* (the yellow container for the quest logic), when I open it, on the right side, I see in my fragment window:

```
"Code not loaded"

```

What does it mean, and how do I fix it?

I'm using the Creation Kit 64bit and Skyrim Special Edition/Anniversary Edition 2021

# Answer
*This question&answer is a cross-post from one of my posts on Reddit.*

---

It means that the compiler built into CK cannot access the source scripts (psc) as a resource. Also, it might be possible that you are *unable to compile* new scripts which the game can use (pex files). Both of these issues are addressed below:

1. In your "**SkyrimSpecialEdition\Data\\"** directory, *delete* "**source**" and "**scripts**" folders (if existing).
*Careful! if you have these, you want to make backup folders so you can keep your contents and paste them back in later. Copy them somewhere else. They have been added by mods or by you before for a reason.*
2. In your "**SkyrimSpecialEdition\Data\\"** directory, unpack "**\Data\scripts.rar".**
3. In your "**SkyrimSpecialEdition\Data\\"** directory, check the new structure:
    1. it should be **"Data\Scripts\Source"** containing all **psc code files** and
    2. **"Data\Scripts"** which should contain all **pex code files**.
    3. Additionally, in your **"Data\Scripts\Source"** there should be a single file called **"TESV\_Papyrus\_Flags.flg".** It helps the compiler to see that these are actually the psc scripts to work with (papyrus source files). So if you have your papyrus source files somewhere else, this little friend has to join them.
    4. Now, we should check if your initialization is unmodified (as vanilla /downloaded) so that your compiler really looks into these paths we prepared above. Go back one level above in the file hierarchy to "**SkyrimSpecialEdition\\"** and look for the two files that tell Creation Kit where to look for the source scripts and where to place the compiled scripts.
        1. **creationkit.ini** (ini file format extensions might be hidden for you, cosmetics)
        2. **creationkitcustom.ini** (this one you can add yourself and it overwrites 1. automatically)
        3. **creationkitcustom.ini** (if you have it), else **creationkit.ini** should contain:
        **\[Papyrus\]**
        **sScriptSourceFolder = "Data\Scripts\Source"**
        **sScriptCompiledFolder = "Data\Scripts"**
        in the Papyrus section. This will make sure, the CK is looking at the right spot.
        4. Control it one last time:

| Folder | File type inside | declaration and appearance |
| --- | --- | --- |
| "Data\Scripts" | pex formate files | "compiled scripts" (binary) |
| "Data\Scripts\Source" | psc formate files | "source scripts" (readable logic) |

Run CK and check if your code is finally loaded! Best of luck! :)

This is the first challenge you have to overcome when you want to make mods, and perhaps the steepest step to get your own mod/conversion done, overall. This is the most challenging part of setting up your environment, so it potentially multiplies access to hobby devs if this is well documented. And overall, I hope more people can realize their ideas and see what great formate games are for art, creativity, challenge, and entertainment. Even writers for videos and games greatly profit from this experience.

---

Disclaimer:

1. *I do not take any responsibility for missing files or broken games, I just share the approach in best faith, with the goal of helping you to find the solution yourself, at your own risk.*
2. *I assume that you have not changed your ini file for Creation Kit, hence a vanilla installation.*
3. *You only have pex files if you copied them in manually, compiled them already, or pasted a mod inside. By vanilla setup, the game uses the pex files compressed in a BSA archive, not in the folders you see below, so no sweat if you do not have pex files at all yet. The compiler however needs the input folder and the psc as source files, and the output folder where to place the pex files.*
4. *If you changed your ini and look for different folders, then of course, you must place your files in these new locations.*
5. *Thank you to everyone working with me on Creation Kit contents, especially Elscrux, Woni, and Tascani.*
> 1 votes

---
Tags: editors, skyrim-modding
---


# Question
Title: How did early 2D first person RPGs render a "3D" maze?
Early first person RPGs like Wizardry, Bard's Tale, Dark Heart of Uukrul, appear to be 2D representations of a 3D maze. I don't think any of these early games were using polygons or raycasting. Here are a few examples:

How did games like this actually create a "3D" view of the dungeon? Are these tiles clever glues together, sprites that are scaled and stretched, or some other technique? I suspect that there were a few different ways this was done. For example, the Famicom/NES versions of Wizardry has really nice and detailed walls compared to SSI's gold box games which look off.

The one I'm really curious about is Phantasy Star. It's one of the few that animates movement I thought most console games of this era treated the screen as tiles so this effect looks borderline magical. I can't tell how it animates, but it clearly has some compromises (such as inaccurate views to the player's sides) which I think are a byproduct of this technique.

I've found some modern techniques for doing this type of thing, but I'm more interested in the historical techniques used in the 80s and early 90s.

# Answer
> 1 votes
(subsequent edit: I understand the games quoted in the OP had more limited movement options meaning this probably isn't the method used, but I'll leave it here as an example of games like Doom and Wolfstein. Also see @2br-2b's answer with video which explains it well)

I'm not sure of the name for it but I have implemented a javascript/html version of how (I understand) early Doom did it. It's effectively wrapping an image of a wall (whatever you want it to look like) onto calculated wall positions. You still need a 'ray' but only in 2D - one doing a 'steeleye span' across the player's view, firing the ray at say 1 degree increments panning left to right so maybe 120 degrees of horizontal view angle- whatever seems appropriate.

Process: Starting at left of observer's field of view, cast a 'ray' out in 2D. This is a position in the 3D space in front of observer, let's imagine at waist height, starting at the observer's position and moving forward until it hits something eg the side of a wall. Imagine firing a ray horizontally at your left-most peripheral vision.

At the point where it hits a wall: we know the position on the wall that it strikes, meaning we know which part of our wall image should be shown.

The 2D-\> 3D bit: Get a vertical sliver of the wall image from top to bottom and plonk that on the screen view, scaled to the distance from the observer. Ie from a 2D position we get all of the wall top to bottom for that spot, but just that one vertical sliver.

Now do the same for the the next position (ie not quite leftmost field of view).

Each time you get a whole vertical slice of the image of the wall, so there's no idea of "up and down". The limitations are something like..

* The height of the wall is usually constant unless some extra programming is added to take that into account (actually this would be pretty easy but might slow things down with extra calculation)
* The corners in walls are always vertical on the screen, not angled/tilted.
* So the player can't 'look up' - ie the horizontal angle of their view can't be anything other than .. um .. horizontal, although it'd be possible to 'jump' the wall corners are still vertical on screen.
* The walls are usually in a maze made of right-angled wall corners, because a diagonal wall would show up in 'steps'. This might not matter if the ray angle increments is small enough though.

To explain further: my HTML/JS version of this placed a DIV at the point where the ray strikes a wall. The screen x-position of the DIV is the ray angle I'm running at the moment (which angle out of the 120 degrees). The screen Y position is always cented vertically. The height is determined by how far away that wall strike was (=original height / distance away * a zoom factor).

The DIV is as wide as I've divided the ray angle increment up by and the height is determined by how far away the strike is.

The image to fill the Div is grabbed from a static wall image, the x position being how far along the wall the strike occurred, and scaled to fit the DIV.

I hope I've explained it well enough to understand!

I expect there are other methods and this might not be a definitive "this is how they all worked" but it's one way of doing it.

---
Tags: rpg
---


# Question
Title: Why do I get a "Validation Failed" error, and how do I fix it?
I'm trying to re-compile a mod to which I have made edits, but when I do so, I get this error

```
**"psc file validation failed. created backup in**
***/scripts/source/backup."***

```

Why do I get this error, and how do I fix it?

I'm using a mod organizer, and the CreationKit64bit 2021.

# Answer
*This question&answer is a cross-post of one of my posts on Reddit.*

This issue occurs if you have a mod organizer with a virtual folder system, like MO2 run Creation Kit through it. Being used to many mods in the loadout and also keeping mods and installation clean and handling tools, most users use mod manager tools. These are very powerful and helpful, but they also interfere with vanilla executions like the compiler. For mod authors that start working in 2021 and the future, this will be one of the first challenges to overcome. The other issue is the "code not loaded" fix, I posted here.

The compiler has (vanilla setup) only access to your temporarily loaded files (added temporarily by your mod manager) and your steam root directory `SkyrimSpecialEdition/Data/scripts`. When you now compile, you will usually gain a working and up-to-date compiled binary pex file, which the game is using to run. It will be stored in `(modmanagername)/overwrite/scripts` (if its a new mod) or `(modmanagername)/mods/modname/scripts` (if its an existing mod).Same applies for the "text code" source script file (psc), which contains your inputs on the quest fragments of the quest object. It will be stored in `(modmanagername)/overwrite/scripts/source` (if it's a new mod) or `(modmanagername)/mods/modname/scripts/source` (if it's an existing mod).

Now, when you load a mod the second time (existing mod), and you have made previous edits, the compiler will look at `Data/scripts/source` in the vanilla directory to load in the psc. For obvious reasons, this will fail. When you compile, you will get the warning:

```
**"psc file validation failed. created backup in**
***/scripts/source/backup."***

```

If you now look into `steam/.../SSE/Data/scripts/source`, **you will not find it**, because you place your files in the virtual folder system `(modmanagername)/mods/modname/scripts/source.` If you look there, however, **this place is empty, too**. You will essentially be stuck here with your first version of the pcs. When you load your quest next time, the quest fragment code will be reverted to what you made before, new edits are gone.

To fix it:

1. First, you need to manually create a "backup" folder where the compiler is trying to place the source script. add: \*(modmanagername)/mods/(modname/scripts/source/\****backup*** AND *(modmanagername)/overwrite/scripts/source/****backup****.*
2. Now, whenever you compile and get this warning, go and look for the psc file, remove the time stamp (pscname\_backup\_year\_date\_time -\> pscname.psc).
3. Take it and copy-paste it in your steam directory where the compiler is looking for it. (*SkyrimSpecialEdition/Data/scripts/source).*

---

Disclaimer:

1. I do not take any responsibility for missing files or broken games, I just share the approach in best faith, with the goal of helping you to find the solution yourself, at your own risk.
2. I assume that you have changed your ini file for Creation Kit 64bit, hence not a vanilla installation. Instead of\* ***"SkyrimSpecialEdition/Data/source/Scripts"*** *(SkyrimSpecialEdition) i have my psc in* ***"SkyrimSpecialEdition/Data/Scripts/Source"*** \*(LegendaryEdition Structure and convention on some Beyond Skyrim teams to avoid confusion. For a detailed description of how to do that little change in the CreationKit.ini or CreationKitCustom.ini (if you have made one), please refer to the other fix I linked above to see how you change the compilers input/ output folders via Creationkit.ini / CreationkkitCustom.ini.
3. You only have pex files if you copied them in manually, compiled them already, or pasted a mod inside. By vanilla setup, the game uses the pex files compressed in a BSA archive, not in the folders you see below, so no sweat if you do not have pex files at all yet. The compiler however needs the input folder and the psc as source files, and the output folder where to place the pex files.
4. If you changed your ini and look for different folders, then of course, you must place your files in these new locations.
5. Thank you to everyone working with me on Creation Kit contents, especially Elscrux, Woni, and Tascani. This is mostly a fix for starters, anyone who knows their way around CK is probably aware of this method by logic.
> 1 votes

---
Tags: editors, skyrim-modding
---


# Question
Title: Unity CharacterController steps on colliders with 0 Step Offset
I'm moving my `CharacterController` with the `Move()` method and for some reason it **still steps on colliders** even though its **Step Offset is 0**.

Here's how the game looks:

* Every objects' **root is at Y = 0**, so their colliders' **center is offsetted**.
* the floor is made up from tiles, with `QuadColliders`.
* there stairs have just a `BoxCollider`
* the player got a `CharacterController`

**Here are the components:**

CharacterController, stairs' collider, and the floor's collider, where the floor itself is scaled to (2, 2, 1):

I've checked the collisions with `OnControllerColliderHit()` and:

* After hitting play the **Y is 0**, as it should be.
* After moving a bit, without colliding with anything the **Y changes from 0 to 0.079**.
* Then if I start running towards a `BoxCollider`, after some time it **steps on it incrementally** under half a second.
    + *(The collider has a 0.8 height, so controller's Y changes to 0.8)*

I'm a bit lost, thanks in advance for all the help! :)

# Answer
> 2 votes
The official api of unity has a vague explanation of each parameter. After testing I got the relatively correct meaning of the parameters.

In this collision situation, as long as the hemisphere of the capsule is higher than the upper plane of the box, it will cross the box. Skinwidth will **expand** your capsule body, The capsule is **raised** due to the collision between the capsule and the ground, So it will cross the box.

So in fact, the height that the capsule body can cross is the **larger** of the value determined by step offset and physical properties.

The maximum height your capsule can cross is 0.88(capsule's radius + skin width)(\>0.8), What you describe is expected performance.

Suggestion:

Reduce the radius of the capsule to make it fit the character better. I think (0.5~0.6) will be fine.

edit:

1. Why use radius: When the collision occurs on a spherical surface, the force vector points to the center of the sphere, It will bring an upward component, causing the capsule to lift.
2. Why 0.5-0.6 would fit better the character: There is no mandatory standard. But the character's collision box should fit as close to the torso as possible, The example in your picture looks a bit too large, which leads to a series of problems that are not intuitive. Your question is one of them.

Sorry I'm not a native English speaker, some words are used incorrectly, have been re-edited, hope it helps.

---
Tags: unity, collision-detection, physics
---


# Question
Title: How can I make the sound files work again when using the Creation Kit for Special Edition?
When using the CreationKit 64bit for Skyrim Special Edition, the scenes and dialogues break and don't show up properly in game.

What happens and how do I fix it?

# Answer
> 1 votes
*This question&answer is a cross-post of one of my posts on Reddit.*

---

Since the introduction of CreationKit 64bit for Skyrim Special Edition, the in-built tool to generate sound files did no longer work within the response tab of your dialogue. Technically, you cannot directly take records during a CK session, and the result is that scenes and dialogues break and do not show up properly in-game.

This is what you can do:

1. place a folder with a dummy file. Use the Stock\\\_1.fuz from fuz roh doh download. `Data\Sound\Voice\(yourmodname.esp)\(yourvoicetypename)\ the ID of the voice line` you read in your response-*FuzRohDoh:* Fuz Ro D-oh - Silent Voice
2. get this dummy file automatically inserted by Fuz Roh Doh, will work for LE, SE and AE if you have the most recent SKSE. You could avoid AE by downgrading your AE to SE again. *Downpatcher:* Unofficial Skyrim Special Edition Downgrade Patcher (Note that you can apparently now use FuzRohDoh again for AE since 09.01.2022, I did not test it yet.)
3. record in legendary edition with the tool provided in Creation Kit.

It is suggested however to use 1 or 2 for dummy files and later replace them with high-quality mastered voice records. Usually, voice actors are happy to support you, and some editing can really help to normalize the files and remove unwanted hall effects and other noise. Alternatively, you can use the voice line generator tool, which is surprisingly well working. If you are interested, have a look at the detailed tutorial for using xVASynth here: Auto-Generate Voice Lines using xVASynth

References:

Disclaimer:

1. I do not take any responsibility for missing files or broken games, I just share the approach in best faith, with the goal of helping you to find the solution yourself, at your own risk.
2. Thank you to everyone working with me on Creation Kit contents, especially Elscrux, Thingy, and Jani. This is mostly a fix for starters, anyone who knows their way around CK is probably aware of this method by logic.

---
Tags: editors, skyrim-modding
---


# Question
Title: Unity VR IK Rig Accurate & Dynamic Proportions For Players
Hope all is well with you! I am messing around with a game idea in Unity. I am working on getting a good IK rig going on for the player since it will be an important part of the gameplay.

I currently have hands that work just like I want them to, updating live to my real-life hand location. With this, I can tell where my hand is actually located in relation to the IK rig. So essentially I have two components, **my controller**, and my **IK rig's arm/hand** updating its potion to my controller's position.

It acts as expected and the models overlap perfectly until I stretch out my arms fully. When I do this I can see the model's arms are not as long as my real-life arms, this creates a jarring disconnect.

How do I solve this? Obviously I can adjust the model to perfectly fit me, but I want the arms to be the correct length for all players, not just a model custom fit to me..

My first idea was to create some allowable stretching in the bicep or forearm. That way the IK rig's hand can always update to my controller's position exactly. **Is this viable? If so, how would that be achieved?**

This creates another question.. I am 6'. what about people who are shorter with shorter arms. If the player model has longer arms than the actual player, wouldn't the IK rig's arms awkwardly bend when the player's arms are simply down at their side? **Is there a solution to this?**

Lots of games seem to have these problems solved as far as I can tell. I don't know what they are doing under the hood, so some guidance on this would be great! Thank you so so much!!

# Answer
> 0 votes
The range of human proportions and ranges of motion is quite large, so you may need to incorporate some degree of per-user calibration.

This doesn't need to be an explicit step in the game setup/menus - you can do it implicitly. Early in the game (or in each session, if you can), have some task that requires fully extending the arms - like matching a pose or reaching for a needed control. When the player does that action, measure the reported offsets between the controllers or from one controller to the HMD. This gives you an estimate of the player's reach.

Now you can form a correction factor. Take the reach measurement you designed for and divide it by the measurement you've taken for the player. This gives you a ratio to convert from runtime player metrics to design-time metrics. You can then do one of two things:

1. Scale your character model/rig by the reciprocal of this ratio, so that the maximum reach of your rig now matches the maximum reach you measured for the player.

or
2. Scale your controller offsets from the HMD by this ratio before feeding them to the IK targets in each update - effectively scaling your player's arms until they match the standard character size metrics you designed for.

When the player boots up the app for the first time, this ratio is just 1.0 - your best starting guess for a size that might work. You can continually measure the player whenever they perform an arm-spread pose to update the estimate, and save it as a player preference so they default to a better fit at the start of the next session.

You may be able to slowly blend the scale factor during play as you refine your estimate, but be careful with this as it might increase the risk of simulation sickness. A safer bet is to apply your latest values when the player teleports or accesses a UI screen, so they don't perceive any lurch unrelated to their real-world movements.

The arms might look a little janky on the first reach, before you've calibrated this ratio, but once you get into the right ballpark it should look smooth from there on.

---
Tags: unity, virtual-reality, rigging, inverse-kinematics
---


title: How do you rotate a sprite in pygame?

text:
# Question
Title: How do you rotate a sprite in pygame?
I am making a game in Pygame and I want it so every time the sprite jumps it rotates mid-air and lands on its side. A lot like Geometry Dash jumping if you have ever played that. I have some code but it won't rotate.

This is my player class

```
class Player(pygame.sprite.Sprite):

    def __init__(self, color, x, y, width, height):
        super().__init__()
        self.color = color
        self.image = pygame.Surface([width, height])
        self.image.fill(color)
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

```

and this is my code to rotate

```
while running:
    if keys[pygame.K_SPACE]:
            pygame.transform.rotate(player.image, 45)
            isjump = True
            v = jump_v

```

# Answer
You have to take the returning value of rotate :

```
player.image = pygame.transform.rotate(player.image, 45)

```
> 1 votes

# Answer
Pygame.transform.rotate doesn't directly affect the image, instead it makes a copy of it so do

```
player.image = pygame.transform.rotate(player.image,45)

```
> 0 votes

---
Tags: python, pygame
---


title: "Video system not initialized" error

text:
# Question
Title: "Video system not initialized" error
I always get the error message "video system not initialized"

I don't get where I went wrong with the code below:

```
import pygame
pygame.init()

display_width = 800
display_height = 600

gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('4 pics 1 word: ASTRONOMY VERSION')

black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)

answered = False
satImg1 = pygame.image.load(r'C:\Users\andrea\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.7\img\satellite.png')

def satImg(x,y):
    gameDisplay.blit(satImg1,(x,y))

x = (display_width * 1.0)
y = (display_height * 1.5)

while not answered:
    if pygame.mixer.get_busy() != None:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                answered = True
    gameDisplay.fill(white)
    satImg1 = (x, y)
    pygame.quit()
    quit()

```

# Answer
> 1 votes
As Juanpa already implied in a comment, you get the error because you call the `quit()` function, which in turn makes the pygame module unusable, and your code should look like this:

```
...
while not answered:
    if pygame.mixer.get_busy() != None:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                answered = True
    gameDisplay.fill(white)
    satImg1 = (x, y)
pygame.quit()

```

# Answer
> 0 votes
you quit inside the loop instead of outside so it will immediately remove pygame

so move pygame.quit() and quit() outside the loop

---
Tags: pygame, debugging
---


# Question
Title: How would I calculate the velocity of a sphere with an impulse applied at the top?
I'm developing a rigid body physics engine and currently have accurately calculated the angular velocity of the sphere when impulsed. Unfortunately though, I'm not calculating the velocity correctly as I'm struggling to understand what should happen. Say for example the sphere has an impulse applied at the top, not only would it move forwards and downwards, but it would also rotate forwards and curve downwards, here's a diagram of what I'm explaining:

Basically, S represents the sphere, the blue arrow represents the angular velocity, and black is the velocity I think the ball will obtain after the impulse as the ball is hit off centre at the top with a velocity curving downwards and the red is the velocity without the curve (not accurate just a diagram) I *know* that if the sphere had an impulse applied directly on the centre of the sphere it wouldn't gain any angular velocity nor would it curve downwards, this hypothetically the scenario where gravity wouldn't take effect.

My question then is A) would the ball curve downwards along the black arrow as I described? or B) would it follow a linear path even if it did angularly rotate?

How would I go about calculating the velocity of the ball if this impulse was applied at the top as I've described?

# Answer
Think of this in terms of conservation of momentum / action and reaction. Let's work in an inertial frame that's co-moving with the ball, so that in this coordinate system, the ball is initially stationary at the origin.

We can imagine the impulse you applied as being the recoil from a tiny little gun mounted on the rim of the ball, shooting a bullet to the left. The exploding gunpowder applies a momentary impulse to the surface of the ball, pointing right, and to the bullet, pointing left.

The bullet flies away with some momentum in the leftward direction. Since we started with zero momentum in the system, the ball's resulting momentum vector must be exactly the negation of this, in order to conserve the total momentum of the system at zero. But since the bullet is flying directly to the left, it has no up or down component. That means the ball's momentum must *also* have no up or down component (there's no corresponding component in the bullet's momentum to neutralize it).

So, your intuition that the ball's movement should be angled downward is incorrect, at least for a ball floating in a frictionless vacuum. Any curving or diagonal deflection we observe in real-world examples would be due to a combination of factors:

* friction with the table the ball is rolling on
* friction with the air around the ball (the Magnus effect)
* the initial impulse not actually pointing directly to the left (eg. another ball or a cue stick colliding with the ball would apply an impulse with a component along the collision normal)

You also can't ever get a curving path from just one initial impulse. To get a curve, there must be something acting continuously on the ball throughout its travel, to continue deflecting the momentum downward (and correspondingly, something else in the system should get accelerated upward to balance out the reaction force). Without any external forces/impulses acting on a body, its center of mass must continue moving in a straight line of constant velocity.
> 0 votes

---
Tags: physics, sphere, body
---


title: Pygame Platform & Player collisions

text:
# Question
Title: Pygame Platform & Player collisions
I am trying to create a platform game where a player jumps between platforms horizontally (using a projectile curve). Currently, I have a class that blits platforms and a background, as well as the player. However, I cannot get it to detect when a platform and the player collide. I have used actual images and then done self.rect = self.image.get\_rect() for both the platform and the character. My question is have I done something wrong with my theory or have I just not coded it correctly.

# Answer
if the level is just an image then you should use masks mask tutorial

```
mask1 = pygame.mask.from_surface(surf1)
mask2 = pygame.mask.from_surface(surf2)
m = mask1.overlap(mask2,(level.x-player.x,level.y-player.y))

```
> 0 votes

---
Tags: platformer, pygame
---


title: Use of CPU vs. GPU on mobile devices

text:
# Question
Title: Use of CPU vs. GPU on mobile devices
I was always told that if a task can be parrarelized, I should put it on the GPU for better performance. Although this is defenetly true for computer GPUs, I was wondering if the mobile GPUs were so bad that it was actually more performant to use CPU whenever possible (p.s. I'm talikng about more common phones, not flagship gaming phone or anything fancy)

# Answer
> 0 votes
As far as I understand it, the main bottleneck on mobile GPUs these days is memory bandwidth. They're designed to work on a tile at a time, using a small but very fast on-chip cache to hold the data for just the current tile. Then once the tile is done, they write it out to slower shared memory. That write out or read back from shared memory tends to be the slowest part.

So, if the workload you have in mind can be divided into "small" chunks where all the working data you need fits in cache, and you only need to pull in or output a "small" amount of data to shared RAM at only "a few" well-defined phases of the calculation, you "could" see a substantial win from moving it to GPU.

But all those words in scare quotes depend sensitively on the particulars of your use case: what kinds of data, what workloads, what target hardware, how much / how frequently, etc., as well as how busy the CPU/GPU and the RAM connection are with everything else your game is doing. So we can't boil this down to a simple rule of thumb. The only way to know the answer to any performance question for sure is to build a test and profile it, to measure what real results you get.

---
Tags: performance, optimization, mobile, gpu, cpu
---


# Question
Title: Have both Cubemaps and TextureArray in a single texture register?
I want to have both Point Lights, aswell as Spot Lights. For the Point Lights I have a TextureCubeArray and for the Spot Lights I have a Texture2DArray. Is it possible to combine these two into a single Texture2DArray and treat the Point Light Shadow Maps as Cubemaps, and treat the SpotLight shadow maps as single textures?
I would like to bind only one array instead of multiple ones.

# Answer
To attempt to give this question some closure:

No, you cannot mix 2D and cubemap textures in a single array.

Doing so would not give you any benefit, since you would still need a branch in the code that reads from those textures: one needs to sample with a 2D UV coordinate, the other with a 3D direction vector.

So you might as well have two arrays, and sample from one array in the first branch, and the other array in the second branch. You could use the sign of your index variable to determine which branch to take, without needing an additional "cube or spot?" variable as input to the shader.

Or, quite likely more efficiently, you could render your lights in two passes: one pass for spotlights and a second for cubemaps, using a dedicated shader for each. Your shader stays simpler and branch-free, and you can apply different culling rules or other optimizations to each pass.
> 1 votes

# Answer
Use atlas for shadowmapss and combine cubemaps manually in shader. Also, this approach will allow to use variable shadow map resolution for close and distant lights.
> 0 votes

---
Tags: rendering, directx11
---


# Question
Title: Error using Asset Manager for loading files from Android temp directory (libgdx)
I'm creating a game for Android using libgdx and Google Firebase for storage. In my Loading screen I download a file from Google Firebase Storage and store it in a temp file. After the dowload ends with success, back in the main thread (Loading Screen) I load the downloaded file with my Asset Manager and then I call finishLoading(). When I do this I get the following error ( I get the error when executing finishLoading() ):

```
A/libc: Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x0 in tid 26492 (AssetManager), pid 26430 (MY.GAME.PACKAGE)

```

Code for loading and calling finishLoading in Loadings creen:

```
myAssetManager.manager.load("/data/user/0/MY.GAME.PACKAGE/cache/FILE_NAME.ogg", Sound.class);
myAssetManager.manager.finishLoading();

```

Any ideas of how can I solve this. Is it possible to use the Asset Manager for loading a temp file ?

Thank you !

# Answer
> 1 votes
I **solved** it. The problem was the FileHandleResolver asociated with the Asset Manager. The default is internal. What I did is create two Asset Managers inside my MyAssetManager class. One for absolute paths (downloaded temp resources) and other for internal. and it worked.

```
public class MyAssetManager {

public final AssetManager manager = new AssetManager();
public final AssetManager manager_storage = new AssetManager(new AbsoluteFileHandleResolver());
...
}

```

I used the absolute one for loading the downloaded asset.

myAssetManager.manager_storage.load("/data/user/0/MY.GAME.PACKAGE/cache/FILE_NAME.ogg", Sound.class);
myAssetManager.manager_storage.finishLoading();
```

---
Tags: libgdx, android, asset-management, storage, firebase
---