Anyone here actually understand projection matrices? The net only seems to have info about the "default" values.
Tweaking with the variables by hand I can get translation, aspect ratio and a bunch of other random deformations, but what I need is to be able to change perspective/scaling to make it look like the scene changed scale - and I can't find what formula I need to apply to the matrix for that effect.
#archived-code-advanced
1 messages · Page 78 of 1
Can you not use Matrix4x4.Perspective ?
Hello all. Any method to execute Update method when my iPhone or Android turn to background mode?
Look into the documentation of the device you want to do that.
You mean iOS docs or Android Docs, not unity docs?
Both
Both? iOS and Android?
Both, Unity with Android and Unity with IOS from the Android Docs and iOS doc.
Also, the library probably have some example inside it.
Never developped on mobile, but Switch, Xbox and PS works that way.
So, I expect the same procedure.
You mean, it is possible to execute in the background mode when you develop on Xbox and PS?
This not what I mean. I mean that documentation is with the platform specific documentation and not with Unity.
Also, I'm not exactly sure or not it is possible to execute code in background. However in both platform there is event that are being trigger whenever the console is suspended.
what does represent console you said? Unity?
There is event that are being trigger by the library of the console. (Xbox, PS)
Both are widly different
Ah, I see Thank you guys
I tried, but it only take parameters for "normal" perspective. There is nothing to change how scale is handled.
Perspective does not handle scale.
Also, I expect that you would need to scale colliders and other things as well. Not just the mesh
It turn a 3D point into a 2D point depending on distance. My guess is that there must some maths that allow to display the results as if the scene has been scaled up/down.
And no, I specificly don't want to scale the actual scene - that's what I'm doing right now and it's an absolute mess, if only because it prevent any mesh from being static, break all light probes and anything distance-based (light source, among other things).
That's why I'm trying to keep the scene as is, but deform what's rendered instead.
In truth, what you want is add an other matrices to define the position of the vertices for that you would need to write a shader.
It might be possible to concat both matrices in one, however I wouldnt do that as other shader might needs the perspective matrix as is.
weird question
but is it possible to open a native linux terminal because I wanna debug log a huge array, doing so in unity just halts the application
Why would you want to do that ?
I'm not sure what is link between a linux terminal and debuging unity
how would the native linux terminal help?
how about writing the data to a file?
I will still be able to scroll once unity halts
on linux
I donno if vscode supports debugging unity c# scripts
VSCode is trash for Unity and its debugger is not supported
Rider works
but yeah I'd just write the array to a file
i don't see how printing it to stdout would be better than that
I have native linux only plugin, so using windows is out of question for me
like I said, the terminal is its own process, and Ill still be able to scroll up once unity halts
ahh I assumed you suggested visual studios which is windows only I belive ?
right as would be any application you use to read a file
you can even read the file in a terminal if you so pleased
oh yeah, I can probably just write to a file
for this bit of code im getting an error that i am not sure how to fix:
if (info.Offsets(out var offset))
{
using (var data = info.MeshData)
{
Mesh.MeshData d = data[0];
var verts = d.GetVertexData<float3>();
//job
verts.Translate(offset);
verts.Dispose();
Mesh mesh = new();
Mesh.ApplyAndDisposeWritableMeshData(data, mesh);
combineInstances.Add(new() { mesh = mesh });
}
}
Error: ObjectDisposedException: The UNKNOWN_OBJECT_TYPE has been deallocated, it is not allowed to access it
it doesn't take me to a specific line either
just to the find curly brace
i put dipose last and it still gives the same error
could be
out var offset
and
verts.Translate(offset);
verts.Dispose();
if Translate does not copy offset then the dispose also disposes offset which when it goes out of scope would cause the error
it seems im not meant to dispose at all unity's example doesn't
i hate this new mesh api
In netcode for game objects in a client authoritative model does the server still have permission to move the client as well? or is it now locked to the client moving themselves
The server still should have permission to move the player’s game object. If you’re doing client authority only you’re going to have a bad time when someone hacks their client to move faster or teleport.
thats only if its intended to be a game between random people, client authority has its uses otherwise
this is more #archived-networking related, though to answer quickly if you're using a client network transform then only the client can update it. the server could still send an rpc if you want
i created my own version of the network transform script, and i am using a server authoritative model anyway was mostly just curious if the server still had the ability to move each client even on a client authoritative model
i appreciate the responses btw!
Hey yall, for the past month ive been trying to figure out how to make a modular ability system. Every now and then on the asset store I see people using advanced dropdowns in order to add to a list of functions and edit their parameters in the editor. I've been trying to reverse engineer that sort of functionality to no avail so I just wanted to ask if anyone knows what they're doing or if I'm even in the right ballpark. I can send screenshots of what I mean if nessessary.
Your question seems like you’re looking for an actual editor? If so check out odin.
Regardless, I use it for almost every project.
Share a screenshot.
But if I get you correctly, it's probably a combination of custom editor/inspector and reflection.
It doesn't solve what part? Your question reads as though you're looking for a inspector creator of abilities.
the ones I see look like this
This would be trivial for odin to do, why can't you use it?
can you expand on what parts of odin I can look into to make it? Bc when I went through the documentation and experimented myself I couldnt do it
I did only just recently buy it so Im kinda new to it
Yep, what I said previously.
The "requirements" and the other addable "components" are probably a subset of classes that is retrieved with reflection, then it's just a matter of using their names in a custom editor.
You would set up the inspector how you want, the. Just serialize to whatever data you want then have your base (abilities class)
Odin would serve as the reference hookup and handler of your abilities.
While reflection in this case would be okay, I wouldn't reccomend making a complex system, all of these can just follow a basic ability structure that is in text / ID format.
Any project my team and I have done reflection with cost us more time than just hardcoding references.
How would I go about serializing multiple classes under one list?
[SerializeField] private List<MonoBehaviour> monoBehaviours;
?
I imagine that's not what they want.
yea i meant like muliple classes like the screenshot I sent earlier
I'm not sure about doing it with Odin(if it's even possible), but it's definitely possible with reflection. Although, you don't serialize the classes there. The list would be just a list of strings mapped to each type in your editor script.
you can use odin and [SerializeReference] to do something like this, odin will handle displaying, instantiating and editing different types
💀
Well it’s basically saving your qualified typename as string
So you break everything if you rename 😄
At least you can use UnityEngine.Scripting.APIUpdating.MovedFromAttribute for stuff at the namespace/assembly level
Yeah but that attribute is horrible 😭
I guess you can put that and re-serialize everything then remove it
Still horrible workflow
I tend to use Rider's find and replace most of the time
That’s probably better
Hello guys, I need you help resolving this error. I updated Unity from 2022.3.7f1 to 2022.3.8f1 today. Now I am receiving this error? Does anyone know how to resolve this?
upgrade all your packages and delete your libary folder
Thanks I'll give it a try.
it didn't work.
Check the source code. What member is undefined? Google it to see what package it belongs to and make sure you have the correct package/version installed.
Can I develop iOS app with writing native code even though I develop Unity app?
You could probably have some sort of native iOS wrapper to interact with what you develop with Unity, I know it was a thing with Flutter
I have two cubes one on top of another , i want the cube thats below to change color as the top cube moves over it , which approach should i use
You mean I must move to Flutter to develop my app?
or you mean native-plugin in Unity?
That would probably be easier yeah
I don't know about that but you can't code Swift in Unity afaik
nvm
Medium
This is a follow up on my previous article about implementing CoreML in Unity together with ARKit.
Thanks, I think this is a best and simple tutorial at a glance
If FixedUpdate() takes 3000 ms to compute, the engine would still batch FixedUpdate calls in a futile attempt to stay consistent with Time.fixedDeltaTime value? In my tests Unity produces around 16 FixedUpdates per 1 Update at this load. And I don't understand why it's not 1:1 since the computational time exceed both deltas.
How Unity handles FixedUpdate() once it exceeds Time.fixedDeltaTime to execute?
Lots of details on this here:
https://docs.unity3d.com/Manual/TimeFrameManagement.html
Long story short - there's a maximum limit of how much time it will spend trying to catch up and it will slow down the physics simulation when that happens to compensate (by doing fewer FixedUpdates than the actual elapsed time calls for)
https://docs.unity3d.com/ScriptReference/Time-maximumDeltaTime.html
In another words Unity promises Time.maximumDeltaTime / Time.fixedDeltaTime number of FixedUpdate() calls before calling Update() even once and showing anything to the user. That's unintuitive, but helpfull! Now I understand why some developers use Update() to read physics data from the environment.
FixedUpdate is guaranteed to run at the cadence of the physics simulation, there's generally little reason to use Update to read physics data since physics data won't change at that cadence (unless you change it yourself in Update)
Unity promises Time.maximumDeltaTime / Time.fixedDeltaTime number of FixedUpdate() calls before calling Update() even once and showing anything to the user
There can be anywhere from 0 toTime.maximumDeltaTime / Time.fixedDeltaTimenumber of FixedUpdate calls in any given frame (per Update call)
Sorry, it was within the context of an absurd computational load within the FixedUpdate(). In my tests a number of FixedUpdate calls exactly matches this ratio per Update. But with no load it sure would be different.
yeah that's a maximum
most of the time the framerate is much higher than the physics framerate
so most frames have 0 FixedUpdates
My understanding is that calling a query like Physics.Raycast during Update() would reduce the load on FixedUpdate(). If a query doesn't result in a manipulation with physics objects, it will result in "better stuttering".
I often see a recommendations to do all physics-related calculations in FixedUpdate(). But as I've just experienced, with a heavy load on FixedUpdate() a user will see complete freezes between Updates(). With a heavy load on Update() there is just stuttering due to fast cycle through FixedUpdate() calls.
Hello 👋
We are working on a VR game and we are trying to see how we can customize the behaviour of IL2CPP compiler (clang as far as I know) to gain anything positive (frame rate, build size reduction etc.) on our debug/development builds.
In our build pipeline, we are passing the additional arguments by using this API: https://docs.unity3d.com/ScriptReference/PlayerSettings.SetAdditionalIl2CppArgs.html
I wonder if there is a list that tells every single argument that we can pass to the IL2CPP compiler during our builds. I've been looking around for a while but I didn't find anything.
Any helps is greatly appreciated.
Hey I see you were talking about SerializeReference.
So, basically, I just overused it in my project cause it makes a lot of stuff easy and fast to do.
BUT apparently, when you create an instance of one of those "reference" in an array, then remove it from the array, the reference still exist in the scene even though nothing access/use it. I check in the scene file, and there is, indeed, all my previous references scattered everywhere. Wtf should I do, is there a way to cleanup those instances?
Which Unity version are you using? I'm not seeing this on the latest 2021.3 LTS.
2022.3.4f1
You need to make your raycast in the FixedUpdate otherwise you might miss collision.
How?
I'm not sure how to explain.
If you do a raycast base on a position that is being update every frame, then you might miss your target.
Also, if your FixedUpdate happens more than your Update, you might want to reduce it to 30 frame per seconds instead of 50 frame.
And you can also manually simulate the update instead of using the fixedupdate.
With Physics.Simulate.
I wouldnt recommand doing that though.
Because if your FPS is too low, the whole game is going to be unstable.
Instead, you should focus effort in reducing the load of your game. Do not try to find work around.
You might be referring to an overpenetration that occurs once an object moves an unexpected amount of space during Update. Which implies that the movement isn't well calculated and framerate-dependent.
No, it can be frame-independent and it will still happens.
Now I'm curious.
Frame independent will just increase the distance base on the time that the frame took.
Meaning, that the object travel more distance (In 1 frame).
Isn't this also includes a precomputed distance during FixedUpdate(), so the system have to only interpolate object between predefined points?
If you want reliably detect collision, you need to do the raycast at every distance.
No idea what you are talking about.
What I've read about frame-independent movement so fare, is that it still kind frame-dependent due to the necessity of Update() calls. However, if a vector is calculated during FixedUpdate(), it then can be reliably lerped each Update() even if there are lag spikes.
If we take an absurd example
Given an object with a speed of 10m/s that is a position X
Frame 1 (Process the frame for 1 second): Obj at position X
-- Raycast from position X--
Frame 2: Obj at position X + 10m
--Raycast from position X + 10m--
If your target object is less than 10m in size, you gonna have a chance to miss it.
With FixedUpdate you have:
A raycast by FixedUpdate. If your FixedUpdate is 0.5s, then you gonna have a raycast from position Obj at position X + 5m and one from Obj at position X + 10m
You can still lerp in a frame in an independent manner in an Update though
Mathf.Lerp(a, b, 1 - Mathf.Exp(-lambda * dt))
In this function dt is still Time.deltaTime. If Update() takes 1500 ms (an extreme example), then on the next frame an object will leap forward to account for the lag, right?
In this particular example (Lerp), this is what you want. To be frame independent.
In the case of raycasting, you want to raycast precisely at each given time to reduce the change of missing your target due to the object being move a large distance.
Hey guys, for example I need to set a animator transition time, due to reconciling on a tick perfect, side predicted client. Have someone an idea how to do that?
I'm already syncing animation states and their normalized time from server to client. But when reconciling while a transition happens the transitions "restarts", so I need to set the normalized time in the transition itself.
You wouldn't you would just store the data and construct your classes with that data.
Do you really want to reconciliate the animation itself ? Pretty sure you usually don't. You just need to make sure that the state of the animator is correct, not the animation itself. I.E. You want the animator blend between the current state and the reconciliate state.
Also, pretty sure you do not want to sync animation between client and server. The animation should be pretty much only client side and the server should not even know there is an animator.
At least, as far as I know.
I'm not an expert in networking
We are currently working on a 100% predictable game. In our case the character meshes are only visuals for the client, but limbs have colliders on the server as well. Therefore it is urgent, that we can reconcile even animations.
In the meantime I found animator.Crossfade(...) what could hopefully help me out. But I'm still not confident about that.
You could only do the check in the server, no need to do collision check in the client.
In fact, you should reconcile that instead of the animation.
I understand what you want, but you don't always get what you want.
There's no way to get "Perfect" timing in networking, not only are you dealing with latency but you're also dealing with hardware. You also don't sync animations, you fire off an event that does the animation, you shouldn't be passing any other data over a network.
you can eliminate hardware by way of deterministic setup and you can also do lockstep to not worry about timing which RTS typically do
if you got run time procedural animations you would need to sync them
You do not need to sync animation. Animation are only aesthetic and having a difference between two client won't matter.
if its procedural you do because you will get drift issues
even more so if its related to user input tracking
You are talking about long running animation
im talking about procedural animations
That are procudural
duration not really relevant
no it doesnt if you want things in sync you will have to sync the animations
Short animation wont drift so far that it will start to matter
it will
You do not have to sync things that are only aesthetic.
thats like saying a small bit of drift in physics wont matter
not all animation is aesthetic
animation matters in fps if you want accurate hit boxes for example
Then your game is wrongly setup for a server experience
lol
You do it server side
not true at all but i cba to go into the complexity and nuances of it all
Why would you want hitbox client side.
Why you need to have hitbox client side.
🤦♂️
if they arent in sync your not seeing the player where they really are
which really matters in an fps
Hit box are not visible
the character's animation im talking about
you still need to sync the animatiosn to the hit boxes
thus animations need to be in sync
also some times the player hosts the fps game not all fps games need to be server side
First, you do not need hit box in client side in a server authorative.
Second, animation will not drift so far that it won't be reliable for the player.
You still do not need to sync animation
the server still needs to follow the animations from the client
The animator define the transition between animation
What animation you are doing procuderaly
That needs to be sync.
it depends on the game
It does not.
its not hard to understand it really depends on the game
Procudural Animation is not really popular.
that doesnt make my point any less valid
how popular something is . does not have any point in this topic
Fine, if you want to include useless information.
its not useless information they were asking about animation syncing
stop making an argument for no reason i have better things to do
Yes, it really matters. Because if you were doing long procedural animation I would agree.
That it can matter. But for short animation, either procedural or not.
It does not matter because the server is the autorithy and animation is purely aesthetic.
procedural animation needs to be in sync if you want two players to see the same thing
or they might see different results due to float differences on their pcs
this is also the case for physics
physics drifts are even more noticeable
Are you serious ? We are talking about network and you are saying that float will make a difference for small duration in animation.
no i said procedural
Sure, because they are cumulate.
christ almighty
I already said I agree on that
so why did you argue it then ?
Why are you still talking about long duration procedural animation
i never mentioned anything about long or short
i said procedural
i made no mention of duration
where in this sentence do i mention anything about how long they are?
anything run time you will need to sync they are not using the animator
Funny, I got the context and the meaning of the first sentence by the rest
animator is for pre-made animations
pre-made will have the data available for the clients
so its easier to sync
Yes, and this is what people are going to use for almost any situation.
procedural is done at run time so two clients might not be in sync. thus procedural animation needs to be sync
And in this situation, that even the original post was about, sync is not something you want to do.
ok but i gave example of when you would need to sync the animation
Where
That is not an example...
im not here to educate you on procedural animation youre derailing the room
Are you seriously saying go away...
if you dont know about run time procedrual stuff go read about it
you cant use them in the animator
You know, you can at anytime drop out.
im not here to give endless examples
this room is for answering people's issues on code - i corrected some one saying you dont need to sync animations - and that isn't always true by mentioning procedural animation
go google it if you want to know
Alright, lets keep it there.
good
Regardless if it's procedural or not, you shouldn't be moving your character with procedural animations for a networked game, this is basic networking 101.
not all animation relates to a character
the case was me stateing you never need to sync animations
I said you shouldn't
because someone said that which isn't true
You need to learn to read.
You seem to have a issue both reading and injecting your own arguments.
You also don't sync animations,
was what you said
there are situations where you do
In extreamly rare cases.
You should not be controlling your character through procedural animation in a multiplayer game.
so ? i still made the statement of when there is times to sync animation so i can read but thanks for your snarky comment all the same
not true
You can sync animations, you don't control movement (Talking about drift eariler).
VR games need to track player inputs, facial mapping stuff, eye trackers
You're just backpeddling now.
non of this can be done in the animator because its run time animations
You do not control your character through that. You sync the positions.
im not back tracking i gave an example of where you do need to sync animations
thats still syncing the animation
VR is not animations 😄
🤦♂️
It's transforms.
if it moves its animation
Yes, I feel the same.
Is this kid retarded
youre confusing animation clips with the general idea of animation
You're confusing VR transforms with animations. 👍🏿
i had no confusion with it when i had to do it for a VR project
so
¯_(ツ)_/¯
you do you
Your entire argument was about drift in player controls, you solve this by Not using animations to control synced clients
This is not a difficult thing to understand.
no my argument was there are situations where you need to sync animations i made no statement on player character
Now you're trying to argue about VR
i merely made a tidbit of info
What is drift to you?
drift is accumulation of differences between clients
physics is a good example of drift and you need to keep it in sync all the time
No one here ever said don't sync animations, 2 people have said don't control your character or VR or anything else with animations.
Yes by the client server.
you said "you dont sync animations" i merely replied saying sometimes you do
NOT each client like OP was mentioning.
he wanted 100% prediction so the client would have to do sync via determistic architecture
so the OP isn't wrong
I think you're misunderstanding syncing with actually passing data, you don't pass an animation over a network.
You call the animation and then update the transforms,
for animation clips sure just send when the animation was triggered etc
but im not talking about premade animations
This is what we're saying...
AND you shouldn't be controling the character with procedrual animations.
but he wanted a 100% prediction so he would need to use a setup where the clients keep themselves in sync
I want a 100% science based dragon MMO, am I going to get that? 😄
It is, just because he wants it doesn't mean he's going to oget it.
Prediction doesn't mean results mate.
unity guarenteed deterministic outcomes across architecture
there for he can
if you're not aware of this you should read up on it
You should read up on latency, I hear it's a bitch.
it was one of the hallmarks of why unity wants to offer "rewind" feature in networking
then you should hear how its dealt with since the days of age of empires
RTS games require deterministic networking or its impossible to sync so many units
it would be painful
the old school way was a fixed point numbers
but they hurt performance
That's not using your main argument of Procedrual animations that's using a set of events that are synced between clients. Our entire argument with you has been about that.
oh were going back to the old argument now?
thought we were on about his wish for 100% prediction
which argument are you trying to have with me here?
No, I need to get back to work, best of luck.
me too
a bit related to something i found on #1064581837055348857, but how many intergers can i fit inside 4096 bytes?
mainly cuz of this bit, this fixed list which has a memory allocation of 4096 bytes
i presume 1024 ints then ?
Int32 = 4 Bytes.
So, that would be 1024 if I am right.
wow
thats a shit ton lol
maybe 4096 is a bit overkill...? idk
with the naming you can probably deduce that this is for a navigation system with A* (not using unity's navmesh solution due to its limitations)
still, thanks, i'll keep the Interger == 4 Bytes bit in mind for the future
You might want to remember that 1 byte = 8 bits more.
Always get me.
likely
its rare that i have to deal with such low level stuff like this
if(nodeA.serializedPathNodeLinkIndices.Count >= 1024)
{
Debug.LogWarning($"PathNode of index {nodeAIndex} has reached it's max capacity of 1024 nodes, cannot add more links.");
continue;
}
i think this should do the trick unless i got the logic wrong, thanks guys
btw you can do this, without any special knowledge:
int sizeOfInt = sizeof(int);
int numberOfInts = 4096 / sizeOfInt;```
@white pulsar You can't store 1024 ints in FixedList4096Bytes<int>, because 4096 bytes is the size of the entire struct, which 2 of those bytes are already used by the struct presumably for its count.
Oh
Depends on what you need, UnsafeList<T> is an option as well.
Or make your own fixed size container.
Fixed-size buffers in structs
but not friendly, you cannot have other unmanaged struct type other than primitive type, though there is a way to solve this problem
Hi, someone knows that its possible to get the OS voice language in Unity? I was researching and I only found Application.systemLanguage, but that doesnt get the speech language. Thanks
any idea how this ambiguity might be caused?
Assets\Plugins\UnitySocketIO\WebSocketSharp\Net\WebSockets\TcpListenerWebSocketContext.cs(185,37): error CS0121: The call is ambiguous between the following methods or properties: 'WebSocketSharp.Ext.IsLocal(System.Net.IPAddress)' and 'WebSocketSharp.Ext.IsLocal(System.Net.IPAddress)'
there's no duplicate of that definition in my project folder
nevermind gave up
what does GCHandle.Alloc actually do in the background ?
Allocates a handle for the specified object.
``` from the docs
<https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.gchandle.alloc?view=net-7.0>
what does allocates a handle mean here ?
This handle type represents an opaque handle, meaning you cannot resolve the address of the pinned object through the handle. You can use this type to track an object and prevent its collection by the garbage collector. This enumeration member is useful when an unmanaged client holds the only reference, which is undetectable from the garbage collector, to a managed object.
It's a way to tell the GC to not collect a specific object until you tell it to
ahh the word alloc is missleading then
I thought I was doing unnecessary allocations
I'm attempting to use Timeline in a multi-scene context, where the Cinemachine Brain is on the main cam in a different scene than the Playable Director / timeline object.
This is challenging as Timeline doesn't seem to support multi-scene workflows.
Searchin the web for solutions I've come across this, but not being a pro-coder, I'm having a hard time actually getting the variables stored across scenes. I could really need some help.
how do I add source generators to existing unity project on linux?
ideally using roslyn
The asset you are linking does not seem to be what you want.
A quick search land me on: https://docs.unity3d.com/ScriptReference/ExposedReference_1.html
ExposedReference is a generic type that can be used to create references to Scene objects and **resolve their actual values at runtime **and by using a context object.
It does seem to be closer to what you need.
i think ive might have found a bug, i have this button that i use for interacting when im on mobile but of some reason it doesnt want to interact with one of the two gameobjects, so ive messed around for about 4 hours now and i found out that if i change the buttons transform in any way and then CTRL-Z (the important part i think), it makes it works but why? And how do i fix this so i dont have to press ctrl-z everytime i play the game?
no, yeah, I read that, but I am completely oblivious to how csprojs, solutions, nuget packages etc wok in unity. I tried creating project with dotnet new sln and dotnet new classlib and installing the Microsoft.CodeAnalysis in the Rider window, but it doens't do much. ISourceGenerator is not found, Generator attribute as well, I don't know how to do that
Are you writing your own source generator, or using one?
I want to write my own which finds classes annotated with my custom attribute and generate appropriate partials
I don't use Rider so not sure about them, but I've heard their UI is practically the same as VS's.
And I assume by adding the package Rider should do restore for you automatically.
What does your csproj look like?
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<!-- https://stackoverflow.com/questions/46621164/how-do-i-target-net-standard-2-0-in-a-freshly-created-net-core-2-0-web-app -->
<TargetFramework>netstandard2.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
also this is inside my <unity project root>/Packages/<my package root>/SourceGen
because I am writing a package
Well you haven't added the code analysis package.
oh, I assumed they are added somewhere in the obj directory in one of the *.nuget.* files
make sure your analyzer's source files aren't being included in your unity project, i think you just want to compile the dll separately in rider and drop that into your project?
to make it work, you need to give the dll the RoslynAnalyzer tag in unity, so it knows to use it
asset label I think it is called
actually what I want is add the support for that in the output package, so that someone using the package can extend with his own classes, annotate them, and the source generation will kick off
but that may come later, for now I need source code generation for myself
i got it going last week. it is suck
i basically apply the asset label whenever I want to turn it on/off
and I need to manually drag the DLL every time I edit the source generator
does csproj detect transitive dependencies or something? for example if Microsoft.CodeAnalysis.CSharp depends on Microsoft.CodeAnalysis.Common will the CSharp only definition in csproj work?
because mac VS lacks the batch build feature
Why do you need to turn off SG though?
because I don’t want it running all the time because it generates files
if you add the nuget package you get the dependencies installed too
It doesn't generate files, they should all be in memory.
it makes a filename based on attribute, so if I type [Make(“myclass”)], it generates a file for m, my, myc, mycl, mycla, myclas, and myclass. All because I’m typing lol
i’m having it make a file.
anyway, it’s a minor inconvenience, and my SG isn’t worth the time I used to make it tbh
If you want to generate file rather than in memory source, imo you are using the wrong tool for the job.
probably
That sounds more like a build step.
i do have a big issue that will take time to explain, that I desperately need help with
do you have time?
i think you might be the only one who can help
I highly doubt that, but you should write it out anyways so everyone in the chat can potentially help.
I’m trying to figure out my electrical grid, and I’m really stuck. I need help.
-General Graph: I have a directed graph of vertices on a 2D grid, where wires/electrical sources/etc define the connectivity. Vertices are like mini directed subgraphs, where a vertex can (for example) pass electricity from up to down, and left to right (i call this subgraph a pass-profile). Edges occur at adjacent vertices that allow connections (ie if V1 allows elec out going up, and above it is V2 which allows elec in from down, then V1->V2 is an edge).
-Flow of electricity: Vertices are either sources (send out signal, and depend on nothing), conductor (move signal from one vertex to next, or receiver (a conductor whose pass-profile depends on how it is electrified). Every source vertex has an ID, and every vertex keeps tabs of which sourceIDs are activating it (and from which direction) (eg a wire knows it is electrified from above by source1&3, and from left by source 1&5). To electrify, I do a DFS from a source, find all vertices connected and directions they were reached, and update their contents.
-My issue: I am struggling with receivers (pass profile changes depending on how they are electrified). What I have been trying to do is: when a receiver is going to change its pass-profile, send out a negative signal to turn off everything it can reach, change the pass profile, then send out a new positive signal. The issue is that I run into loops and vertices where you reach them from a different direction (ie direction from source ≠ direction from the changing receiver). This makes it hard to update everything in a way that is correct. Can someone help me?
I'm guessing your problem involves loops in the graph?
it’s a couple of things, really
i can fix loops, but fixing loops means I unfix branches upstream of the receiver
and the presence of diodes in the graph makes some things screwey when I have loops
Oh wait, it was you who I gave the semilattice explanation last time.
yes
what I could probably recommend you is take a bite at this problem from a more physically-correct standpoint, where energy flow is an implicit function of voltage potential. You would flood-fill potential for vertices, consume the potential for receivers and then see if electricity flows (and in which direction).
I thought it was someone else and was just about to refer you to that conversation 😅
lol
i figured out how to block infinite loops
i think
i refactored dramatically, but I’m still stuggling
i thought about that, but I don’t want wacky jank related to not going far enough
if I put something with logic, I want that logic to be preserved. I do not want it to also depend on how far you are
it’s a maker style game, and I want to minimize the headaches for someone trying to use the thing which is my core mechanic
which is already pretty complex
wdym by "not going far enough"
if signal intensity drops off with distance, then the logic of the circuit depends on how far the connections are
like minecraft
unless you use repeaters, which I always hated as a system
levels in my game should be finite, and evaluating the circuit on one frame should be doable
if i’m understanding you correctly
but maybe i should be storing distance to each vertex direction from the source?
... you don't have to add the drop-off distance then, no? :|
it wouldn’t be a drop-off, but to measure distance via BFS
which is a more complex data structure. But I could do it if it would fix my problem
BFS and DFS are both very simple, DFS keeps it's data implicitly on the function execution stack, BFS explicitly on the manually created stack in the function body. In terms of performance and reliability you could even say BFS is safer because it doesn't get impacted by the maximal call stack depth that DFS does. What I mean by flood fill is: you have (probably) some sources (they are like batteries), connectors (liek diodes) and receivers (any component converting electricity into work). Image below is a mental model of that. I suggest you thinking about this model because It may simplify some of your work.
Trying to cache my Transform component why doesnt this work tho?
because you update the cached transform's position
Transforms are reference types (like all classes in C#)
you have two references to the same Transform
what is not work? its behavior same as my expectation...
you should restrict the T parameter, it should be unmanaged
If you use google translate for JAP -> ENG better use https://www.deepl.com/translator
i think i have an idea
- give all sources & receivers a serial #.
- When source turns on, DFS from source (stopping at any receivers), and give them its source ID from those directions reached.
- For each receiver reached, receiver reads its current source state, and decides if it should send an activating/deactivating signal for its own id and in which directions.
this way a vertex knows if it is only being turned on by a given receiver and/or a given source?
well i should say i make a backup from my Transform right
then i dont set the position of my cached transform but i set position of the transform.
so my cached transform is still the same right because its a backup from before the operation
i think this might work, but i need to think thru counterexamples before coding more lol
It's not a backup. It's a reference to an existing object. You don't clone the objects. If you want to clone, you have to do it explicitly. You just make a new variable that points to an exiting thing
maybe you didn't quite cach the difference between value and reference types
so its like a pointer
?
you just create a new reference to an existing instance
how to unpointer it than?
yeas, like a pointer (under the hood, managed by the language)
is there a way tho?
is there a straightforward way to make a ulong 128 bits? or related
fixed size buffer in struct
you must copy/clone the values one by one
what file do I download for an updated gradle? binary or complete?
like a struct for a 128bit integer?
Vector3 is a struct (i.e. value) type so you should be able to just write val cachedPos = transform.pos and it will create new vector with the old values
try binary only. Complete may include things like zip with documentation etc.
yeah thats indeed a way but stupid tho thought i was really smart
what you want is not caching, it is deep coping an instance
The binary will contain the .jar file?
possibly, idk, I always did my gradle setup with IDE :P
(so I never bothered with installing it manually)
I only have to due to lightship ardk
@cerulean wasp What are some example circuits that you have trouble with?
Not in Unity ™️
.NET 7 has UInt128
back to my problem with source generators - I so I can't add a source generation project to my package? I have to create another project and only use buit DLL?
well, that's what the unity doc page recommends
because ideally I would want this to be somehow available in the same repository
you would probably have a problem with this step:
Create and assign a new label called RoslynAnalyzer. To do this, enter “RoslynAnalyzer” into the text input window in the Asset Labels sub-menu. This label must match exactly and is case sensitive. After you create the label for the first analyzer, The label appears in the Asset Labels sub-menu. You can click on the name of the label in the menu to assign it to other analyzers.
because you wouldn't have a plugin dll to do this with
is there a way then to add a subproject to my package in the /Packages/, make unity build the dll and assign the tag then? (automatically maybe, or if the subproject changes, the dll is regenerated but tag remains)
i don't think there's a built-in way, but it's probably possible to set it up with enough scripts - you could keep the source in a hidden folder of the package and write your own script to invoke the build system
hmm, I am starting to wonder if I didn't fall into an XY-problem trap
rather than needing to recompile it all the time can you feed it a config file or something simpler?
because what I ideally want is:
- add atribute to my, or possibly user-defined files
- generate partial classes for those annotated files (with appropriate setters and constructors)
Do you need to modify the generation logic?
I don't think I need to recompile the generators often (if any)
it's just weird for me to think about what is essentially a part of this package (generators) as separate project
Oh that's what you are hung up on.
I'd just ship the dll (and optionally the source of the SG project) and call it a day.
main issues look like loops with diodes going into them, and branches both up and downstream, surrounded by diodes.
i think i figured something out again. can’t wait to see how wrong I am.
Can you show the circuit?
these are the two main test circuits i am up against
in a square with an arrow means transistor, where connectivity (perpendicular) is turned off if it’s arrow port is active.
number in square = source
arrowheads outside boxes are diodes
top circuit tests that the algorithm doesn’t get stuck in infinite loops. Bottom circuit tests that what something sends out is properly updating things
Did you take into accounts oscilators? Is your divagation about things not looping essentialy a way of preventing oscilations?
i need it to halt
player will be fucking around with it. you can’t have the game hit an infinite loop, because if I try to evaluate it all in one frame, then the game will freeze.
because there is no out
how does the source marked with I work in your case, in which direction does it give the power
it gives source outward in any direction it is connected to
it does all one DFS. So if 1 is connected to up and left, then it sends a signal of 1-ON to anything it can reach from up or left
so in the top circuit you basically have the oscilator if both left arrows (I guess inputs?) are off, right?
tfu
if both left arrows are off, then it should just let electricity thru
when someone powers any of the left transistors, then it oscillates
stable in that tick
yes
next tick, it will not change without something externally changing it
you’d need to bring in another source
and if that source is clicked, it need to do its thing and finish.
into a new config
and halt
you know that the DFS approach makes it nondeterministic when you want to simlaute electricity flow with the DFS, right? Depending on which branch is taken first the result will differ
well, I’m checking for that
rarher, on paper, making sure that the algorithm ends on same spot regardless
i might be able to block off infinite loops at the start of the level, before anything evaluates
what is your intent for a player experience when he encounters infinite loop?
the general rule is; if there is any path that can forseeably cause an infinite loop, that transistor allows electricity in, and never spits anything out
it becomes a dud
this also blocks circuits where what it does makes no logical sense
hmm, maybe start a thread for that, because it seems like it's becoming a lengthy discussion
i forsee players wanting to primarily use circuits with more sensical inputs. like turn 1 on to open a door, then turn 2 on to block 1’s signal so the door closes…
But it’s basically expected that players will do stupid shit
i think I have a lead for now. i just hope this works.
my lead is something closer to BFS
so, let me get this straight, you want players to be able to play with it, but don't have too much freedom and let loose their creativity? doesn't it sound restrictive to you?
seems like a bunch of unnecessary restricions
creativity, but if the circuit does something that no one can predict, that isn’t helpful to anyone
(Use semilattice 😄)
there will be other parts that send signals at given times
like one piece that sets a delay before turning on. and another that sets a delay before turning off…
the logic just needs to clearly flow without infinite loops
that depends on how you create your rules. If your rules are atomic and predictable, then everytihng else is predictable as well. For example I think about is makeing 2 phases of calculations: one is propagating potential, another is making components react to the potential changes. This sounds deterministic and possibly simple to do, because in phase 1 only potential propagates acoording to already set component state, while in phase to only components state changes without affecting potential flow, so everything can happen simultanously.
becasue your infinite loops checking, DFS etc. seem like a complicated set of hidden rules that massively add to programming complexity
and add a bunch of edge cases
my current plan is:
- DFS from source to all receivers.
- Add each receiver to a queue (unless it fails a dependency check).
- while queue not empty:
—DFS from frontmost receiver to send out its receiver ID (depending on its previous and current electrical state). Stop at any receivers.
—For each receiver found, if receiver is not in queue, and receiver passes dependency check, then add it to the end of the queue.
Done
if I do a dependency check, then I can also telegraph it by drawing something on screen to show that a given tile is not functional
you should first discover it by doing the logical thing of seeing “i wonder what happens if I try to make an infinite loop”
has anyone experienced this error with astar? NullReferenceException: Object reference not set to an instance of an object
Pathfinding.EditorBase.OnInspectorGUI () (at Assets/AstarPathfindingProject/PackageTools/Editor/EditorBase.cs:104)
UnityEditor.UIElements.InspectorElement+<>c__DisplayClass72_0.<CreateInspectorElementUsingIMGUI>b__0 () (at <da771086bc2e4cfc9ad0a72e083a7f98>:0)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)
hmm, I created new C# library project and it can't find ISyntaxContextReceiver
the ISourceGenerator is available though
hmm, the Microsoft.CodeAnalysis version 3.8.0 doesn't have it and I don't know what it has instead of that. However installing Microsoft.CodeAnalysis.Common in 3.9.0 makes it available
i needed to grab multiple nuget packages to make a source generator
i saw one tutorial on youtube that helped tremendously
and so many which were 100% useless.
the good tutorial was like an hour long
Introduction to C# Source Generators, a comprehensive development guide covering the process of creating source generators in Visual Studio and Rider.
Patreon 🤝 https://www.patreon.com/raw_coding
Courses 📚 https://learning.raw-coding.dev
Shop 🛒 https://shop.raw-coding.dev
Discord 💬 https://discord.gg/xgNS26k
Twitter 📣 htt...
This was critical. Also I needed unity’s little tutorial to know how to enable a source generator in unity
me, honestly
the amount of shitty in quiality tutorials and docs is unbelivable
thanks a lot, maybe I'll try to purify it into TL;DR later and do a blog post of my own xd
from the amount of problems I encountered already I could have written hundreds of Medium posts already...
there’s just a lot that goes into it
yeah, the whole ecosystem is very complicated. For example compared to Java's gradle this it's like rocket science vs highschool math
you need to: set up packages, set up connection to unity, make new project, learn how to make the source generator AND syntax receiver, and learn how the syntax tree works to be able to pull info from it.
it’s not complicated. there’s just a bunch of shit you need to know before you can do anything
what is it about the first two steps, "Set up packages and set up connection to unity"?
and you get no validation if you’re doing it right until it’s almost entirely done
you need a bunch of packages to make a source generator. Like code analysis and a few others. and they need to be the right versions for unity compatibility
and you need to know how to make unity actually use the source generator
again: you have no idea if you fucked up until you are very deep in. takes a while
Install the Microsoft.CodeAnalysis NuGet package. Your source generator must use Microsoft.CodeAnalysis 3.8 to work with Unity.
yeah, but then this dude: https://medium.com/@EnescanBektas/using-source-generators-in-the-unity-game-engine-140ff0cd0dc
writes syntax generators for unity that supposedly work and uses some subpackages with different version
They are using 3.8 though
Well, for reference here's what one of my SG's .csproj looks like:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.8.0" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
</Project>
any idea how to create multiple objects containing a material with a decal shader graph where each object has it's own texture ?
i don't really want to create multiple materials just to change the texture
my current solution: script that creates a mat and assigns a different texture per object
1 shared material with decal shader for multiple objects, but each object having it's own texture?
sounds simlpe — expose a texture via property in a shader and pass it in the script for each object / assign in material overrides or something
take a look at material property blocks
Current State I’m going to go off a basic unlit shader in this tutorial. In all tutorials since that one we always set the properties at a “per material” basis. This allows us to do everything we ever need to do in theory, but depending on the circumstances it might also force us to use tons of different materials. This not only makes a scene ha...
and check official documentation
it may be required to do something like that:
Properties{
[PerRendererData] _Color ("Color", Color) = (0, 0, 0, 1)
}
and if you use shadergraph, they should have this as a toggle on property
ah soryy, that is legacy, you should be able to make it work without it
Hmm, I don't know, you will have to check. Sorrym I missed that part in your question.
yeah without a renderer i can not set a property block i guess
what about the DecalRenderer component?
`using UnityEditor;
namespace UnityEngine.Rendering.Universal
{
[AddComponentMenu("Rendering/URP Decal Projector")]
[CanEditMultipleObjects]
[ExecuteAlways]
public class DecalProjector : MonoBehaviour
{
public DecalProjector();
public Material material { get; set; }
public float drawDistance { get; set; }
public float fadeScale { get; set; }
public float startAngleFade { get; set; }
public float endAngleFade { get; set; }
public Vector2 uvScale { get; set; }
public Vector2 uvBias { get; set; }
public DecalScaleMode scaleMode { get; set; }
public Vector3 pivot { get; set; }
public Vector3 size { get; set; }
public float fadeFactor { get; set; }
public bool IsValid();
}
}`
docs don't mention a DecalRenderer
Is Zenject deprecated (last commit 3 years ago)? Is there any other DI framework to use that is maintained? Or do you recommend against using it in Unity?
Ah sorry, I see there is Extenjecy fork. But last commit also 6 months ago
Maybe this will be enough https://moderncsharpinunity.github.io/post/dependency-injection-on-unity-part2/
Modern C# in Unity3D
This is the long-awaited continuation of my previous post about dependency injection.
VContainer: https://github.com/hadashiA/VContainer
Reflex: https://github.com/gustavopsantos/reflex/
I'm injecting pretty much all dependencies, but the amount of times I needed to setup something complex and couldn't use Unity's DI (inspector serialized values) ended up being very few in most projects, so I felt having some glue scripts around for those cases didn't seem like a heavy burden. Having code that is walking through larger hierarchies just to pass in few references didn't feel super reasonable.
Yeah I’ve been using my very minimal implementation so I won’t need big maintenance 😄
https://github.com/cathei/PinInject
my method works. it finally works
ty for all the help @hardy jacinth and @scenic forge
even though I didn’t use a lot of those ideas, it was something tooster said at the end that gave me the idea that worked. And burrito helped a lot earlier on. big thx
oh hey @hushed fable didn't realise you were on this server
So I'm trying to work with Unity's IAP package. Is there a reason to not generate products individually? It seems you're supposed to upload multiple at a time in batches.
I have to deal with some code someone else made that involves adding individual products, and I'm figuring out if I should try making it work or if I need to scrap it and figure out a system that uploads those individual products in a batch instead
Also, what happens if you try to generate a product that's already been generated? Does it override it or create a duplicate?
oh god what have I found...
if you use C# records, and by chance you have a cyclical reference, then everything crashes with stack overflow... because compiler generated toString and printMembers are recursively calling each other...
but the worst parts is that it crashes everything — any debugging session, whole editor etc...
and it's inherently a C#'s problem
Honestly this is understandable, what else would you expect from cyclic reference.
Crashing debugger part is not desirable though, that should be fixed.
I am fine with syntesizing methods that are recursive (although I find it weird), but the side effect of crashing debugger and crashing the editor is grossly unexpected. I assume some kind of exception should be thrown and error shown in the debugger.
Hi, is there any way or tool to analyze reserved native memory?
on addressables percentcompleted is only for downlaod content, not for load scene really?
Hi ! Since a SerializedProperty have hasMultipleDifferentValues, is there a way to access these multiple different values ? floatValue, intValue, etc will return a single value, so I'm assuming this is just a flag and I'd have to parse SerializedObject.targets to get individual values
You can assign them all at once by assigning the value, but yeah, you can't read all of them without getting the individual SerializedProperty of each one.
So the correct way to read each values would be something like this ?
foreach(var target in serializedObject.targetObjects)
{
SerializedProperty someFloatProperty = target.FindProperty("SomeFloatProperty");
Debug.Log(serializedProperty.floatValue);
}
As far as I know, yes. I don't see any methods in SerializedProperty to query the multiple different values.
OK, thanks. I didn't find anything in the documentation either, so I just wanted to be sure I wasn't missing something.
how do i combine meshes correctly?
public void CheckAndUpdateMesh(Block block)
{
float x = block.transform.position.x;
float z = block.transform.position.z;
MeshFilter meshFilter = block.GetComponent<MeshFilter>();
CombineInstance[] combine = new CombineInstance[4];
Vector2[][] cornerOffsets = {
new Vector2[] { new Vector2(1, 0), new Vector2(0, 1) }, // Top-Right
new Vector2[] { new Vector2(-1, 0), new Vector2(0, 1) }, // Top-Left
new Vector2[] { new Vector2(-1, 0), new Vector2(0, -1) }, // Bottom-Left
new Vector2[] { new Vector2(1, 0), new Vector2(0, -1) } // Bottom-Right
};
float[] baseRotationAngles = { 0.0f, 90.0f, 180.0f, 270.0f }; // One for each corner
for (int i = 0; i < 4; i++)
{
Vector2[] offsets = cornerOffsets[i];
Vector2 diagonalOffset = offsets[0] + offsets[1];
bool side1 = blockMap.ContainsKey(new Vector2(x + offsets[0].x, z + offsets[0].y));
bool side2 = blockMap.ContainsKey(new Vector2(x + offsets[1].x, z + offsets[1].y));
bool diag = blockMap.ContainsKey(new Vector2(x + diagonalOffset.x, z + diagonalOffset.y));
(string meshSource, float rotationAngle) = SelectMesh(block.item, side1, side2, diag);
Mesh cornerMesh = LoadBlockMesh(meshSource); // This will load the Mesh
float finalRotation = rotationAngle + baseRotationAngles[i] + block.rotation; // Combine with base rotation
combine[i].mesh = cornerMesh;
Matrix4x4 scaleMatrix = Matrix4x4.Scale(new Vector3(0.25f, 0.25f, 0.25f));
combine[i].transform = scaleMatrix * Matrix4x4.Translate(new Vector3(offsets[0].x * 0.25f, 0, offsets[1].y * 0.25f)) * Matrix4x4.Rotate(Quaternion.Euler(0, finalRotation, 0));
}
meshFilter.mesh = new Mesh();
meshFilter.mesh.CombineMeshes(combine, true, true);
}```
i have 4 meshes for each corner of a block - i choose them and then i want to combine to form a single mesh to then load the block
Just modify the vertices, normal and triangle array.
that doesnt say anything to me
i want to glue them together
4 glued meshes in center
If you do not know what is the triangle, vertices and normal array, you need to do some research.
i know what they are
Then, what you do not understand by combining those array ?
im working with Mesh cornerMesh
i dont know how meshes work under the hood wheres vertices and all that stuff
i just need to combine thats it
meshFilter.mesh.CombineMeshes(combine, true, true);
makes it weird
it should be full size
What do you mean full size ?
touching
Touching what ?
Then, combining mesh will not do anything here.
Combine mesh does not modify the result
They will still be 3 blocks, exactly how they are after you combine them.
Combine mesh simply merge mesh together to batch them for GPU performance.
it combines as if it squishes them all into one
It will not do that.
If you want to do that, you will need to do it manually.
Maybe there is a library for that, however I really doubt it.
In fact, you should read on Marching cubes.
It will still not merge them ?
Haven't made a video in a while. That's because this marching cubes algorithm took me awhile to unravel. Most of the work was in the 256 cube configurations and the isofaces it takes to build them. I figured them all out myself (even though there were probably daat available on internet somewhere). Oh well, learn the hard way, and I'll never f...
This gap will not disappear if you combine mesh together.
why not
Because, combining mesh does not change the data.
It simply combine them in 1 mesh
For performance reason
After positionning them, you will want to combine them though.
For performance reason
Static Bashing.
ok so you say the combining is literally just combination of meshes as one where it doesnt change anything
Exactly !
okay so then ill need to position them before combining
Yes
Does the image you're using have a transparent background?
It looks like the fake PNG you get on Google
Can you send it?
The background isn't transparent
Anyone have a png of a white arrow on a transparent background? I know it's weird I'm asking for one , like "Just make one in paint bro" but I updated my pc to windows 11 awhile ago and it's messed up all my pc apps.. like they are there but I cant use them. Trying to get windows 10 downloaded again
Thank you
TestClientRpc(new ClientRpcParams {Send = new ClientRpcParams{TargetClientIds = new List<ulong> {1}}}); why this error? Assets\NetworkFPSController.cs(37,74): error CS0117: 'ClientRpcParams' does not contain a definition for 'TargetClientIds'
Here is that void [ClientRpc] TestClientRpc(ClientRpcParams params){Debug.Log("testing client rpc");}
you would have to look at the definition of ClientRPCParams
seems clear there is no TargetClientIds field or property in that type
How to go to the definition?
look it up in the docs or just jump to the definition in your IDE
I use netcode for gameobjects and in documents that property exists
Servers can invoke a ClientRpc to execute on all clients.
Okay
I will check it👍
This looks different than your code:
ClientRpcParams clientRpcParams = new ClientRpcParams { Send = new ClientRpcSendParams { TargetClientIds = new ulong[]{clientId} } };
You wrote ClientRpcParams instead of ClientRpcSendParams
basic error
That's the issue probably
Thanks 🙏
Im so blind sometimes
i think i have to change the arquitecture of my game, im using a loading screen that loads scene addressables like main menu or gameplay, the problem is im loading these scenes are additive to be able to show a loading progress, this is working ok. the problem become when i load additive gameplay and some objects are instanced, and these objects move to root scene and not with the scene loaded additive, so when i move to main menu again, these objects instanced are alive in main menu
in summary, should i load gameplay as single or check when i instance any game object to move to correct scene?
When you instantiate an object it becomes part of the "active" scene. This is a thing you can control:
https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.SetActiveScene.html
https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.GetActiveScene.html
Nice!! Thanks for suggestions
Noun Project has the most diverse collection of free icons and stock photos. Download SVG and PNG. Over 5 million art-quality icons and free photos.
How do you link between collider and the component you want to get in raycaat hit.
I know several ways to handle it but would like to know your approach.
The script on that child with the Collider.
The script on the root and a general script on the child with collider to link it with root gameobject.
hit.Collider.GetComponent<ScriptA>()
hit.Collider. GetComponent<RootLink>().Find<ScriptA>()
My way is
First I check if RootLink exists on the Collider gameobject or not.
If it exists, find the script.
If it does not, try to get that component on the Collider gameobject itself
Another way is to find that script using GetComponentInParent
But I do not like it and it can cause some problems in specific situations
If there's a complex hierarchy on the object you hit the best bet is basically:
MainScript ms = hit.collider.GetComponentInParent<MainScript>();
ms.SomeFunction();```
let that script deal with the intricacies of its own hierarchy
that's not our concern
i have a script that make the gun rotate at your mouse and the shooting .But i want when i m walking right or left i can only shoot 180 degrees in my moving direction
ok
Yes but it can be buggy
how so?
It searches all parents until the scene root
I'm assuming this is some object like... an enemy or a bullet
Maybe that. Instanced go does not have it but the parent has.
why would there be an Enemy or Bullet script on anything up through the scene root except the object we care about
It returns the script but it is clear it is wrong
there's no bugginess, just use a component that clearly demarcates the root of the section of the hierarchy you care about.
Because of that, I prefer to find the root of the instanced go, and search downward on children not parents
the downward search part is definitely an antipattern
that requires your raycasting code to know way too much about the hierarchy of the object it's interacting with
Always that script is not specific like enemy or bullet!
Think about nested panels Ui
find the root of the instanced go
I agree with this part. Find that root and make sure it has some specific component that we care about
from there, just call a function on it
the script can manage its own hierarchy and deal with those details
Enforce a separation of concerns 🙏
Yes, it is clean, thanks
RootLink component keeps the root of the go. Assign it to collider go
also a boolean field to search on children or not.
Are you using the source generator in embedded package or in Assets folder?
and how it is in your case
because I made some source generator, put it in my Package directory but it's not working at all (no symbols are detected)
a while ago I managed to make it work for a bit (attribute generated by source generator was seen), but I moved something here and there and now it doesn't work (it worked on the stage where it was in the Assets folder)
omg why is it so hard, I don't friggin understand how to do it
both importing dlls to a package and making unity recognize my source generators...
I have a question for anyone with some experience using GeNa. I've spent a bunch of time trying to figure out a strange behavior that is preventing me from accomplishing a game mechanic. I am trying to create 200 x 200 terrain tiles with various configurations of GeNa created road pieces on them. I create the spline and then bake the mesh which adds it as a child to the terrain. The issue is when I reposition the terrain the road doesn't move equally with the terrain. It seems to move with a 50% offset. In other words, if I move the terrain 100px the road only moves 50px. I don't see any attached scripts on the road gameobjects that would apply this change so I am assuming there is still some relationship with the Gena Manager that is doing this? One solution might be to place the terrain and then reposition the road, but that seems like it shouldn't be necessary.
In fact, just now I deleted the GeNa spawn manager altogether and it is still doing it so there must be some other reason.
Ok I think i've narrowed it down to being the mesh renderer? I disable the mesh renderer and I can see that the mesh collider is still positioned correctly. Is it possible the mesh renderer material has an applied offset or something?
really hate the submesh setup in unity
theres no way to extrude along a spline with submeshes
In Assets.
Have you imported the SG dll into your project and given it the appropriate asset label?
is there a way to get the current frame being rendered to the viewport and project it to a texture
BUT just a single object from the frame is being projected to the texture with nothing but transparancy around it
like if an object was there and then suddenly it was a floating png
https://www.youtube.com/watch?v=8L98ODoZ0kE
like this effect but in real time
Yeah, render textures
Render only that object with a spearste camera to a render texture.
sick! thanks man!
wait, how do i make it so that camera only sees the object?
With layers. You can specify the layers that camera should render. Put the object on a separate layer.
a render layer?
or is it just called a layer
it is just called a layer, sorry
thanks!
Are you sure it's and advanced issue? Either way, share the code properly.
!code
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.
Sorry, and yeah it appears to be. It seems to be related to the networking im doing
Null reference exception is not advanced regardless of where it is thrown.
huh. Ok sorry, I'll move it to a better area then
And upload your code to paste site.
Hi ! A few weeks ago, somebody suggested to encapsulate the use of SerializedObject in a using, but is there a reason to this ? SerializedObject automatically calls Dispose() when destroyed so the risk of bad memory management is limited and, for example, if I create new SerializedObjects from serializedObject.targetObjects and wanted to cache them so that I don't have to make new instances on each OnInspectorGUI call, I wouldn't be able to respect the using scope. Is this suggestion a real/important one, in which case your insight is very welcome, or can I ignore it ?
hey. structure question.
how would you structure this data?
you have a non-runtime data that consists of general data as well as upgrades and some data related to formula for calculating certain values.
and then there's a runtime data that just has the final values
as you see, there are a lot of data overlap between the two
and as the DRY says, 'don't repeat yourself'
I can simplify those scripts in a smaller text format if that makes it easier to read
here:
public class NonRuntimeData : ScriptableObject {
public float health; // or 'healthBase'?
public float mana;
public float damage;
public GameObject prefab;
//...
public float level;
public float healthBonus;
public float manaBonus;
// ...
}
public class RuntimeData {
public float health;
public float mana;
public float damage;
public GameObject prefab;
// ...
}
declare a serializable struct outside these card?
that consists of the common variables? well that would just be the RuntimeData class
since nonRuntime contains runtime
You don’t have to dispose it, it’s one of those things Unity not following standard C# rule
i use struct because it can copy the value types, isolates the run time data from the initial value
from you runtime constructor i think you may prefer it....
So encapsulating a new SerializedObject() in a using is not mandatory ?
Not mandatory yeah
It's not. I tend to do it because if you make something disposable then that's what you're asking of me. It is using a destructor to do it... Which is generally not advised
gotcha, so like
class NonRuntimeData : ScriptableObject {
[SerializeField] Data data;
public float level;
public float healthBonus;
public float manaBonus;
//...
public Data Evaluate(/*...*/) {
Data d = default;
// evaluate d...
return d;
}
}
[Serializable] struct Data {
public float health;
public float mana;
public float damage;
public GameObject prefab;
// ...
}
right?
spotify link? did I see right 👀
I failed my copy paste T-T
I totally feel you
Isn’t level/exp runtime data?
So, ignoring Unity, in a plain C# context, would it be a bad practice to cache IDisposable ? Or is it I just have to make sure to call Dispose() when I release the cache ? Still learning about IDisposable, sorry if my question sounds dumb
ignore the names;
but generally, no, in this context, the level refers to the level of the card. in the game we don't show the level (just damage, hp, and things like that for now). if we had to show the level someday, I'll just add it to the runtime data
just keep the data that will different from initial value inside the struct, the prefabs may be the same all the time...
Not necessarily bad practice but you should call Dispose eventually (possibly by making containing object IDisposable as well). using is just syntax sugar.
it's not bad practice per se. but you'll be making it hard to use. if you use it, you gotta use it well
like unsafe territory
IDisposable implies that user controls release of the resource. But Unity.. doesn’t care lol
Putting Dispose() in a destroyer is not recommended ?
Depends, if it's unmanaged object you must
if it's a UnityEngine.Object then why not (edit: oh I thought u meant OnDestroy. but yeah finalizer is recommended for disposing stuff, if you're in control of the lifespan of your class )
OK. I'm more familiar with C++ when it comes to finalizer, so I wasn't aware it wasn't recommended in C# (mostly used C# in Unity until a few weeks ago, in a very basic way, but I'm trying to go past the Unity's way)
if I extract yet another class it'd be too much classes
If you want to be the C# standard then you can use Dispose pattern https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose
But Finalizer is not same as C++ dtor, just syntax looks similar, but it’s not RAII
gets called on GC collect I guess?
Yeah GC has to call it
definitely bad then...
Yeah, I looked for it after sending my message. GC stuff.
Well, I didn't consider it because I was focused on the reason why I should put SerializedObject in a using in the first place haha Now you helped me have a better grasp on it, yeah, I will probably make my class implement IDisposable
No idea what's going on when I copy my *.dll to my Packages/<packagename> directory:
Assembly 'Packages/me.tooster.sdf/SDF.SourceGen.dll' will not be loaded due to errors:
Unable to resolve reference 'Microsoft.CodeAnalysis'. Is the assembly missing or incompatible with the current platform?
Reference validation can be disabled in the Plugin Inspector.
Unable to resolve reference 'Microsoft.CodeAnalysis.CSharp'. Is the assembly missing or incompatible with the current platform?
Reference validation can be disabled in the Plugin Inspector.
Unable to resolve reference 'System.Collections.Immutable'. Is the assembly missing or incompatible with the current platform?
Reference validation can be disabled in the Plugin Inspector.
why it cannot be loaded?
for source gens (generally any roslyn analyzer) you need to follow a specific procedure: https://docs.unity3d.com/Manual/roslyn-analyzers.html
I've read this manual probably 3 times already, but it still doesn't want to work, or the instructions are too vague
did you get it to work inside Assets folder ?
you can also take reference from my package which is using source gens: https://github.com/somedeveloper00/SingletonScriptableObject
source gen proj at https://github.com/somedeveloper00/SingletonScritpableObjectSourceGen
once, but I don't know how, and after I moved some files around I broke it and now I don't know how to go back
Thanks, I'll take a look in a jiffy
ah yeah when you move that dll , you'd need to restart the Editor
I tried that, but there were some weird problems and it didn't work since then
for example when I moved the dll from Packages/ to Assets/ and restarted unity now, the unity prints error:
error CS0006: Metadata file 'Packages/SDF/SDF.SourceGen.dll' could not be found
l not contribute to the output and compilation errors may occur as a result. Exception was of type 'NullReferenceException' with message 'Object reference not set to an instance of an object.'
but now it at least detected the generated attribute from source generator
but still, even though Rider shows autocompletions and redirects me to generated source, unity says things like
Packages/SDF/<directory-with-assembly1>...: error CS0246: The type or namespace name 'SDF' could not be found (are you missing a using directive or an assembly reference?)
on a side note, whys your package name SDF? it should follow the giudeline "com.[developer name].[package name]"
also, for Unity to recognize your local package you need to have a certain file structure in your package folder. example being my package up there, make sure README and packages.json and LICENCE are there, and put everything you need to compile at either /Runtime folder or /Editor
otherwise Unity won't compile your local package properly
oh and make sure your analyzer is NOT inside any other assembly. or else it would just work with that assembly and not the main one (Assembly-CSharp)
(note that your /Runtime doesn't necessary need a separate assembly to work. it's for convenience only. you can, like me, make a sepaarte /Runtime/src/ for your package scripts with a separate assembly (preferably following the naming guidelines), and a /Runtime/sourcegen for your analyzer)
I think I misnamed it in the beginning and forgot about it, I'll check in a sec. Aside from that, I have things like READMe, package.json, an asmdef (but root namespace is empty, is that wrong?), As for the sourc egenerator in the assembly, I'll check in a second. So I should try putting the dll in the root of my package? Also, where do I put common code (for editor + runtime + tests + samples etc)
I'm gonna mention that the primary usecase for my package is the in-editor work, if that changes anything, and I currently don't have any runtime scripts (not even Runtime directory)
So I should try putting the dll in the root of my package?
no need. just make sure it's not under any folder with a assembly definition
Also, where do I put common code (for editor + runtime + tests + samples etc)
editor scripts go to /Editor folder, runtime scripts go to /Runtime, test scripts go to /Tests and samples will go to /Samples:
├───Runtime
├───Samples
└───Tests```
> I'm gonna mention that the primary usecase for my package is the in-editor work
so, if the analyzer is also an editor-only thing, then I would do it this way:
├───Editor
│ ├───sourcegen (all source gens)
│ └───src (all scripts, and the editor assembly definition)
├───Runtime
├───Samples
└───Tests
but feel free to use any structure you think is best for your project. as long as the source gen DLLs are not in any separate assembly, it'll be fine
- I updated my package to put the editor scripts inside the /Editor properly, so to follow the guidelines. you can check how that's implemented, the referencings and whatnot.
by common code I meant the code that can be used in both editor and runtime
that would be runtime code
if it goes to build, that is
if it doesn't go to build, it's editor
ok, so editor includes runtime, I thought they are completely separate
can I create sub-assemblies inside my Editor directory then?
sure, yeah, why not. editor usually can't function without the runtime, but runtime must be able to function without editor
i don't really know much about sub assemblies to be honest
don't know if Unity even supports them
have you guys ever had a situation where you preferred using an abstract class over an interface? So far to me seems like interface is superior since it can be modular instead of limited to one parent class inheritence
yes, when you stick to DRY principle and share data in one common class. There are pros and cons of both abstract classes and interfaces. For example a con of an interface is that you have to explicitly implement interface methods and properties in classes implementing it. You can resort to using default interface implementation, but then you can't use them directly on a type without casting to the interface first ((IInterface) obj).implDefaultMethod(), (contrary to how it works in Java, for example). You can't also restrict the construction of such types. But with abstract interfaces you can, for example, restrict constructor to protected, and require derived types to provide factory methods.
Abstract class would be able to hold actual data whereas interface would only request for implementation (both do this).
There are just things that from a design standpoint make more sense for one or the other at times
awesome thanks guys, sounds like one is explicit whereas the other is implicit being the main difference
well, saying that "the main difference" exists is most probably an understatement
imo the most common "main difference" mentioned is that interfaces should mostly be understood in a form of a contract that something fulfills (implementation agnostic), while abstract class includes implementation details
Interfaces can implement functions in c#, the difference I'm referring to with data is that an abstract class can hold actual variables.
Yeah I understood that
Inheritance models "A is B," composition models "A can B."
generally find composition the better approach as well, things are just easier to follow
People do say "composition over inheritance"
Unity's "using components to compose behavior" encourages composition as well.
yes, although that's a bit different than the original definition of composition in software development I believe
generally whatever makes you write less code 🤷 have it whatever name it has
yeah composition is not heavily defined, interfaces help alot with it though
but unity components are really no differnet then just having a class that has other classes as fields to add features instead of extending
just wish, when clicking and dragging into fields it could do it via interface type, like GetComponent does
Not just writing less code, maintaining that code as well
it helps more on the maintaining side
If later on "A is B" no longer holds true, it's going to be a painful experience refactoring it.
makes it way easier to rip things out when no longer fit for purpose
and can rewrite parts while effecting less of the codebase
though man wish C# had implicit interfaces
it really changes how you write things, since you start doing all interfaces on the consuming side as a well to state the dependencies of a method or object
Yes! The duck typing in Go for example is amazing
yeah that is what i am referring to
its like duck typing but still 100% statically typed
It would resolve the issue with Behavior, Collider, Renderer all having .enabled without being in the same inheritance chain for example
also makes it easier to mock things in tests
Structural typing 😄
and easier when you want to write something that can work with a existing thing or your own new type
TS has it as well and it's a joy to use.
since you just write a interface that has the method of the existing thing you care about and that is it
yeah never got too deep into TS, only used it for like 3 projects
most familar with this approach from Go
know a lot of people think its boring, but really like Go alot
Goroutines avoids the whole colored function problem that plagues languages that use C# style async/await.
If only Go had error bubbling like Zig/Rust so you don't need to write if (err != nil) everywhere...
well most people dont understand concurrency
or even what async/await is
since its async/await is just a way to hide the cocurrency from the user, so when they do hit a problem they dont understand why
but yes goroutines and channels are very nice
yeah the error handling is very verbose, but i do prefer it to what all the try/catch langauges do
not used enough Zig/Rust to give comment on how that
thought rust just did it through its enum union thing so Result<T>
You just need one experience of "welp this method is async now, I guess I need to refactor everything that calls it to be async, and then everything that calls those to be async, and then..."
When you write try x in Zig or x? in Rust, it's equivalent to compiler inserting a if (err != nil) return err for you.
so x being the returned error, or x being the thing you are calling?
or it being like the returned enum that could have some or error
Yeah that, any (result, err).
is there a good short hand for wrapping as well?
in Go i often add context to the errors as i return up
That I'm not too sure, but obviously you can always do your own manual check.
often ending doing like a return fmt.Errorf("My Own Error Message: %w", err)
prolly should just try it, but does zig have defer?
Not too sure what that is
can do something like
defer f.Close() for example
then that gets executed after the function returns
and it does not matter where the function returns
Oh yeah I think so, same keyword as well.
cool, yeah its useful when you error handling is more or less bailing early with a certain return type
guess used in similar ways to the finally in Java,C# etc
but function scoped
Or using.
less setup then using which is nice
since you just give it a statement to execute
but yeah similar idea to that or pythons with etc
Hey, is there a way to set offset of currently playing state?
this is get only. Without using Play() function?
if I use Play() function, why should I use parameters at all in animator... am a bit confused
I have many zombies in scene and everyone are in sync with animation when walking. I just want to randomize offset a bit to be different
can I set this somehow before transition?
from code to be randomized
you can't touch the transition settings at runtime outside of the editor unfortunately. As far as im aware from outside the state you can only really set the normalised time with Play.
Why don't/can't you use Play jsut to get them all started at an offset?
indeed 👍
CrossFade is also a option
another option is to use playables. doesn't have a proper editor though, but it's all editable from script
https://docs.unity3d.com/540/Documentation/Manual/Playables-Custom.html
this is way more modular than Mechanim's Animator
(Timeline uses this)
there has to be some custom visualization/editor repos out there too, for playables
Thank you for your answers!
I have really simple animator with just idle and move
with IsMoving parameter when zombie moves
I wanted to make it somehow randomize offset of move animation when zombies start moving around
And Playables are too low level for that
sounds like CrossFade would work for you then. its essentually you jsut making a manual transition, can you can specify the duration and offset etc.
CrossFade and Play yes but, this means I do not have to use parameters then?
CrossFade Does not need any transition in Animator yes to work?
yeah thats right
Very strange that I cannot use Parameters + Randomize offset at the same time?
not sure what your game is exactly. but unless your zombies are all playing red light green light they'll naturally desync themselves? So you might just need to initialise them at a random offset?
Ah nope. it is really simple. they just come to player
when they spawn they are in idle but when they start moving they are like soldiers
same animation, very synced.
I want somehow to randomize offset
and was interested if I could set _animator.SetBool("IsMoving", true); and after that set offset or something
so this means, I have to use just CrossFade with randomized offset... what if I just use CrossFade every time then
why do I need parameters, I have really simple fsm
what do you suggest?
Then just add a random before activating them ?
You could also have different "Alert" animation
Which take a different amount of time to be done
Thank you for suggestion very much! I will try that
you could also take a look at DoTween and see if that would fit your use case
DoTween for what
to blend 2 animations? Zombie Move and Zombie Idle?
I managed to solve it using Crossfade
ah sorry, I just skimmed through chat after seeing this
how do I add dll to a package?
I want it to be available for some assemblies in that package
but when I try to assign Assembly References (with Override References for assembly turned ON) there are only the unity dlls
@cloud crag I'm not sure if this is what you're looking for,
however! I thought I'd let you know that it is still an option.
you could use the https://docs.unity3d.com/ScriptReference/StateMachineBehaviour.OnStateEnter.html
method on an Animator State like so: https://docs.unity3d.com/ScriptReference/StateMachineBehaviour.html
then have a randomized delay before starting the Animation Clip...
essentially something like this: https://hastebin.com/share/asozonimap.csharp
keep in mind that it's not the best way to solve your problem... (it's wacky, but worky...)
Hello. I have a little mathematical question, based on that thread:
https://forum.unity.com/threads/what-is-dots-equivalent-of-unityengine-worldtoscreenpoint-which-takes-camera.1362358/
It is a DOTS thread, but there is nothing from DOTS there (except for float3, float4, float4x4 which are basically the analogs of Vector3 and so on - nothing difficult. And also there is a math.mul function which is just an overloaded function of matrix multiplication). In fact there is a code for manual WorldToScreenPoint()
So the question (attention to the screenshot): the first step of translating 3d point to the screen is to translate its global coordinates to coordinates based on the camera (so basis is camera`s direction vectors - right, up and backward. And a zero coordinate is the camera's position). And for translating to that basis we need to use an inverted matrix. But here is used something strange instead of that (transformationMatrix is not an inverted matrix, it is something different...). But at the same time code works good and without a mistake. So what is that mystical transformationMatrix and why does it works?
Hey everyone, I'm here looking for suggestions, I want to integrate AI into my FPS game, I want to create behaviors like patrol, attack, attack force, and alert state behaviors, but especially the behaviors I've been working on are cover behaviors. , and behavior of flanking the player, but I feel that everything has been getting more and more complicated for me, I want to know if you can recommend any asset from the Unity Asset Store that will help me with the basic behaviors but that will allow me to create my own advanced behaviors.
At the moment, the ones that I have seen that are closest to what I want are these two assets "Invector FSM AI Template" and "Behavior Designer - Behavior Trees for Everyone", if someone has used them and can tell me which of the two I want can help me meet my goal of advanced behaviors without using ML, or if you can recommend me a new one please.
Note, that you usually don't need a full-blown inverse matrix. In cases liek that you often want a change of basis matrix, simply. The inverse matrix hes very strong assumptions, for once that M*M^-1 = M^-1*M = Id. A simpler thing is a pseudo-inverse (if that's what it's called, I don't remember official name) matrix. For example it assures only one part of that equation, i.e. xAB = x, where A is a psuedo-inverse of B. In this case xBA =/= x, i.e. B would be right-hand pseudo-inverse (because only when multiplied on the right with A) it works "like" inverse. This case is similar, it uses a simpler matrix which accomplishes what is wanted without calculating full-on inverse, because it's used only on one side of the equation. Read more on https://en.wikipedia.org/wiki/Change_of_basis
In mathematics, an ordered basis of a vector space of finite dimension n allows representing uniquely any element of the vector space by a coordinate vector, which is a sequence of n scalars called coordinates. If two different bases are considered, the coordinate vector that represents a vector v on one basis is, in general, different from the ...
change of basis matrix is often simply created from the basis vectors by using them to construct row/column matrix (depends on definition of your vector, is it column or row)
this works because the new basis vectors are all orthogonal (so a new basis is just old basis + translation + rotation, without skew)
I believe the matrix in question I want is a half-inverse, because it only applies from one side
as for the concrete math behind it, you would have to draw the thing yourself and see whwat is multiplied by what
because most probably what the matrix in your screenshot does is calculate for each component in the vector a dot product between the vector in old basis and the column vector of a matrix, which describes the camera basis vector
there is a hidden *1 multiplication probably after in that equation, because one of those bases (target?) is already an orthonormal base (1,0,0 etc.)
As I understand it is, but column vector of a matrix doesn't describe the camera basis vector: the first column is for all x coordinates of basis vectors, then the second column is for all y coordinates of basis vectors, and the third column is for all z coordinates of basis vectors. So the rows are describing these vectors, not the columns
I feel that your explanation makes sense for me, but can you clarify a little: to what is that half-inverse matrix should be applied so it works? It should be a float4x4 matrix as well, if I am not mistaken
yeah, my mistake, they are row vectors
they are only used to change vector from one basis to another basis. They could be linked together with any other homogenous (? i.e translation + rotation?) in acombination with translation matrices to be used in pose matrices stacks
from the code you linked above, it looks like it's applied to "a point in a reference frame, where a camera is in the (0,0,0) but rotated in any way", this the camera basis vectors to form rows in the matrix
I propose you check it in 2D, see with yourself but follow the thinking path of "I have a vector U in world space and I want it in camera space — how do I do that?", where you invent what the matrix must look like. Starting thinking about it from the inverse/half-inverse matrix is like starting a proof from the end and trying to find a way to that solution.
Well, I am trying to proof that this matrix should be half inverted, but I have no succeed
So if it is half-inverted the equality from the first picture should be right ("r", "u" and "b" are the - camRight, camUp and -camForward. And so Rx is camRight.x and so on)
So the result of the multiplication is on the second picture - it is just a bunch of dots products between these vectors. (r,r) = (u,u) = (b,b) = 1 is true because camRight/Up/Forward are all normilized. But all other values are not guaranteed to be 0-es if I didn't mistake in my calculations. So because of that the equality from the first picture is not true and that matrix is not half-inversed
Can you please hint me where I am wrong in this proof?
Just in case - E is a matrix of identity
on the first picture you have essentially written M*transpose(M)=E (btw identity matrix is most commonly written as I or Id)
that's not the same as A*B=Id
https://www.geogebra.org/calculator/fkqbc3dy this is how I was thinking about it
intuitively it makes sense that this matrix is half-invertible, because it means "B is a change of basis matrix, when I multiply it by P I go to basis coordinates. So when I am in basis B, I just get old coordinate system as new basis and do the same"
I don't know how to understand the matrix transform intuitively geometrically
sorry for the quality, I am using mouse to draw xd
No sorries, you are doing very much for helping me understand this thing. Thanks a lot
I am trying now to understand all of this :)
no problem, the best thing is that I also understood it now for the first time in my life :)
I think you should stop thinking about the matrix all together. It is just a tool which lets you compute the final vector.
in short:
you translated point using p-camPos, so now your camera is in (0,0) but it is rotated. your point is in non-rotated camera space now.
