#archived-code-general

1 messages · Page 91 of 1

heady iris
#

e.g. for save points, or for the "weapon spec" that's used as a template for each weapon in your inventory

#

so, slightly higher stakes there 😛

#

as the old adage says, there are only two hard problems in computer science: cache invalidation, naming things, and off-by-one errors

late bloom
#

Fair, but if you're concerned about deletion, and re-adding. Wouldn't the deletion already cause the issue?

#

Or do you mean between patches, you delete something and re-add it, before ever deploying?

heady iris
#

Yeah.

hallow apex
#

Hi guys. Maybe someone can advise. Has anyone used dragonBones in their unity projects?

heady iris
#

Or if something is removed and then I change my mind down the line

late bloom
#

There's no way to overwrite a GUID is there?

#

Else you could write an editor script to overwrite it

steady moat
#

You can override a GUID, but you gonna make every reference in the project go missing.

heady iris
#

in this case, that wouldn't be a huge deal, since I'd have already deleted the dang asset

#

this would be strictly to put an asset back to the right state so that old saves can find it again

kind cloak
#

Hi guys, i dont know how to explain this, but i want the sphere (it's a particule) to appear as a glowing sphere, but in play it appear like the first pic...

heady iris
#

the skybox is eating it!

#

maybe you need to adjust where it is in the render queue

#

if it's transparent, but draws before the skybox, then it won't have touched the depth buffer

#

so the renderer will say "well, nothing's there! draw the sky!"

#

which render pipeline is this?

kind cloak
heady iris
#

the answer will probably depend on if this is the built-in RP or the URP

kind cloak
#

built-in !

heady iris
#

so this is from a particle system

kind cloak
#

yup

heady iris
#

so, you should have a Material assigned here

#

double click on that to inspect it

hexed pecan
#

Its with anything inheriting from UnityEngine.Object

#

Components, SO's, GameObjects, Textures, materials for example

granite nimbus
hexed pecan
#

Yeah

#

Didnt realize I necro'd an hour old conversation

granite nimbus
#

iirc only the == is overloaded, something like "is" doesn't work

heady iris
#

i've never thought about how is behaves with null values

#

or "null" values 😛

#

does null is Foo always produce false?

rain minnow
#

yes, it's anything derived from UnityEngine.Object . . .

hexed pecan
#

Here you were asking about what class it works on so thought I'd clarify that it is with any UE.Object

heady iris
#

not to be confused with System.Object

#

the ultimate base type

granite nimbus
heady iris
#

right

granite nimbus
#

I'm not sure if the overload spreads to the implicit
if (myObject) or if (!myObject), or to !=

heady iris
#

they also overload the implicit bool conversion

rain minnow
#

it does . . .

heady iris
#

hence why if(thing) works

#

i got confused by how that didn't work with other types at first

#

i figured that was just How C# Worked

granite nimbus
#

ok makes sense👍

dull yarrow
#

I have a itemClass :

{
    public itemType type;
}

public enum itemType {
    Consumable,
    Equipment,
    Gold,
}```

How can i add/make the item to have certain variables based on the type? 
Or do i have to create in this case 3 diferent items classes?
heady iris
#

indeed: each one has unique behavior

thin aurora
#

I forgot what these type of languages are called but c# is not one of them

heady iris
#

I guess you could also just give every item all of the functionality

#

and then just make it so that you can't eat your armor

#

and can't equip your health potion

dusk apex
dull yarrow
dusk apex
#

I'm assuming you want to simply use one super Scriptable Object and have variable behavior/parameters

rain minnow
#

items are always tricky bc you can go with inheritance or composition (component-based approach) . . .

thin aurora
#

Languages like Typescript allow you to dynamically define variables by combining generics and the never keyword to specify variables/parameters/functions that should never exist under certain conditions, but c# does not have that (unless you start using dynamic and expandoObject, but let's never do that).

dusk apex
# dull yarrow Can you talk more about that?

Normally, you'd create multiple instances of the Scriptable Object and reference them.. leaving which to be used up to whoever manages them instead of having them self manage/change or hold multiple identities.

dull yarrow
#

Got it, and for pecific items that have unique characteristics
I create lets say a specific function of the unique item
How do i "set it" on my chracter?
I cant make ifs for every unique item when the iem is equiped
Is there something like transfering functions?

ashen yoke
#

virtual

#
class Item
{
  public virtual void OnEquipped(){}
}

class Weapon : Item
{
  public override void OnEquipped() 
{
    base.OnEquipped();
    // custom weapon code
}
}
#
class EquipmentManager
{
    void Equip(Item item)
     {
    item.OnEquipped();
}
}  
#

but yeah you can "transfer functions"

#

that is called a delegate

#

or you can do something like

#
class ItemEquipHandler : ScriptableObject
{
    public virtual void OnEquipped(Item item){}
}

class WeaponEquipHandler : ItemEquipHandler 
{
  public override void OnEquipped(Item item) { //custom weapon code}
}

class Item : ScriptableObject
{
    public ItemEquipHandler onEquippedHandler;
}

class EquipmentManager
{
    void Equip(Item item)
    {
        if(item.onEquippedHandler)
           item.onEquippedHandler.OnEquipped(item);
    }
}
#

sorta strategy pattern

lethal plank
#

well idk why but it kinda messy

ashen yoke
#

what do you mean messy

#

enum is an integer

#

when you are using it normally by assigning integer values like 1,2,10 it is associating that int 2 with some compile time word

#

but you can use it differently

#

instead of assigning a whole int value you can assign specific bits in that enum

lethal plank
#

idk why

ashen yoke
#

int has 32 bits, and you are associating specific bit positions

heady iris
#

specifically, the enum needs to have values that are powers of 2

#

1, 2, 4, 8, 16, 32, ...

#

a power of 2 has a single "1" bit set somewhere, and every other bit is a "0"

ashen yoke
#

each bit starting from left going right is a power of 2 excluding first bit which is one

heady iris
#

2^0 is a power of two :p

lethal plank
#

oh

ashen yoke
#
[Flags]
enum Values
{
  None = 0,
  SomeVal = 0 << 1,
  SomeVal2 = 0 << 2,
}
heady iris
ashen yoke
#

or

[Flags]
enum Values
{
  None = 0,
  SomeVal = 1,
  SomeVal2 = 2,
  SomeVal2 = 4,
}
lethal plank
#

:0

ashen yoke
#

or

[Flags]
enum Values
{
  None = 0,
  SomeVal = 0x1,
  SomeVal2 = 0x2,
  SomeVal3 = 0x8,
  SomeVal4 = 0x10,
}
heady iris
ashen yoke
#

yes

#

the fact that each bit in the enum int is treated as true or false, means you can combine several values into one

heady iris
#

that one ought to be

[Flags]
enum Values
{
  None = 0,
  SomeVal = 1 << 0,
  SomeVal2 = 1 << 1,
  SomeVal3 = 1 << 2,
}
ashen yoke
#

this also means you cant use normal integers there

lethal plank
#

thanks guys

heady iris
#

yeah, since 1, 2, 3, 4, ... will have overlapping bits

#

and it'd be nonsense

#

so, if you have n bits, you can either store a combination of n values, or you can store one of 2^n values!

lethal plank
#

i never use this though

heady iris
#

combinatorics strikes again

ashen yoke
#

this is easy to understand if you learn how numbers are encoded
assume we have a 4 bit numerical value type

[0,0,0,0]
encode 1 into it
[0,0,0,1]
encode 2 into it 
[0,0,1,0]
encode 3
[0,0,1,1]
encode 12
[1,1,0,0]
^ 
[8,4,0,0] 8 + 4 = 12
lethal plank
#

xd

ashen yoke
#

thats why assigning 12 to a bitflag enum means flipping 2 bits

#

which can be desireable

[Flags]
enum Values
{
  None = 0,
  Wood = 4,
  Stone = 8,
  WoodAndStone = Wood | Stone,
}
heady iris
#

so close to Rock | Stone

ashen yoke
#

yes that is how binary number is encoded

#

integers at least, in c#

heady iris
#

a binary number system has only two digits

#

decimal has 10; hexadecimal has 16

#

base64 is 64!

lethal plank
#

and it will be negative number if reverse
i figure out them on my casio calculator XD

ashen yoke
#

no

#

negative numbers use the last bit

#

to indicate sign

heady iris
#

two's-complement my beloved

lethal plank
#

eh

ashen yoke
#

signed numbers

lethal plank
#

i reverse them on my calculator and it just become negative

digital fern
#

Hello there, I am struggling with RTS Controls... Is there someone who has the will to help me ?

ashen yoke
#

ask the question

lethal plank
#

ah

#

yes i was wrong

#

i tried on high number so..

rain minnow
# lethal plank thanks guys

yeah, you can combine them like so . . .

[Flags]
public enum DayOfWeek : short
{ 
    Sunday    = 1, 
    Monday    = 2, 
    Tuesday   = 4, 
    Wednesday = 8, 
    Thursday  = 16, 
    Friday    = 32, 
    Saturday  = 64,
    Weekday   = 2 | 4 | 8 | 16 | 32,
    Weekend   = 1 | 64
}```
ashen yoke
#

@lethal plank in essense since both bit flag approach and normal int approach are allowed on the enum just by the fact that its an int and all of that is allowed on an int, you need the [Flags] attribute merely to inform unity inspector that the enum is actually bit enum and not normal, the attribute itself doesnt do anything, it is only read by relevant code, like unity, to make decisions on how to treat it

lethal plank
#

0000 0000 0000 0000
0000 0000 0000 0001
is 1
1111 1111 1111 1111
1111 1111 1111 1110
is -1 checked

heady iris
#

correct, because you flipped the most significant bit

lethal plank
#

oh
1111 1111 1111 1111
1111 1111 1111 1110
is -2 xd

digital fern
#

Given that i have a scene with different entities (Units, Items, OtherSelectableThing).
The player can select 1+ entity at a time.
The player can select a "Unit", the UI display all the available commands (MoveTo,CastSpell,Attack)
The player choose "CastSpell" command, the UI display a new menu with different spells (Thunder,Heal,Fire)
The player choose "Thunder" spell, the mouse become a target.
The player click on a random location, the spell is casted.

What "Big picture" components would you use ?

At the moment, i have :

  • UnitController
  • PlayerController
  • MoveAbility
  • CastSpellAbility
  • SelectAbility
  • SelectionUI

My problem is, who the hell should be responsible of what in all this mess ? Should the PlayerController handle the inputs logic ? Should the SelectionUI be responsible to buffer a Command object that the Player should execute ? Should the Unit receive the inputs logic once it is selected ?

I've tried so much different since 7 days i'm exhausted

heady iris
#

I had a lot of "controller" components for sure

ashen yoke
heady iris
#

I had an "RTS Selection" component that handled the current selection. It had a list of selected units, plus an optional "active" unit

#

think how Blender handles selection

#

the "active" unit is the one that gets its statblock drawn and that has its abilities displayed

digital fern
#

So you would implement an "ICommandable" interface to each ability of the UnitController ?

heady iris
#

I just made everything a Unit

#

buildings are units that cannot receive move orders

#

for orders, units have a queue of Orders. They work on whatever's at the head of the queue. Orders can report if they're resolved, and if so, the unit instantly starts working on the next order

#

orders can create more orders

digital fern
#

Alright but, did you split the "MoveOrderAbility" into another controller or was it part of the UnitController ?

heady iris
#

e.g. you try to cast an ability, but you're out of range: the unit gets a "move into range" order, then the ability order re-queues itself

ashen yoke
heady iris
digital fern
#

Orders are not really my problem at the moment, it is more how i build theml

heady iris
#

in my system, the order directly controls what the unit does -- e.g. setting the nav agent's destination

digital fern
#

I have a StateMachine for the PlayerController

heady iris
#

in hindsight, it might have been better to just have the order suggest what to do to the Unit, which then actually moves and stuff

#

for abilities, I have a single abstract "Ability" class. It stores data about things like what kind of targets the ability can use (units, ground, self). each concrete ability derives from it

#

when the ability is triggered, it creates an IEnumerator, and the unit then checks that enumerator every frame to let it work (and maybe let it signal that the ability is over)

#

so, a manually-handled coroutine

digital fern
#

Yes, that' what i will do i agree

heady iris
#

I made almost everything an ability. Mining resources is an ability!

digital fern
#

But my problem is, how do i build my hellish command

ashen yoke
#

what is the problem? code related?

digital fern
#

Not code related, it's more like the "Design"

heady iris
#

It looks like I gave units orders directly from the selection system

digital fern
heady iris
#

that's an interesting choice, past me!

#

It has worked out pretty nicely. It was very easy to write an AI system that just gives Orders to units as needed

#

here's how I handled right clicking on the map

#

oh, that's missing Act

#

...you know, this doesn't give much more context, does it

#

lol

digital fern
#

Ok so i see i'm not clear enough with my problem

#

Let's say i have no problem with the move and act method

#

My question is, how do you know that you are ordering "Move" and not "ConsumeThisArtifactToInstantlyWinTheGameItem"

#

Or that you are ordering "CastSpell(SpellKey,TargetPos)"

steady moat
heady iris
#

for just right-clicking on stuff on the map, I ask each entity if it has a default "thing" it wants to do to whatever is being pointed at

#

for example, villager units know that they want to use the "Mine Resources" ability on a resource pile

#

soldiers know they want to use the "Stab Lots" ability on enemy units

ashen yoke
#

i still dont get it, you have an active context, i.e. primed spell cast, you click the spell cast cmd is sent to unit cmd queue, you dont have any specific overriding ctx active you send move cmd

heady iris
#

for left-clicking, that's up to the input manager knowing what state the player is in. if they're trying to cast a spell, then the input manager should know that

digital fern
#

Ok, let's say that "Soldiers" can "Stab","Kick" and "DanceAround" ennemies

#

And that you can control which action you do using "1","2,"3"

#

Who is responsible to listen for 1,2,3 key inputs

#

^ For this exact reason @steady moat

ashen yoke
#

you are asking what type of class should coordinate the actions of a unit?

heady iris
#

in my game, the input manager knows which unit you currently have selected

#

it checks if the spell can be casted, and, if so, swaps your cursor and gets ready to cast it on what you clicko n

steady moat
#

The player listen to input.
The Unit listen to whatever action you pass to them.

heady iris
#

If the player clicks on a valid target, the unit receives an Ability order

#

the unit then figures out what to do (maybe move in range, maybe just immediately start casting the ability)

#

equivalently, the AI can decide that it wants to cast a spell, and thus give the unit an Ability order

oblique badger
#

All I'm trying to do is access the Dictionary but its throwing a tantrum whenever I do, can someone help a lad out

heady iris
#

it's null

#

you showed a small screenshot, so I can't tell what line number the error is from

#

I'm guessing it's the debug.log line?

#

if so, AmountHolder is null. fix that.

rain minnow
oblique badger
heady iris
#

not null

#

it is currently null

rain minnow
ashen yoke
#

unit should be treated as ai agent, with a queue of commands
whatever you call the class doesnt matter much, but it should be an asynchronous fsm/bt
i.e. some orders are synchronous, you cant move while casting, but you can move while shooting, so you the agent can execute 2 non blocking orders in parallel, the orders themselves can contain the code to execute them asynchronously, i.e. coroutines with captured data
that agent code should govern all of the unit components

heady iris
#

critically, the unit should not care about user input at all

#

if it does, then writing AI will be a pain in the arse

ashen yoke
#

in case you will have the player controlling the unit, player controls it through generating commands through ui

#

in case of AI it does the same, but directly, from the point of view of the unit there is no difference

digital fern
#

Thanks for all your replies

heady iris
#

i also took advantage of that behavior to let orders generate more orders

#

that was very very useful for me

#

the Ability order doesn't need to handle the "walk close enough" logic

#

there's just a Walk Close Enough order

#

and a Face The Target order

rain minnow
ashen yoke
heady iris
#

this does sometimes cause problems when you have bad logic and it creates infinite orders

#

oops

digital fern
#

Alright so what i have in mind now :

  • InputsDispatcher : Listen for inputs, dispatch them to his registered "Receiver"
  • PlayerController: Is a "Receiver", he can store informations like "CurrentUnit", "CurrentOrder", "CurrentOrderPosition", and SendStoredCommandToUnit()
  • UnitController : Is a "Selectable", "Targetable" and an "Orderable", he can store and execute "Orders"
  • ItemController : Is a "Selectable" and a "Targetable", he can store informations about the item and what effects it does when used
  • Order : Is a base element to store a routine to execute, and a status
  • MoveToOrder : Is a concrete element to store a destination and a navigation routine to execute in order to get a COMPLETED/IMPOSSIBLE status
  • PlayerControllerUI : Is a "Displayable", it can display things on the UI given a "PlayerController" regarding its CurrentUnit, CurrentOrder and CurrentOrderPosition, it will display different Things
#

Approximately

ashen yoke
#

Queue should have its own controlling class solely responsible for maintaining the parallel queues

#

i just remembered that the unit bt should function on its own

#

it should process orders when they are available, but the unit is active all the time, and its better to have a bt which is fed orders

heady iris
exotic burrow
#

Hello can any one help me figure out what line 6 does

1-    public override IEnumerator Shoot()
2-    {
3-        // ...
4-        
5-        // What does this line do?
6-        yield return StartCoroutine(base.Shoot());
7-    }
digital fern
#

Am i heading toward a decent architecture or am i completely out of purpose

leaden ice
ashen yoke
#

what i mean is that the unit is responsible for executing orders

digital fern
#

Unit should be able to play "on its own"

#

If it had enough queued orders it would mimic gameplay

heady iris
#

I'd suggest implementing a basic enemy AI as you do this

#

it'll help to highlight any bad abstractions

digital fern
#

Alright so if the AI can't play easily given my design then i'm wrong implementing

heady iris
#

Right.

digital fern
#

Thanks for your replies @heady iris @ashen yoke @rain minnow @steady moat

ashen yoke
#

depends on how tight is your ai, in starcraft there is barely anything units are allowed to do outside of input, max they do is chase if they arent holding ground

#

in that case an fsm would work

digital fern
#

rofl, you know, the RTS part is not even the core gameplay

heady iris
#

my current AI prototype is mostly weight-based

digital fern
#

i'm just giving myself some really bad pain right now 🤣

heady iris
#

build town centers near resources and far from town centers

#

I shoved all of that math into bursted jobs

#

vroom

ember ore
#

Is there a way to run this :

 string url = "https://files.rcsb.org/download/" + file_name + ".pdb";
    using (UnityWebRequest www = UnityWebRequest.Get(url))
    {
        yield return www.Send();
        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            string savePath = string.Format("{0}/{1}.pdb", Application.persistentDataPath, file_name);        
            System.IO.File.WriteAllText(savePath, www.downloadHandler.text);
        }
    }

Synchronized? I hate async api, makes the code so unreadable

#

Or to make a synchronized web request somehow?

heady iris
#

well, you can do that if you want to freeze the game...

#

is this in a coroutine? that lets you write code that feels synchronous

#

you've got the yield return www.Send() already

ember ore
#

I just want it to freeze in this case. It doesnt matter, its not something very important

#

So what exactly needs to be changed? E.g. www.Send returns an object which does not have any methods to make it force to wait

ashen yoke
#

@ember ore post the full method

ember ore
#
        public IEnumerable DownloadText()
        {
            var url = "https://drive.google.com/file/d/1tkZHHgPXT00jqgJPS5FKLEJY5R5688Fk/view?usp=share_link";
            using (UnityWebRequest www = UnityWebRequest.Get(url))
            {
                yield return www.Send();
                if (www.isNetworkError || www.isHttpError)
                {
                    Debug.Log(www.error);
                }
                else
                {
                    string savePath = string.Format("{0}/{1}.pdb", Application.persistentDataPath, file_name);        
                    System.IO.File.WriteAllText(savePath, www.downloadHandler.text);
                }
            }
        }
ashen yoke
#

nah i dont see a way

#

you need to run updates for the coroutine to function

mystic rock
heady glade
hexed pecan
#

You can use layer based collisions

heady glade
hexed pecan
#

Tags wont prevent a collision/trigger message from happening

heady glade
heady iris
#

put the trigger colliders on different layers that are set to not interact

hexed pecan
#

You can also just return if the other collider has isTrigger enabled

#

But using layers is good when possible, more performant too

heady glade
urban marsh
#

Hello everyone !
I have a question about "how to do things correctly".
In my game, the player has spells that can "curse" an enemy, so some effects happen when they die.
To handle this, I have created a interface (CurseInterface), and spells can create a curse and add it to a list of curse in the Health script of the monster, which will handle calling a function of the curse (defined in the CurseInterface) when the monster dies. that way. I can have monsters explode when they die (because the curse added to the monster has a link to an explosion prefab, which it will instantiate on the position of the monster).
All this works, but I get warnings in the console :
since the curses need to be able to instantiate prefabs in the scene, they inherit MonoBehaviour. But since they're just basic scripts that I want to be able to add and remove to the monsters (some spells curse enemies only while they're in a zone, so they add the curse when entering and remove it on exit), I create them with "new" rather than instantiating a nearly-empty prefab that I would attach to the monster's instance.
Is there a better way to handle all this ?

mystic rock
heady iris
#

read the documentation.

mystic rock
heady iris
#

put the trigger on a child object and change its layer, then

#

if you have a Rigidbody on the parent object, then it should still receive the trigger events

#

or just slap a component on the child that handles them

hexed pecan
#

Yep you need a second object for the trigger

#

In order to use a different layer

heady iris
#

i use child objects with triggers very frequently

hexed pecan
#

I kinda have to a lot of the times

limpid crane
#
    {
        currentQuestionIndex = Random.Range(0, questions.Length);
        Question currentQuestion = questions[currentQuestionIndex];
        scoreText.text = "Score: " + scoreAmount;
        timer = 30.0f;

        questionText.text = currentQuestion.QuestionText;
        for (int i = 0; i < answerButtons.Length; i++)
        {
            answerButtons[i].GetComponentInChildren<Text>().text = currentQuestion.AnswerOptions[i];

            if (i == currentQuestion.CorrectAnswerIndex)
            {
                answerButtons[i].onClick.AddListener(CorrectAnswer);
            }
            else
            {
                answerButtons[i].onClick.AddListener(IncorrectAnswer);
            }
        }
    }``` can someone help. i have a list of questions each having 4 options and one correct answer. how do i make it so the correct answer isnt set to the same button every time
leaden ice
#

shuffle the answers

#

fisher-yates shuffle

limpid crane
#

i tried that but then it sets the answer incorrectly

#

new Question("This PC is recieving a large number of files from multiple sources, what type of attack is this?", new string[]{"DDoS", "DoS", "Phishing", "Ransomware"}, 0), the questions have a set correct answer

heady iris
#

you tried that?

#

oh, I see

#

well, you could read the right answer with the index

#

shuffle the answers

#

and then find the index that the right answer wound up in

limpid crane
#

hmmmm ill look into that

solemn raven
#

thank you so much for expaining, i fixed my code based on ur input ❤️

chrome mural
#

hey boys
at which point someome can say he's intermediate in programming?
cause everyone seems to know how to do it
and i dont

limpid crane
heady iris
#

at least with List<T>, you can just use IndexOf

#

assuming you don't have identical string answers

#

which would be very cruel

#

i presume you are not re-creating The Impossible Quiz 😛

limpid crane
#
        new Question("This PC is recieving a large number of files from multiple sources, what type of attack is this?", new string[]{"DDoS", "DoS", "Phishing", "Ransomware"}, 0),
        new Question("This PC is recieving a large number of files from one source, what type of attack is this?", new string[]{ "DoS", "DDoS", "Phishing", "Ransomware"}, 0),
        new Question("This PC has recieved a suspicious email and has sent a similar one to all contacts, what type of attack is this?", new string[]{"Phishing", "DoS", "DDoS", "Ransomware"}, 0),
        new Question("This PC has recieved a suspicious Popup that is demanding money in order to open a document, what type of attack is this?", new string[]{ "Ransomware", "DoS", "DDoS", "phishing"}, 0),
        new Question("after closer inspection you have determined this PC is being infected by a form of ransomware, How do you repair this?", new string[]{ "Run Antivirus", "Turn PC off", "Pay the fee", "Ignore it"}, 0),
        new Question("after closer inspection you have determined this PC is involved in a DoS attack,  How do you repair this?", new string[]{ "enable traffic filtering", "Turn PC off", "Run Antivirus", "Ignore it"}, 0),
        new Question("Jules has been sent a link to a commonly used website, however the name of the website is wrong in the hyperlink. What should he do?", new string[]{ "Delete the email", "Turn PC off", "Run Antivirus", "Click the link "}, 0),
    };``` these are my questions lol
heady iris
#

one suggestion

#

you should make a ScriptableObject that holds a question and its answer

#

it would look something like

#
using UnityEngine;
using System.Collections.Generic;

[CreateAssetMenu(menuName = "Question", fileName = "New Question")]
public class Question : ScriptableObject {
  public string question;
  public List<string> answers;
  public int correctAnswerIndex;
}
#

perhaps the correct answer could always be the first one, to simplify thigns

#

you could then just have a List<Question> and shove all of the question assets in there

heady iris
limpid crane
#

its for my final project aha, im making a game based around teaching a user cyber security

#

with that question object do i just copy paste all the questions in?

heady iris
#

each question object would store a single question and its answers

#

right-click in the project view -> Create -> Question (it ought to appear near the top)

#

you'd need to rewrite whatever used the old Question class, of course

limpid crane
#

yeah, ive sorted it now

dull yarrow
#

I have a list of all the items with ID order
When i am changing the inventory and applying stats. Should i use the data of the item, or get the data of the item from the list of all items by ID?

unborn flame
#

DialogueManager.GetInstance().EnterDialogueMode(inkJSON); this is my line 39 why is it giving me this error ?

winged mortar
#

Is your dialogue manager null?

unborn flame
#

im not sure

#

i do i check that

#

how

heady iris
#

re: this, I read up on custom converters for the Json.NET package, and I worked out how to completely get rid of the separate "data" struct

#

the internals are still a little scary to me, but now it just looks like this

#
[Serializable]
public class Progression {
    public UplinkSpec lastUplink;
    [JsonProperty(ItemConverterType = typeof(IdentifiableConverter))]
    public List<UplinkSpec> uplinks = new();
}
#

oops, I forgot to annotate the first one..

#

a save winds up looking like

#
{"lastUplink":null,"uplinks":[[1913176568,1205621800,3900081345,1309863492]]}
unborn flame
# winged mortar Is your dialogue manager null?
    {
        if (instance != null)
        {
            Debug.LogWarning("Found more than one dialog manager in the scene");
        }
        instance = this;
    }``` i have this code so it should not be null if it was i should be tolded by debug
heady iris
#

the converter parses the guid and then asks a static class to look that guid up

#

i wonder if i should just serialize a hex string of the guid at this point, since it's actually better than encoding the four uints...

winged mortar
unborn flame
mossy shard
#

how do i cut the collider of an object by a bit , but only from the top

#

and object still acting the same, just with a smaller collider from the top

winged mortar
#

Show code + console

unborn flame
unborn flame
mossy shard
#

what size

#

i don't have any size

agile tulip
mossy shard
#

i just got radius, height and center

#

and for the height i tried editing it but the mesh going trough the ground

winged mortar
#

But I am sure there's an edit bounds button

#

Looks like 3 squares with lines between them

mossy shard
#

this is what i do

#

float newSize = originalSize / 2f;
float yOffset = newSize;
Vector3 newCenter = originalCenter;
newCenter.y -= yOffset;

    playerCollider.center = newCenter;
    playerCollider.height = newSize;
#

tried the offset original-new, didnt work

unborn flame
#
    {
        if (playerDetected && Input.GetKeyDown(KeyCode.E))
        {
            DialogueManager.GetInstance().EnterDialogueMode(inkJSON);
        }
    }
    
}
unborn flame
#

is the console not the debug log?

winged mortar
#

I'm taking about this

#

Popular function to write something to the console for debugging purposes

mossy shard
#

i tried to edit it's overall offset

#

still going trough the ground

winged mortar
#

Do it in the editor and validate by placing your object in the scene manually

#

You should be able to see the collider outlines

#

I have a feeling that your piece of code puts the collider through the floor

mossy shard
#

it does that

#

i just need a way to fix that

#

and done

#

no need for editor

winged mortar
#

And as soon as two colliders have intersected, they'll just pass through

mossy shard
#

yes! that's exactly my problem

#

so how would i fix that

#

i don't know exactly how colliders work when changing them

winged mortar
#

The conpution of your offset is incorrect

mossy shard
#

i would need original-new, right?

winged mortar
#

Uhhh

#

Could you repost your code but this time with

#

!code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

winged mortar
#

It's awful to read on mobile without syntax highlighting

mossy shard
#

ok sir

winged mortar
#

If you don't add an offset your mesh goed through the floor right?

#

With about 25% ofbit going through by any chance?

#

Because I think you need to offset by new size / 2

winged mortar
#

What you could do, is place your character or whatever entity slightly above ground

#

So like 5f above ground or whatever

#

And see where it settles

#

Because I think now your character would hover above the ground by 25% of your height

#

So you have to do new size / 2 as offset

mossy shard
#

ok it works

#

but the character shakes when i move

winged mortar
#

That's probably a new issue

mossy shard
#

OH btw @winged mortar i need newSize/2 because the height-2 is -1 from bottom and -1 from top?

#

that's how it works?

winged mortar
#

Yes exactly!

#

That's why I wanted you to try and use the inspector

mossy shard
#

i didn't think it worked like scale

winged mortar
#

You get instant visual feedback

#

I mean you define a center point right

mossy shard
#

ye

winged mortar
#

And then when you use a 1,1,1 collider

#

It is basically 0.5,0.5,0.5 away from the centerpoint

mossy shard
#

oh alr

#

btw

#

could the shaking be because

#

i am always changing when pressing a button

#

i mean GetKeyDown gives true for the duration i have the key down or just once?

heady iris
#

well, look at the documentation

vagrant wyvern
#

so i tried out post processing for the first time and followed a tutorial but the vignette effect isn't working help

#

this is what i currently have on my main camera

heady iris
#

are you using the built-in render pipeline?

vagrant wyvern
#

what's a render pipeline

#

i'm very new to this sorry 😅

heady iris
#

when you created the object, what template did you use?

#

I'm guessing you're using the built-in one. It's labeled as "Core" in the templates, iirc

vagrant wyvern
#

yeah I think so

#

this thing right?

heady iris
#

right

#

okay, so that's the first important bit

#

if you were using anything else, you'd need to use a totally different system for post processing

#

I actually don't know a lot about the built-in RP's post processing

vagrant wyvern
#

oh wait thats a channel

#

also realized there was a beginner code channel whoosp

#

i shall go there

heady iris
#

nah, go to the post processing one

#

this is not a code problem

rotund burrow
#

is it possible to destroy gizmos like debug.drawLine ?

leaden ice
#

they only draw exactly when you tell them to draw

#

if you don't want to draw them, simply don't.

limpid crane
#
        for (int i = 0; i < questionsSO.Length; i++)
        {
            QuestionScriptableObject questionSO = questionsSO[i];
            string[] answerOptionsArray = questionSO.answers.ToArray();
            questions[i] = new Question(questionSO.question, answerOptionsArray, questionSO.correctAnswerIndex);
        }
``` am i doing something wrong?
#

i am only able to set one question object when i need 7

leaden ice
#

wdym by that?

#

"only being able to set one question"

limpid crane
#

i need 7 questions in the array however in the inspector i am only able to set one question

leaden ice
#

what's stopping you from setting more?

#

this code doesn't have much to do with the inspector btw

limpid crane
#

i realised

#

unless im doing something wrong

leaden ice
#

What is this picture showing?

#

1 question? Show the definition of QuestionScriptableObject.

#

Seems like you declared it as a string instead of an array or list of strings

limpid crane
#

public QuestionScriptableObject[] questionsSO;

leaden ice
#

this is in some other class

#

what script is this in>

limpid crane
#

am i supposed to declare the scriptable object in its own script?

leaden ice
#

Yes

limpid crane
#

then how do i access it in another script?

leaden ice
#

though the little snippets you've shared here are too small and scattered for me to make heads or tails of what you're doing

leaden ice
#

generally

heady iris
#

the scriptable object is a class. instances of that class can be stored as assets. you can reference those assets.

heady iris
#

and drag the assets in

limpid crane
#

when i declare that it says it cant be found?

leaden ice
#

Well if you haven't declared something called Question then yeah

#

basically we are all confused and guessing because you haven't shared your code

heady iris
#

you called it QuestionScriptableObject

leaden ice
#

or at least not enough code for us to make sense of what you're doing

limpid crane
heady iris
#

I'd rename it while you're at it

#

rename the script in Unity

#

so that it understands that the new script is actually just the old one with a new name

#

and then change the name of the class

scenic hinge
#

I haven’t seen any mention of this, but does Unity mind reflection? Or is it going to tank performance?

heady iris
#

there's nothing special about it in Unity, afaik

#

other than if you're using code stripping in IL2CPP builds

#

since it can be hard to tell that you're using a method if you only ever call it through reflection

#

it's gonna be less performant than just calling the method normally

rugged storm
#

Hay I have a set of tiles and want to draw a outline of a specific color around a area of them to denote the range of say attack distance or movement range but I have no clue how to even start could anyone point me in the right direction?, i can already detect and get a list of tiles that will make up the area i really just have no clue how to draw a line around them, moved this here from urp cuz i don't really know what section this would apply to

heady iris
#

so you don't want to just draw a grid pattern on top

#

you only want the edges

rugged storm
#

Only the edges

#

similar to what you see in games like xcom

heady iris
#

and it's tile-based, rather than being a smooth circle?

rugged storm
#

Yes, this image is a example

heady iris
#

the first thing that comes to mind: you have a set of tiles that you want to outline

#

each tile draws a line if that neighbor isn't in the set

#

(for all four neighbors)

#

oh right, and that's how you'd get the set of tiles, by searching :p

leaden ice
#

sorry noticed he said he already has the list

keen canyon
#

Hi! I'm having a bit of problems with my camera and I'm not sure why it's happening. Currently, my camera can see through the terrain at most angles even though it isn't actually under it. It's set to orthogonal and I've tried messing with the distance but it's almost always showing something under the terrain. I've also made a script to prevent the camera from going under the terrain but for some reason it always looks under it.

heady iris
#

orthographic, you mean?

keen canyon
#

oh yea

#

mb

leaden ice
heady iris
#

the near clip may be too far, yeah

leaden ice
#

but basically - for an orthogonal camera - you'd have to make sure the entire near plane of the camera isn't clipping through the terrain anywhere

heady iris
#

it can be non-intuitive, since we're so used to perspective views

rugged storm
#

okay, issue is how would I draw said line, I get the logic of each tile checking if it's neighbors are in the area and then drawing it bassed of that, just dont really know the method of drawing it.

keen canyon
#

I see

#

My near clipping plane is set to 0.2

heady iris
keen canyon
#

I'll try changing it, thank you!

heady iris
#

0.2 is pretty close

leaden ice
rugged storm
#

Oh did not know line renderers were a thing, thanks

heady iris
#

i'm not sure if using hundreds of line renderers would be a Good Idea (tm)

keen canyon
#

Yep. That worked. I set it to -40. Thank you!

leaden ice
#

hundreds probably not

heady iris
#

i didn't know you have a negative near clip

#

i guess it makes sense for an ortho camera

#

that should be roughly equivalent to pulling the camera 40 meters back

leaden ice
#

I didn't know that was possible either

limpid crane
#

alright so im now back to where i started but with a scriptable object. so my problem is ``` private void SetQuestion()
{
currentQuestionIndex = UnityEngine.Random.Range(0, questions.Length);
Question currentQuestion = questions[currentQuestionIndex];
scoreText.text = "Score: " + scoreAmount;
timer = 30.0f;

    questionText.text = currentQuestion.QuestionText;
    for (int i = 0; i < answerButtons.Length; i++)
    {
        answerButtons[i].GetComponentInChildren<Text>().text = currentQuestion.AnswerOptions[i];

        if (i == currentQuestion.CorrectAnswerIndex)
        {
            answerButtons[i].onClick.AddListener(CorrectAnswer);
        }
        else
        {
            answerButtons[i].onClick.AddListener(IncorrectAnswer);
        }
    }
}``` how do i shuffle the buttons but keep the answer to the correct text so for example if phishing ismoved to button 1 it is still correct
#

because at the moment my problem is the answer button will always be the same so index 0

rugged storm
#

question with line renderers, when I set a position, what is that relative to? is it world space or is it relative to the pivot point of the object the component is attacked to?

#

like say I have a 1x1 grid tile with a line renderer on it, how do I draw a line from the top left to the bottom left of that tile?

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

heady iris
#

i think it defaults to world space

limpid crane
heady iris
#

you'll probably want to turn that off. you can then figure out the right coordinates by just slapping an empty child on the tile and moving it around

#

look at the local position (the position shown in the inspector)

mossy shard
#

how do i see coliders in the scene view when running

#

no, i have nothing on gizmo to show me

#

no, in preferences i cannot find gizmo either

#

and no, i am not using an older version to not have those features and the proprieties of the collider don't have show feature

gray mural
#

Gizmo => make sure colliders are checked

rugged storm
heady iris
#

this is not a coding problem

dull yarrow
#

I have a list of all the items with ID order
When i am changing the inventory and applying stats. Should i use the data of the item, or get the data of the item from the list of all items by ID?

clever pier
#

hello

#

I wanna make that when a player enter the server call him player1 and when another one enter the server call him player2

#

but im having trouble

mystic rock
#

how to see if every gameobject in a gameobject array is disables

simple egret
mystic rock
#

yeah how do i do a for loop

simple egret
#

That's something you would Google

heady iris
mystic rock
#

did i do it right

        for(int i =0; i < EnemiesInWave.Length; i++)
        {
            if (!EnemiesInWave[i].activeSelf)
            {
                nextWave.SetActive(true);
            }
        }```
#

my goal is to make it so that if every gameobject in the array is disabled it enables the nextWave gameobjet

heady iris
#

this checks if one object is disabled

simple egret
#

Yeah that doesn't check if all of them are disabled

heady iris
#

perhaps you should declare a bool that's set to true, then set it to false if any object is not disabled

simple egret
#

It checks all yes, but not whether they're all off

leaden ice
simple egret
#

The inverse, all disabled to switch to next wave

heady iris
#

yeah

leaden ice
#

oh I see

#

fixed

heady iris
#

also, a useful tip

#

"true if all disabled" has the same meaning as "false if any are enabled"

#

my suggestion turns it into the second one

leaden ice
simple egret
#

Yeah it's better because it bails out as soon as the first element that doesn't match the condition is found

heady iris
#

there's some latin name for this

leaden ice
#

they will both bail out early

heady iris
#

i just found a bunch of new weird symbols on wikipedia

simple egret
#

Discord LaTeX support, when

wide terrace
heady iris
#

ah yep, that's it!

wide terrace
#

looks occult :/

heady iris
#

looks occult 🥳

simple egret
#

Yeah De Morgan's is used to invert boolean expressions for example

A • B => !A + !B
wide terrace
#

I never finished my comp sci degree, but my absolute favorite coursework was translating parts of the US constitution into propositional expressions for a "discrete mathmatics" course

#

It was just sort of pleasantly mind-bending

burnt echo
#

Hey, I'm looking for a quick and dirty solution to decoupling some of my code.

Short explanation, I have a panel that has some code in OnEnable to randomly generate some selectable objects on it. This panel is default inactive to be hidden, but can be pulled up from multiple sources. Instead of referencing this panel is all these places, I wanted to try activating it with an event Action. So that the panel is hidden and just listening for when it needs to display

keen bone
#

could someone tell me why this works only if im trying to connect from my pc to my pc but not from my phone to my pc(im trying to send sensor info to untiy)? https://pastebin.com/8WvnqTa5

heady iris
#

so you'd need to have the panel register itself with all of those event-holders

burnt echo
#

Obviously while it's inactive, it's not listening, so I tried putting the listener in a script on an empty parent, but now some of the OnEnable/OnDisable code is reacting funky...

keen bone
#

none

leaden ice
#

Also where is this code running?

#

and where's the code that sends the data?

heady iris
#

!code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

burnt echo
heady iris
#

right

keen bone
# leaden ice what error(s) do you get?

absolutely no errors it just doesn't want to connect from my phone to my pc. it works only on the local device.
code that im using on my pc:

import socket

client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('192.168.1.102', 2555)
client_socket.connect(server_address)
message = "hi"
client_socket.sendall(message.encode())

response = client_socket.recv(1024)```
burnt echo
#

Yea, I have it subscribed, but I think because it default state is inactive/disabled, I don't think that's working until it's been turned on once

heady iris
#

show your code; I can't guess what you're doing

leaden ice
burnt echo
#

Ok, sorry. Give me a few min. Thanks

keen bone
leaden ice
heady iris
#

that's right

#

it listens on any ip address the machine has

leaden ice
#

isn't it normally 127.0.0.1 ?

heady iris
#

that would only listen on localhost

keen bone
heady iris
#

so other machines on the network couldn't talk to it

leaden ice
keen bone
#

ofc

leaden ice
#

idk you could be on 5G ¯_(ツ)_/¯

keen bone
#

dude..

#

you blamed 5g?

#

lol

heady iris
#

on mobile, in general :p

#

this is not a unity problem, so i'm not sure you'll get a ton of help here

leaden ice
#

but yeah this seems like a general networking problem at this point

keen bone
#

its the code sense my python version of the server works fineeee

heady iris
#

i am confused

#

so your python server works fine, but you have some other server written in C# that is not fine?

burnt echo
leaden ice
#

Also why not this?
listener = new TcpListener(IPAddress.Any, 2555);

keen bone
keen bone
leaden ice
#

The Any field is equivalent to 0.0.0.0 in dotted-quad notation.

#

seems likely

simple egret
#

Maybe it's Unity that's blocking it? Have you tried running the server from a good old console app

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

keen bone
#

i dont remember if it worked ;-;

simple egret
#

Gotta check again, then

keen bone
#

well first ipadress.any doesnt work

#

1sec

#

im going to look for the other code

gray mural
simple egret
#

A network analyzer like Wireshark could also see if packets are being exchanged

mystic rock
#

ill change it to that rn

leaden ice
#

that's a lot more code and somewhat less efficient but that does work.

gray mural
mystic rock
leaden ice
#

System.Linq

burnt echo
# gray mural what's the problem here?

I'm trying to decouple some some code and remove some references. Here's my original question:

"Short explanation, I have a panel that has some code in OnEnable to randomly generate some selectable objects on it. This panel is default inactive to be hidden, but can be pulled up from multiple sources. Instead of referencing this panel is all these places, I wanted to try activating it with an event Action. So that the panel is hidden and just listening for when it needs to display"

mystic rock
#

ok thank

keen bone
dusk apex
#

Yeah requires linq else cs foreach(var e in EnemiesInWave) if(e.activeSelf) return; nextWave.SetActive(true);

burnt echo
gray mural
simple egret
#

Also I'm assuming you debugged a bit and that you know your code is executing

burnt echo
keen bone
gray mural
tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

heady iris
#

oops, already mentioned

simple egret
#

Events is a regular C# thing, it doesn't care that your object is disabled. Your event handler WILL run if it's subscribed whatever the state of the object is

heady iris
#

i walked across campus, so I'm getting caught up :p

gray mural
heady iris
#

i scrubbed through the chat a little too fast

simple egret
#

So you definitely can enable objects with an event, given that the target object has subbed to it, and that the event is getting invoked

burnt echo
heady iris
#

Awake won't run until the component is active

burnt echo
#

Ok, so there's the disconnect I'm missing

gray mural
simple egret
#

Also on line 17 you have some exotic syntax, is that intentional? Where you toggle that boolean

burnt echo
#

Lol, yes that was intentional. I saw it somewhere as a quick way to toggle. I'm assuming there's a better way?

simple egret
#

It works, so no problem here

heady iris
#

i'd just do gameObject.SetActive(!gameObject.selfActive) or something

burnt echo
burnt echo
gray mural
simple egret
#

That's exactly what they want to avoid, coupling

#

Hence the use of an event

#

Plus that piece of code is quite convoluted, FindObjectWithTag exists

gray mural
#

that's wrong

#

you cannot find non-active GameObject with FindObjectWithTag or Find

#

you can try though

simple egret
#

Well pretty sure FindObjectOfType GameObject is also wrong because GameObject isn't a component type

#

And even if it works, it's not pretty

gray mural
#

that's the best solution that works

heady iris
gray mural
#

unless you do not want to drag you gm

heady iris
#

if there's going to be more than one panel, then someone is gonna have to hold a reference to someone

#

it could be that the buttons know about the panel, or that the panel knows about the buttons

gray mural
simple egret
#

They have a GameManager with an event

#

But do whatever lol

gray mural
simple egret
#

what?

gray mural
burnt echo
#

I mean I understand some referencing is necessary, I was just trying to find a better way to do it since I know I'm going to have multiple different ways of opening that panel. The button in the pastebin is just the first one I've been working on. If the easiest and cleanest way to do it is just to make a direct reference to the panel, then that's what I'll do.

heady iris
#

that's what you should do.

burnt echo
#

I was just hoping to learn a better way is all I guess

heady iris
#

the button needs to know what it's targeting

#

that's a very reasonable way to tell the button what to target

#

use an event on the button if many things need to listen to a single button

burnt echo
#

That makes sense... Event when it's more listeners, not more sources

tropic quartz
#

I like making some simple script to manage a bunch of UI/canvas stuff and putting it on a parent object.
That way I can hide/unhide panels and stuff all I want since the script is on a diff object. (often on parent)

neon plank
#

Why calling NavMeshAgent.ResetPath produces an error if you call it when the agent is disabled or not placed in a NavMesh? How can I reset the path in those situations? I know that path doesn't work in those situations... but as soon the agent is enabled or placed in NavMesh again it will recalculate the path. Instead, I want it to forget the path.

knotty sun
neon plank
twin vector
#

I want to make reusable cast bar, what are the best practices for telling other components that casting has been finished, any help would be great 🍻

leaden ice
#

I.e. the thing that does the spellcasting fires off events and the UI listens to those events in order to display what it needs to

#

this allows the spellcasting thing to have zero knowledge of the UI stuff

twin vector
#

Thanks, I'll try with that, also no spellcasting, only reloading and hacking 👀 🍻

knotty sun
neon plank
#

Oh, will try

stone echo
#

If i have a script Dog on my gameobject which is a child of Animal, will calling gameobject.getComponent<Animal> give me the Dog script?

somber nacelle
#

yes

neon plank
stone echo
#

awesome ty

heady iris
#

the big brain move: GetComponent<Component>

#

i guess that could give you the Transform

mild wolf
#

Hello, using the new input system, how could I go about getting a reference to a device from one player input and manually making another player input use that device?

woeful slate
#

How should I handle having a hitbox for the character as well as having a generic hitbox for tool usage (sword, pickaxe, etc)?

#

I tried having two BoxCollider2D, but I don't think that works?

#

Does it require having a child script?

heady iris
#

If you need to distinguish between two colliders or two triggers, then yes

somber nacelle
#

i personally use a physics query (like overlapbox) for tools since they don't necessarily need to always be looking for collisions

heady iris
#

true

woeful slate
somber nacelle
#

well first, do you know what a physics query is?

languid pilot
#

What is the best way to make game saves for survival game? How map looks, player inventory, what player had build on map etc?

woeful slate
#

oh like, raycasting and such?

somber nacelle
#

yeah, that's exactly it

woeful slate
#

oh wait, why do tutorials suggest box collider rather than just doing overlap query

#

overlap query seems way easier

somber nacelle
#

a lot of tutorials are not good or show things the lazy/easy way.

woeful slate
#

although one question I'd have is for example in a sword swing, an enemy could walk into the animation after I do the overlap query

somber nacelle
#

there's a few things you could do, if you're actually using an animation for the sword swing I would create some animation events at key points in the swing, the events will all call the same method that uses the overlapbox or whatever query you decide to use, then you could either just immediately damage the enemies when they are first detected, or you could add them to a list/set (HashSet to prevent hitting the same enemy more than once) and at the end of the animation have another event that applies the damage and clears the list/set

#

there are also other ways you can handle it of course, but i generally find these to be a good balance of easy to set up but also fairly accurate without relying on collision messages

woeful slate
somber nacelle
#

one of the biggest drawbacks is that you won't actually be able to visualize where the physics query is though. so you'd have to either draw the gizmos yourself or use a debugging library for it. personally i use this one: https://github.com/vertxxyz/Vertx.Debugging

woeful slate
#

should also clear up the collision issues I was having earlier where i couldn't hit an enemy while attacking unless i moved between swings

woeful slate
somber nacelle
#

sure but it's harder to see if you actually got it right without actually visualizing it in some way

woeful slate
#

true

#

i'm relatively new to unity, I was working in ue5 before so I appreciate the help

#

i think part of my complexity is coming from the fact that I'm making a Character class and 3 subclasses for each character type (goblin, skele, human) and they have different logic

#

one thing I wish was cleaner was animations

#

I feel like my system is ... not great

#

i basically just have a "animation broadcast" system

#

and so then the skeleton, human, and goblin each have animations to match all of those (except skele who only has a few)

#

i have to send it to children, because otherwise the hair, and tool animators don't animate properly

somber nacelle
#

you may want to consider checking the docs pinned in #🏃┃animation and learn how to set up transitions and the like so you don't have to manually call Play with specific strings and can instead just pass data about what the object is doing to the animator and let it handle switching to the correct animation states. just my opinion though 🤷‍♂️

woeful slate
#

well it could, but it'd look v awful

#

so i followed this recommendation of just running my own

latent latch
heady iris
#

i like when everything is code

#

i don't use animations to make things rotate; i just calculate it in a script

dusk apex
# woeful slate https://youtu.be/nBkiSJ5z-hE

He seems to be doing exactly what Animator was created to resolve - not having to code or manage the transitions of your states (once set). Where Animation behavior is decoupled and we'd basically throw flags to attempt state changes. I'm not a fan of the UI and the Animator visually but this doesn't feel like the correct approach.

woeful slate
#

Like every single animation state needs a transition to "character_take_damage" in that case

somber nacelle
#

fun fact, you can have multiple layers in your animator

dusk apex
latent latch
#

It makes sense when using 3D models, but if you're using 2D sprites and skipping the transitional frames then just calling the animation is fine

woeful slate
dusk apex
#

Some folks want public access to everything, static everything and whatnot.. which are very efficient for specific tasks but these are technically boiler plates.

#

His hard-coded strings had a negative impression on me.

#

Changing stuff in Animator would require you change stuff in the script.

woeful slate
#

But there isn't anything in animator to change

dusk apex
#

Ideally, you'd want to write code once and not have to change it.

dusk apex
#

Then you'd have to go through all of your scripts and change every string name etc

woeful slate
#

Transitions don't make sense when every animation can lead to almost every other animation

dusk apex
#

For 2d, it'd be useful a bit as blends aren't necessary

woeful slate
#

You get n^n transitions

heady iris
#

especially when some animations can go to some animations, and there're enough that you really don't want to manually write every single transition by hand..

dusk apex
woeful slate
#

I would love something better

latent latch
#

Well, you're never going from a dig to an attack animation usually

#

it's dig, to neutral, to attack

woeful slate
#

If you queue up an attack during the dig

dusk apex
#

It simply feels like.. cs private int score; public int Score {/*Convoluted stuff*/}where you'd not use properties there if things were simple but it'd be redundant to have those procedures implemented by the caller.. this is so backwards UnityChanOops

#

Sometimes simple is better but his illustration was mostly (imo) an appeal towards ascetics or those who are struggling to use Animator the normal way.

woeful slate
#

My biggest struggle is that the superclass is dictating what animation the subclass should play and as such the super class needs an explicitly defined non changing set of animations

#

Cause all characters have health and can take damage but then they all have different damage animation sprite sheets

#

And sure you could make it some kind of dictionary that the child has to implement but you're still just calling animator.play

#

And then on top of that each character has different logic to go with each type of animation because a skeleton does more damage than a goblin or something

#

My setup definitely doesn't seem ideal

#

Maybe I should just make my character superclass an interface?

#

But I'm not necessarily sure what that would clean up

glossy basin
#

So.... I went to sleep for a while and closed unity, when I came back I found this 😄

woeful slate
#

ok I think I figured out what's causing me pain

#

my Human character object has a body sprite, a hair sprite, and a tool sprite

#

previously I had the body sprite on the parent so it was like

Human - Body Sprite
--- Hair - Hair Sprite
--- Tool - Tool Sprite

#

but it seems like it'd be easier if I moved body as a child

#

am refactoring everything right now, not sure if it makes sense, would appreciate y'alls thoughts

#
using UnityEngine;

interface IDamagableEntity
{
    // All entities have health
    int maxHealth { get; set; }
    int health
    {
        get
        {
            return health;
        }
        set
        {
            value = Mathf.Clamp(value, 0, maxHealth);

            if (value <= 0)
            {
                Die();
            }
        }
    }

    // Functions
    abstract void TakeDamage(int damage);
    abstract void Die();
}```
#
using System.Collections.Generic;
using UnityEngine;

interface ICharacter : IDamagableEntity
{
    // All characters can move
    bool canMove { get; set; }
    float moveSpeed { get; set; }

    // All characters have movement input
    Vector2 movementInput { get; set; }

    // Collision detection
    float collisionOffset { get; set; }
    ContactFilter2D movementFilter { get; set; }
    List<RaycastHit2D> castCollisions { get; set; }

    // All characters have a rigidbody
    Rigidbody2D rb { get; set; }

    // All characters have animator(s)
    List<Animator> animators { get; set; }

    // All characters have sprite renderer(s)
    List<SpriteRenderer> spriteRenderers { get; set; }
    void flipSpriteX(bool flip)
    {
        foreach (SpriteRenderer spriteRenderer in spriteRenderers)
        {
            spriteRenderer.flipX = flip;
        }
    }

}```
woeful slate
#

What's a better way to do this?

    public enum AnimationState
    {
        Attack,
        Axe,
        Carry,
...
        Watering
    }

    // Dictionary from AnimationState to string
    public IDictionary<int, string> animationNames = new Dictionary<int, string>();
    animationNames.Add(AnimationState.Attack, "attack");
    animationNames.Add(AnimationState.Axe, "axe");```
#

am trying to have it such I can use enums, but it seems kind unideal

#

Thinking I could have some kind of JSON file, but then its not type safe

latent latch
#

enums are fine, and you can break them into categories too if you want

#

pretty much the basis of a statemachine

woeful slate
#

just feels very roundabout

latent latch
#

Seems fine by me if you dont want to explicitly write the string when you swap states

lean sail
#

why do you need to link int to string for animations?

vagrant agate
#

change your animation names to match your enums

woeful slate
lean sail
#

yes but why do u need an enum/int associated with it and why in a dictionary

winged mortar
#

You can do enum.ToString()

#

And it'll give you the name, make sure the anims match that ;)

lean sail
#

if you're going to look it up with AnimationState.Attack, why not store the animation name as a const string?

woeful slate
lean sail
#

you're gonna have the same thing as an enum and then in a dictionary

#

but if u want it in 1 data structure instead then its fine i guess

woeful slate
#

I'll do enum.tostring ig

plucky karma
woeful slate
#

lol

#

back to dictionary

plucky karma
#

Let me re-read above. There may be another solution.

plucky karma
#

Are you using that to compare the enums.toString()?

woeful slate
#

all I want to do is animator.play(ENUM)

#

and then it converts to the right string

#

so i can avoid typos with my strings

latent latch
#

dictionary is love

plucky karma
#

It sounds like you can get away with using scriptable objects instead?

woeful slate
#

that all seems like overcomplicating it compared to just 20 constant string variables

#

the 20 consts just look ugly

latent latch
#

who care if it looks ugly

#

if it works it works

woeful slate
#

i care

plucky karma
#

I think you're over engineering this?

lean sail
#

the exact same functionality, and no dictionary lookups just for 20 extra strings. not even 20 extra lines, because ur enum will need each string anyways

plucky karma
#

Establish minimum requirement of your game first. Prove the concept. Demonstrate what makes your game fun and enjoyable with primitive geometry and simple animations.

#

All of the fancy stuff can sit right on top of that principle of rules you made.

#

What good of a game if it can't function over how good you optimized your enum to string collection?

woeful slate
#

right now I'm not making a game

#

I'm mainly just trying to learn unity, I'm familiar with unreal, fullstack, etc

lean sail
#

🤔 you mean c#? because this whole string business is not related to unity one bit

woeful slate
#

c# and unity's specific frameworks yes

plucky karma
#

You have some C++ background. Now that I see it your perspective.

#

You are overcomplicating the design.

#

Unreal and Unity have some similar concept that you can translate over, but unity takes thing less descriptive than unreal.

woeful slate
#

i went ahead and switched it over to constants

plucky karma
#

Instead of relying on enum, you can instead use scriptable object to help further customize your game. Start something small and grow from there.

quartz folio
woeful slate
#

another dumb question for y'all

lean sail
woeful slate
#

What would cause it to prevent me from creating a subclass?

#

I haven't had issue before, but feel like I'm missing something super basic pepe_sweat

quartz folio
#

... what is the error

woeful slate
#

The type or namespace name 'Character' could not be found (are you missing a using directive or an assembly reference?) [Assembly-CSharp]

quartz folio
#

What's in Character.cs then 👀

woeful slate
#
using UnityEngine;

abstract class Character : MonoBehaviour, IDamagableEntity
{
    // All characters have a rigidbody
    Rigidbody2D rb { get; set; }

    // All characters can move
    bool canMove { get; set; }
    float moveSpeed { get; set; }

    // All characters have movement input
    Vector2 movementInput { get; set; }

    // Collision detection
    float collisionOffset { get; set; }
    ContactFilter2D movementFilter { get; set; }
    List<RaycastHit2D> castCollisions { get; set; }

    bool tryMove(Vector2 direction)
    {
        if (direction != Vector2.zero && isAccessible(direction))
        {
            rb.MovePosition(rb.position + direction * moveSpeed * Time.fixedDeltaTime);
            return true;
        }
        return false;
    }

    bool isAccessible(Vector2 direction)
    {
        // Cast a ray in the direction of movement
        int numCollisions = rb.Cast(direction, movementFilter, castCollisions, collisionOffset);

        return numCollisions == 0;
    }

    // Health
    public int maxHealth { get; set; }
    public int health
    {
        get
        {
            return health;
        }
        set
        {
            value = Mathf.Clamp(value, 0, maxHealth);
        }
    }
}```
quartz folio
#

Bizarre. Does the error exist in Unity, and are all these files saved?

woeful slate
#

relaunching everything, once sec

#

ah that might contribute

#

ah yeah, vscode errors are super janky sometimes

#

importing system generics works

swift falcon
#

Hey, im struggling to do some logic if the string is same as it was last time the function was called

            oldText = null;
            var note = oldText += Notepad.GetText;
            mewText += note + "Added";

            if(newText == Same as oldText)
            {
                bool = true
            }

here is a very simple example, I cant get anything to work, any ideas? And yeah I do know about String.Equals

#

I'll keep trying, but if you have an idea please suggest it

neon fable
#

I'm making a attack on titan fan game and when you grapple onto a wall, I want the camera to slightly tilt towards the grapple point on the z axis so that the camera tilts when you swing around a object however I'm not sure what the best way to do this is. I tried making use of the LookAt function and limiting it only to its z axis but I get janky results when it comes to looking around since I think its using global rotation. What's the best way to achieve this?

heady iris
rugged storm
#

I'm trying to draw a boarder around the tiles in an area and I got this but if the if the true if statements aren't consecutive it leads to lines being connected to each other where they should not, any thoughts on how to fix? or what might be a better way to do this?

#

example of the problem (the diagonal lines and also the top most tile having a line across its bottom)

lyric panther
#

so i have some portals but i'd like to turn them off if they're occluded by geometry. I could use raycasts but i'm not sure where to cast from or where to cast at. i was thinking cast from each corner of the bounding box toward the camera but i'm not sure if that'd work?

lean sail
#

Spherecast might be more helpful

#

@lyric panther

woeful slate
#

I want to have animation events in the children that call functions in the parent, is that possible?

#

or do I need to make mini-helper scripts for each to enable that

dim skiff
#

So i've been trying to teleport my player and it's just not working, what am i doing wrong?

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

public class tpPlayerOnLevelLoad : MonoBehaviour
{
    private bool hasTeleported = false;

    // Update is called once per frame
    void Update()
    {
        if (!hasTeleported)
        {
            GameObject teleportLocation = GameObject.FindGameObjectWithTag("teleportLocation");

            if (teleportLocation != null)
            {
                Debug.Log("trying to tp");
                GameObject player = GameObject.FindGameObjectWithTag("Player");
                if (player != null)
                {
                    player.transform.position = teleportLocation.transform.position;
                    Debug.Log("teleported player");
                }
                else
                {
                    Debug.LogWarning("No object with the 'Player' tag found.");
                }

                Destroy(teleportLocation);
                Debug.Log("deleted the tp location");
                hasTeleported = true;
            }
            else
            {
                Debug.LogWarning("No object with the 'teleportLocation' tag found.");
            }
        }
    }
}
silk tinsel
#

Not sure if this question should go in here or in editor-extensions, but I have a custom icon on a script that is annoyingly huge in the scene window. Is there a way for me to have that script not show it's icon on top of GameObjects it is attached to in the scene window?

void basalt
#

Try disabling the cc before you teleport

#

and re-enable right after.

#

@dim skiffThis also doesn't need it's own class. You're going to screw yourself up by making every little thing into it's own class

dim skiff
#

i see, ok

void basalt
#

You should create a function for it, on your main character

dim skiff
#

it was a part of my roomManager script, that is always in my level, but it was breaking, i thought it was because it was trying to teleport on the same frame that the teleportLocation was insantiated, so tried to put this script on the room prefab so it starts after its loaded in yk

marsh hawk
#

how would I make a character point in a direction? All the sources I find don't involve looking toward a specific direction and are just about rotating.

dim skiff
random sandal
#

I am using I tutorial to do a inventory system so I can learn more coding and something I see pop up often are =>

Example: [SerializeField] private List<InventorySlot> inventorySlots;

public List<InventorySlot> InventorySlots => inventorySlots;
public int InventorySize => inventorySlots;

Can anyone explain what it does

rain minnow
rain minnow
random sandal
rain minnow
random sandal
#

Ok thanks for the help have a good day

#

Or night

solemn raven
#

hey, this is weird

public enum Type
    {
        A = 0,
        B = 1,
        C = 2
    }
public Type type = Type.A;

.... // later

Debug.Log((int)type); // 604 ?????????????????????
#

what 604 means ???

#

anyone alive ?

latent latch
#

What's the debug right after you assign it

solemn raven
#

fixed it , nvm , i was debugging a different variable

latent latch
#

^^

lyric panther
#

is there a way to call the camera to only render the depth texture, execute some code, then render the color channel?

#

is there a way of accessing unity's occlusion culling stuff to check if an object has been culled?

quaint escarp
#

Implicit cast from NativeList<T> to NativeArray<T> has been deprecated; Use '.AsArray()' method to do explicit cast instead.
Why?

lyric panther
#

I'm trying to do occlusion stuff where a portal turns off when you can't see it with the camera. i tried casting a ray to see if it's occluded but there were too many raycasts that it made a bigger impact performance then always having the portals on. does anyone have any ideas on how i'd do this?
an idea i had was to check the cameras depth texture to see if anything was occluding but that'd not quite work
because i'd only be able to check the render texture from last frame, and the occlusion might've changed since then
i'm quite stumped.

#

occlusion culling doesn't work either because i'm handeling the rendering of the portal myself

west lotus
#

Using the depth texture from last frame is quite all right. Occlusion info wont change so drastically from frame to frame. It’s good enough for nanite heh

lyric panther
#

is that what nanite uses?

#

the depth texture method would have a single frame of the portal being visable but not on which would break the illusion of the portal being an extention of the space instead of an actual portal

west lotus
#

That way it will be registered as visible a bit before the actual important part is

#

Sure you loose a frame or two of perf

#

But if your portal effect is that heavy consider optimising it

lyric panther
#

it's mostly just the camera rendering

#

until i figure this out i'm just using frustum culling + having small levels so every portal outside the level disabled

west lotus
#

You could use the culling group api

#

So that if the portal is out of main frustum disable portal camera

lyric panther
#

mm that's what i was thinking but i'm unsure how it works

#

I'm not sure if it's going to work because the portals have no mesh renderer

west lotus
lyric panther
#

I'll look into that, thanks

west lotus
#

You dont need a mesh renderer the culling group uses a bounding sphere to do the check and you receive a callback where you can do your custom logic

marsh hawk
#

I'm trying to make it so that the red rectangle will be clamped from 90 to -90 on the while looking at the mouse on the left side. However, the rectangle will only look to the right side. Switching the 90 and -90 only makes the rectangle look at 90 or -90. Does anyone know how I could solve this?

knotty cargo
#

Me and my friend are working on a game that is tempo-based.

Currently, I’m keeping tempo in a singleton, then having a Boolean value either be true or false based on if the current game time is on or off best.

This works in theory, but Unity has some variance in update times, so it’s a little wonky. Initially, I had a timeSinceBeat value that kept reference of the most recent beat, though if one got off sync, then all others would be basing off of the off sync beat, so it’d slowly fall out of time.

This was fixed by keeping total time and referencing that instead since I can know where the next beat should land.

The issue is, beats are always either too fast or too slow due to the way updates work. Right now, I’m checking if(currentTime >= timeOfNextBeat - some fudge value), but this results in beats that are either too fast or too slow. If I remove the fudge area, it’ll still result in beats that are too slow. I’ve attempted this in both Update and FixedUpdate, but neither are as precise as I need. What’s a good solution to this?

#

Ideally, I would check if(currentTime == timeOfNextBeat), but currentTime may never be that value since it will most likely skip that exact number within a single update

twin hull
heady glade
#

I'm trying to understand how to properly code edge tolerance to my 2D game. Any advice or tultorials that may help?

#

Also I didn't felt it at first but that optimization in the camera is god's bless upon plataformer gamedevs, I came back to my project 3 days after I added, played and felt great.

gray mural
#

Hello,
how to I call method TupleRange of this class in my another Unity Script ?

using UnityEngine;

public static class Helper
{
    private static float TupleRange(this (float min, float max) tuple) => Random.Range(tuple.min, tuple.max);
}
someTuple.TupleRange();
#

I guess I should write using Helper, but it does not work

#

is it problem with unity or lack of my c# knowledge?

gray mural
#

it was the most stupid question ever. thx @hexed pecan

hexed pecan
#

All good lol. I never thought of adding extension methods to tuples so I learnt something

gray mural
hexed pecan
#

Might improve readability IMO

#

But I get it tuples are fun to use

stone gale
#

Input system, Invoke Unity Events, happened to trigger on both when i press left mouse button and when i lift my finger from the mouse.

urban marsh
#

Hello everyone !
I am currently designing a spell called "Rain of Arrows" for my 2D game. it's what you would expect from the spell :
the player aims its mouse with a circle previewing where the spell will happen, then clicks, and arrows rain on the circle-area.
I want the arrows to fall randomly in the area, and I would like for each pixel to have the same chance to receive an arrow hit, so the spell is useful against hordes of enemies in a wide zone.
I am currently thinking about HOW to randomly determine where the arrows should fall, and I was originally thinking about determining the position like this :
Vector2 arrowOffset = Quaternion.Euler(0,0, Random.Range(0, 360)) * Vector2.up * circleRadius;
with arrowOffset which would be added to the position of an invisible prefab created where the player clicks their mouse (the center of the circle).
There is a problem with thie method : there will be more arrows in the center, and fewer on the exterior.
I made a drawing :
There will be as many arrows in the Red as there will be in the orange (and as there will be in the yellow).
Do you guys have an idea on how to have the random more spread out, while keeping it in a circle (so no simple Vector2(Random.Range(0, sideLength), Random.Range(0, sideLength)) ???

stone gale
#

Input system, Invoke Unity Events, happened to trigger on both when i press left mouse button and when i lift my finger from the mouse.
How to make it only work when i only press it?

mossy snow
urban marsh
#

I feel like "rejecting the point if it's not in the circle" in a complicated check for nothing. Especially as I want my "rain of arrows" to create 50-100 projectiles.

#

but maybe it's not, with a simple sqrMagnitude

latent latch
#

Maybe have two different circles, the smaller one would base their arrows more in the area that you want

#

the larger one would cover all of it but with the chance of it hitting the middle as well

#

Or do three circles like your images and divide the arrows evenly

#

oh, or are you asking you want them completely spread out?

#

then you can use this

urban marsh
#

oh wow, I didn't know this existed ! 😄

latent latch
#

There's no 3D version of it sadly but I've written something similar for it if you need that instead

#

Oh, there is also a 3D sphere overlap too

gray mural
#

it should be better though

ruby fulcrum
gray mural
#

does somebody know how do I serialize struct from another struct without refering to this class?

private Helper.Tuple myTuple;

// how to do this?
private Tuple myTuple;
simple egret
#

Take it out of the type it's enclosed in

urban marsh
#

This worked :

do {
    arrowOffset = new Vector2(Random.Range(-rainCircleRadius, rainCircleRadius), Random.Range(-rainCircleRadius, rainCircleRadius));
} while (arrowOffset.sqrMagnitude > rainCircleRadius);```
But I went for the simpler 
```Vector2 arrowOffset = Random.insideUnitCircle * rainCircleRadius;``` and deciding to let Unity what my random would be 😄
simple egret
gray mural
simple egret
#

Yes

#

I don't get the issue you're having though, then

#

Can you post an example of how these types are structured

gray mural
# simple egret Can you post an example of how these types are structured
using System;

namespace Helper
{
    public static class Helper
    {
        [Serializable]
        public struct Tuple
        {
            public float min;
            public float max;

            public Tuple(float min, float max)
            {
                this.min = min;
                this.max = max;
            }
        }

        public static float TupleRange((float min, float max) tuple) => UnityEngine.Random.Range(tuple.min, tuple.max);
    }
}
#

I will be changed soon, but for now I can access it just like:

private Helper.Tuple tuple;
urban marsh
simple egret
gray mural
latent latch
lucid valley
#

Thats all the engine Unity C# code

#

If it's in the C++ side then you're out of luck

#

Editor -> Mono is where the main stuff for the editor is

urban marsh
urban marsh
heady glade
urban marsh
#

eh, too bad, I'll use the function, and not know whether it's the random type I want, but as long as it works and does not lag, I4m good.

lucid valley
#

yeah thats the only stuff for Random

#

rest will be C++

urban marsh
#

😢

latent latch
#

Some talk about it

#

and how to make it even more random

#

Ah, this is with a minimum radius if you want that

young wigeon
#

I'm trying to clamp velocity for the x axis of the player using this:

    void FixedUpdate()
    {
        if (rb.velocity.magnitude > maxspeed)
        {
            rb.velocity = Vector2.ClampMagnitude(rb.velocity, maxspeed);
        }
    }

but because of this the character is unable to fall fast on the y axis because it clamps both the x and y

#

how do I clamp just the x axis?

ruby fulcrum
#

oh wait nvm its clamp magnitude

#

then that might not work

#

record the previous y value and apply it?

young wigeon
#

my movement system right now is using AddForce to make it more floaty and make it have to accelerate

ruby fulcrum
#

you can still use rb.velocity =

#

to limit the speed

#

addforce for speed limiting wouldnt work

#

rb.velocity = new Vector3(rb.velocity.x, 0, rb.velocity.z);

young wigeon
#

but wouldn't that make it so that my character would float?

mossy snow
#
var vel = rb.velocity;
var clamped = Vector2.ClampMagnitude(vel, maxspeed);
clamped.y = vel.y
rb.velocity = clamped;
ruby fulcrum
#

no

mossy snow
#

although you might want to clamp just x, your code will clamp overall magnitude which is probably not what you want

young wigeon
#

yeah

young wigeon
ruby fulcrum