#💻┃code-beginner
1 messages · Page 745 of 1
i better get used to GetContacts then. thanks for the advise. i'll let the below get help now
with the slider
how can I set a function that take a float or int , can I call it everytime I update the slider ? I forget how to do it
Choose the function from the "Dynamic" section at the top of the function list
fix this as digi said
Since it says 0 there right now it will always feed in 0 as the parameter
hum
This worked nearly perfectly, but I think I want a SpringJoint, rather than a HingeJoint. It makes the object move in 3D rather than on a single axis. Thanks for the tip.
Now I'm deep in Spring Land, trying to figure out why this thing is CRAZY
The HingeJoint was a lot more stable, and tended to settle in the middle of the screen where the invisible grabber is. But the spring joint almost wants to remain constantly at motion.
there is a dedicated #🏃┃animation room you can talk to
Hi! I'm trying to make a camera pan to the right when I click a certain button
have you done the Essentials and Junior Programmer Pathways on the learning site?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hello. When moving in a specific direction and checking distance between object position and destination position to snap, how to not fly over the object?
Theoretical example:
bool isMoving;
float speed = 10;
Vector3 finalPosition;
private void Update()
{
if (!isMoving)
return;
Vector3 direction = GetDirectionToPosition(finalPosition);
transform.position += direction * speed * Time.deltaTime;
if (Vector3.Distance(transform.position, finalPosition) <= 0.1f)
{
transform.position = finalPosition;
isMoving = false;
}
}
In the example above we can fly over the destination if our fps is low without snapping. Can someone help me with a good approach here?
I'm sorry
ACK
Oh I haven't :0 Is that good for me to learn from?
nevermind me. i thought i was in general chat
yes, it is the best start
consider using something like MoveTowards so you don't overshoot your destination
Oic, thanks! Where can I find it?
follow the link in the bot message i posted up at the start there
Ok thanks, wish me luck 👍
I can't really move towards, because move is kind of random. So i choose an angle, calculate the direction, and then check for closest snap position.
So I have been trying to make a spawn system like Left 4 Dead and I'm getting errors constantly (I just recently started using statics and I didn't really understand the concept except it is accessible from everywhere)
Here are my codes
https://paste.mod.gg/nxiexdygtlkl/0
https://paste.mod.gg/nxiexdygtlkl/1
A tool for sharing your source code with the world!
A tool for sharing your source code with the world!
I never got any help on this
so I'm bumping it with some clarification
the reason the material's on a quad is because of the particles attached to it
its a prefab
so how can I orient it to face away from a surface it's on
Or sometimes I have a specific destination, but adding some smooth movement (like wiggling for example), that move towards cannot provide.
you can use the normals to get the direction facing "away"
and how would I do that
I'm 100% doing something wrong here but idk what it is
it always faces towards positive Z
Hi, is there a way to avoid Dictionary or Hashset lookup with State machines?
It seems pointless in state machines where all transitions from one state to another are pre-defined. Technically no lookup is needed, each state already knows the other states it goes to before program runs.
But how would that work then? I want to avoid reference nightmare on Awake() but also avoid runtime lookup.
// processed by state controller, Dictionary/Hashset lookup
public int nextStateHashedValue() {
if (...)
return hashOtherState1;
return this.hashedState;
// in the Controller, myStates[this returned value]
}
// return the new state directly (requires pre existing reference?)
public State nextState() {
if (...)
return ??????; // state member variable that has to be assigned in Awake()?
return this state, but the instance, somehow???;
}
I've seen people do like, a bunch of addTransition(stateToSwitchTo, Func<bool> condition) on Awake() but I prefer to write the state logic by hand. So I have this dilemma.
⭐ TLDR;
if (nextState != 0)
currentState = myDictionaryOfStates[nextState];
// etc```
```State nextState = currentState.getNextState();
if(nextState != currentState) // or some kind of integer comparison whatever etc.
currentState = nextState; // NO DICTIONARY OR HASHSET LOOKUP
How to achieve 2nd behaviour where no lookup is needed? Without reference nightmare of instances in Awake?
ok maybe I do need to figure out how decals work cos there's another issue I just ran into when shooting a physics object
The important part is your direction, and you dont tell anywhere, what you pass in for direction 😄
yeah but idk how to make it figure out that direction
I'm not well-versed enough in this stuff yet
are you using raycasts?
yes
and what does that raycast?
what
Not sure what you mean here? You want direct reference for every state to their next and previous state?
I advice you google those types you are using like raycast and raycasthit and see, what the docs tell you about it. You shoot a ray, it hits something, what info does that hit point give you
well I got the raycasthit thing set up...
that's over in this function
yes, and you need the info of that point to create your impact graphics. And you want to align it with its vertices which is what correct setup normals do. so try to use the normal on the hit position
I want to avoid the lookup. So yeah, the nextStateToSwitchTo() would have to return an instance of a state, rather than returning an integer or string that's used to lookup in the Dictionary or Hashset.
I also want to avoid doing this in Awake.
myStateInstance1.stateToSwitch2 = myStateInstance7;```
But there's no way right? 
it's already normalized though?
two thoughts. First, I am not sure you can really reference array items by reference while creating them, so you would have to work with scriptableobjects or whatever do get references to work with. Why do you even want to avoid the state lookup? Are you looking up your state multiple times a ms?
normalized? You are mixing up terms here. The hits normal does return a direction vector pointing away from the surface. Normalize is something different
No, I think the most frequent would be like 4 times a second.
I already gained some FPS and stability by switching to int lookup over string Keys
I am not sure, this is the best setup then. But if you want to stick to your dict, you might have to live with the lookup and manually setting them either via integer/string or in awake
Yes thanks for help. I'll just leave it that way, it's not worth ruining the code. I hoped there was another way
Unless its breaking your performance, I would live with it. maybe someone else has a better idea
The usual knowledgeable homies are having a blast in unity-talk i think 
where does this conversation start? bit hard to follow, maybe i can take a look
oh nvm, my discord just didnt load properly while scrolling up 😄
You are dropping fps over a simple dictionary lookup? How many lookups per frame are you doing?
you could probably do hundreds of thousands of lookups per frame without your fps dropping below 30
I've got 380 FPS just want more
at that point the editor is limiting your fps
you are doing whats called premature optimization
I can prob get more in build
you got any more hints? I've been going at it and getting nowhere
Yeah i am. I'm writing "the final code"
I'm on like version 40-50 of my scripts so... Yeah
I'm cutting out everythign I can, optimizing evrything I can
let me make this clear, nobody is EVER gonna write the final code 😄
But they dooooo though
Maybe not modern unoptimized poopoo
Older games run like a Toyota bro
🥺
real reason is, i test my game on a cheaper computer. so
There I'm only getting 180 FPS, so I'd like to support that level of machine too
I have no idea where to go someone please help
Still got a lot of game to add, so. Every optimization counts 
What you can do is create all states at the beginning and then hard link the reference of the next state to a property
So like option #1 before?
myStateInstance1.stateToSwitch1 = myStateInstance2;
myStateInstance1.stateToSwitch2 = myStateInstance7;```
Does anyone know codes for a unity game?
What
I tried that and nothing changed (visibly)
Debug.Log("Hello World") there you go fresh off the presses
how did you use it
No semicolon? Nice prank
basically, yeah, would be the easiest solution that doesnt need lookups (or atleast only once at the start of the game state machine)
bro gave homie his first error
I never said it was a full line
can we get that image of einstein and the other mf
Specifically there’s a game called BUILDNOWgg
What do you currently get when you just set the rotation to the normal vector?
fair enough. I wonder how much FPS i'll gain, for making my code horribly ugly and hardcoded 🤣
Are you the developer of the game
No
Then whatever you're about to ask is best asked to them, not us
probably not much, as i said, premature optimization
You can also use reflection to create one dict of all states but show another dict where you can set the prev and next state in inspector with a custom editor 😄 Worth the work? Not sure 🤣
should I just send my whole code so yall can take a look at it
yeah and please summarize what is the desired result
Probably.
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hasn't been clear to me and i've been reading all day ur posts
is there a way to include a non unity c# project in the sln that unity generates?
Are u trying to apply a decal onto a surface or something?
not exactly
I've been following a tutorial that appears to be getting less and less useful as time goes on
well, you are trying exactly that. impact hole texture/object on the hitpoint of your raycast
and by useful I mean it's shit
"a tutorial"? you mean you don't have 4 open at the same time?
If I'm making, say, 100 nearly-identical objects, with identical rigidbody and Box Collider settings - is there an easier way to do that than copy-pasting 100 prefabs? Say, if someone accidentally removed a rigidbody or collider component from one object, it'd be a pain in the butt to track it down.
To check which info is the best? Which method is right for you?
ok hang on a minute

damn
Yeah 100%. Object pooling no?
prefab? + prefab variants
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Object Pooling allows you to have 100s of prefabs "ready to go" at anytime. Whenever one is needed, you simply "activate" it, rather than actual Instantiate and Destroy which are slow.
read his questione one more time.
Please use one of the code bins in the bot command because pastebin is 1000% unadulterated cancer
how so
That's probably what I'm looking for actually, thanks.
I would like to see the code, not the ads or their algorithmically chosen pastes
You answer it then if you know what's needed
hhhhh
nvm looks like prefab variants was it
He needs prefab variants idk how on earth you managed to put together object pools from what he asked for, but no need to be a dickhead
Appreciate u calling it like it is 🗿 good one cheers
You're using a direction vector as euler angles
cos it needed a quaternion thing
I thought you were being dramatic, then i turned off my adblocker you are not kidding.
So, if your surface normal is straight up, you'd have a direction vector of 0, 1, 0, which is going to give you a rotation of one degree about the Y axis
Which part is broken exactly? The placement, or?
angle
it goes to the right spot, texture and particles are just fucky
I'm on a work machine that is still stuck on chrome for the time being so I no longer have an ad blocker. I literally cannot open the site
It's utterly unuseable
speaking of Object Pooling - please get the Instantiate outta there ASAP 😭
no more ad block on chrome?
that was what the tutorial said to use
Which direction is the "up" direction on your bullet hole object
I had no idea that was bad practice
uh how do I find out? would it not just be the same as anything else?
If you look at the prefab with the transform gizmo on, which arrow is pointing in the direction you want the bullet hole to be facing
Like, is it the front you want to see it from? The top? Depends on the orientation of your prefab
well the direction depends on the angle of the surface it's hitting
I'm asking which direction on the prefab is the one you want aligned to the surface
Most people making tutorials have no business teaching.
nah ur fine, yeah it's very expensive to Instantiate and Destroy at runtime
Object Pooling is kind of like, having all the Lego pieces ready from the start of the program. And you just turn them on or off as needed, never creating or destroying from a memory standpoint.
Z axis apparently
I've noticed
this code is awful sir please do not follow anymore tutorials from the same creator.
So the 2nd parameter is not working - the hit.normal right?
Tried Debug.DrawRay? 
So, set the object's forward to the hit normal. spawnedObject.transform.forward = direction
You might need a -direction instead depending on whether it's facing towards the Z-axis arrow or away
well I'll be damned
When you use a direction vector as a direction vector things tend to work
crazy, allat for a 1-line edit
It's not degrees, so Quaternion.Euler makes no sense
Guys why are we trying to fix this code instead of advising him to start over?
if (tags.Contains("modBurstFire"))
{
attemptingToFire = Input.GetKeyDown(KeyCode.Mouse0);
if (canShoot && attemptingToFire)
{
burstBulletsRemaining = bulletsPerBurst;
Shoot();
}
}
else
{
attemptingToFire = Input.GetKey(KeyCode.Mouse0);
if (canShoot && attemptingToFire)
{
Shoot();
}
}
like what is this atrosicity aint no way we are using tags for this.
State pattern moment?
the hell is a state pattern
State, Object Pooling, Coroutine...
This code needs a lot, and it's not even 200 lines
I'm just gonna go ahead and retire...
Because I answer the questions that were asked. If I took the time to answer the questions that need to be asked I'd be stuck here forever
clearly the guy in the tutorial was mentally disabled or some shit
nah he's just a beginner / doesn't care to write good or optimized code
With that kinda code, you might need an Intel i9 processor just to shoot some bullets around lol
So, give State and Object Pool a read. It's a beautiful thing, trust me
State especially. It's so easy, once you have it set up, to literally add anything you want
fuck this guy in particular
You can probably add diving & swimming to your character in an hour, if you have animations ready
If we're going to tell someone to throw everything out because the code isn't the best, why suggest something that's still bad? If it's gonna be re-done, it should use actual decals not object pooled prefabs
18.9k subscribers? 😥
Already told him to use decals! RIP
But you won't end up making something actually good on your first go around. Or second or third
or, at all really
I am nowhere near ready for that
most of my movement is running and jumping
@true pine in the URP sample projects they have decals
Should be easier to do than what you have currently
Sometimes you just need to step on the rakes until you figure out why you shouldn't be doing them
So just keep making stuff, honestly. Ship of Theseus this into something workable
I'm not very good at figuring stuff out on my own
never have been
A good skill to learn, never to late
And then suddenly, one day, you will
Never speak those words again, we're all at some point on that same ladder.
Maybe except for digiholic, he knows everything I think.

maybe
its ok your next problem after solving this would have been "why does my firerate fluctuate with my fps"
And also, everyone has different interests and strengths. Expecting to be a solo dev out of thin air happens to 0.00000000000000000001% of the developer population. Most specialize in a specific area - programming, 3D Modeling, Animation, 2D/UI.
Yesterday I burnt campbell's tomato soup because I was playing Balatro
Knowing how to make soup isn't that important
(this is ragebait)
I'd send a gif but it'd probably get deleted
massive respect
none convey the emotion quite the same as that one dog with closed eyes
chat done got quiet
not allowing gifs in discord is crazy
Depends on the server
this isn't a social server, this is a place of learning. gifs and reaction images just create useless noise
Gifs are fine. Pointless reaction images are not
I'm gonna be honest, the tag system was my decision
I wanted something like tf2's code where weapons would inherit from a basic "stock weapon", getting a list of "tags" for modifiers that don't have a value and another list of "attributes" for modifiers that do have values
So you have some inheritance there, "per instance member variables / config"
change the numbers, change the model, have some code that changes the text on the info card, update visuals/sounds, bam. new weapon
Many ways to skin a cat or whatever they say
more than one way*
see I never knew these existed
putting "Sprites" inside SO isnt that expensive right?
[field: SerializeField] public Sprite Icon { get; private set; }```
i mean something like this
There is certainly a better way to do this than using tags im not familiar with the way tf2s weapons work so I cannot really give any advice. But as stated you probably want to do this with inheritance.
...had a realization that maybe the particle effect and the bullet hole texture shouldn't be connected to one object, cos if I shoot something with physics, the bullet holes just kinda chill in the air
So, you have some base "Equippable Thing" class... then you have a "Fireable" that is not only equippable, but also can be aimed & fired... a "Throwable" that can be thrown rather than fired... Etc
it's exactly as "expensive" as any other reference
good 👍
ty
The sprite will be in memory anytime the scriptable object referencing it is within scope.
So when you go to equip a new item...
You're not equipping a firearm, or throwable
You're equipping EITHER of those things, and the computer will allow either to fill the slot
Then you just have different behaviour depending on what's equipped ...
This is called Polymorphism
yeah, the idea was for a ranged slot, a secondary that can be anything, and a melee
So, like every shooter game ever basically 🙂 mine included (WIP.. can't even shoot yet)
no I got something unique here, I'll be able to cook once I figure out what I'm doing
I might have a video that explores some valuable strategies.
Haha me too. It's always <popular game> but with <your spin on it> remember that
I personally take a different approach but this a very solid way to do it.
I've been getting ideas for the greater majority of 2 years
slowly building the concept of this game
Sure what way do you choose?
Composition instead?
oh snap, as is mine!
I just want the game to be popular enough to get its own community, doesn't need to be some award-winning legendary game
Smiling & laughing irl thank u good one
but its unique, never been done before
oh snap, ... !
Lol
But, I'd work 10 hours a day doing something I love, even if it's average money
yea
mine is stardew valley but with more multiplayer element, making it like a party game in endgame
so yeah, the formula still works
need the spiderman pointing at each other GIF
mine is a FPS but you're playing only with the minimap 😉
I wanna take my time but I kinda can't cos it's only a matter of time before I end up doing 9-5 slave labor
and remember, no matter what games ur trying to make, u only succeed when u can build the whole thing out 🤣
this
Mine is Roblox for adults with less programming restrictions and better netcode
9-5 slave labor is super common.. alot of us fall in that category.. you have to do ur 5-9 after the 9-5
Believe me, you wanna suffer up front when it comes to game dev
If it helps I'm on 11pm-7am then coding
👀 ☝️ see
roblox might as well be for adults at this point
that's a discussion for another day...
Learn state, object pool, inheritance, polymorphism, at the minimum trust me
Or you're gonna end up with code that is very hard to upgrade, change, maintain, improve
thank you
would that website you linked me to before be a good place to start?
SRP too, single responsibility principle
im more of a minecraft fan rather than roblox lol
Let me rephrase. Similar concept to roblox without the blocky style graphics.
just do the whole SOLID at that point
Google
W3Schools
I'm saying, just to have a character moving around, pick up items, maybe use them, put them back
That's already gonna be hell without the strategies I mentioned
i like interfaces more rather than virtual/override now
Then you wanna turn it into a full game? Yeah no. Not without those patterns
I had like 3,000 lines in my Player_Controller.cs, now it's all separated by responsibility ...
I know c# syntax shit pretty well, unity-specific stuff and the mountain of methods and things it provides is the issue
Camera related stuff, animation related stuff, interacting with nearby items stuff, etc
learn, input class, save system, menu/pause/exit system, and settings system
alot of this stuff is put off way too long
All separate scripts, separate configurations, only accessing each other when needed
ok yall making a huge list for me here
i split a 3k line script into 4-5 scripts by extension method
You best be writing down a TODO list
lmao.. the more the merrier 😄
I wish someone told me this when I started
Well in that case my go to are
GameDevTV
Packt
Zenva Academy
UnityLearn
good idea
Well, @rocky canyon did but I didn't listen
it happens 😄
how should I prioritize this stuff exactly
just get familiar with the engine first..
Well movement is #1
The main thing is to not dig yourself into a hole... "Tech Debt" it's called
movement is mostly ironed out already
Dirty code, 3,000 line files
the hardest part is to pack ur code to make it look more precise and tidy
I don't have very many issues or things to expand upon there
I'm less worried about that at the moment
making it exist/work first
Function over form is number 1 priority.
It may be compact but won't work as intended, okay where's your bug?
Hundreds of lines of code and you can spot the bugs when highlighted, great.
If it's 3k lines and functions as you want, why split
If your Update function ends up looking like this... You're probably doing fine and you can build a whole game
void Update() {
readInput();
checkIfGrounded();
calculateNextPosition();
calculateNextRotation();
moveToNextPosition();
// etc
}
See how it's English? It's step by step? Someone who's not a developer could probably get the idea.
So when you revisit some part of the code, oh guess what, it's in freaking plain English what is happening
I usually do "make it exist/work" or "find out if it's even possible to do this in this way", then "OK it's possible let's make it clean and easy to work with."
DRY, ETC - two great programming principles.
It's tempting to just "keep going" but that's how you make a spaghetti mess.
yes
everyone's first Movement script should end up being over 1000 lines.. then refactored down (learning better coding practices in the process) 😄
You wanna add jetpacks to your game in 2 hours? Or you want it to take 8 hours and always bugged?
Yes. Learn and experiment, then determine the best way to accomplish the thing, and clean it up
this is how i learned most of the syntax and functionallity i use day-to-day
i split with a specific pattern tho
lets say data manager.cs :
- get data
- set data
- upload data
- load data
data.cs (static class with only extension method for data manager.cs):
- utility getter/setter
- deserialization function (for load data() )
- validation (for load data() )
getting laughed at.. and roasted for my else-if chains
Okay that's enough gold in the chat. Cya later Homies 
and how does one "get familiar"
Get stuff wrong until you eventually start getting stuff right
Ask it on a date
just take a bit of time to look thru the engine..
the menus..the components.. the settings
sounds infuriating
Want some more advanced videos? You'll be exposed to more complex stuff.
It's important to know, how much you don't know.
that is a list far too great for any mortal to comprehend
Okay just asking because I saw someone before mentioning splitting out their jump into a different script
this a good list?
I would think, jump can be included in other Motion related code
in order of importance
https://www.youtube.com/playlist?list=PLFt_AvWsXl0fnA91TcmkRyhhixX9CO3Lw
this playlist really helped me when i was starting..
if anything it showed me what to expect.. and helped me learn a bit of terminology i could use later on to research things on my own...
kinda hard to do that when u dont know what words to use
thank you so much, anything but the jackass I was watching before
avoid Code-Monkey until ur more experienced 😄
kinda random from my pov. Did you actually checkout the learn paths on unity itself?
One of the best ideas is to have scripts related to feature: so player movement should be in one script
Enemy movement in another
Combat in one script etc and block it off in modules (allows you to share your modules between units)
i will not stand having more than 500 loc on a single script
theres gotta have something more to split
9 years ago, could be misleading at some parts
nah.. its all relatively the same..
code doesnt change..
velocity is now linearVelocity..
thats about it 😄
yah well, you are right. if its just about coding and not unity UI setup stuff
DRY, ETC (Clean Code principles)
FixedUpdate vs Update (if you need Physics, that's a rabbit hole to go down Tbh but it's solvable)
Minimizing garbage allocation (eventually)
ya, im sure they'll venture off and learn specifics from other places
i used it as a crash-course basically
A good test to do is take the unity modules or vector etc, mathf.abs and all of those methods and write your own to use instead
whats DRY?
^ i was guilty of this ALOT when i first started
writing out my own logic and then someones like why not use "thisClass.ThisFunction();"
i was always like.. u gotta be kidden me
still happens.. just not as often anymore
thats why we have unity community lol
and we improve from these little hints
bit by bit
and now im obscessed with linq queries
Writing your own logic allows you to understand how the methods work and the code behind it.
https://www.youtube.com/watch?v=jSauntZrQro
https://www.youtube.com/watch?v=NsSk58un8E0
https://www.youtube.com/watch?v=YR6Q7dUz2uk
https://www.youtube.com/watch?v=YdERlPfwUb0
https://unity.huh.how/lerp/wrong-lerp
https://youtu.be/qPQkFYt7smk
https://www.youtube.com/watch?v=QzMIi2gKB1A
These videos will show you some of the more tricky/complex stuff that can be done in Unity. Remember even great channels like Jason Weimann make mistakes, and even have multiple videos for same topic.
it really compress ur iterations, u might need 3 foreach loops to do stuff, but if u can write a correct query, u can do something like
foreach(int element in numbers.where(x=>.....).select(x=>...))```
instead of
```cs
foreach(....){
-> foreach(....){
....
git-amend another great channel. Would you look at that, his latest video is about decals lol
Can anyone speak to their experience either splitting out or combining functions? I have this Grabber class that allowsme to pick up items, and I want to add the ability to bring items closer or further from the camera using the scroll wheel. I could see us making two functions - one for bringing the item closer, and one for sending it further. Or we could make a single function that takes the Scroll Wheel value as a parameter, and then moves the object based on that parameter.
Any thoughts?
Just a heads up, that Linq query might look nicer, but under the hood it is at least as slow as the nested foreach. Making code cleaner for your own sake as a programmer is valid, but don't go thinking Linq queries are faster and start overusing them
The main idea is, "if object is not at DesiredPositionFromScrollWheel, move to that position"?
Why do we need 2 functions? This can be done in Update() with SmoothDamp or however you like
Not quite. The Player Class manages the input from the scroll wheel. When the scroll wheel moves, it calls a function in the Grabber Class. Either one of two functions - decrease distance/increase distance, or a single function: ChangeObjectDistance.
And the distance that the object moves will be a variable that I'll tweak to make a smooth movement feel to it.
thats worse 😆
lol
probably fine when not done too much all the time
You're saying the scroll value alone would suffice?
sorry talking about linq myself
Oh, haha
#1390346827005431951 place for threads
float epsilon = 0.08f; // Snapping distance
void Update() {
if (Mathf.Abs(desiredItemPositionFromScrollWheel - currentItemPosition) > epsilon)
currentItemPosition = Mathf.SmoothDamp(...) // or however u like
else // Probably not great to assign this every frame, maybe check equality first too
currentItemPosition = desiredItemPositionFromScrollWheel; // Snap to exact desired value
}
I'm curious if it can get more efficient than this, assuming the scroll wheel should be read every frame.
There's no need to overcomplicate. Doesn't matter where you call the functions (WHEN probably matters though), where the data is stored, how you read the input. Get access, and do what's needed. Or if nothing is needed, do nothing
Thats some dangerous advice there 😄 "Doesn't matter where you call the functions"
Technically speaking as long as things happen in the right order, yeah it doesn't actually matter
the worst/most frustrating input i've ever worked with was the scrollwheel
Why? it only provides delta rather than an absolute value?
As long as the spaghetti is not cut, its tasty? 😉 Things get difficult to find out if any spaghetti is cut or not or where, because you got a whole bowl of pasta in front of you 😄
i can't remember.. it was a zoom on a top down strat camera..
and i was doing audio clicks w/ it..
i cant remember the exact issue.. but it took me a while to get it worked out where it smoothly worked.. (didn't overshoot) and the audio sync'd up nice and pretty
not advocating disorganization here, any project that's to become a full game should be easy to read
How can i get this option on the material i want to put the shader on, i dont want to have multiple shaders with just a texture difference
proper naming of classes/methods/and variables help out tremendously
they can almost replace comments if they're good
is there a way to add an external project to the solution that unity generates?
ofc' i use xml summaries now
Posting this again for relevance
void Update() {
readInput();
checkIfGrounded();
calculateNextPosition();
calculateNextRotation();
moveToNextPosition();
// etc
}
camel case functions... ewww
I'm a huge advocate for code that speaks for itself. Plain English, as much as possible
😛
its your code..
You would create a parameter, name it whatever you want, and assign the texture to that parameter in the inspector or in code
i just figured that out lol, didnt know i could do that
its better than whatever tf they use in c is read_input(); check_if_grounded() etc
✔IfGrounded(); ftw
emojis in the variable names 2026
they show up in my comments sometimes
so if this isn't possible how do you guys handle when you got a non unity program that works with your project? is opening two visual studio instances the only option?
uh unrelated but how would I change my mouse controls in the editor
I wanna swap middle mouse and right click so it's more like blender
i usually work w/ one instance for each project..
i didnt know u could open two solutions in one window
or if rather
no i mean like I have an asp.netcore app that I use for authing players who logged in. I open that in one visual studio instance then another visual studio for my unity project.
I would love to be able to attach the asp.netcore project to the solution unity generates but its not looking like its possible
unity doesn't even support nuget packages, of course it won't support completely separate projects
Nothing wrong with having two vs code instances open and running two solutions. But you do not really "integrate" it into unity. You just have two windows open with two environments
Any news here? I wanna help but you haven't posted any code. And what you said wasn't relevant to the solution I posted - doesn't matter if you have delta scroll position or absolute scroll position, that code works fine.
And if you aren't using either of those, please educate us on how you get scroll wheel input.
Maybe use a Curve for smoothness. Something like, difference in position vs. max distance to move this frame perhaps. SmoothDamp is usually good enough but I use Curves cause they're fun.
Here's a simple ScriptableObject class so your Curves don't reset when you exit Play mode.
[CreateAssetMenu(fileName = "CurveAsset", menuName = "Scriptable Objects/CurveAsset")]
public class CurveAsset : ScriptableObject
{
public AnimationCurve curve;
}```
Hope this helps. I didn't mean to be rude when I said it sounds like things are being overcomplicated.
Just not a fan of having two seperate solutions ik nothing wrong with it just was hoping I could get around it because I do not like the workflow its imposing on me
PS - not sure if [SerializeField] and public are equivalent 👌 experts chime in
You could also just build an app out of it and not run it through vs code 😄 But not sure, what is giving you headaches in the situation. Maybe you can explain a bit more
inspectorwise, its the same result.
public fields are accessible outside the class
Oh last note, with a Curve make sure to have a minimumAmountToMoveThisFrame clamp or it may never resolve, just keep doing float math
public fields are serialized by default (if they are serializable), SerializeField just tells unity to serialize a non-public field
Lol, you didn't exactly answer the question I was asking, but you did propose some code that I'll consider. After some experimentation, turns out one function would be best for this - and I'll take a look at the code you provided for smooth/damp.
Thanks for the feedback though, it helps in the next step of this.
Im using visual studio not vscode. So its an asp.netcore webapi player sends credentials to webapi and then gets a token back in return that is used to verify if authenticated. both the web api and the unity project rely on some POD classes, so I have a visual studio solution with the webapi and a "shared" dll that is referenced by both unity and the webapi. It is currently under development so when I build the shared dll it executes command in visual studio to copy the dll to the plugins folder in unity. Only problem is you cant just copy it in like that it fails every time unity is preventing it. So anytime I need to make changes to shared.dll i have to go into unity delete the existing one then copy the freshly built one from the output directory to the plugins folder. Its annoying and inefficient
AFAIK the question you had was to use 1 function or 2 - the answer I gave was none at all and to just use variables (desiredPosition, currentPosition) with every-frame checking (if in the right state) as I wrote out (Events wouldn't save much FPS unless the scrolling won't be happening every frame when object equipped)
There's a great video from Toyful Games about Springs, that could be worth looking into as well. That's where I first saw this kind of "set the DesiredValue when needed and the per-frame code just handles it" But there can be issues with overshoot.
https://www.youtube.com/watch?v=bFOAipGJGA0
Meet the BEST Game Feel method you've never heard of! Very Very Valet is available now for Nintendo Switch, Steam, PS5, and Epic Games Store
https://toyful.games/vvv-buy
~ Ryan Juckett's Excellent Spring Code ~
https://www.ryanjuckett.com/damped-springs/
~ More from Toyful Games ~
- Physics Based Character Controllers in Unity - https://www....
iirc rider supports that if you want to give it a try, a non-profit version of rider is free now
It's not my goal to know your exact use case 🙂 - hope the knowledge helps even if it's not exact to your case.
Sorry, I see the issue - I meant method, not function. Basically the difference between this:
and this:
Uh huh.
Yeah please give it a try "DesiredPosition" and "CurrentPosition", with the every-frame if (different < epsilon) that I wrote
I literally see nothing that doesn't make this the optimal and simple solution
SmoothDamp already does some epsilon stuff internally so that's optional
Pick whatever looks cleaner in code,
if you have a variable input for example you dont want to decide if that is for decrease or increase -> 1 method
if you have different buttons that have 2 clear distinct paths -> 2 methods
// yes
Thanks, that's what I was coming around to through experimentation. That makes a lot of sense. I also just realized that I'll need to implement some logic for controllers in the future. So I'm gonna take another stab at the input side of things.
The smoothing algorithms legend himself 🔥 Ahhhh today is, a day
Wait so 2 functions instead of if (scrollInput.y < 0.0f) ? what
boy do i love springs 😄
i have 1 for almost everything, position, rotation, scale, and more
i wish SmoothDamp was more configurable so i didn't have to use Curves
now i want to spring a color 👀
yes... rider does support this thank you.
No exactly the opposite, you have input that doesnt have 2 clear paths to split into 2 code execution paths so you keep one method
Vengeful, I'm working on it. I'm not even turning your suggestion down - I'm learning how to use it.
I just don't have an instant response to you because I'm working through new functions I've never used before.
Just seemed like what I said got shot down that's all. Yes trust us, this is the way. It's not even my knowledge, I learned this from the people here lol (and YouTube videos confirm.)
Personally I would do the two method idea, that way later if I want to execute it manually instead of via the scroll wheel I have that ability. If you know for a fact you're never going to do this vengefuls suggestion is the best way
It can hard to achieve some behaviour, whilst having the computer do as little work as possible. That's what we're here to teach about though

is there a easier way or do i have to turn it into an array
Animator[] _oldAnimators = _oldDoors.ToArray();
_oldAnimators[0].Rebind();
_oldDoors is a list of Animators
Yeah, I'm mulling it over. I think the only way the player will do this is by scrolling the scroll wheel, or using a controller to do LB+LStick Up and Down. Both of which should return similar numerical results I think. Still gotta verify that.
I don't think there will ever be a non-+/- float or Vector2 value to perform this functionality. But...I could be wrong. 😂
_oldDoors[0].Rebind()
Do you need the array for smth?
We're getting into "How much user customization do you want to give the player" territory. And admittedly, thinking about potential accessibility controllers...maybe I'm wrong.
You can use the list to Rebind like digi showed . . .
You could have multiple factors that affect the desiredPosition or yield control to other systems.
if (offsetPosition > 0.0f)
desiredPosition = offsetPosition; // switch control to some other desired value
For example in most games, movement is affected not only just by the player control, but how much items are in their inventory (weight), debuffs, etc.
Over Cucumbered
not my style of games :D...
DoomGuy runs around like madman w/ 9 equipment slots
The BOTTOM LINE is that you always have, some desired item position and some current "Item position based on scroll (& other factors)" right? So that system ONLY does that 1 thing
This is called Single Responsibility Principle. Where you get the inputs from, what extra modifiers and logic go on top of that, that's all cool. But the system, is the system
You shouldn't have to change the actual system, to add more or different functionality
but yea, good example..
lots of things in a game can be affected by different mechanics
a + b is a really nice mindset to have handy for alot of things
and its clean b/c u don't have to toggle off that functionallity.. just set it to 0 to ignore it..
a + 0 = a
Moar Modular
In other words, when an item is equipped, the game always brings the ItemCurrentPosition towards the ItemDesiredPosition, smoothly.
How those are calculated, how much change happens each frame, what kind of controller the user uses, is all separate and unrelated to the main item-relocating system itself.
u can do the same thing with multipliers.. but using 1 instead of 0
Are events really that good or is Unity just checking if the event was fired every frame 🥹
I need more FPS 🥹
yes.. events are everything..
i actually need to rewrite almost all my code to use them more often
Update()s for the Birds
Is firing 60 events a second better than checking a value 60 times a second
probably..
lol.. if ur checking a value against another value isn't that 2 checks?
🐔 and the 🥚
i mean, i think thats why the new input system is what it is
ur gonna get in trouble asking those kinda questions around here!!! 😰
and events are just easier to work with..
That's true. started / performed / canceled are fast huh
Nahhh subscribing and unsubscribing is expensive
callbacks.. all that good stuff
and events are just easier to work with..
that was part of the easier in my statement
Ohh
i haven't a clue how perfomative it would be
b/c i dont use em enough 🤣 edit: im going to start adding them into my codebase tomorrow ✅
Need to make some tutorials of my own at this point
What I do know, i know well. Keep saying the same things every day in chat
one of ur statements ^ just got stank-eye'd up there
yeah i noticed. it's fine, i've tried it before lol
like when your character exits a Midair state, unsubscribe from jump? Yea get outta here
And I'm not. I'd been using current and target position in my update function.
Though I'm not sure how this:
if (Mathf.Abs(Vector3.Distance(targetPosition, grabberRigidbody.position)) > epsilon)
grabberRigidbody.position = Vector3.SmoothDamp(grabberRigidbody.position, targetPosition, ref grabberSmoothVelocity, 0.1f);
else
grabberRigidbody.position = targetPosition; // Snap to exact desired value```
would be more performant than this:
```Vector3 targetPosition = playerCamera.transform.position + playerCamera.transform.forward * grabbedObjectDistanceFromCamera;
grabberRigidbody.position = Vector3.SmoothDamp(grabberRigidbody.position, targetPosition, ref grabberSmoothVelocity, 0.1f);```
ohh nooo.. that'd be over-complex by any standard
ya...
Maybe for "once or twice in 10 minutes" subscribe/unsub is fine
it'd be more like im teleporting my player/loading a new scene/showing a cinematic
-# hold my input for a minute
(Is it that last .08f where some secret sauce is happening?)
how would that be an issue?
The two dont relate, you use an event if you need to subscribe to something changing. Just directly read the value if youre going to need it every frame
i didn't say it'd be an issue..
thats when i'd possibly unsubscribe from my InputHandlers()
That's fine, if you're OK with how SmoothDamp behaves
I found it takes too long to resolve, always. Especially if you modify params in anyway like the smoothTime
The 0.08f is just the closeness to trigger an exact-value snap
SmoothDamp does that internally but it's not customizable i think
I just use curves and epsilon or clamp with a minimumVelocity to ensure resolve
Curve junkie over here lol
I'm about halfway to loving it. I'm noticing two strange things - when I rotate the camera and scroll the scroll wheel at the same time - the object doesn't get closer to the camera until it stops rotating - this screams "async" issue to me. And the second is that as I rotate the camera - even moderately-slow, the object is kinda jerky.
Got it, ok!
I see no reason why those 2 parts of code wouldn't run side by side
u could seperate the two..
zoom/pan w/ an outter gameobject wrapper..
and then rotate an inner
Maybe the calculation is wrong, I didn't look deeply into it
Me neither. Is it a Fixed Update problem?
Yes, it is.
golden rule with FixedUpdate() is don't have Input in there..
Interpolate though, I'm not sure.
Physics is a whole topic
Input - you mean controller/player input right?
yea don't poll for input in fixed
I don't.
cool cool..
It's only performing the smooth damp movement to the target position.
But it seems like the camera movement and scroll wheel somehow aren't happening at the same time - and it's weird because when the camera is rotating SLOWLY, it's fine.
I don't think you can just move Rigidbody like that
Maybe try Physics.SyncTransforms() after you directly set a Rigidbody transform.
I think with Kinematic Rigidbody, MovePosition and MoveRotation don't screw up the interpolation?
there's rules to it, I forget the exact details.
MovePosition work for both, but as we had earlier a case, its bad for like restricting player movement with walls or what not. Its more to like push things away while your character is moving
Hang on, new info - the above wasn't true. Whenever the camera (or maybe the mouse) moves, the scroll doesn't work - but when there's no mouse movement, the scroll "catches up" to the new location.
Physics.SyncTransforms() didn't fix it.
You can also turn interpolate off, on a kinematic RB, and just set position directly in Update.
I'd recommend getting this working without Rigidbody first. Just a regular GameObject.
i recommend that dozens of times..
i always tell people if things aren't going ur way or ur having an excessively hard time with something
break it into pieces.. and work on a single piece in isolation... all by itself.. nothing to go wrong but the code ur working on..
once u get it working and u add more and more to it you'll easily being able to pinpoint where the code goes rogue and stops working..
much easier than working out a full mechanic w/ lots of moving pieces all at the same time..
heck theres even times when i'll have something not work.. and i get it fixed just to realize i broke the thing that was already working..
that happens less often too when i go at it bite by bite byte by byte 🤪
I had the same issue when "picking up" a Rigidbody. (SetParent to Player's hand) - so basic huh? Unity tries to control the Rigidbody when Interpolatation is enabled. So i just had to disable that on pickup.
itemToPickUp.GetComponent<Rigidbody>().interpolation = RigidbodyInterpolation.None;```
FYI it's not great to `GetComponent<>()` at runtime. I'll be getting those references on Awake() eventually in a "ItemThatCanBePickedUp" script to avoid this.
Idk if that's helpful, it all depends what exactly you're doing with the Rigidbody.
How can i tell if a animation has played(from a script) in an animator
i mean. its not as bad as running a Get in Update() or soemthing 😄
atleast in urs is only when u pickup or drop something
I think there's a conflict here with the grabbedObjectDistanceFromCamera value. It's being used to determine the target distance from the camera. And while the camera is rotating, it's also being updated as the player scrolls the mouse wheel.
Which happens in another class's Update class.
well thats also a no-no
updating the same thing from fixed and update at the same time especially a Transform
Could that be the root of the issue? targetPosition is updated in the FixedUpdate step, and dependent on a variable whose value is changed in the Update step.
The transform itself is only updated in FixedUpdate.
Yeah 100%
oh, well if its depending on a value updated in Update() its possible its changing quite drastically compared to the last value Fixed() thought it was
You should change the "desired position" in Update, but only ever move the object in FixedUpdate, towards that Vector3 desiredPosition
Unless you were to go the other route and remove Interpolation. Then you don't need FixedUpdate until you re-enable Interpolation
Interpolation is the SmoothDamp, right?
First thing I'd try is to remove that last line of FixedUpdate, replace with MovePosition
No - Interpolation is a Rigidbody setting that tells Unity to approximate the position of a Rigidbody in Update. Why? Because FixedUpdate is not synchronized with Update
Heh, I had MovePosition before, but replaced it when adding the SmoothDamp. didn't realize the two were compatible. Trying it.
An object moving at 50 FPS (fixed) will not look good if the game is at 60 FPS.
MovePosition has a speed to it too. But if your desiredPosition is smoothly calculated, you can just have infinity max speed.
Still no luck. It's as if the changes to grabbedObjectDistanceFromCamera from the TryChangeHeldObjectDistance method are queued up to happen AFTER any other updates to the position of the Rigidbody.
Screenshot of picked up object Rigidbody?
I g2g so let's get nitty gritty ASAP
please 
I think thats a good issue for a thread to talk about 🙂
I'll start one there, Thanks joer.
I meant from Inspector of the configuration
LOL, that makes more sense. I was like wtf
My brain is melting out of my ears actually, so I'm gonna sleep on it and come back to it with a fresh pair of eyes.
Thanks everyone.
With more pics & code 100% we will get it sorted out the issue 🗿 cya next time! 
Simply put
Fixed update is anything to do with physics and rigidbody interactions
Late update camera etc
Update is anything pre physics
Update is not pre physics, its not tied to physics at all. Its just once per frame
In the list of calls it goes Update -> fixed update -> late update as per Unity documentation
this is the execution order
https://docs.unity3d.com/6000.2/Documentation/Manual/execution-order.html
and update/late update still aren't tied to physics. Make a monobehaviour with all 3 methods and print out a unique message from each. you'll see the count of update/lateupdate logs dont add up with the amount of ones from fixed update.
i dont know where you got that info, but that list of calls is just wrong
They're separate loops. One of them is going to occur before or after the other simply due to the fact that Unity is multi-threaded, but the timings have nothing to do with each other. You shouldn't think about it being "before late update" because it isn't. It's called when it needs to be
| | | | | | | | | | | |
| | | | | | | | | | |
Fixed update is even,
FPS you can have overflow like 240 FPS of game but only 60 FPS monitor..
Hence interpolation is Unity estimating the Physics stuff but on Update’s time (“FPS”).
Physics is commonly at 0.02s (50 times per second) but games run at 60, 120, 144, etc
Unity themselves state physics should be calculated in fixed update
That’s correct. The “order things happen” we were clarifying
yes, because it's not tied to the visual framerate
nothing that we said contradicts this
Yeah that's what it's for
theres a reason its called the physics loop in the link i sent
PhysX looks good Ngl. Real good
Right so if update is based on your frame rate calculation, then anything not tied to physics should be in it. Hence pre physics as I said, arguably could be post physics but then just use late update
Literally just this message was what we were clarifying yes
You can switch Physics to run on Update time too! lol
For non deterministic funk?

update is not pre- or post-physics, it's a completely unrelated loop that runs separate from fixed update at a different framerate
🐴
some (visual) frames its called before physics, some after, some multiple times, some physics is called multiple times (because your fps is lower than the physics tick rate)
update is all over the place while fixed update is, well, fixed - it runs consistently (by default) 50 times a second
Maybe a quantum computer in the future can run PhysX at 500 FPS (fixed). 0.002s 
With 40 solver iterations
Hi, is there a channel for shader help specifically or would it just be here?
Try the art-asset workflow section
Okay, thanks
you're really confusing yourself here with it. imagine it as two separate systems entirely and it should make it more clear. theres no before/after/during consideration here when thinking of how update runs compared to fixedupdate
#1390346776804069396 is the forums for it
Ok thank you
Yeah imagine 2 cars …
One stays at speed 40
One goes 35, 37, 42, 37, 32
Clear?
Sometimes they line up, or are close, sometimes not. That’s it
Just odd that unity would write the detail in a flow chart if they were two different systems.
They both take frame rate
Take data from how many seconds past
One calculates quicker than the other
Both normalised with their respective deltaTime
Can you send the page? Maybe there’s an asterisk or explanation elsewhere
I was wrong on the order though that I conceded.
They both take frame rate
what do you mean "take frame rate". fixed update ISNT tied to your frame rate in the slightest. Set your target frame rate to 10, fixed update will still run 50 times per second
Take data from how many seconds past
fixed update doesnt really. fixedDeltaTime is 0.02 unless you manually change it
the last two points really just dont make sense given the context
That is the only place it’s mentioned on that page, though. So you’d have to go to Physics API or FixedUpdate to learn more yeah
they show it this way because thats the execution order. as digiholic said, its not multithreaded so it technically does run in some order
Which was my original point you disputed saying there is no order
you still arent understanding, what i wrote isnt the same at all compared to your original point (where the order was wrong still)
There is no order. Physics runs on its own time lol
u can see in the flow-chart how they loop back on themselves
And they take frame rate because a frame rate is a base calculation between 1 second and another, they are varied based on other factors
i dont think I can explain it anymore clear that fixed update does not use your frame rate
maybe reread some of the messages above because there isnt much value in us repeating the same points over and over
yield is cool … framerate saver
This is getting nowhere on either side
Dead Cells needs some of that Ngl
It’s getting to, you learning about yield hopefully ??
You think we’re playing here bro? You wanna know more or not
That loop does not state it goes back on itself it says when 1 process is finished it can go back and restart
They both take frame rate
No, one is at frame rate. One is at a hard-coded time step defined by your project settings.
One calculates quicker than the other
While I guess it's technically correct in that you're incredibly unlikely to end up with both loops taking exactly the same amount of time, it's not designed for one of them to be the "fast one"
If you have a frame skip of say, 2 seconds.. the fix update method would be called many extra times to offset the frame skip whereas update would only occur once
if everything was consecutive you'd not have any of those loops returning back to a certain block
it'd only be at the very bottom
it really feels like they're trying to teach us here by saying "This is getting nowhere on either side". It's really hard to teach someone who won't accept that something is wrong
i think theres some ego/argumentative nature here
Always a little but, we’re here to learn more not say things are one way whilst being clueless
How it specifically works is that whenever it comes time to run FixedUpdate, it checks the clock time to see how much time has passed since the last one. If at least your FixedDeltaTime has passed, it runs FixedUpdate, then increments the internal physics clock by one of those deltas. If it's still greater than that fixed delta, it'll run again. And so on.
If your Update loop is very very very slow for a brief period of time (let's say you've done a non-async additive scene load of a massive scene file), it will run a full Update and then do potentially dozens or hundreds of FixedUpdates all at once
Bro … this guy knows everything
If your Update loop is super clean and barely takes any time at all, it'll run dozens or hundreds of Updates before enough time has passed for one FixedUpdate
digi is a wizard
My original message, which I conceded to update issue. In which I mentioned fixed update and physics and unity designation
Then the execution order provided by unity
(Unless you VSync or framerate cap it, at least. If you do then it does that "hold for time passed" schtick for Update as well)
Least shameful screenshot
Bold of you to assume I didn't make an infernal deal for these abilities
||The deal is called student debt||
Update() and FixedUpdate() are running the same race...
they're neck and neck... only Update has super tiny strides
also these concepts work about the same in all engines, and are very easy to test by making artfically slow updates
I‘m trying to make a mini game called quantum connect 4, i already have rough idea how to make the turn taking & placing chips part, but i have no idea how to do the win checking (to check 4 chips lining up)/randomizing part
every time you press observe, enter observe phase, the chips have (30 or 70)% to turn into black or white chip (the result is random each time), if no 4 same chips lines up, the turns back to the original chip, if Player1 and Player2 both have 4 connected during observe phase, the player who pressed observe wins
More like... "taking the same path". Update is racing that path, FixedUpdate is just kinda vibin'. Goin its own pace.
Use a bitboard
Hmm… how to search for vertical or horizontal or diagonal 4 in a row on a Grid
lmao.. perfect 👍
There is a better algorithm than brute force right
thanks! i'm gonna check it out
i would totally brute force it haha
Same it’s just a connect 4 game
I’m sure there’s some super tricky fancy way to check though
if the board only has a few hundred tiles the approach does not matter much
wouldnt it be pattern recognition?
Naive way that is almost certainly not optimized but should work:
Loop through all pieces. Have each piece check each direction, and if it encounters a matching piece, check that direction from that piece. If you see another, do one more. If that one also matches, you've found four in a row! Otherwise, go back to the original piece and check the next direction. When you're out of directions, skip to the next piece.
Brute force it first until the game works, then you can go back and algorithmify it
algorithmify 🗿
ConnectFour, made by Crysis
also doing it the simple way, you will likly realize simple ways to optmize later as you work
don't prematurely optimize
https://www.chessprogramming.org/Bitboards
Resource if you need it. It uses binary and so is quick
its easier to be clever when its readable and you already have it working and seen some patterns in what its doing
there wouldnt be an alternative to needing to check the row/column/diagonal after a piece was placed
any alternatives would most likely be worse or just more complex
best time to get those eureka moments and that dopamine hit
is painstakingly staring at ur ugly code afterwards
also that grid only has 49 spots so no need to be clever, just get the game done
Normally, you'd only have to check the most recent piece, but since this one has some randomness to it you might need to check more often
Right? But… knowing computer science, surely there’s a fast way??
oh yea true, you'd have to check through the whole board anyways with their observe feature
Is it “unsolvable” at least under some O(..)
Definitely. But for a 7x7 board? Who cares.
So there is a fast way? Whats it called
The thing could be O(n^n) and still run faster than a modern computer could run the rest of the game
Lol. im just curious
after googling im seeing the top results as the way that digiholic described
no, no matter what you do, all the pieces need to be checked at some point. Theres no world where you can avoid checking a specific cell in the grid
Yes it has that minimum.
even without going crazy on it, there are lots of ways of avoiding doing work and using previous steps to reduce work needed in later steps
but non of that is avoiding checking the whole grid
its just making sure you do not check much more then once
looks promising just skimming
but also gets into the realm of what Bawsi said
The bitboard is pretty fast apparently, whoever sent it before good one
You wouldn't need to check every single cell to know in connect four.. just the ones directly around it and store the state of the board...
Bitwise stuff is quick always huh… any language any scenarios
I did as it was the easiest and quickest method you would use on any grid format
Layers in Unity work on that or? I know there’s some bit stuff going on
Yes layers are bitwise operations
because that's what CPUs are made for
Way to make me feel dumb i felt smart saying that
its also completely unnecessary in most cases. Unless you're doing hundreds of thousands of operations per frame, you aren't gonna notice a difference in fps
readability > 0fps increase optimizations
yes but it makes you feel smart
i get nervous anytime bitwise comes up 😄
Why? It's not hard... Binary calculation is relatively simple
Bit board mostly just reduces memory. Would only be a lot faster for certain operations
Maybe it’s one of those “understand it fully once & then it makes sense forever”
bitshifting and layermasks almost caused me to have a nervous breakdown
i think im better equipt to handle it now tho 😄
If you do it a lot it becomes habit, if you avoid it it feels foreign and weird
Yeah easier the 10nd time around right
Once you get hang of how binary works it's not too bad, I have had to sit down and write out as many numbers as I can using the 8 bits... I say had to I wanted to
great point..
now im disappointed in myself 😄
i think using scratch paper and trying to visualize it a bit better would be useful
ill try that next time i tackle em
There really just isnt a great point in forcing it into code, especially if it hurts the readability of your algorithm. Other people dont wanna sit and try understanding it too
Mac and windows calculator can show you bits as well
Useful to visualize
You guys know about the cheat sheet for VSCode I'd hope
Like alt+shift+down copies your line down etc
can toggle bits on and off or do operations and see which bits are flipped
yea thats really useful.. imma test that out tomorrow 🙏
I'm confused to why you'd need a mouse? Unless you're meaning select text etc
like those guys who just use their whole computer w/o mouse only keys
like i said.. im not the guy that code without a mouse... some people know all the shortcuts
and jump around and do crazy shit
nah that's insane lmao
selecting MULTI lines.. copying pasting em dropping em down.. going back changing Types
etc
ctrl shift K
delete selected lines (dont have to select the whole line)
multiline select is very useful tho
works on current cursor line too
Alt+down shift your entire code line down
There's one I think was shift+tab which changes your line from 4 spaces to 0 etc
really i am one of those people that knows way too many vim motions and prefers cli apps for a lot of things. None of it matters, how fast you can input stuff is never the bottleneck.
i still cant remember the bloody hotkey to format
I mean the vertical blinking line like ur next typing position
ctrl a, ctrl x, ctrl v
exactly 😉
-# or just enable format on save
my god, i been following a tutorial on youtube and got stuck at the firsts tep >.<
i followed it to the T, and still it doesnt work. If anyone able to help heres my problem
i am trying to create a fnaf clone, one for halloween and im trying to set up a scroll function on office, ya know. So when player hover on the edges of the screen it moves to that side. but no matter what i do it doesnt budge at all!
heres the code:
using System.Collections.Generic;
using UnityEngine;
public class ScrollArea : MonoBehaviour
{
public GameObject background;
public float scrollBoundX;
public float scrollSpeed;
public bool left;
private void OnMouseOver()
{
if((background.transform.position.x < scrollBoundX && left) || (background.transform.position.x > scrollBoundX && !left))
{
background.transform.position = new Vector2(background.transform.position.x + scrollSpeed, background.transform.position.y);
}
}
}
iirc OnMouseOver is for the old input system
oh... fack
Posted a resource in resources for you to have a read and enjoy
you need to i think implement IPointerOverHandler (or enter/exit)
and make sure you have an event system
would look at stuff like IPointerEnterHandler and IPointerExitHandler
Sounds like YouTube almost
lol
eh, some people still use the old input system
Maybe it’s from b4 the new input system came out
i like the new one
for now 😈
The new input system became the default in unity 6 which is pretty new
Although the input system has existed for years*
i like it being event/callback based
new one is massivly better
im coming from renpy so yeah im lost as hell
takes more setup to use and pushes you into better practices
also i started with unity 6 so that was the default and might as well use it
To be fair.. the new input system is Unreal engines version just changed a bit
Can’t really complain yeah. Do u guys recommend using the built in processor like scale Vector2 etc. deadzone
It’s possible to edit all that at runtime too right?
i use both 🤫
mostly only as needed, like if stick drift is a issue and something you want to expose
Well I wouldn’t make a settings menu without dead zone support
the scale can be used as a setting but i often also use it, when i have multiple input devices 1 bind that act quite differently
like mouse vs stick inputs for example i often need to scale one
Oh yeah i have separate scale for mouse look / controller look
Hard to find online about “Unity new input system change deadzone at runtime”
Yeah those ones. I wanna change them at runtime too
it is
The more I let Unity handle stuff, the better I feel & the game runs
hell ya
Agreed... Once I've checked their maths
you will still need some processing after depending on your game, but you can have your scale multipliers be per input device or per bind
i might just get rid of my input class stuff
same lmao, my code is horrible so i just let unity figure it out
also stuff like normalize and invert and deadzones
I always have this feeling that like, oh probably the built in Unity way is faster
And it usually is obviously
yeah
i knew it had deadzones but invert wtf?
It has invert? i do that manually …
just be carful with normalize most people new misunderstand it and bugger there inputs up
i dont know how many times ive written inversion code
oh yea im super familiar wiht normalize
altho i always forget about it until i go bak to the code
im like tf? Ohhh wait!
lol
you can also just write custom processors for the input system
Ahh ok this is the page i was looking for all along. Nice
gotta focus switching things out and getting rid of some of my redundant code for now
Releasing this year? or it needs more
perfect timing too just made a brand new template project
I’m so behind i dont have enemy AI even started
Pretty much everything in Unity can be redone if you wish, even without access to base code
with only the new input system
templates are cool
How complex do you need
all my ai do are kamikaze sprint at u so dont feel bad
i had a really smart one.. w/ senses and stuff but got corruptd
If you can just hit me with some key words or things to look out for
fun fact did you know you can add your own templates to unity hub
behaviour trees
I know navmesh is important. I already know state machines
2D or 3D?
and become a master at the animator
2D doesn’t have navmesh or
nah u have to do a* or something
Why would it, it’s just
I was meaning more what's your ai focus
Yes
there are many ways to do pathfinding
i use a hybrid approach
have done 2d with my own A* based on a tilemap or a quad tree
with a navmesh and custom movement logic
I mean basically it’s just the path finding that i don’t know yet
never had a cause where A* on a mesh made more sense in 2d since you need a way to define that mesh
a* a* a*
State, detection with triggers etc, all chill
a³
u need to be able to disable the navigation too
for things like knockback
or anything like that that would move it extra from the pathfinding
or u could bake it in i guess
I mean the senses idea mentioned was a good one to implement
Sound you just need footsteps decibels
Visual just use raycast
Guess you could implement smell too
What 🤣
senses/ sensor and a sensor array
or just not use the nav mesh agents directly to control your movement, but use it for your own steering and movement mechanics
ya
I doubt sampling audio would be valuable
for what?
The computer knows where things are, how fast they’re moving (how much noise they’re making)
Nah lol i thought that’s what dragoon meant
no.. that doesnt make sense
u could easily do that with proximity and volume levels
Would be cool though. Maybe a quantum computer can do it
cool idea tho..
No, I'm saying implementation of sound is easy for the ai
it does remind me this guy made a full echo and reverb system
I saw one guy who was just doing like… “anything that moves makes sound”
With materials and other params
u could walk into a space and the audiowould start bouncing around and echoing
Can’t find that anymore but it was sickkkk
sound for enemy AI is just distnace, and tagging what actions are loud vs quite etc
materials is something ive seen for players and enemies alike
Half Life kinda does that i think
no need to overcomplicated it the user will never notice
depending on what ur walkin on u change out the footstep sounds
There’s a lot of math behind which sounds play
ok but my point is its not using the audio to decide that
Physics material, then have the audio changed base on that. Footsteps may sound quieter on grass than wood and have a different effect applied
lol.. nerds
oh i never said that..
itd be using materials is what ive seen in teh past
to decide the audio but yea if we're still talkin ai i said
u could easily do that with proximity
Running the entire game thru a VST compressor real time lol
so i agree with that part
I wondered if Escape From Tarkov was doing that. That game sounds terrific
Nobody’s doing real time compression right … real time reverb, yes though ofc
well with a proper system like fmod you more or less do have a bunch of stuff like vsts
A reason to use audio is if you wanted to implement perks that adapt things It was mentioned using speed etc. which if you want it so you can perk and run but quieter, you don't want the calculation based on velocity rather than sound it makes... So checking against audio feedback helps
Physics material to define it's parameters
so checking agaisnt audio directly would make game design very hard while keeping things sounding like how you want
like audio being triggered is really just invoking a event, so just provide what args are needed for other systems with that
Triggering fine, but getting the audio feedback after the variables have been altered based on your conditions (IE crouching, running, grass or broken glass.. etc.) just change decibels and effects and just check against that. The triggering audio sure event invoke
its not
Not at all
its just changing some properties of how something is going to play when it was going to play anyways
Like, sampling an audio source from down the hall, 3 floors down
To find out how much of it reached bounced etc or
I don’t even know how complex Unity sound simulation is
they are not talking about that though
oh ok nvm then
That is what I'm talking about yes vengeful
also defualt unity game audio is not that complicated
You mentioned AI I'm talking about a reactive ai based on sound output by your player etc
no bounces are happing, its just how loud is sound, then there is a exp^2 falloff
that is so unnecessary though
As for this, there's a formulae for it. You'd need material conditions too
true.. cookie, but this is fckn awesome lol
80 gold dubloons!!! Omgosh
but what i am saying is there are ways to get the exact same outcome that do not involve sampling audio listners
Most stealth games implement it
they just fake it
and are much much cheaper
til u make it
its not even faking it, its just realizing ai's do not care about the audio its self, just the conditions it was made with and where they are relative to it
true.. lmao.. like the clicker zombies in that game.. they dont hear u walkin.. they just know ur way too fkn close.. lol
oh, n ur moving..
I do feel like we are in the wrong feed for these conversations
thats the easiest, you can vertex paint your terrain mesh with certain colors (green for grass, yellow for sand surface etc ....) and pass your character position to the shader then pass it back to play the sound
wouldn’t Unity already have a mask internally that has that info?
since the terrain is painted with the textures themselves
which exists as a texture in the case of a terrain
so in the case of a terrian or a mesh with vertex color used for different materials you would need to sample it
there is but the still textures are the influences
So by default it’s the same as dropping a material onto a cube
I'd say regardless of whether unity has it or not... Research how it works, try to replicate it, understand the maths and logic behind it, you'll implement it much better (even if you use unity version)
I thought the terrain painting works like that underneath, green red yellow
think you are mixing up terms, we are talking about cases where you can not have mulitple physics materials since its all 1 object 1 terrian collider
where you need alternate ways to know what the player is over
u could simply use tags or layers as well if it was the case of an indoor space or walkin on meshs vs the terrain
Or a script that you have an enum attached to and just change based on that (get component rather than compare tag)
get component is more expensive
How often do you plan on doing it is the question
I’m hoping, with Procedural Terrain Painter, there’s some way to access the value at some xz location
Might not be idk how that thing works
aren't we talking about footstep sounds? that would be pretty often
Probably not too bad every 5 frames
Raycasting and checking a layer would be the better option . . .
Nobody will complain if the sound switch is a few frames late
(Sometimes the update will coincide and be on time too)
well all you need is the texture if doing what cattywampus and passerby said
Could just have the vectors plotted out stating that between xy and xy is this sound, etc
or wait no Coroutine method would always wait exact same # of frames
a coroutine waits a certain amount of frames if you code it to do that. the same way you could do that in update or code it properly to use real time
Oh, yeah. So it could line up with when person changes material they’re on
yield null does
its 1 frame you loop
but now are tieing stuff to exact frame rate which is not great
Yeah im saying, something that for happens “exactly every 5 frames” - it would only be 5 frames late at the most & can other times be only 1 frame late etc
I can feel in Dead Cells that they do that for the flying eyeball monster. It looks laggy compared to other monsters
Do you recommend a different way of load balancing?
you frame count in update or yield n frames
pretty standard stuff
Surely 1 of those is better than the other
does not matter
Ah, another “0% FPS gained”
if its continous i would lean towards just a update method and counting frames
don't over think things
AI is completely frickin useless for unity coding, holy cow
To put simply.. it's not there to do your job, it's there to help a little bit
then don't use it
public class HoverDetector2D : MonoBehaviour
{
public bool isHovering = false;
private void OnMouseEnter()
{
isHovering = true;
Debug.Log("Cursor Entering " + name);
}
private void OnMouseExit()
{
isHovering = false;
Debug.Log("Cursor Exiting " + name);
}
}
it doesnt even tell me whats wrong with the script, nothing it does works
Unity have plans for it, all that can be said
are you using the new input system or are you using the old input manager (Input class) for input?
because its a glorified chat bot, if doesn't know shit
You don't get your mouse input data?
you're using the old input system methods
because context of if that would work or not is based on how unity is setup and what other things are going on
we were not over this like an hour ago
#💻┃code-beginner message