#archived-code-general
1 messages ยท Page 105 of 1
thanks for trying to help through this as well, such a weird bug
I am a bit less experienced with 3D physics and have been trying to make this code work properly
public class Hand_Controller : MonoBehaviour
{
[Header("Physics")]
public Transform controller;
public float maxForceRange;
public float handMovementForce;
private new Rigidbody rigidbody;
public void Start()
{
rigidbody = GetComponent<Rigidbody>();
}
public void FixedUpdate()
{
Vector3 offset = controller.position - transform.position;
float distance = offset.magnitude;
offset = offset.normalized;
rigidbody.AddForce(offset * Mathf.Lerp(0, handMovementForce, Math.Min(1, distance / maxForceRange)), ForceMode.Force);
Quaternion rotation = controller.rotation * Quaternion.Inverse(rigidbody.rotation);
Vector3 torque = new Vector3(rotation.x, rotation.y, rotation.z) * rotation.w;
rigidbody.AddTorque(torque, ForceMode.Force);
}
}
everything works fine except the movements are extremely springy, and will either result in the object constantly bouncing around the target point or shaking right at it. Rotation behaves significantly better, but still suffers from the same issue
sorry for reply after convo over, i think u would be interested in knowing...
restarting unity fixed it
i swear this might be a bug because my pc shut down unexpectedly last night
Forces will overshoot, and next frame you might be compensating back. You are not resetting velocity. Another way would be to use fixed delta time with your offset to set the velocity, but might cause issue if hands can be impacted by other forces.
I'm aiming at a relatively physics based system, wouldn't resetting velocity mess up handling of heavy objects?
assuming that when a heavy object grabbed forces are applied to it as well
Yeah, something like springs would work better.
Or add some dampening perhaps that mitegate when it's close to target.
i feel like a damper would be needed regardless
Yeah, doesn't unity spring joints have this included? I can't remember
springs will still cause the issue of bouncing around a target, or shaking at it. Dampers are specifically for "object constantly bouncing around the target point or shaking right at it"
yea
im not entirely sure what the use case of this is, which is why i didnt suggest a spring
hmm, taking current speed into consideration and dampening it when closing on the target does sound like a good idea
whats your suggestion on how picking up heavy objects in this case would function then? attaching spring joints between the hand and contact point on the object?
Spring between your vr hand and physical. Your carry force is in the spring force.
using unity's physics component spring instead of my code? am I understanding you correctly? just a bit sleepy, may be misunderstanding
the spring force, if the object is attached to your hand, will drag the object directly towards your hand
it depends on how the movement is supposed to look
when u pick up an object, is it flying to your hand? or is it supposed to be contacting your hand and never leaving
yeah no I'm only interested in physically picking up objects, launching them towards the player is done separately
imagine a player putting their hand on a crate and trying to lift it, I simply want some weight to exist, not completely inertia-less handling
not boneworks level nauseating physics, just some weight for a nicer feeling
With weight you mean hands won't match real world hands position?
a spring could help then but u would have issues with customizing the spring force. Its only 1 force, not a customizable force in every axis
the force should dynamically adjust to a certin point to avoid the distance becoming too long and the player losing conrol
again, been doing it with my code
I'll add dampening and check how it looks, gonna make grabbing later once I got hands themselves working
the best way to add ranged grabbing is probably via alyx-like ballistic trajectory launching, they aren't super complicated to calculate and keep the physics feeling
should be good as long as I don't forget 7th grade physics
trajectory sounds odd, why not just a raycast
unless u mean something else, not really sure what alyx-like ballistic trajectory launching means
i just mean if u have a trajectory height, it might hit something unexpected along the way
games usually do it via simply pulling them towards the player
oh u mean to send the object to the player, not detect the object i get it
yea thats just 1 formula to calculate
a bit more complicated, but imo the best way is to give the player some more control. Launch the object when a player pressed a grip button and makes a sharp movement, with the object trying to make the trajectory match with the pull direction
could potentially allow for curve ball grabs but thats just cool if the player pulls it off
Anyone have a suggestion on how I can get all children of a parent including children of children etc.
like every single object that might be under an object
maybe doing it recursively
I couldn't put together in my head how I would set that up
there a reason to need it to do it this way?
Yes and no
longterm probably not
Looking to combinebatch a ton of instantiated objects
GetComponentsInChildren iirc does search all children and grandchildren etc
How would I go about doing it recursively?
This method checks the GameObject on which it is called first, then recurses downwards through all child GameObjects using a depth-first search, until it finds a matching Component of the type T specified.
depth-first search meaning it should be able to reach
you dont even need to do it recursively yourself, yea the method gives u every child but also it gives u the parent too
since its DFS, its guaranteed that the parent is the first element so you can remove that or skip it if u want. If they change how it searches then that logic breaks
it's easy too
[SerializeField] private List<Transform> familyTree = new();
private void Awake()
{
familyTree = GetComponentsInChildren<Transform>().Skip(1).ToList();
}```
Guys i have a system to set my UI toggle to on if my int is 1 and off if it is 0 but now i cant change the Toggle value in game pls help
my Up date function
private void Update()
{
if (Mute == 1)
{
MuteToggle.isOn = true;
}
else
{
MuteToggle.isOn = false;
}
if (MuteToggle.isOn == true)
{
Mute = 1;
}
else
{
Mute = 0;
}
}
you should not be doing this in Update
also !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.
What in then
Sorry
the obvious place would be the onchange event of your toggle
Where else tho bc i am using player prefs and i want to be able to change the value in the editor via a int or smthing that works with player prefs like a string or float or int
convert the bool to an int
it's technically an int under the hood anyway (at least it is in C, probably is the same in C#)
yeah but i cant go PlayerPrefs.GetBool
if you want editor changes to be reflected in PlayerPrefs then you would use the onvalidate method
I don't remember if you can cast it to int but you can do PlayerPrefs.SetInt("key",yourBool ? 1 : 0)
At least i think you can use ternary operators in methods
you can, ternary just evaluates to the consequent or alternative expression. its not like its a special data type or anything
Yeah, I'm never too sure since i basically never used it like that
also the bool in C is kinda different from bool in C#, u cant do the exact same logic
idk how to word that, u can do the same things obviously by converting. But not the same syntax if thats a better word
Yeah i forgot that bools technically don't even exist by default
C really confused me
in c and c++ a bool is a concept. In c# a bool is a type
like in C/C++ you can add a bool to a number directly
How do i set the isOn value of the toggle to be the same as the saved player prefs?
i think there is a method that allows that but i forgot it. Otherwise you can use another ternary operator yourBool = PlayerPrefs.GetInt("key") == 1 ? true : false;
what does the error say
and the isOn ?
MuteToggle.isOn?
yes
Wait what if i add a bool that is called MuteBool and give that bool the same values as the toggle?
no
Ok nvm
Why would that help
Idk Wytea said i need a bool
because he does not understand the difference between reference types and value types
MuteToggle.isOn is one
Oh ok I have no errors now ill let you know if it works
Okay it half worked
The toggle saved but the audio didnt mute as the toggle is on
Wait nvm didnt work at all
the toggle is always on nomatter what'
returning to my dampening issue, I am unsure how to calculate the necessary force. If its applied after a certain range so that the hand's velocity reaches zero once it reaches the correct position, I'm basically adding a deadzone in which player's movement won't be registered
I can calculate the force necessary, but I dont know after which point to stop acceleration and start dampening it instead
theoretically speaking the dampening force could be static, but I am still unsure if it will prevent bounciness
Do you know why that is?
Wait its only showing and loading data from the first save you cant change the value and save it will stay at what you had it as first
I don't understand why you want us to spoonfeed your whole project if you clearly have no clue how to program
No offence, but please learn basic c# first, before you even consider Unity
We could help you now, but we both know you will be back within the hour with another basic question that any tutorial would cover
And atleast post in the proper channel, #๐ปโcode-beginner , and not here
i didnt say that
he does seem to do this, if he doesnt like/understand the answer in one channel he just posts in another. He even had this is advanced yesterday
his player prefs issues, which should have taken 5 minutes has been going on for days
Imagine the stuff he would have been able to learn in that time
if he could be arsed, which apparently he cannot
Sure, I would love to start on my amazing mod, but I've been looking at various articles and videos for the past three weeks because I know the moment I even consider starting it I would be stuck because I have no clue how stuff works
(Not Unity btw, but (G)ZDoom and Zscript)
As with anything, you first build up a conceptual understanding of what you want, then you dive into the nitty gritty of 'how do I do that'
hey, so im trying to add perlin noise to a grid of cells.
for (int x = 0; x < gridArray.GetLength(0); x++)
{
for (int y = 0; y < gridArray.GetLength(1); y++)
{
float n = Mathf.PerlinNoise(x, y);
n = (n + 1) / 2;
c.buildCost = n;
GameManager.GM.cellList.Add(c);```
this is my current method, though when i try it, every single cell has the same cost
Perlin noise takes a value between 0 and 1. Then it repeats.
its always 0.7326366
oh im passing in the grid point of each cell as an int
Yep. That's the issue.
hmm, still can't figure this out. Directly setting velocity to difference between positions divided by fixedDeltaTime works just fine, obviously, but then hands are completely weightless. Still can't figure out the bounciness with forces
(talking about VR hands)
hey guys im kind of stuck here... Ive spent hours trying to get the reels to calculate the winnings and its not working https://gdl.space/sipujocequ.cs and https://gdl.space/lupugosivu.cpp
can someone take a peek?
are you able to be more specific on what you mean by "its not working"
what are you expecting to happen, and what is happening instead
is this some chatGPT code
oh you're crossposting
im sorry yeah im just trying to meet a deadline
so is this chatGPT code?
yes most of it
how about you start with this
if your plan was to just get some ai generated code, find out it doesnt work right off the bat, and have other people come in and fix it for you, I'm out
no its not that i lost sleep over this
i just dont know how to explain best im gathering screenshots
don't trust AI to write your code unless its a helper like copilot that just quickly completes or suggests you lines
ChatGPT doesn't understand anything, its just a text generator
How do you guys deal with naming private properties?
@rancid hornet you should open a thread before you start posting all those screenshots
In what sense?
usually toss an underscore as the first symbol of their name
I like to use properties over fields, but the only thing I dislike is how private properties generally should start with PascalCase
ok so is anyone down to help?
...what
you havent even begun to explain what's going on
You'd need to answer all of the questions asked.
Pascal is for functions/getters, _camelCase for privates, camelCase for publics
alright fair enough
_someField is easily recognizable as being private.
but properties start have Pascalcase too
What's wrong with PascalCase?
yeah, private props also should use pascal usually
so public SomeProp { get; set; } and private SomeProp { get; set; } look the same.
perhaps use _PascalCase?
why not _SomeProp
im actually at work on break rn so im gonna continue this in about 6 hours
What they've suggested - underscore.
that's what I would suggest to use too, but it's definitely not 'usual' to do so , hence I don't do it
sorry guys for the inconvinence and for being a disgrace ๐

who's reading it. You, or the PC?
yeah just tell the thing to fuck off and disable that particular warning
It's your adventure, good luck.
well since I want to send in some code for an internship, it kind of does matter
because it may have some additional logic
props make sense if you want for example to make it public to read and private to set
ah, you didnt write virtual so I assumed that it didnt
gotcha
yeah you still should go with the underscore, readability matters more
bump btw, trying to make physics based VR hands that take object weight into account
forces are what makes it hard
I think if its private, "additional logic" could make it a function, if its public where you need to validate the data as "additional logic", a public property could make sense, unless its a requirement of your internships code structure
it also feels weird to do something like this
because now in the class itself as it's now a question of 'do i need a field or a prop'
and then there's this which just screams 'please make me autoproperties'
no those four properties are neccessary, i need them to be available publically
but i don't want other classes to set them either.
hence the properties, which literally do that with { get; private set; }
tell me what's unnecessary about that
the IDE allready tells you that with the green wiggly lines ๐
Sounds intuitive but is it necessary? Should others really only have read access to these members (or any access at all)? They can already be acquired using GetComponent with reference of the instance. Caching sounds great but depending on how often it's used, a get component would suffice.
it tells you something else, which is to turn it into autoproperties.
then do that .. or why do you not want that?
did you even read what I said
Privatizing the fields makes sense as you're wanting to cache but not expose the members. However exposing component caches is usually for convenience or design-integrity purposes and not necessarily "necessary" - often associated overengineer.
If your concern is that public Rigidbody Rigidbody { get; private set; } does not have some indicator that the setter is private, I think you are overthinking things..
...?
public Property { public get; private set; }
sorry for a late response
iirc like this
Do anyone know if it s possible to center the pivot point of an object through some coding lines?
public Property { get; private set; }
So what he had is correct
Actually, it makes a lot of sense. This is the best way to expose data from a class without risking mutation (as of right now)
I would say what he's doing is the perfect way, code style and everything
Then again, I'm starting to wonder what code to actually look at since there are two different styles
have you read the rules ?
we not gonna fix the bad code some ai gave you, go and learn on how to code and then actually code
then we gonna help you cuz by then you know how to fix it by yourself with some help
but like you want us to fix the code for you
not gonna happen
oh no, are people asking humans to fix AI-generated code? Why can't they ask the AI again?
lol
You need to edit the pivot point in the modeling program and re-import or use an empty GameObject as the parent and place it where you want the pivot to be . . .
Is it possible to create an instance renderer that doesnt take a full matrix but instead a buffer of 2d positions? (Using a custom shader offcourse.)
If yes, does anyone have an example in code of this, I can only find how to do it with full 4x4 matrices and not using custom data
Thanks guys
Hello, someone on my development team wrote a script to assign keys to certain images. I was wondering if there was a better way to do so.
https://gdl.space/ayorotuqux.cs
anyone knows how to implement a replay system, where it shows how you died as a gif or something
Starting from Unity 2017.3, Unity provides a built-in package called "VideoCapture"
Use a dictionary populated from a ScriptableObject
Could you use https://docs.unity3d.com/ScriptReference/Material.SetFloat.html ?
@steady moat I dont think that works for instance data
Speaking of dictionaires, im having a dictionary problem, ```cs
public AudioClip PRsound4;
public AudioClip PRsound5;
private Dictionary<string, AudioClip> musicDatabase = new Dictionary<string, AudioClip>().Add("S1", PRsound1);
As it says, can't reference another field in your field initializer
Use awake or start to do it
Ah ok thanks
also, calling Add like that wouldn't make sense anyway; it returns void
you can, however, use an object initializer
var numbers = new Dictionary<int, string>
{
[7] = "seven",
[9] = "nine",
[13] = "thirteen"
};
stolen straight from the C# docs
note that this still doesn't refer to other fields.
ah ok
PulseRifleSoundsList = new List<AudioClip>(){PRsound1, PRsound2, PRsound3, PRsound4, PRsound5};
PulseRifleSoundsList.ForEach(AudioClip clip, index => PulseRifleSoundsDict.Add("S"+index, clip));
``` Also another issue but where have i gone wrong here
tryna do a for each lambda expression
- There is no usage of OOP. Group things together. (UpImage, UpInput, Up)
- GetComponent should never be called in an Update function.
- Using string for binding is weak. Use enumeration instead.
- The naming convention is not uniform
private static SpriteManager instance;andprivate bool ImageChange=true; - There is static variable same if we are in a Singleton.
public static bool CanChange = false; - The spacing is not uniform.
ImageDelay <= 0&&CanChange - The mapping should be done with Serialized Data such as ScriptableObject
- The UI should try to not be refresh every frame, but use events to refresh its state only when necessary.
Do not forget the usage of Atlas
What do you mean ?
you don't put types in the lambda parameters list
also, I believe you need parentheses for multiple arguments
FooList.ForEach((foo, bar) => Debug.Log(foo + " " + bar));
wait
ah i see, alr thansk lol
is there an overload of ForEach that provides two arguments?
false
it takes an Action<T>
Action being a function that has a void return type
so, it accepts a function that has one argument of type T
There's probably something in LINQ for that.
O(n^2) moment
tried writing some dampening, the issue still persists, but in a different shape. All of my attempts result in the hand moving extremely slowly and having issues when changing directions, sometimes going orbiting. Lowering dampening power speeds the hand up but significantly worsens the orbiting and redirection issue
Hello, I have issues with Admob. It works fine on Android but crashes everytime at startup on ios. What can I do to fix it?
Here is the AdManager code. I don't know what to do anymore tried everything online. It workes fine without admob plugin.
Error: libc++abi: terminating with uncaught exception of type Il2CppExceptionWrapper
ok good luck
You have 12k batches ?
ok how do i reduce batches then
HDRP is a physics base rendering pipeline.
im on URP lol
I guess URP does too then.
bcause kelvin is the superior unit of measurement
bro literally said "Just do it lol" ๐
What are some 2D coding concepts I should learn for unity? If you have any resources for topics that I should learn that would be great.
Does it really matter if it is 2D or 3D ?
yes
yeah sorta
He probably meant Clean Code, Polymorphism, OOP, etc.
ah, well, the standard OOP package then
I think this is a follow up of #archived-code-general message ?
just keep in mind that unity still uses hella old .Net (iirc its 4.8 or 4.7.2)
Coding Concept are higher than language.
You could use C and still be able to apply "coding concept".
2D I just remembered to put that
It does
So, what you want to learn is not "coding concept", but unity specific things.
Me and my team are lacking of skills and I want to research some coding practices to improve my code and my teams
!learn
๐งโ๐ซ Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

It is a color temperature.
Both
Change from the โFilter and Temperatureโ mode if you donโt want that
Just take the coding course. But, this will only show how to make things. A lot of how to make "good things" are not included in those specific tutorial.
For clean code, you might want to read this: https://blog.unity.com/engine-platform/clean-up-your-code-how-to-create-your-own-c-code-style
For OOP, you might want to read: https://www.w3schools.com/cs/cs_oop.php
I try to maintain clean code that is maintainable but I wanna improve it more and learn more coding concepts. I know a little OOP but feel like I donโt know it too well and concepts like Atlas and ECS seem interesting.
You should keep yourself away from ECS.
youuu wanna learn the basics first for sure
My teammate originally had it at 1200 lines of code
Thatโs what I told him to use
Yes
still can't figure out how to handle force-based VR hands, interested in the physical approach because simply setting the velocity will make all objects feel completely weightless, but all relatively simple approaches I've tried either result in extremely slow or extremely springy/orbiting hands. I have a theory that would require much more extensive calculations but it just feels so bootleg and wrong and I'm not even sure if my idea will work
What is wrong with moving the hand directly ?
wdym
Rigidbody.MovePosition() ?
there are two ways, either setting velocity or applying force, setting velocity removes weight and has issues with portraying inertia
same reasoning?
yes, so that picked up objects don't feel fake
If you do that, you will "unsync" the hand with the real hand.
...yes, thats what I'm talking about
I have two separate objects, my controller (visible for testing purposes) and the hand itself
but whatever I try either results in the hand being super slow or too fast without dampening
and flying past the controller
Do you have Use Gravity activated on the Rigidbdy ?
It is always best to check it first.
yeah no the issue is with dampening
Then, you could use Rigidbody.MovePosition with lerping.
Joint with the physics of the Rigidbody.
I am trying to use forces here, you have to keep in mind that we're talking about VR, hand collisions are a pain in the ass and you really want to avoid direct movement
I'm not sure what is the issue with Rigidbody.MovePosition. However, you could apply a force towards the real position that reduce with distance.
sigh
simply adding the force results in no dampening whatsoever and hand catapults through the controller, either springing back and forth or going on an orbit, you seem to be misunderstanding what my issue is
that reduce with distance
And, you will always have orbiting with a force.
...I just said, I'm not stupid - I perfectly understand this
This cannot be mitigate if you want to use force. You will need to remove the whole force at a specific points.
Redoing what a MovePosition does, but with the usage of a force.
Personally, I would do a lerping.
I do understand that I need dampening to negate the force, the issue is how much of it
...christ how hard is it to understand
simply teleporting will not give objects around any inertia or weight
you will be able to pick up and move them around without any inertia
lets goooooo ive already increased fps by 10 frames
Reset your velocity each frame to 0.
Calculate the direction between your object and your target.
Apply a factor to your direction base on the distance or not.
Add the velocity to the Rigidbody.
If you do not reset to 0.
You are going to orbit.
okay I think its pointless to try explain the issue and my intentions to you, sorry
but you are trying to solve an entirely different problem
Alright, I might not understand your issue. However, this is seems like you do not want to try to use the available tool (Rigidbody.MovePosition), or to solve an impossible issue (Orbiting with forces).
I have this disabled...however when I save a script it still refreshes everythng
what am I doing wrong?
It works from my side. Unity 2021.3.21. (CTRL-R to import/save)
while MovePosition would work to move the hands, it simply teleports them, spawning an issue: objects that you pick up still have no inertia. When you move your hand around, it won't have any resistance from said objects, which defeats the whole point of using forces
What do you mean by teleport ? It does not...
Rigidbody.MovePosition moves a Rigidbody and complies with the interpolation settings. When Rigidbody interpolation is enabled, Rigidbody.MovePosition creates a smooth transition between frames. Unity moves a Rigidbody in each FixedUpdate call. The position occurs in world space. Teleporting a Rigidbody from one position to another uses Rigidbody.position instead of MovePosition.
it still ignores any weight
doesn't work for me ๐ฆ
I am using the standard asset character controller in a project, the project has a swimming mechanic that is work so far, but I need to rotate the character controller collider 90 degrees on the y when the player is in the swim animation. I have tried several different approaches but the collider always stays in its original position. this was the last thing i tried. swimRotation = Quaternion.Euler(0f, 90f, 0f);.
when the swim trigger is activated i have this characterController.transform.localRotation = swimRotation;
This is why you should move a percentage. Not the whole thing.
...
that STILL ignores the weight of the held objects
when you hold something heavy it should have more inertia than something light
It will.
you're just slowing the movement down to make it smooth
Test it.
You have nothing to lose except maybe 15min.
If it works, it works. If it does not, then it does not.
This is what I would do.
Otherwise, you gonna fight with the velocity of the Rigidbody.
refreshes what?
that should only take effect on assets
5 sec
when I save a script I want unity to not refresh everything until I CTRL+R
Did you try to relaunch Unity ?
no idea, according to some blog post auto refresh should disable compilation
updated burst and relaunched
@steady moat yeah just as I expected, your method gives the body exactly 0 inertia, making it completely unable to interact with other bodies
lets see if its fixed
here I attached a spring joing
nope
if its supposed to stop compilation but doesnt its a bug
never had to turn it off, why do you?
its annoying
Windows + G for video. Pretty hard to know what you are doing with a screenshot. Rigidbody.MovePosition should push other object.
...yeah there's no point in this
ok I have a question
I like having the individual wall blocks like in minecraft, but I have a feeling that is really inefecient and will cause a lot of lag. However, just scaling the blocks causes the material to not appear well. Do you guys have any idea how i can have the materals scale with the object? or can i not do that
uvs dont change from scaling
looks nice but is multiple objects, so more lag
it stretches
I think wait can I just
yes its how its supposed to work
if you want them to remain constant, you need to use world space shader
hold on maybe this is easy
typically its triplanar shader
its not, you need the worldspace/triplanar shader
im not on urp
and too far in to switch
but
its fine theres other issues anyways
then find/write one
like the wall bases stretch out
cant do anything about that
I can also try mesh merging
that might work
ill take a look and see if I can do it before runtime
ok
ill try static batching instead
maybe that will helo
*help
this is an LTS version right?
dont know, you can also use instancing
yeah imma look at allllllllllllllllll the things
bcause 15 fps is prettty bad
so I need to fix it
did you profile it?
just to exclude any fixes based on guesswork
are you in deferred?
quality/graphics settings
gotta love this crap
oki
how many lights in the scene?
which is fastest?
Application.targetFrameRate = Screen.currentResolution.refreshRate;
Application.targetFrameRate = Screen.currentResolution.refreshRateRatio;
theres a lot but the profiler said it wasnt really that
it depends on your game
"refresh rate is obsolute, use the one that doesn't work instead please"
I changed my camera to deferred ill see if its any faster
if it is faster it indicates a massive problem
yeah seems like you have lots of lights
unless I changed something
your lights are prefabbed?
the ugly looking part is most likely your post processing
which needs to be setup differently sometimes for deferred/forward
no like It was looking good then it stopped looking good
ive no idea what you mean by that
It is true that rigidbody does not seem to interact correctly with other bodies if the body is not kinematic which does goes against what you were trying. Maybe the following would work for you. The only issue, is that forces applied to the hand are lost.
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class Hand : MonoBehaviour
{
[SerializeField]
private float _velocitySync = 1.0f;
[SerializeField]
private Transform _target = null;
private Rigidbody _rigidbody;
private void Start()
{
_rigidbody = GetComponent<Rigidbody>();
}
private void FixedUpdate()
{
Vector3 vector = _target.position - _rigidbody.position;
Vector3 velocity = Vector3.ClampMagnitude(_velocitySync * vector.normalized, vector.sqrMagnitude / Time.fixedDeltaTime);
_rigidbody.velocity = velocity;
}
}
do you have a prefab per light type
alright
then edit the prefabs in such a way that the light range goes only as far as it is absolutely necessary for it
okki
im also a blithering idiot I accidently turned something off I think
but that should be handled by "important light"
you can balance that with intencity
yeah
but why would the lights kill yo textures
ok so
pros its faster now
cons its different
pros 2 I actually like it more
btw if lights are static and dont move, u can bake them
they didnt that was me being a blithering imbeceile
they are generated
so I cant bake them
do you have shadows?
lower shadows to absolute bare minimum necessary per light if you can
on top of that, disable "cast shadows" on all mesh renderers that dont need them
bibut they loook niiiice
its all procedural right?
you were the one we talked about navmesh?
alright, i dont know if there are already solutions but you need to find some culling solution that works at runtime
its good for right now
unity built in requires offline baking
culling will give you the most perf boost of all
like occlusion culling?
Contribute to przemyslawzaworski/Unity-GPU-Based-Occlusion-Culling development by creating an account on GitHub.
its old but has lots of stars, didnt test
the only issue, is that forces applied to the hand are lost. you're once again suggesting a solution that completely goes against anything that I've said
its pointless
yeah there are plenty of those
maybe its language barrier, dunno
maybe I've fried my brain and having issues with explaining again
The hand still react to the environment and the mass of objects like you wanted.
how does it look
imma stylize the bars later dw
wait, wdym by forces then
Look at the video I sent. Is it what you want or not ?
OH I get what you've done there, hmm
yeah this could work, I'm assuming that dragging a heavy object also would be harder
It is.
didn't expect that of all things to work, huh, I think I'll need to look into how unity handles velocity again
But, if you want the hand to react to something like an explosion.
apologies for my previous messages
It wont work.
i like where this is going
lemme try no shadows see if it looks nice still
Next time, work with me. Not against. I do not know everything.
I tried a slightly different approach and it didn't work before
yaaaay
ooh it does still look good and its slightly faster
overburned
also if you want to push for realism you can use a cheap trick
maybe no grain
I like cheap tricks
you basically find or make yourself a light cookie
with an actual physical IES light profile
I know what a light cookie is what is an ies light profile
its what they use in archviz to fake realistic lights
Assets\Scripts\DontDestroy\GameManager.cs(17,39): warning CS0618: 'Resolution.refreshRate' is obsolete: 'Resolution.refreshRate is obsolete. Use refreshRateRatio instead.'
anyone know how to do that?
neat
so, so much nicer without grain
//Application.targetFrameRate = Screen.currentResolution.refreshRateRatio;
this does not
maybe
just maybe
its because you commented out the line
another issue is that you are using default unity shader with the crappy light model
henceforth preventing it from being run
wdym
no
it has an error
oh
just ignore the error itll be fine trust
let me turn off vignette
this is cool
By default, Unity lights use a linear falloff model
you want inverse squared like irl
Application.targetFrameRate = (int)Screen.currentResolution.refreshRateRatio.value;
Assuming most people don't actually have like 144.56hz
we should probably move out of here with graphics discussions
JUST spent 5 hours making lights flicker back and forth with some lerp sheesh
sweet thanks
wonder why they changed the code for that
yeah thats true
ok i thought steam survey
would show how many people use 60hz
but apparently they dont collect data on refresh rate on monitors
Im using more because some phones only get 30hz
Thsi server is made for
yes
For what
for anything to do with unity
My man joins random servers without knowing what they're about
ill get a light cookie going at least
True
Where are you from guys
how u found the server? xd
why unity in particular? lol
I was searching random words
what are the words
oh my god they're a bot
This is a code channel people
Oh
bots are written in code
hey im fully stumped and confused on this 1. As shown in the video when i have my slope movement "enabled" its making my jump go weird only when walking. ive tried to comment out the code to figure out where the problem is but only found what function is causing it. ive tried to just stop that slope movement by only enabling it when im not jumping or if im grounded both of those didnt work. https://gdl.space/akexaticuc.cs
i need help on this error when opening unity
but not related to unity
are you on VPN?
I'm in ohios peris
this goes in #๐ปโunity-talk
and is likely you are using VPN or blocked by your ISP
well the bot clearly failed the captcha so we should kick them trust
stop with the offtopic..
anyways back to code
not a code question tho if it is on opening probably belongs in #๐ปโunity-talk
Ok
still not a code question
welp thx for spamming, no one can see i need help now
did you read the replies at all ?
which means it's NOT a question for #๐ปโcode-beginner
i read it
sorry
but no one is guiding me
keep the channels on topic then please its bussy enough

I guided you
check VPN / ISP
yes please
can you chillout with the spamming , thx
Your collider is probably going slightly in to the terrain causing you to appear to bounce. Try using Debug.DrawLine to see if movement direction is what you expect it to be, or give it a very slight extra upwards direction to make sure it doesnt clip in to the ground.
i dont have vpn but isp is normal i used to download it and it work but now it doesnt
now compared to what
<@&502884371011731486> Shitposting
There we go
i dont think that pings the moderators but ok lol
well theres nothing wrong with isp and i also dont have vpn
It does, why would this be there otherwise
!mute 915205642262835270 7d Shitposting
Here it comes
THE SAGAR ๐งฉ#6969 was muted.
clear the IP is being blocked so , no you're wrong
I use ipconfig release and renew
your IP stays the same if the ISP controls it
If I ping these IPs, both time out.
So what do I do
we don't even know what page that is ?
Go to #๐ปโunity-talk and add some explanation on what this screen is
It's just that I don't know what do I even explain it
what
oh could that be my controller.move pushing the player into the ground because i did make it so the player slides down a slope only when they are on a steep slop or sliding, so there would be some downward force. but should be 0 any other time like when im jumping on the platform .
I want to generate some terrain heightmap on the GPU for later simulation and tesselation
I'm confused about what tool I should use to do that
shaders? shader graphs? compute shaders?
compute shader
alright, thanks
how do I fix this error?? It's in visual studio
Hey, so I have an interface called IPausable. As the name suggests, it is for making objects pause themselves when the main TimeManager class tells them to. The interface has a function called OnPause() and I want to call this function in all inerfaces of this type when the game is paused. How can I do this without using FindGameObjectsOfType() and such? I thought of initialising them and making everyone add themselves into a static list at start but I don't think that's very practical either. How would I go about achieving this?
Have each pausable object register itself with the time manager when they're enabled
Hm yeah I thought of that too but didn't know if it was a good idea. Thanks a lot!
or rather
I wouldn't make IPausable at all
I'd probablty just have TimeManager have an OnPause event
and things that care about the game pausing and unpausing can just subscribe themselves to that event
you could even make it a static event to make things easy
these errors are still popping up. I actually just updated my unity to the latest version 2022
I think I can do the registering thing by putting an initalize method on the interface that forces the classes to subscribe/register themselves to the TimeManager
I'm having a problem (I think I'm just dumb).. I have this gameObject, it has to move 90 units. I need to clamp the max movement speed, so I have a maxMovement variable, and I need to multiply that by time.deltaTime, to make it framerate independent. But, now I need to calculate the max amount of time it could take the object to move the 90 units and I'm having a brainfart on how to do that, with time.deltaTime not being a constant. Could anybody point me in the right direction?
I'm using a ScriptableObject as a database of GameObjects that I want to instantiate at runtime. Can I not do that? I'm just trying to get a reference to a gameobject as a prefab, but it seems to be instantiating the game object as well..
public class PropDatabase : ScriptableObject
{
[SerializeField] private GameObject GreenGlupiePoseA;
... etc ...
public GameObject GetProp(CutscenePropType propType, PropPoseType poseType) => (propType, poseType) switch { ... }
}
// elsewhere..
GameObject newPropPrefab = PropDatabase.GetProp(prop.PropType, prop.PoseType);
GameObject newProp = Instantiate(newPropPrefab, propTransform);
// do some stuff to newProp .. but nothing to "newPropPrefab"
it's simply distance / movementSpeed
You're calling Instantiate(newPropPrefab, propTransform); - of course it's instantiating
not sure I understand the question/issue?
I'm getting two instances instead of one
PropDatabase.GetProp just returns a gameobject that's referenced in the scriptable object
maybe your code is running twice and you don't realize it
hm, perhaps.. will check
if u really think that instantiate is the only one, then it might be executed more than once
Also check for any new GameObject() potentially in that switch expression you elided
For some reason though, at max speed, it seems to take 2 times as much as what I calculte my distance / maxSpeed by
this is the code, running every update
{
float maxClamp = ballSwingMaxSpeed * Time.deltaTime;
axis = Mathf.Clamp(axis, 0, maxClamp);
anchorRotationEulers -= new Vector3(anchorRotationSpeed * axis, 0, 0);
ballAnchorRot.transform.localRotation = Quaternion.Euler(anchorRotationEulers);
}
In this case, it rotates 90 eulers, I set the maxSpeed to 800, so that should take, at max speed, 0.1125 seconds to complete. But it takes 0.23-ish at max speed. I confirmed that it does clamp every frame
Does anyone know how to rotate a vector3 point around another vector3 point?
Hi! how to correctly make reference to ragdoll joints in prefab so when object instantiated, it doesn't link to prefab but his object
get the difference vector between them and rotate that - then add the rotated difference vector back to the origin point.
You can rotate vectors by multiplying quaternions with them
You'll need to acquire this during runtime
Lets say that point is p and you want to rotate it around pivot cs var offset = p - pivot; p = rotation * offset + pivot;
rotation is a Quaternion here
Whoever instantiates it should have access to both and would be able to properly setup references
Thanks, I know about rotating with quaternions I just couldn't figure out how to do it around a point
I've checked it multiple times now, in different setups. It almost seems as if duration = (rotationDistance / maxSpeed) * 2 . But I cant figure out why?
I need to find a course in unity quaternions / vectors lol. It's so hard to understand
You "just" rotate other quaternions with Quaternion * Quaternion or vectors with Quaternion * Vector3
Learn to use the helper methods like LookRotation, AngleAxis, Slerp
Use gizmos/objects to visualize the rotations
Yo!
I got a problem here. I'm trying to find a Transform far away from the this transform. How do I do it?
by the way this is a prefab
hello, im playing around with .snippet files.. and i got a raycast shortcut working great.. only if i were to type out some of it and hit tab.. it leaves what is left over..
i would like it to remove the things i typed before.. but can't figure out how to do it..
read your error message
it should act more as this
heres my snippet
i do however notice the one i made is white.. rectangle. similar to the if snippet
however the ones that replace what you have typed with code look like ur normal methods.. so not sure what im missing tbh
The Unity methods are custom, they're injected by the IDE package, they're not snippets
Your snippet works as expected, it adds the code in place, and can't modify things before/after it
Hello everyone, quick question.
Having a lot of animated damage popups/health bars in the world, what is more efficient, 1 canvas in the world space for everything or multiple canvases (1 for every element in the world space)?
ahh so its not possible? im searching google here.. and i found something that says that Unity's stuff is snippets with replacements that replaces the identifier with teh desired code block
Yeah it's whatever IDE you're using, the Unity package you installed for supporting it that registers these custom analyzers and completions
i used Expansion and SurroundsWith but there seems to be a <SnippetType>Refactoring</SnippetType> as well ๐ค
ya, thats the only thing i see different is Refactoring
meh, ill try messing with that.. but im clueless right now ๐ i just think its super cool to be able to define a raycast autocomplete..
ive been needing that w/o ever knowing it.. and if i can't get this working i'm still pleased ๐
i can go ahead and make a few for OverlapSphere, Input.GetKey stuff, and a few others i have planned now that i know how to do it
... ๐
i try to have as few canvi as possible
Ones from the top of my head: if statement with CompareTag() check, and TryGetComponent call
omg yes TryGet will be one for sure
i can't figure it out.. but i could make it where the code just include Raycast(ray...
so then i could type if(Physics.Ra.. and tab it out
Refactoring didn't work like i thought it would.. but i learned something more..
it makes it soo.. when you press Tab it shuffles across all the parameters you can change
this is probably default behavior.. i changed it back and removed Refactoring, and it still allows this
thanks for the insight tho SPR2 ๐ i know enuff to make a few QOL snippets atleast
ty
is it possible to expose class/struct member only to certain class/struct (no inheritance)?
like maybe I could try creating some custom property [ExposeTo("MyClass")], but is there a more convenient way?
only through the use of access modifiers:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/access-modifiers
much of those rules have to do with either inheritance or assembly boundaries though
I mean, I want a certain class member to be accessible to 1 specific another class, but not whole namespace ๐คทโโ๏ธ
a better approach might be to use interfaces
Maybe like a delegate to a getter if you wanna subscribe to it
if you expose your object as an interface you can tightly control which members are exposed
hmm, both approaches seem good. thanks
depending on the usecase, you could even declare one type inside the other and the nested type would be able to access the non-public members of the containing type
no I mean my 2 classes that I want to "connect" like this are completely separate
in fact one is even static and the other is not
well i had no way of knowing that considering your vague "certain class member" statement. and is also the reason i started with "depending on usecase"
well I specifically mentioned that I want to inheritance. ofc I can nest them and it will work as intended ๐
nesting is not inheritance
oh well, I want no nesting too ๐
You're describing an equivalent of C++'s friend keyword. We don't have that in C#
Do get; / set; fields have any overhead?
Im trying to automate spritesheet animation.
How can I get an array of all the cells of a png?
Sprite[] sprites = Resources.LoadAll<Sprite>(path);
Seems to always return nothing
The overhead is the property itself vs having them only as fields
I meant as in performance
Maybe an incredibly small amount, since they reference a field. But realistically, no
show resource folder
I am new to unity. What is the resource folder. I can only find the assets folder
The path im giving is "Assets/Sprites/Player/king"
where did you even get that syntax ?
searching on the web and docs
if you read the docs you should read how Resources works
AssetDatabase also doesnt work
Resources.Load<T>() and its variants requires a special folder arrangement to work, that's described in the docs
So I just create the folder inside Assets....? Would the path then be Assets/Resources/Sprites/Player/?
Depends on what value you set into path
"Sprites/Player" will be the correct path here
https://docs.unity3d.com/ScriptReference/Resources.Load.html
read how the folders are treated
The path is relative to any folder named Resources inside the Assets folder of your project.
whoa it worked!
Yea bet
I was mixing up some path stuff as I was using System.IO stuff to handle paths elsewhere, just needed to change the file structure like you said and edit the string
Note that once built, the Assets are packed, so you cannot use the stuff in System.IO to read them because they're not files anymore. Use Resources or Addressables instead
Yea my system is pretty jank. Il probably just use my resource folder as temp storage to automate the animationsand outputting the result back to Assets
anyone know how to achieve a card scroller like this?
I have a ScriptableObject A. In A.OnValidate, I fire a System.Action OnValuesUpdated, so that methods subscribed to it can get updated.
I have a MonoBehaviour B, which has a reference to a A ScriptableObject, which I set in the editor. In B.OnValidate, I subscribe to A.OnValuesUpdated.
When I modify A in the editor, the B.OnValidate fires as expected, but is uninitialized. For example, if I have an int on B, and set the default value of it to 1, but in the editor I set it to 3, the OnValidate will debug.log it as 1.
How do I fix this?
they have overhead, but just for you to feel how incredibly negligible it is - even if you have a thousand properties with { get; set; } vs a thousand fields, you will notice 0 difference
so realistically you never sacrifice code structure to performance gain of using field
just manipulate position and scale + order in layer field on sprite renderer? don't see any problems
๐ข this is sad
I have to do extremely roundabout ways to achieve same thing
What do you mean by uninitialized ?
It does not seem like what you are describing is an initialization process. For example, if I have an int on B, and set the default value of it to 1, but in the editor I set it to 3, the OnValidate will debug.log it as 1.
It is like the class is not instantiated. I can't access any values that pertain to the object or gameobject in that case
Are you sure you are not looking at one instance and debugging the other ?
I don't want to initialize anythin, I just want to be able to use the values I've set from the inspector, for that particular gameobject. (which holds the component B)
If you set the value at 3, then you should get the value with a value of 3.
Yeap. So just to reitarate, I change my SO A, the OnValuesUpdated callback is called, but it I can't access any values set via the inspector.
There is something that is not working correctly that I cannot guess because I do not have the code nor the project. Try debugging using other means. Maybe do a GameObject.FindObjectOfType ?
Tried illustrating the problem here to be more descriptive. I literally tried everything and I can't understand why it works the way it works.
You could try to do a CustomEditor and use the Update function.
Doing this way, I am pretty sure you gonna be able to get the correct value.
Problem is I can't move on phsycologically until I know why it doesn't work
If I were to guess, it would be either, because the Prefab (Not the Scene Object) is the one actually getting the callback or that you do have an other instance that is subscribing to your event. All mixed with wrong timing for the subscription.
Thank you very much for the good suggestions, I'll keep looking!
Hello people, I'm having trouble with vectors and the OnDrawGizmos ๐ต, I can't manage to make it do what I want, displayed in this image
here's what I have so far in the code section
void OnDrawGizmos()
{
foreach(var connection in connections)
{
bool hitted = Physics.BoxCast(connection.GetPosition(), Vector3.one, transform.position + connection.GetPosition(), Quaternion.identity, connection.DistanceFromCenter * 2);
Gizmos.color = hitted ? Color.red: Color.green;
Gizmos.DrawWireCube(connection.GetPosition(), Vector3.one*2);
}
}
I can't get it to "extend" in the correct direction
I'm using a physics raycast of a box and I would like to have a visual representation for it, to see if I'm messing it up (I am)
I am using Native Gallery to allow user to pick audio, but it is not letting .ogg audio pick. https://github.com/yasirkula/UnityNativeGallery/blob/master/Plugins/NativeGallery/NativeGallery.cs
To extend the box you need to use a direction vector, e.g. (0,0,1), not the (1,1,1) vector. If you want it rotated into local space of the object you need to set the gizmo matrix to the transform matrix of the object. You might also enjoy this little package https://github.com/vertxxyz/Vertx.Debugging
anybody? why can't I pick .ogg file?
But the DrawWireCube() method only gets a center and a size, I assume I should calculate the center of what I want but I'm not the best in vector calculations, all I can get together is : I have a middle point, the center of the object, I have the pseudo direction I want to go, that's one of the four points, let's say the forward one, is there something I can do to calculate stuff and tell it: "hey, draw this, move it in this direction by this amount?
Native Gallery is also for Audio.
Gizmo drawing is a stateful api, you do Gizmos.matrix = transform.localToWorldMatrix and all subsequent gizmo.draw calls will use it. https://docs.unity3d.com/ScriptReference/Gizmos-matrix.html
I've came up with this solution, what do you think ?
void OnDrawGizmos()
{
Gizmos.color = Color.white;
Gizmos.matrix = transform.localToWorldMatrix;
Gizmos.DrawWireCube(oneoftheconnections.localPosition * 2, Vector3.one);
Gizmos.matrix = transform.worldToLocalMatrix;
}
oh yeah, that's how you do it
set the local to world matrix, then do everything in local space
bingo
how can i check whether an object is colliding without attaching a script to that object? is that possible?
I instantiate it with the Instantiate method
No. Unless you do physics queries at it's position manually, which might not be a great solution compared to a script on the object.
hey, what are you trying to do?
code looks ok if you don't ever touch it again, but why use matrix overall?
var pos = transform.position + 2 * oneoftheconnections.localPosition;
Gizmos.DrawWireCube(pos, Vector3.one);
or is it the size you were having issues with?
alrighty
thanks
is there a reason you don't want to attach a component?
just a bit messy having a scriptable object script, a script for logic before the building is placed and a script for logic for when the building has been placed
i think that's clean
you know what's messy?
having a script with ten jobs, including doing physics queries on a bunch of objects it has spawned
oh yeah doing it that way would be messy. but if unity stored whether it was colliding with anything i could have just had a single method rather than a whole new class and script
Maybe a dumb question, but I'm new to transitions, This changes the center of the camera's position, but it does it instantly without a smooth transition. How do I add a smooth transition?
You'd have to check using another script. I don't see what's wrong with using a separate script on the object though?
Unity passes the collision object with their collision/trigger messages or physics queries . . .
yeah its fine dw, ive already sorted it out with a script on the object, was just asking if there was an easier way
You assign the position to a specific value, there is no transition here. This is akin to a teleportation. You need to move from the object's current position to a target position over time . . .
Nice, glad you found the easiest way . . .
๐
is there a way to detect a unity action during a loop?
if(InputReader.onSubmit != null && index != 0){
dialogueText.maxVisibleCharacters = line.Length;
break;
}
what I'm having trouble with
What's onSubmit? Is it an event?
So basically an event. Checking if it's null simply checks if anything is subscribed to it.
*event action
You should subscribe to it outside your coroutine and when it triggers raise a flag that can be checked in the coroutine.
Or maybe even stop the coroutine from the subscribed method.
Along with the logic for displaying all the text.
Sure. Why not?
That's the default approach that unity provides with the input system.
The connections are children of the object that has the script attached, so I had to use local positions bc the world position wouldn't work properly when the object moves, pic related, white cube is my solution, yellow one is yours, object has (0,0,-10) as vector of position.
ah, well ok.. doing the proper math might not be worth it then
I assumed they were children of the object
Yeah, and since apparently the gizmos thingy works on world space only I had to make it be in local position just for a moment
Hey guys !
So my WebGL game stopped working in localhost and on my server.
It just gets stuck here and doesn't load?
It's been working fine for over a year now. Anyone else seen this at some point and able to help? ๐
Wow that's weird - It's requesting a double up of the original directory:
try it on another browser that supports webgl
thatโs very interesting
right! I'm investigating
i am having a vary frusterating issue with my code
may anyone help please
it is a lot
Don't ask to ask. Summarize your issue, share the relevant code and screenshots/video of the issue if necessary.
AI car racing
the help is in Begghiner code
i have 2 colliders how can i detect if on or the other was hit
has anyone seen this before? trying to make a build for my game and the editor crashes reporting a ton of 'asset.cs' files that don't exist in the project?
Script 'Packages/com.betscript.citybuildings/City_Buildings_Pack_Vol.4/Building_331/Prefab/asset.cs' will not be compiled because it exists outside the Assets folder and does not to belong to any assembly definition file.
Script 'Packages/com.maksim.pbrmilitarypack/Characters/Elite_Soldiers/Models/Soldier/asset.cs' will not be compiled because it exists outside the Assets folder and does not to belong to any assembly definition file.
Script 'Packages/com.characters.actorcore/young-fashion-vol-3/casual-f-0030/Prefabs/asset.cs' will not be compiled because it exists outside the Assets folder and does not to belong to any assembly definition file.
Script 'Packages/com.```
i have a prototype that does that, but it uses layout groups. idk how to get the overlayed layers thing that sells the "3d" effect
Assuming that you're using one of the built in callbacks like OnCollisionEnter(Collision collision), you can just use collision.collider to get a reference to the collider that triggered the callback.
fixed?
You could do one of them trigger
Just fixed it.
Turns out having a # in my build folder messed up the template URL somehow.
I wouldn't be able to tell you why or how or what, but using only plain characters seem to work
I'm kind of at a crossroads for what movement method to use.
I was using the 2d rigidbody movePosition, but that interferes with gravity.
I was thinking of switching to setting the velocity in the RigidBody, but the unity doc recommends I don't do that.
I don't want to use AddForce as I lose too much control.
Lastly, I could try to make my own movement tech but then I would have to re-implement a lot of the existing functionality like gravity, collision etc.
What are other people doing?
Some extra information:
Many characters will be using the same movement tech, not just the player.
I want somewhat decent control over their motion.
The game is 2d, side view.
Any issues or benefits you encountered while using any of the systems would be helpful
I would hesitate to point you towards a single solution, but I will say, that in side scrolling platformers I almost always roll my own gravity, and I avoid the 2d physics system for everything except cosmetic stuff like particles.
In my experience, platform gravity that feels good has nothing todo with real world gravity.
Ok thanks
It isn't actually a 2d platformer, they just share the view. So definitely agree that for 2d platformers faked 2d gravity will feel better for the player
I work in 3D, though the options with physics are similar, I use velocity in FixedUpdate to handle physics-related movement, I use a Vector3 (in your case, maybe a Vector2) and MoveToward or Lerp that vector to the value I want, instantly add to it for jump, and subtract from it over time at a fixed rate in Vector3.down to apply unique gravity for that object/player, because I have the velocity managed, and I know I only manipulate it in specific places of my code, its one way you could handle your movement, MovePosition is often used for kinematic rigidbodies, if your implementing your own logic, as you pointed out may be more hassle than its worth, depending on how complex of a system you might be after, Unity also has a First Person and Third Person controller, you can maybe take a look at how their code is structured for movement, and translate it to 2D, essentially removing an axis
Are you in this case using a rigidbody on your character?
I am using a Rigidbody component in my case, yes, the same logic should apply for a Rigidbody2D as well, just with 2D math and vectors instead
hey is possible to make my slopeMovement = zero just before i leave the ground/jump because i believe there's still values other than 0 before i do jump causing unwanted movement.
private void slopeSlider()
{
//1 Bug: When player gains speed by sliding they can jump with excesive speed and the vector.
if (isGrounded == false)
{
targetSpeed = sprintSpeed;
slideMovement = Vector3.zero;
return;
}
if (SlopeChecker() && slopeAngle != 0)
{
if (isSliding)
{
isSlopeSliding = true;
Vector3 slopeDirection = Vector3.up - slopeHit.normal * Vector3.Dot(Vector3.up, slopeHit.normal); //Gets direction of the slope
slideMovement = -slopeDirection; //Makes it so -slopedirection goes down instead up
}
else
{
isSlopeSliding = false;
slideMovement = Vector3.zero;
}
slideMovement = (Vector3.ProjectOnPlane(slideMovement, slopeHit.normal).normalized) * currentSpeed; //Makes players stay on slopes
controller.Move(slideMovement * Time.deltaTime); //Move the character along slopeDirection
}
But then you're also applying your own gravity by subtracting at a fixed rate towards vector3.down, yeah?
So in that sense gravity is off for your objects?
It's a good idea to limit the amount of places I alter velocity. Are you directly setting it when you move or are you += setting it?
have you tried it?
that code there? yes
I mean have you tried setting slopeMovement to 0 just before the jump?
i swear i did, but ill try again
I am applying a constant downward force to act as my gravity, yeah, that does mean my player or object using the system would fall at a different rate than Units default physics, if I choose to change the default values, it allows me to change how fast I want gravity to be for the player, and how floaty I might want my jump to feel, maybe I want a trigger that changes things that enter it to zero gravity like space, etc
I set my velocity with interpolation, for example it may look something like rb.velocity = Vector3.MoveToward(someVector3, someTargetValue, t);, here are some resources I found helpful for building mine:
https://gamedevbeginner.com/how-to-jump-in-unity-with-or-without-physics/
(this video may give a better understanding of the math: https://www.youtube.com/watch?v=acBCegN60kw)
https://gamedevbeginner.com/the-right-way-to-lerp-in-unity-with-examples/ - I decided to build a wrapper for this, so I can treat t like time, and have the wrapper do the math and handle delta time
Learn how to jump in Unity, how to control jump height, plus how to jump without using physics, in my in-depth beginner's guide.
An update to the Better Jumping in 4 Lines of Code, including fixes to the Physics Update, along with some alternate methods of applying force and gravity to the player.
Support Board to Bits on Patreon:
http://patreon.com/boardtobits
Check out Board To Bits on Facebook: http://www.facebook.com/BoardToBits
ok just tried it and can confirm that its a no go
can I see the jump code?
!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.
If you want to know the very moment you leave the ground/your bool becomes false, you could setup a second bool and use that as a "last state" to act like an event (or you could call an actual event too), for example:
bool lastSlopeState = false;
bool currentSlopeState = false;
System.Action onLeftGround;
if(someCondition) {currentSlopeState = true; DoOtherStuff();}
else if(someOtherCondition) {currentSlopeState = false; DoMoreStuff();}
if (currenttSlopeState != lastSlopeState) {onLeftGround?.Invoke(); lastSlopeState = currentSlopeState ;}
You can do something similar for landed or any specific condition you want to get notified about, it does mean youd need some extra variables and statements, but it could help, in this case you could subscribe to onLeftGround and reset whatever values you need there
StateManagerCode: https://gdl.space/exabisegoj.cs (where slopemovement is handled) i also tried to set my vector to 0 when i enter the jump state.
I don't see where the jump velocity is applied
Thanks a lot! This is a lot of information, I'm currently reading through it and seeing what parts apply to me etc. If other people are comfortable setting velocity directly that may mean it's okay for me to do it too. Thanks for all the resources and for explaining how you use it!
is the jump state in a different script?
yep ill grab that 1 real quick for yah, that where i put slidemovement = vector3.zero
i tried to add a boolean in the jump state found that a bit hit and miss, so idk if that will apply for the vector. https://gdl.space/tosupihefo.cpp
I'm not familiar with the State system you are using, where is EnterState called?
Oh I see it. it's in SwitchState()
Does SwitchState get called somewhere other than Start?
Can I see the code that calls SwitchState(new JumpState()) or something similar?
i believe this is what your looking for, its in every state that way u can jump in whatever state your in
if (movement.controls.Player.Jump.WasPressedThisFrame()) ExitState(movement, movement.jump);
i think thats the only place where i call it, but i did go find all reference and it pops up with that same code ^ but only in idle and ExitStates
idk if this would work but im just gonna see if i press space bar to reset,
I get it. That makes sense. I think the problem is a "kind of" race condition.
So you're setting the slideMovement to 0 when you enter the jump state, but as far as I can tell, you continue to run slopeSlider() every update which will set it back. I think you were counting on your ground check to be false immediately after you jump, but that will almost certainly not be the case. You probably need to find a way to give yourself a grace period after hitting the jump button where you don't do a ground check.
can anyone help with discord oauth integration with unity, i have got to the part where i open up the auth window and everything i just cant figure out how to extract the code from the URL and exchange it for user id and stuff
ok welp thanks for helping, i think i was on the right track in terms of problem where the vector still has its values when u jump causing that motion in the video. It was a lot worse before i reset the target speed because player could gain speed from sliding and then be able to use the speed to go up fast. **Now a feature **
Sorry, I don't understand. Is that the intended behavior?
Np, there are often many ways to approach problems, and each part of the API will have its uses in certain cases, if your confused about the functions of how rigidbody movement works, take a read through the docs, often they also explain use case and limitations of components API, but it is certainly good to also get some other opinions maybe when more people may be coming online later
nah not the part where yah jump. i dont think it will be game breaking tho
Yeah, basically every solution "works" but there's always a trade off in terms of what you can and can't do, and where you have to put extra effort in.
Maybe I should have asked this first: what is the behaviour you are trying to implement. I thought that you were trying to allow the player to jump while sliding, but keep the velocity of the jump consistent with a jump from a stand still.
If I run SetActive(true) on a already enabled object does that โrestartโ the object? Or does it have something built in that would ignore the request
you could always put a log in OnEnable and see if it is called when you call SetActive on an already active object
there's also no indication of whether it makes that check on the cs reference either since the entire method is in native code
https://github.com/Unity-Technologies/UnityCsReference/blob/master/Runtime/Export/Scripting/GameObject.bindings.cs#L261
by "restart" to mean call the Start() method again?
Once I get home Iโll test
ahh so when the player slides it changes the slideMovement Vector to the angle of the slope so player slide to the bottom (first part before jump), but when you do that and then jump u get that extra boosted jump where you go back where u started sliding. (not intended) i think the slideMovement still has the values of the slope angle before you jump which gives it that forward boost.
Start and/or OnEnable
well Start for sure won't run a second time
curious if it dirties canvases and initialises animators
I see. I didn't know that the jump in your video was more than expected. I still suspect that problem lies in your ground detection remaining true for at least one frame after you hit the jump button.
that could very well be, might just try making the radius less to test your theory
That will also have problems since you are dealing with slopes and your character stays vertical on them leaving a gap directly below, which I'm guessing is where your ground detection sphere is
yeah no go on that 1, smallest it can possibly be before it wont allow player to jump
Hm, so you are applying this downward force even if the person is currently standing on the ground? If I try to replicate this it appears my X-speed is getting cancelled out
Basically this
Vector2 gravityVelocity = (Physics2D.gravity * rb.gravityScale);
rb.velocity += gravityVelocity;
Appears to cancel out any horizontal velocity I had
What property would tell them apart?
if you pass the two colliders into your script as properties you can compare them directly
Hi everyone
something like this:
public Collider colliderOne;
public Collider colliderTwo;
public void OnCollisionEnter(Collision collision)
{
if(collision.collider == colliderOne)
{
Debug.Log("I guess it was Collider One");
}
}
I wrote that code in Discord not a code editor, so it probably doesn't run, but you get the idea I hope
Hmm when I did those public things in inspector they appear to both select the same collider
You need to drag in the two colliders into their respective slots
if you drag the same one into both, then they will both be the same one
Does anyone know if it is possible to pass a array of positions, instead of matrices when using gpu instancing (fixed scale/rotation). Cant find any examples online, thanks a lot
I dont always apply gravity, no, just when my character is considered "airborne", and specific cases like inclines, I cancel it for some actions like animation locks, I call it from its own function so I can control when it should be active, something similar to if(!isGrounded || isAirborne) {Fall();}
I see. I had some success not applying any gravity of my own if I only altered the x-velocity of the unit and kept the y velocity from the last frame
and then just using the default rigidbody gravity
Howdy friends, I have this little trigger forwarder script
public class TriggerForwarder : MonoBehaviour
{
public UnityEventCollider onTriggerEnter;
public UnityEventCollider onTriggerStay;
public UnityEventCollider onTriggerExit;
[ReadOnly] public bool onTriggerEnterEnabled;
[ReadOnly] public bool onTriggerStayEnabled;
[ReadOnly] public bool onTriggerExitEnabled;
private void Start()
{
if (onTriggerEnter.GetPersistentEventCount() > 0)
onTriggerEnterEnabled = true;
if (onTriggerStay.GetPersistentEventCount() > 0)
onTriggerStayEnabled = true;
if (onTriggerExit.GetPersistentEventCount() > 0)
onTriggerExitEnabled = true;
}
void OnTriggerEnter(Collider other)
{
if (onTriggerEnterEnabled)
onTriggerEnter.Invoke(other);
}
private void OnTriggerStay(Collider other)
{
if (onTriggerStayEnabled)
onTriggerStay.Invoke(other);
}
void OnTriggerExit(Collider other)
{
if (onTriggerExitEnabled)
onTriggerExit.Invoke(other);
}
}
I have these bools so it doesn't waste time invoking stuff I have no interest in invoking, but is there a way to completely prevent these functions from running depending on my bools that exists outside of the function?
like I don't want OnTriggerStay being called if that bool isn't true
If you dont need custom gravity or dont want to implement it now, the default Unity gravity on the rigidbody should work just fine as well, just a bit more limited in controlling object-specific gravity, but its good to address one problem at a time, what does your full script look like and what does it do currently? You can use a code paste site if the script may be a bit long



