#⚛️┃physics
1 messages · Page 31 of 1
Ofc you can write your own tool that parses the SVG (xml?) into points/shapes and create polygoncollider2D's out of those
Why is that crazy or wild?
Unity uses Box2d for 2d physics. Here are the things it supports: https://box2d.org/documentation/md_collision.html
the thought crossed my mind. then i thought surely someone else did this and now everyone uses that
convex polygons and line segments are the clost thing
(svg is based on xml)
It's not trivial to just support arbitrary curves for collisions
That makes it all click. duh. thank you for that
svg supports bezier curves, text, css, animation, transparency, gradients, masks, a bit much to decide a conversion from all that to some shapes
I do have mostly straight lines but the curves are what require me to up the sampling when generating the colliders in unity. so maybe i do the straight lines in one sprite and the curves in another
Thank you all for explaining this. I feel like I understand why what I expected was a lot to expect
Edge colliders seem to be way better for what I am doing and I was able to whip up a script that reads the vector path data from the SVG file (had to give it a txt extension and get a lil help from chatgpt) and converts each straight-line path into a scaled, flipped set of Unity edgeCollider points.
Is this fine to not use rigidbodies for animated characters hitboxes?
I mean they are just there for bullets and raycasts to collide into them
I am pretty new, but all signs point to yes that is fine. Are your bullets physical objects with rigidbodies? If the bullet has one that the character doesn't need one. just colliders is fine if you ask me. if there is no bullet object (just raycasts) then you dont need it on either. Still would like to see if a pro agrees.
however, i also spent a few hours last night trying to composite edge colliders only to find out (it seems) you cannot composite them 🙂
I wonder what are possible edgecases where I used to use collision.contacts[0].point as a place to spawn something
at what cases I would get multiple contact points?
weird U shaped collider hitting a wall?
I guess for an explosive with a more or less potato collider using [0] point to spawn explosion nothing can go wrong
But for weird complex colliders... I guess I would have to calculate average?
@kind mauve Use the first contact when you know it doesn't have to be super precise.
There are many cases where you get multiple contacts:
-Two colliders touching at some corners, each point gets its own contact (like your U shape example)
-Two collider edges are touching, it generates a few contacts along that edge
-^Same but with faces, for example a box resting on a plane
can I at least expect at latter cases that those contacts are more or less symmetrical?
No idea, go and test 🤔
Like a Debug.Break + some Debug.DrawRay for each contact on collision
in some cases you might want to spawn something at all the points
Anyone know if there is something equivalent to ConfigurableJoint damping/spring in 2D?
This specifically:
joint.angularYZDrive = new JointDrive
{
positionSpring = Module.Data.JointStrength,
positionDamper = Module.Data.JointDamper,
maximumForce = Mathf.Infinity,
};
I'm using ConfigurableJoint to create a tree-like structure, but since my game is 2D, I have all of my 3D objects locked on z-axis. I'm wondering if I could use 2D physics and gain some performance and stability. Right now I'm testing HingeJoint2D but am not seeing any spring force options
Example of what I need - notice the springyness (3D version)
Example of what happens in 2D with hinge joints (currently converted my code to 2D with hinges, don't have a video with this tree using ConfigurableJoints, but trust me its stable :D)
I just want to admit that this looks cool
Any reason why updating configurable joint angular drive values in editor doesn't affect them unless i do that while not play mode?
Not that i know of. You mean inspector or via code?
inspector
Pretty sure the configurable joint inspector is a bit buggy
Is there a good way to get this to work with? I’ve been trying with animations to limiting success. I can’t get the speed I want.
Not enough context. Are you making a pinball game or what
Yes
What speed? Speed of the ball?
You shouldn't use actual physics collisions for the launch mechanism (unless you are making some ultra detailed simulation)
Just set the velocity of the ball's rigidbody
Oh ok I will add that into the collision code
I do need to clean up the model though
I was reading the documentation and it says to use add force
yes do that
What mechanism is this?
I thought its what launches the ball but apparently not
If its supposed to bump the ball on collision then yeah addforce
it's a bumper from the looks of it
(the pink and white part at the top is the actually visible part in the game)
My code looks like this, but my car is shaking a lot. I’d really appreciate it if you could help me.
Is this AI generated code?
yes,I got some help
Please let people know in advance when you’ve used ai
Have you tried asking the AI about why it's shaking and how to fix it?
yes,I asked many times
ok,sorry
Do you have interpolation enabled on the Rigidbody?
yes
happy to provide mor information if necessary, im unsure what category this goes in, but I was redirected here after asking in general. My player object interacts with the white object by walking near/over it to "pick it up" (opens UI canvas) but for some reason when i walk away (which is set to disable the canvas and does so successfully) the player gets stuck (no moving, including jumping, camera still can rotate) for some reason . been getting stuck between houses and in other spots too, with no obvious explanation, its been driving me mad. the colliders are slightly oversized but, the sphere collider has "slippery" physics so shuldnt be getting stuck to anything and there's not even a boundary where the letter is. theres a collider on it but its set to "is trigger" and its not even the envelope that it gets stuck on, but a second or two after. I tried disabling the script that turns on the canvas and it still didnt fix the issue so its not a scripting issue. I dont know if its related to how Ive been getting stuck in other nearby areas or not, but its immensely frustrating!
It'll almost certainly be related to your code or the scene setup. There's not enough information here to diagnose it exactly. One good thing you should do is pause the game in the editor when the issue happens and double check everything in the scene - the movement script, the colliders, etc.
Actually - now that I think of it
This may be the biggest clue:
the player gets stuck (no moving, including jumping, camera still can rotate) for some reason
This is pretty typical of what happens when you have set Time.timeScale to 0. The camera rotation often still works because it's not multiplied by Time.deltaTime
Are you setting the time scale to 0 when you open this menu @stuck saddle ?
i feell ike i am stupid because i have no idea where to find this information 😭 i am doing this in for a class and they have only taught us visual scripting, im not even sure how to access the C# code
but i dont think its connected to any visual script i made so i think it must be a setting or something, maybe a setting that has altered that
could it be related to the particle system coming out from the white object (particles not pictured here)? even when i disable that it happens, though
In your code
this is something you would be doing in your code
I think it is in your code yes
show your code for when you open the menu
YOu can show the visual script
there is no C# code if you did a visual script
im not opening a menu, i disabled the script to test if it still did it when i turned the canvas off
BTW if this is based don like an OnTriggerEnter or something, it doesn't matter if you disabled the script
ohhh
it still runs
ok yeah its probably that then
let me show it
wait its not on trigger enter i thoughti t was for some reason
its on update
How many scripts are in your project
four graphs but there are a looot of embeds
most are on the player though
but this issue specifically wasnt happening in that area til i added the envelope
(white object)
Just check all of them and see if you're setting time scale anywhere
(this is part of why visual scripting is not great)
ok yes, i am, but only when the pause menu is activated
i noticed though i actually can move very slightly after walking over the object if i hold down a move key long enough. like veeeeery slightly
so it has to be an issue with that object specifically i just have no idea what
Paste screenshots of the scripts here
sorry i am not sure which scripts you mean, the only script i have pertaining to this object is disabed, the on update one
i can still send it if you think its relevant
i mean maybe its a player movement issue i guess? but i havent had the issue before with other stuff
Don't have enough context to ask for a specific script, so just paste them all I guess.
Faster than us asking tons of questions in this instance
Especially the player movement script
ah
i think i figured it out
i made a script to make jumping more realistic to ground my player and it is pushing down on my player while im walking too
so that must be why the friction when i walk on the letter makes me stuck
yup, that was it. i genuinely wouldnt have figured that out if you guys didnt prompt me to check that script so i really appreciate the help :)
im wondering if this could be a physics issue, what do you guys think? https://discord.com/channels/489222168727519232/1477422337610744039
Hi all, I am trying to setup wheel colliders for a motorbike with a sidecar but getting all kinds of balance issues. What do you pros do in this case?
it is steering in random direction even when i just drive forward or back
i have only rear wheel is for motor
front wheel is not a "steering" wheel per se, as its pivot is elsewhere because that's how bikes work
and the sidecar just has a wheel collider but it doesnt perform any special function, throttle or steering
i am not sure how to setup collider for chassis in this case, or where centre of mass should be exactly, i assume "at the centre" but apparently not
I'm working on crouch and wall running mechanics for an upcoming horror series!
Hello ! I have a question regarding Fixed Joint. I have a serie of connected rigidbodies. But the structure never settles and wobbles/runs away. The problem seems to be that the collider overlaps. But Fixed Joint has an "Enable Collision" that I have obviously unchecked.
My issue is that my game will create such structures at runtime and I can't assure there won't be overlaps, so I need to support it. Any ideas ? I've skimmed internet without any luck at the moment : (
I have tried using configurable joint and I can get the structure rock solid. But it still tries to "run away" ^^'
I have heard the fixed joint being quite unstable. Do you need the breaking behavior or why do you use them instead of parenting all the parts within one rigidbody?
Fixed Joint Vs Collider Overlaps
I'm using Mirror for multiplayer and it does not like reparenting
hello, how do i make the object i grab be more attached to the magnet? I used a fixedjoint for the object, and i cant make that the magnet will have more force because it has similiar results, and changing linear damping doesent work either
Can you explain what exactly you're trying to do here and what's going wrong?
Im trying to make a good magnet, but when I catch something the object doesent stay in the magnet very well
And another thing, I had to disable collision with the object i catch with the player but it doesent look good, i did this to prevent the object to move the player unvoluntarily but is there a way to just make the object slide off the player? Same thing with the magnet
The matrix thing doesent work
- make the player a kinematic body. that solves the problem of the object being attracted hitting the magnet and moving it involuntarily.
- how are you implementing the attraction/repulsion? im guessing the red object in ur video is the magnet and the white object is being replused and the gray rectange is being attracted to the magnet. Are you computing the distance between the magnet and the objects to attract/repulse or do u have something like a field around each object (a trigger col or something) and objects react to the magnet when they come in contact with each others fields?
i will just show the code, but how to show the code not as a txt file?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Magnets have more influence the closer an object is. Have the forces applied be relative to the distance the object is from the magnet, as opposed to a flat value.
so how would you recommend me to attach an object smoothly in my magnet?
you were shown above how to send files properly
use the pastebin sites
share links, not files
and btw i cant put the player in kinematic or it will push objects trough the wall
If input && distance <= maxDistance, get direction and addForce in that direction towards the magnet.
addForce relative to distance, ie, addforce * distance^-1. Or * (1/distance)
a powerful website for storing and sharing text and code snippets. completely free and open source.
this good?
i dont get it sorry
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
So..... the way i got my motorbike and sidecar to work with wheel colliders was just to ignore the sidecar specifics, and just have 4 wheels total, just like a car, 2 of these are legitimate and present on the motorcycle, 2 are just placed invisibly to the side of that.
It's fake as hell, but whatever, it gets me passed my task
Kinda depends on the goal, day/night, lamps, screen light, etc.
Not a physics question^
oh okay, but what will this improve here?
nvm i got it, thats actually cool, i didnt think about this
but does anyine have any idea of fixing the problem with attached objects?
why is making a magnet so hard... is my game idea too hard for being my first real game? Do you recommend me anything else or am i just not good
Hello everyone, I have an issue with the rigid body in my vr game and to be more specific on what issue Im having I have a mazebox and the player is suppose to grab and when the player grabs it it activated the phsyics for the ball and the player is suppose to tilt the mazebox until the ball goes to a hall.
but the issue is the ball dropts all of the sudden or jumbs off the maze box
I made both the box and the ball continues in their rigid body but still problem is not fixed does anyone have any reccomendation to how to fix it
well... this kind of thing is always pretty finicky. A few things i'd do:
- Make sure the maze box is actually rotating via the physics engine. This means if it's kinematic it should be using Rigidbody.MoveRotation. If it's dynamic it should be using angular velocity and/or torque
- Make sure the maze box has
continuous speculativeas the collision detection mode - which is the best for rotating objects - Try to keep the rotations slower/less jarring. Too sudden of a movement has the potential to be too much for the engine to handle in one frame
Something that absolutely baffles me about Unity is that doing rb.MoveRotation ignores rb interpolation. I set my fixed timestep to 0.05 (so 20hz) just to make it apparent when interpolation isn't working. Interpolation is on, i rotate my character, and the rotation is insanely choppy. Positional movement is fine though. I move my character by setting rb.velocity, and positionally, they interpolate as intended. but doing rb.MoveRotation completely bypasses rotational interpolation. I did find out that setting rb.angularVelocity and also rb.AddTorque don't bypass it, which is cool, except using those to turn a character is super impractical in my case. It'd be like a balancing act to get my character not to topple over and summersault since you have to have the rb rotation constraints freed up. I just wanna set my rotation without my character's rotation teleporting man...
MoveRotation only obeys interpolation for kinematic bodies. Both MovePosition and MoveRotation in 3D are really intended for kinematic bodies only
I see. what's the solution to trying to rotate a non-kinematic rigid body then? Like a player. For example, if I want to align my character to a ground normal for example.
It depends - do you need physical realism for this rotation?
Does your character ever actually rotate? Is this like a game where you're on the surface of a planet? Or are you just talking about a world where the ground is always the same orientation?
Nothing crazy, i'm just rotating their rigidbody gameObject, which is the parent object of the entire player. So just matching the transform.up to the ground normal.
Quaternion toTargetUp = Quaternion.FromToRotation(rb.transform.up, groundNormal) * rb.rotation;
nextRotation = Quaternion.Slerp(rb.rotation, toTargetUp, alignSpeed * Time.deltaTime);
rb.MoveRotation(nextRotation);
should i instead manipulate the rb game object's rotation in Update? For example: transform.rotation = X
I actually just tested it. So instead of MoveRotation I set the transform.rotation directly in Update. It was rotating at 20 hz so that's a no go.
My hack right now is to use rb.MoveRotation and perform it in Update so it isn't choppy.
that doesn't fix or change anything
MoveRotation just queues it up to happen in the physics update
this doesn't actually answer any of my questions
no - never modify the Transform directly
It did fix it because even at 20 hz, it's moving at my framerate instead of at 20 hz
you can do rb.rotation = nextRotation; in Update
directly
but it won't have physical realism
hence why I asked about if you need physical realism for it
(i.e. collisions etc)
I am taking a capsule that has a rigid body on it, and rotating it from upright, to tilting on a slope with some lerp time
So far I've been doing it via rb.MoveRotation but that doesn't interpolate.
Ground is not the same orientation. there are slopes the player should rotate to align to
the player also rotates on their local y axis with left/right input. the camera is fixed behind them. It's here where you an also see the 20 hz rotation.
the player also rotates on their local y axis with left/right input
And how are you doing that?
if you're modifying the Transform directly, that will break interpolation
All MoveRotation
and if you're doing MoveRotation there, that will conflict with this MoveRotatio
MoveRotation cues up the rotation until the next physics update
And it doesn't interpolate with rb interpolation right?
having two different scripts doing it at once will not work well
AFAIK it only respects interpolation for kinematic bodies
I see, which mine isn't. What method would you go about rotating the rb on its local y. In order to spin on that axis via input.
if you don't need physical realism, which you don't if it's a capsule, again you can directly do rb.rotation = in Update
I see, I'll give this a try, ty!
I tried setting rb.rotation directly and it made it so that both rotation AND position interpolation was bypassed. I think if you directly edit the transform of a rb it bypasses all interpolation.
The RB Is not the Transform.
Correct, modifying the Transform breaks interpolation
Sharing your code might help
rb.transform.rotation, same result
This is a simplification of what I have now
In Update():
float turnInputSmoothing = Mathf.Lerp(turnLerp, horizontalInput, 3f * Time.deltaTime);
float turnSpeed = 120f;
float deltaDegrees = turnInputSmoothing * turnSpeed * Time.deltaTime;
Vector3 localUp = rb.transform.up;
rb.transform.rotation = Quaternion.AngleAxis(deltaDegrees, localUp) * rb.transform.rotation;
You can recreate this by making the fixed timestep 0.05 to make jitter more obvious. It'll make things that don't interpolate look like they're running at 20fps. Anyways, then take an object and rotate it around its y axis. I have a cinemachine follow camera behind the player at all times, CM Brain set to LateUpdate. You'll see the rotation is laggy. And if you move the player during the rotation (I almost always move by setting rb.velocity), the movement will also be laggy. But move without rotating and your movement will be interpolated correctly.
It seems directly modifying the rb.transform will bypass any interpolation, position OR rotation. However, when I do MoveRotation(Quaternion.AngleAxis(deltaDegrees, localUp) * rb.transform.rotation) instead, it doesn't seem to bypass the interpolation on either position or rotation.
yes, that's the transform.. you aren't supposed to modify the transform
try rb.rotation
rb.MoveRotation only interpolates for kinematic rbs
rb.rotation doesn't interpolate, it's a teleport
for dynamic rbs you would generally use angularVelocity or addTorque
I did try rb.rotation
right here
well yeah rotation and position are teleports
Then why are they being suggested lmao
All good lol, I'm basically asking how to rotate a rigidbody in a way that doesn't break rb interpolate
MoveRotation breaks it, setting rb rotation breaks it
is it dynamic or kinematic
Dynamic. Setting angularVelocity and doing AddTorque doesn't break it. However i don't see those as really being good ways to precisely control my player's rotation. For example. I want to align their transform.up to the ground normal, doing AddTorque/angularVelocity would be insane
welp angularVelocity and AddTorque are the ways with interpolation then
for that task you'd probably want angular velocity
you could do what MoveRotation would do and calculate the needed angularVelocity to get to the right rotation (assuming your player will already be close to the correct rotation)
(if not, it might be jarring and you'd want to make that happen over multiple ticks, probably)
doesn't angular velocity have momentum and stuff? you'd need to like, counterbalance it constantly? also in order for angularVelocity to work, you need to have your rb rotation constraints disabled. so my character would be rolling and doing summersaults lol
you could just have angularVelocity = Quaternion.identity in the case they're already upright (which should result from the math without having to add a special case)
for the latter, i'm not sure, i don't know what order the simulation is applied in. i'd assume setting angularVelocity directly with some specific rb setup could get there but i'm not confident
I pretty much just want to smoothly lerp my rb towards an orientation and have rb interpolation that rotation so it doesn't rotate at 50 hz since the default timestep is 0.02.
Unity not having a way to do this is insane
this isn't really a unity thing
this is what physx provides
(i agree it's kinda weird, just saying to blame the right person lol)
i don't have the time to test this stuff right now, so that's about the limit of what i can recommend
I used to be able to use the unity physics debugger to show all colliders, but now its simply not working.... did something break recently, running 6000.0.58f2
I have gizmos on, I reset all physics debugger windows then selected show all
but still nothing
you can
https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Rigidbody.MoveRotation.html
Says in the docs:
"Use Rigidbody.MoveRotation to rotate a Rigidbody, complying with the Rigidbody's interpolation setting.
If Rigidbody interpolation is enabled on the Rigidbody, calling Rigidbody.MoveRotation will resulting in a smooth transition between the two rotations in any intermediate frames rendered. This should be used if you want to continuously rotate a rigidbody in each FixedUpdate."
ive personally tried it as well. lerping with interpolation off may or may not give jittery visual but using rb.movepos/moverot with interpolation smooths out the jitter
MoveRotation breaks interpolation. You can test it by turning the physics step to 0.5 and you’ll see it hard jumps with zero interpolation
a physics step of 0.5 is an extreme case. it never occured to me to test it with such values
Just like how MovePosition also breaks interpolation
It’s just to make it obvious when interpolation is breaking. Pretty much for testing purposes only
I spent 16 hours yesterday testing what breaks it or not lol
Actually I lied I was testing with 0.2 which is 5hz
you should prolly compile your findings and post them
MovePosition doesn't break interpolation, it just doesn't work for non kinematic bodies, it's meant for kinematic
Same MoveRotation call for both having interpolation on with physics step of 0.2. MovePosition and MoveRotation are only really meant for kinematic bodies but the documentation is all but clear about it.
Exactly, that aligns with my findings
In this context I mentioned I have a non kinematic character
In that case you should not be using MoveRotation
So my question is, what is the alternative to MoveRotation for rotating a non kinematic rb object while keeping interpolation. Let’s say I want to lerp its transform.up towards Vector3.down.
as mentioned many times:
- angular velocity
- manually setting rb.rotation in Update
Second point is false
It's true and I do it all the time.
Directly setting rb.rotation interrupts interpolation. You’re just brute force teleporting the rotation
I would also consider combining the two. Using angular velocity to get the interpolation and use rb.rotation to make it always stay in phase no matter what
but you're doing it in Update so you get perfectly smooth rotation anyway
It makes it so position stops getting interpolated too though
not in my experience
Maybe if you've turned on a setting
like "automatically sync Transforms" or something
I know this works because I've solved dozens of peoples' issues with jittering in their first person controllers by having them rotate via rb.rotation = instead of rotating the Transform
and they get smooth motion and rotation
I can check for a setting but in my tests I did yesterday, when you are actively setting rb.rotation, interpolation for position stops
I have pretty much all default physics and rigidbody settings in my project. Other than 0.2 timestep for stress testing
And besides that, angular velocity is probably the most insane way to control an objects orientation
My solution was to use MoveRotation, which, like setting rb.rotation, it’s a brute force solution that teleports the rotation every frame. However, unlike setting rb.rotation, using MoveRotation doesn’t seem to break the positional interpolation.
you can just use angularvelocity to "set" the rotation directly like this.
// In FixedUpdate:
Quaternion delta = targetRotation * Quaternion.Inverse(rb.rotation);
delta.ToAngleAxis(out float angleDeg, out Vector3 axis);
// Remap from [0, 360] to [-180, 180] so we always take the short path
if (angleDeg > 180f) angleDeg -= 360f;
rb.angularVelocity = axis * (angleDeg * Mathf.Deg2Rad / Time.fixedDeltaTime);```
or maybe that's 2d physics actually...
In 3D it only sets the angular velocity for kinematic bodies, for non-kinematic it just teleports like rb.rotation. For 2D they work for non-kinematic too afaik yeah
I am having this issue where when my legs that have ragdoll properties hit the ground they jitter/bug out. I want them to lay smooth on the ground.
Hey guys what is the formula for the corrective angle to level out a turret to the horizon (or any other angle really) if the entire platform is not on level ground?
Project the direction vector on whatever plane you want it aligned with
i have a trigger collider that is causing physical collisions with another collider. anyone know why this could be?
additional info: i have a character controller with a capsule collider & an attack animation, when that animation is played, an attack hitbox is set to active, this is a box collider set to be a trigger. it is quite clearly intersecting with he capsule collider. i have set in the physics settings of the project that the layer the attack hitbox is on not to affect the player layer but it's still causing collisions. the only thing i can think is that the attack hitbox is a child of the player (not the capsule collider though)
the capsule collider on the CC being the attack hitbox or the player hitbox?
a CC is already a collider
it's a rigidbody based movement system, not the character controller component. the attack hitbox is a seperate thing, let me get a screenshot
ah, gotcha.
what do you mean by "it's causing collisions" exactly?
when i play the attack animation, the player is stopped while running as though bumping into something or if standing still and attacking, moved slightly backwards
are you sure it's this collider? are you getting collision messages with that collider?
If I delete this collider entirely, the issue goes away
I've just edited the collider substantially so that there's no chance it can collide with the capsule collider of the player and the issue has also gone away now, i don't understand why "Is Trigger" isn't working
How do I get an object to move across surfaces without being projected into the air if the surfaces are not perfectly aligned? I am using a sphere collider (that might be the issue). You can see in the video I hit a small bump and fly up. I am using forces and not translation (more context).
the best thing to do would be to replace the colliders at those points to be one continuous mesh collider instead of two separate colliders
Okay, so I need to update level/3d design, rather than a physics problem
im having an issue where the colliders are affecting animation. any way to fix this?
essentially walking onto a new tile will sometimes make the vacuum jump between the inAir animation and the grounded animation
sounds like an issue with your code that detects if you're grounded
Probably the case of the classic literal edge case where the collider collides with the edge of two colliders even though there shouldn't be an accessible edge. It can make the character bumb a little and be airborne for a very short duration. It's a limitation of the discrete physics engine which probably can't be fully prevented without making the whole floor out of single continuous collider. You can prevent that in your ground check by adding little margin that allows the player to be slightly off the ground. You can also use different ground checks for the movement and the animation if you want
thats the issue.
Ill try out your fixes shortly!
Thanks!
SOLUTION!!!
im dumb as hell
I was using OnColliderStay() for groundchecks
i was meaning to swap it over to a casting approach but Ive been too lazy and forgot about it
but now its a Physics.CheckSphere() function and it works amazing.
Im working on a movement controller
using unity ECS
im doing a drag and acceleration-based approach
whenever I jump towards a corner like the one provided on that cube, it tends to bounce me upwards higher than a jump normally would
Im not quite sure what to do
I did set up the physics material
here's the movement system's onUpdate
I'm not quite sure what I can do to mitigate this issue
theoretically I could just make it not actually use a rigid body velocity and instead just cast in the direction of the calculated velocity and move it based on that
but I have a feeling that that'd have some unintended side effects
and it would make it so that I cant interact with other physics objects properly
which isn't the end of the world, I dont need them to interact necessarily
but it's nice to keep that option open if possible
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
hi, i am doing 6. from https://learn.unity.com/pathway/junior-programmer/unit/player-control/tutorial/1-2-move-the-vehicle-with-your-first-line-of-c?version=6.0
Overview:
In this lesson you will make your driving simulator come alive. First you will write your very first lines of code in C#, changing the vehicle’s position and allowing it to move forward. Next you will add physics components to your objects, allowing them to collide with one another. Lastly, you will learn how to duplicate objects in...
however even though i have the rigid body on both the car and the object, the car still goes through the obstacle in a way
IIRC that tutorial is terrible and has you move a Rigidbody with transform.Translate
Basically just throw that tutorial in the trash. Dynamic Rigidbodies need to be moved via the Rigidbody if you want physical realism.
Does anyone have any ideas about this? ONLY the second assert is failing.
(Single collider on the raycasting transform)
Given the Physics2D Raycast Docs say: Notes: Raycasts will not detect Colliders for which the Raycast origin is inside the Collider do you have any hints or ideas as to why the last assert would fail?
RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.up, rayLength);
Debug.Assert(GetComponent<BoxCollider2D>().bounds.Contains(transform.position), $"Position {transform.position} is outside of its collider bounds {GetComponent<BoxCollider2D>().bounds}");
Debug.Assert(hit.collider != GetComponent<BoxCollider2D>(), "Raycast hit own/origin-containing collider, which should not happen.");
Thanks!
You linked the Physics doc, not Physics2D doc!
Physics2D is capable of detecting a query starting inside a collider
I was literally staring at the types thinking I might have something which isn't 2d at one point but I never considered I was reading the wrong docs
such a classic bit of oversight haha
the type that wasn't 2d was in your browser lmao
Suppose I might be cheeky and ask if there is a reason for that? (Quite new to 3d programming)
I can only assume that it's computationally simpler to check if the point is inside a collider in 2D than in 3D
Like testing a PolygonCollider2D would be way simpler than testing a MeshCollider
Could just also be that that's how it comes out of the box with the 2D engine (Box2D) vs. thet 3D engine (PhysX)
void OnTriggerEnter(Collider other)
{
if(other.gameObject.CompareTag("Bumper"))
{
b_Rigidbody.AddForce(-other.contacts[0].normal,ForceMode.Impulse);
Debug.Log("added force");
}
}
what am I doing wrong
contacts is an error
What exactly do you want to happen? That would add force towards the normal of the contact which is unlikely to be what you want
I want it to be pushed in the other direction
triggers don't have collisions, so they don't have contacts
How would I change it?
Other direction related to what?
of the other object hit
If you want a normal physical collision, just don't make it a trigger and it'll automatically bounce normally
I'm trying to have it like launch in the opposite direction of the collision
so, normal collision behavior?
I wanted to be very forceful because it's supposed to be a pinball bumper
i think you could also achieve that by setting a really hi bounce coefficient
Make it a normal non-trigger collider and then you can add extra force towards Vector3.Reflect(b_Rigidbody.velocity, other.contacts[0].normal)
Is there a way to compare tag or something? I'd like to make sure it's the right object that it is hitting
Yeah, I got that working but other does not exist
It also does not work if it's just velocity
I do in fact still need help finding a way to mitigate this...
(please ping reply)
it appears to me youre hitting the edge of the cube with your current velocity and having said velocity transferred into upward momentum?
im not expert on physics but it seems like that could be an issue
still need help
You have to give some details. Show the code and the errors, and be more specific than "does not work"
Ok
Thats what I was thinking but I dont know if theres any good way to mitigate that
void OnCollisionEnter(Collision collision)
{
if(gameObject.CompareTag("Bumper"))
{
Vector3.Reflect(b_Rigidbody.linearVelocity, other.contacts[0].normal);
Debug.Log("added force");
}
}
Does that Debug.Log work when you collide?
Also Vector3.Reflect returns the new value, you are currently not doing anything with it.
It should likely be b_Rigidbody.linearVelocity = Vector3.Reflect(...)
Oh this code wouldn't even compile
You changed the parameter to collision so you have to use that instead of other
it now compiels but does nod do debug.log
not
I got it working but no force is added
because you're not adding any force
how do I? with this
you're also still comparing the tag on the wrong object afaict
if you still have gameObject.CompareTag("Bumper")
you're checking your own tag, not the object you collided with
this is the code for the ball
right, so you're checking if the ball's tag is "Bumper"
which doesn't make sense
Vector3 direction = Vector3.Reflect(b_Rigidbody.linearVelocity, other.contacts[0].normal);
float speed = 10;
b_Rigidbody.AddForce(direction * speed, ForceMode.Impulse);
how do I check the other?
by using the parameter in your OnCollisionEnter
void OnCollisionEnter(Collision collision)
{
Debug.Log("aaaaa");
if(collision.gameObject.CompareTag("Bumper"))
{
Vector3.Reflect(b_Rigidbody.linearVelocity, collision.contacts[0].normal);
Vector3 direction = Vector3.Reflect(b_Rigidbody.linearVelocity, collision.contacts[0].normal);
float speed = 10;
b_Rigidbody.AddForce(direction * speed, ForceMode.Impulse);
Debug.Log("added force");
}
}
it works thx
That first Reflect line is pointless and can be removed
The second one is doing all the work
ok thx
Also small nitpick - collision.GetContact(0) would be slightly more efficient.
Yep, most unity properties that return an array usually allocate a new array every time you call it
There's usually a newer method replacement GetX
In my Unity 2d project, my player uses a capsule collider to navigate an uneven environment.
I on the other hand, slide off the side of platforms because of the capsule collider.
How do I stop the player from sliding off edges while still being able to move up and down slopes with the capsule collider
Probably the simplest fix is to disable gravity when grounded
Can one develop on mobile?
technically yes, realistically/practically no
Anyone know how I would make something like infinity from jjk like red and blue
A sphere
configurable joint target rotation isn't the same as transform rotation?
are they in different spaces?
So I want doors double doors to open when a player touches them like you hold the controller and have to physically open the door
I’ve been struggling the past 3 hours
I don’t know how to take screenshots on my laptop
Guess I’ll have to google it bc there’s no screenshot option on the keyboard
Google did not help
I have to snip every image I can’t just screenshot
Gah
my hinge is right there to the right where the rotate is
Is there a way to smooth sliding collisions with Unity Physics? I'm porting my game from Godot to Unity and while it was buttery smooth in Godot in Unity it seems to hit weird "bumps" regardless whether my tube is a box collider or a mesh collider, and it always seems to hit "bumps" in the same spots
in physX, sliding a box across a mesh collider can produce glitches at triangle boundaries that may look like jumps you are seeing. A sphere-like shape has fewer issues with that. You can play around with contact offset and bounce thresholds to maybe fix it for your particular situation. Otherwise you can make your own physics by moving the rigid body kinematically and ray casting.
Thanks Anikki! your response makes sense and helped me find https://docs.unity3d.com/Packages/com.unity.physics%401.4/manual/ghost-collisions.html
I’ll try a few strategies out, thank you!
Be careful, the documentation you refer to is for Unity.Physics, which is the physics engine for ECS (Entity Component System). If you are using Monibehaviors, you are using PhysX which is a different engine. While there may be some common ground to the behavior you are seeing and solution to them, I just wanted to highlight the distinction.
Hello! I am fairly new to unity, this is from one of my "dev logs", I was just wondering if anyone knew why this was happening? I saw a video that said using convex for multiple items is bad for performance in a game cause it uses a lot of computer power, I was just wondering if there could be an easier solution for this or a work around. I don't want to learn the wrong way to do this. It works as expected but i think there could be something else the pros do that i'm missing
You have it completely backwards. It's concave colliders that are bad for performance.
Convex is much simpler
Anyway Unity's physics don't support dynamic Rigidbodies with concave mesh colliders, precisely for that performance reason.
If the Rigidbody is dynamic, the collider must be convex
oh that's interesting. Thank you for clarifying
so this should be completely fine?
fine in what sense?
If you're ok with those collider shapes, it's fine yeah
if you want a more realistic collider, you could use two or more smaller colliders, including convex meshes and primitives
Fine, performance wise. Using collisions for each pin
Okay thank you. I’ll look into that
There's no general answer to this. If there's only ten pins in the game, it almost certainly doesn't matter what kind of collider you use. If there are 1000 pins, then it makes more of a difference.
I see. Appreciate this 🤝
is it possible to enable/disable rigidbody?
Depends what the purpose of doing that is. Usually making it kinematic (3d) or setting simulated to false (2d) is enough. Otherwise you'll have to remove or add the component
If during Runtime, Can it be removed, aside from being fully destroyed, and then fully re-added? Oh.. i think that is what you are saying, nm
@viral elbow you have a response ^^
im using navmesh, so enemy can follow player. The enemy can also dash, however it uses rigidbody to do that and rigidbody and navmesh dont work well together. So I wanted to see if i can enable/diable rigidbody for dash, as I will be disabling navmesh agent during that action
movement-navmesh
dash-rigidbody
but only one must be active/enabled at a time
Why are you using a rigidbody in the first place?
Oh yeah forgot I need to learn physic
... to dash?
dashing is awkward with navmesh, so i use rigidbody. follow player, rigidbody disabled-> start dashing, rigidbody enabled and navmesh disabled->after dash, rigidbody disabled, navmesh agent updated and enabled
elaborate
collider cast needs a rigidbody too...
it doesn't
just use a capsule cast or whatever for your hitbox
its a function you can call on Physics
for a dash, if it's teleport-y, just find the direction you want it to go in, cast forward and see if there's something in your way, if there is, use the distance value to put it against the thing or whatever
and if you want it to happen over time, just do some logic where every frame it does that protocol for part of the distance
ill try it out, thanks
np
capsulecast? its called spherecast
also its not collider cast its raycast
Both CapsuleCast and SphereCast exist
then what does capsule cast do?
is it just spherecast but with different x and z widths?
thats my assumption
same thing as a spherecast or boxcast but with a capsule shape instead of a sphere or box
that is so usefull thank you
(sarcasm)
I mean... not sure how else to describe it
a capsule is the same as a sphere in the y axis
Physics casts cast a shape through the scene
but different widths in x and z
so is it like a capsule lying on its side?
the raycast i mean
It can be in any orientation you want
A capsule is like if you cut a sphere in half and extruded it
dumah i know what a capsule is 💀🙏
now take that and cast it through the scene in a straight line
and you can define the orientation and scale?
your description of a capsule as a "sphere with different widths in the x and z" made it seem like you didn't
okay maybe i did a bad job at explaing\
the capsule is defined by the two focus points and a radius, so yes any orientation and size you want
the 2 focus points are the same point is it was a sphere
if you make a degenerate capsule where the two focus points are the same you get a sphere yes
this diagram shows the two points - A and B, and the radius
you can put the points anywhere and use any radius
bruh i aint that stupid
then google it lmfao
i have bad experience with raycasts
can someone help me make a force like an magnet
what issues are you encountering?
that kind of attractive force is just a force that changes with distance
I've been learning as I'm going but I just want to make basically an attractive force like thing infinity from jjk
have you tried googling that kind of stuff, as a start
thought this would be a better place to look sorry
in general you should look to existing resources first, because they'll likely have known working solutions, and it'd be faster and give more results if one doesn't work
general questions will yield general answers - if you have more specific questions, or you can't find info about something, feel free to ask
lol its just like those ppl on reddit who never do a google search and jump striaght to asking the unemployed
but at least that way, the responses will show up in future google searches whereas here it wouldnt
Hey, I'm trying to make a level where you throw a cyllinder around but I have a problem where my cyllinder hit the jointure of my floor parts, I was told in #💻┃code-beginner that I can use V to snap vertexes together, it's a really cool tool but I still somehow have the issue afterward (and i can't really use that for turns), would anyone please know how I can avoid that?
this is a common/well known phenomenon called "ghost collisions"
not a solution to your problem but something to research
My "temporary" solution for now is to use ProBuilder and use the merge object tool
I can give you a formula but it's not very accurate and definetly not the same as it works irl but if you need something simple it will be perfect
yes merging the meshes into one collider is one option
how do yall simulate fluids?
i mean im making a planet and stuff and right now, the player is shooting a raycast downward and if it hits the ocean floor, it applies water physics to it
but that only works for a static ocean
and doesnt actually behave like fluid
so i am curious to know how some other ppl here do it
this is an incredibly broad and deep topic, with many different answers, and it's going to depend heavily on what aspects of "fluid simulation" you're actually interested in.
well i have experience with minecraft, roblox, cities skylines, and kerbal space program
ksp sort of works how mine works now
just a static sphere
minecraft is not volume preserved so its wierd
roblox water doesnt even have any physics itself
it only has physics for things interracting with it
and cities skylines water is i just lwk dont understand it
ok well the real question is what you are looking to do in your game
im honestly not too sure yet
right now, its just purely aadventure and exploration
but im planning on adding other aspects to the game
like actual progression
Doesn't sound like anything that needs a realistic fluid simulation
its a mini planet where you walk around
however i want to add like digging and placing stuyff to it
like deforming the terrain mesh when you interact with it
That's a completely different subject
but then the water wouldnt work
For terrain deformation you probably want marching cubes
marching cubes?
since when were you here
its a public discord
also @timid dove your name keeps reminding me of percy jackson. like praetor raina avila ramírez arellano
lol
@gleaming flint Keep it on-topic, please.
sorry mb
OHHHHHHHH ive seen this before
but most of the results are for terrain
right now, it takes in an input seed, hashes it, then uses the seed to generate a 2d perlin noise map, and applies vertex offset based on the values of the noisemap
thats for the terrain
but idk about the water
Howdy doodles, would anyone have good knowledge on the configurable joint and the behavior between the joint and it's connection if made during play? I can't for the life of me get it to a result that works.
Hey small question is it right if i'm using the mesh collider with a none rendered mesh to be used to make custom physics collider for more complex collider? or should i'd rather script my own collider?
I don't know what you mean by "to make custom physics collider for more complex collider" but it is totally fine (and often recommended) to use different meshes for rendering and physics and also to have a collider without rendering anything. Rendering and physics are separate systems and don't require each other to work. Mesh Collider makes collision shape out of a mesh and Mesh Renderer renders a mesh, there's no inherent connection between the two (other than that of mesh colliders picking the same mesh that is rendered if nothing else is specified). I don't know what you mean by "script your own collider" either, but you likely don't need to do that regardless.
My bad i miss spoke. I knew they were two different things and that even if i don't have a mesh rendered i could make a custom collider but i was wondering if doing something this way was not recommended cause it could cause some problem.
Also what i mean't by script your own collider is actually making a custom collider system, long time ago i was looking how to do a cylinder collider for the bottom of a trashcan but on the unity forum they were saying there isn't a way to do that since it's not supported by Physx and that i should make a custom collider system with a script. I just discovered how to do that with the mesh collider cause i was playing with the mesh collider. that's why i was wondering if it was a good idea and wouldn't lead to future problem!
It won't cause any problems in itself no. In this case there no need to do that but just in case you are wondering, optimized realtime physics engines are complicated and math heavy libraries. It's far from trivial to do one yourself. Don't know what custom collider system would refer to other than a whole physics engine. PhysX being open source your could probably take their source code and add some custom stuff to it but making unity work with that would probably still mean a lot of work.
well that was pretty much the plan if i wanted to do custom collider. Though i thought i could try to communicate with the physics engine to make custom collider using code but probably not possible like that
I'm at least not aware of any ways to directly modify the physics engine from within unity. I have heard contact modification could be used to do some custom collision shapes but in this case I don't even know what the point would be in messing with the engine. The primitives, mesh colliders and combinations of those are usually all it takes for most games
yeah still thanks for the answer ^^
why is OnTriggerStay2D() not running on the Player Attack script? neither collider is excluding the other's layer and they're set up to collide with each other in the collision matrix. im 100% sure the method isn't running because i have it set to log if it runs, which is not happening.
im aware the attack's collider is disabled, but it gets enabled temporarily through script when im trying to get them to collide, so i dont think that's the issue?
- I don;'t see any Rigidbodies here
theyre in the parents
Rigidbodies are required for all physics callbacks
- you said "temporarily"
how temporary are we talking about?
about 0.15 seconds
yeah
I wouldn't use trigger colliders for that at all, that's a really clunky way to do it because you have this weird async thing going on where you enable it then wait for a callback.
You should use a direct physics query
you will get an immediate answer right in your attack function
alright i will probably try that
still though do you have any idea why this isnt working?
might be that it's not enabled long enough (a physics simulation frame needs to run). Mught aslo be that the scripts need to be on the Rigidbody objects not the colliders to receive the callbacks
ohh interesting thank you
Is it possible to create a mesh collider that isn't convex and also is a trigger?
It seems like no. If you show what kind of mesh you need the trigger for and why, we can maybe give some advice as to how to best achieve the same in other ways
just a simple torus. I need to make a shockwave.
What kind of shockwave? Why you need trigger for that?
a torus scaling up, similar to ULTRAKILL. I need it to deal damage
I would do something like:
- An OverlapSphere and exclude anything within a minimum distance (the "inner radius" of the torus)
- Two OverlapSpheres and exclude anything that shows up in the smaller one as well (the inner radius)
Distance check in code could be fine too
I have a beginning position and a target position. How do I shoot a projectile in an arc so it would land on the target?
figure out what that arc is, mathematically
if it's falling due to gravity, it'd be a parabola, for example
Yeah, there is gravity
then it'd be a parabola
figure out another constraint, like the travel time or horizontal speed
from there it's kinematics to find the rest of the variables
Lets say travel time is 1 second
so you need another constraint actually
so travel time constrains horizontal speed
you need additionally, one of:
max height
vertical speed
overall speed
launch angle
Lets say: gravity, travel time and launch angle
That might actually be too many constraints. I think given gravity and launch angle, there are only one or two launch speeds which would end up in the correct target position. That would mean the travel time would not be a free variable there. Travel time and gravity would definitely be enough to produce one trajectory, my intuition is having hard time understanding whether there are finite or infinite trajectories to choose from, my best guess would be the former. The travel time definitely defines the horizontal speed but also has relation to the vertical component (if you shoot higher up, it will take longer to drop back).
Instead of picking random constraints, it would be much better if you explained what you are actually trying to do and for what it's needed.
Most cannons for example don't have any control over the launch velocity and can only change the angle to hit the target
Does travel time here mean a duration before the gravity kicks in? So it flies straight for that amount of time?
Travel time is how long it takes for the objects to hit the target
Ah right of course
Are you going for super accurate aiming/perfect math formula here?
Or is it going to be "humanized" somehow
Accurate
We already know what the distance between the start position and the target position is, and travel time is already set
Gravity is also already set (Physics.gravity.y*rb.gravityScale)
But now the launch angle isn't set right?
Assuming the projectile is in free fall without any forces acting on it (like drag), calculating the horizontal speed is trivial. The only thing left would be the vertical speed (which would then define the angle at the same time) which you should be able to calculate from the acceleration (gravity) and the travel time (and the y levels of the start and end). If you need drag or something like that, then the problem suddenly becomes much harder
That should actually give you only one possible starting velocity meaning the travel time and gravity should be enough constraints to unambiguously define the trajectory
Let me know if anything that I said is wrong, it is quite some time sice I last time used these formulas
Is there an equation for the vertical velocity
That is the equation for the vertical velocity. Well, you have to get v0 into the left side alone, but that is quite basic level stuff (move some terms and divide by t)
It says Vx?
Wouldmt it be Vy?
That doesn't matter. It's formula for position in constant acceleration in one axis, might as well be Z
You have acceleration along the Y axis, so you can just imagine there's y in the place of x in that formula and life is good. The original source of the image for more information: https://www.physicsthisweek.com/topic/position-kinematics-equation/
So:
Target position=Starting positionprojectile velocitytime+0.5gravitytime²?
yup, from there you need to solve for projectile velocity
you could also say vt = 1/2 g t^2 if the starting/ending Y pos are the same and gravity is downwards (simplified from the above)
then v = 1/2 g t
True, we don't even know whether the start and end are at the same level. That's why I asked for more information eralier with little success
Does the physics world really get rebuilt every fixed update if you move a collider without a rigid body on it?
idk about the entire physics world, but at least that collider gets rebuilt, iirc
What does rebuilding mean here 🤔
It probably needs to at least update the collider's AABB and move it to the correct position in the spatial structure
If it would recalculate everything then it wouldn't be that efficient
im assuming rebuilt means it's cached and that gets recalculated idk
I've seen a few things saying something along the lines of the physics world / part of the physics world gets rebuilt when you move a collider without a rigid body on it.
That colliders without rigid bodies are implicitly static and treated as such by performance optimizations, which cause extra overhead when moving colliders that don't have a rigid body on them.
Ignore whatever you have heard. That indeed was a thing some 10 years ago, unity specifically addressed that when they updated the PhysX version in unity 5 or 2017 or something. I can try to find you the article. Basically that's a thing from the past you don't need to worry about no more. Moving objects that do not have a rigidbody have been more than fine since then
I saw a unity staff/dev say this for 2D physics back in 2022, so I looked it up and people say the same thing for 3D physics.
I would actually prefer a way to check myself
What call would it show in the profiler?
if it was rebuilding parts of the physics world
I have no clue about 2D. I will try to find you the article about it, last time I checked, all the stuff regarding the PhysX update were not up on the webpage
yea I couldnt find anything about this on the API or manual.
Some of the other articles are not up anymore and I couldn't find them in wayback machine either (or I just can't use the thing)
So assuming it hasn't changed since, all colliders are nowadays treated as dynamic because people never understood the system and ended up in performance trouble. I don't even know how the rebuilding would look in the profiler, I don't think I have ever even used unity version where that would have been a thing.
If people online say it's still a thing, I'm not surprised, people are really slow to find about updates and expect things to work as they did 10 years ago. I have personally never faced such performance issue with "static colliders" and would love to see the hard evidence about it if that was still a thing
docs contradict this part
all colliders are nowadays treated as dynamic
even in latest docs
https://docs.unity3d.com/6000.5/Documentation/Manual/collider-types-introduction.html
The Unity documentation refers to the following collider types:
- Static colliders: The GameObject has a collider but no physics body (Rigidbody or ArticulationBody).
and then it describes how static colliders are different from other types
In the article I linked the "treated as dynamic" refers to the underlying collision tree structure only. The docs page doesn't talk anything about performance. It is no surprise moving via transform is bad for the simulation like illustrated by the example of sleeping body not waking up when object is teleported inside it via transform. Combining rigidbodies and moving static colliders isn't great but the point was that there is no "recalculation" of any heavy structure happening (as far as I'm aware).
couldve been more specific in your conclusion, but fair. haven't gotten that far into it yet
Sure, I honestly didn't know "static colliders" were still used as a term, "treated as dynamic" was definitely imprecise wording
Can I move a collider via animation? Not the gameobject, but edit the component values.
You can do whatever you like in your animation with serialized values but note that changing the collider shape in an animation won't necessarily have realistic physical results. For example rapidly upscaling a box won't realistically launch objects resting on top of it.
when I try animating the values in the collider, they don't actually keyframe. They change as if I wasn't trying to animate them.
So, If I were to set keyframes:
size 1,1,1
size 2,2,2
the end result will be 2,2,2 as if the animation keyframes never happened.
and yes, I'm sure I'm adding keyframes and the background on the value turns red.
trying to change it here doesn't allow me. I can type it in, but the value doesn't change
Are you doing this in play mode?
when you say they don't "keyframe" do you mean they don't interpolate between keyframes?
or they don't change at all
No, scene.
They don't interpolate, or snap. They just set and change the keyframes behind them
If you're trying to move a box collider it's probably better and more correct to give it a kinematic Rigidbody and turn on "animate physics" on your animator
and then actually move the position of it
rather than the collider center
Anyone have any insight for an approach to make instantiated objects account for lagging behind its source object? For added context I have physical bullets shooting from a gun, but when rotating at higher speeds the bullet's spawn position tends to lag behind a little bit. I guess this counts as a physics problem? If not I can ask in a different channel.
You would really need to show your code. Whatever you're seeing is an interaction between your code and the scene
Alright will do
private void Shoot()
{
Ray ray = new Ray(targetCamera.transform.position, targetCamera.transform.forward);
GameObject bullet = Instantiate(bulletPrefab, bulletSpawn.transform.position, bulletSpawn.transform.rotation);
bullet.GetComponent<Rigidbody>().AddForce(targetCamera.transform.forward * bulletForce, ForceMode.Impulse);
Destroy(bullet, bulletLife);
}```
This is the function that instantiates the bullet at *bulletSpawn*'s transform position, which is here, parented to the root bone of the gun's rig.
I can get a clip of the object lag if needed
it's only visible for like a frame (before the bullet transforms and travels forward) and I'll probably make the mesh renderer disabled ultimately, but I worry the lag will cause some collision/trigger inconsistencies for like if you drag shoot right beside something** **
need more context for this code
show the full script
i.e. when does Shoot() run
is it in FixedUpdate? is it in Update?
If it's in Update then you need to remember that physics don't run every frame. You may get:
Frame 1:
- Spwawn the bullet
- rotate the camera a little
Frame 2: - rotate the camera some more
- physics finally runs
So it would look like the bullet is sarting to move from a point away from the bullet spawn poiint because it only starts moving a whole frame later after you turned a bit already.
well see I thought about that and I think I'm going to need to rework how it executes because I tried processing the inputs and stuff in FixedUpdate instead and it doesn't quite work as expected
that's probably why though
I suppose I could use like a listener variable that gets checked in FixedUpdate and then executes the function there
I think this idea worked
Im trying to make a script for dragging objects in 2D but once they are let go off they will be "thrown" in a direction where the mouse was moving but for some reason once I let go off the object it either nearly completely loses horizontal momentum and starts falling or the object moves quite slow
https://pastebin.com/WXt6a3kh
I tried chaning a few different things and trying to do it with TargetJoint but it doesn't seem to help. (This could be the wrong place to ask or me just being stupid but I hope someone could help)
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Did you try dragging an object that just has a collider, a rigidbody and this script and nothing else?
Because it sort of sounds like something else could be modifying its velocity
Also I can sense some framerate dependency issues. You are updating prevPos in Update but it should be done in FixedUpdate so the final launch velocity would not depend on frame timings.
Is the idea that moving the mouse faster would result in a greater velocity when releasing?
Ehh.. didnt decide on whether mouse speed shpuld depend, but i do need RB so its affected by gravity + i will try putting it in fixedupdate
This AddForce method isn't really right for this application either
For this sort of thing I would be measuring the velocity (or average velocity) from the final frame of holding (or averaged over the last several frames, potentially dropping outliers), and setting that velocity directly
try using a PID controller
Hello all, I have a problem and would like some assistance.
The situation: Two balls in a box.
The problem: I would like the balls to bounce off each other, but not transfer any velocity. I would like gravity to still take effect and such, as if the collisions were perfectly elastic.
What I have tried: I have set the physics material on both objects to the settings as seen in the picture.
Thank you all!
If you want to customize a collision you pretty much want to go with https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Physics.ContactModifyEvent.html
forgot to mention, unsure if this would change anything, but i am using universal2D, not 3D
but anyways, i am pretty new to this, so how exactly does this work?
This doesn't work in 2D, no
(btw, universal just refers to the rendering pipeline, the physics is just 2d)
what do you recommend i do than?
i see
probably just track your velocity for each object beforehand (in fixedupdate) and in OnCollisionEnter2D just set their new velocities to exactly their old velocities reflected on the collision normal
Hey, i have a problem with crouching when using built-in CharacterController. My character has a height of 1.7 but even though, im standing in front of 1.85 empty space i cant get benath it, i have to crouch. ChatGPT told me its because of the step offset so i set it to 0 temporarily for a test and this bug really disappeared. Earlier i was using rigidbody and i never had any issues with crouching, it was "pixel-perfect", but how do i solve the crouch issue with this built-in CharacterController? is there a solid fix? im thinking of making my character ~ 1.55(it seems like reducing 0.15 fixes it) but i feel like it might cause other bugs later that i cant foresee at the moment
CharacterController has a skin width
check what yours is set to
and then double it because there's a "skin" on top and bottom
my skin width is set to 0.01
The height is also not inclusive of 2x the radius for the endcaps
IIRC
The height is the distance between the centers of the two spheres
ohhhh
So to get the total actual height of the cc it's like height + 2*radius + 2*skinWidth
Double check this though
I could totally be wrong
im going to test it now
so my character height is 1.7 + 0.4*2 + 0.01*2 = 2.52
i put a ceiling-block 2.5 above the ground level and im moving freely, at 2.2 still freely, starting at 2.1 im getting slowed for a short time, also, like i said, setting step offset to 0 solves the issue entirely. I think it has to be something else here
step offset is 0.46
This is over my head then (pun intended), sorry
I think I was wrong about the radius
The total height is probably just height + 2*skinWidth
thank you for trying to help tho 🙂
https://discussions.unity.com/t/character-controller-step-offset-and-moving-through-gaps/515689
found a few topics like this, 13 years later, still not fixed 😢
could someone please help me figure out why my wheel rbs absolutely freak out when they're connected to other rbs with a fixedjoint?
The wheel top-level parent is made of an empty with an rb and hingejoint. It has a sphere collider rb as its child, and set as the hingejoint's connected body. I've set the layers to exclude other placed parts (i.e the grey cubes you see me place).
Both the wheel rbs are set to mass of 5 (for a total of 10), and each cube has a mass of 10.
oh
had to turn off preprocessing on the hinge joint
spend hours debugging ts and then figure it out within minutes of writing a discord message 😭
how do i get limbs to stop drifting like this (making togglable ragdoll)
the structure is the armature has rigid bodies, colliders, and joints, and colliders are turned on when ragdolled
i tried fixing it by turning on isKinematic on the limb rigidbodies but it just ruins the player physics n starts making me fly
it also sometimes snaps back into place
I’m making a pong-like game, but for some reason the ball will start spinning when hit at certain angles when it should be still. How should I fix that?
should it spin at all? if not, just constrain the rotation
Is there an option to do that for the box collider?
no it's part of the Rigidbody
Is there an option on there to do that?
That's what we just said
Oh sorry
what does Max Collision Shapes really means for particles?
given I want accurate results using particles to deal damage, would it make sense to increase it from default 256?
Can someone help? The wheel physics dont seem to work sometimes, i have no idea why
i dont know but add a sphere collider and rigid body to the wheels.
we would need more details
What details?
The car uses 4 Wheel Colliders, which sometimes dont colide with the box colider i have on the object i show on video
like how the car prefab is set up. Screenshots etc. Code. Whatever scripts are on it.
The car itself has a Rigidbody + trigger box collider, on a "Vehicle" layer which shouldnt colide with anything
Then i have BottomCollider and TopCollier on VehicleColision layer for actual colision
Then there are 4 wheels on default layer, which sometimes do not colide with the platform
I can show anything else
Here is the script that instantiates the car
You're putting the car on the UI layer?
yes so UI camera can catch it
I remember trying to make it a different layer which didnt help, the issue persisted
i would take a look at the car in the in the hierarchy window when the wrong thing happens
see if anything is different
dig through all the physocs components etc
Anyone got any tips on how to create a fairly stable and accurate ragdoll? im trying to use the ragdol wizard with some simple synty characters but im just getting some strange results where arms twist Un-naturally I assumed implementing ragdolls would be simple...
Bone axes are probably wrong—Unity expects limbs to bend on specific directions, and Synty rigs often dont match that. The ragdoll wizard is just a base, so you need to manually fix joint limits (especially twist). Also make sure colliders and mass distribution are reasonable, or physics will behave weirdly. Basically, the twisting comes from bad joint setup, not the ragdoll system itself.
Okay thanks but how do I know how to configure my joint considering the character mesh? The character join component has soo many values to configure.
Focus on Axis and Swing Axis so the joint matches the bones natural twist. Set Twist Limits small for forearms/calves and bigger for upper arms/thighs. Align the Anchor to the bone pivot and adjust Swing Limits so limbs don’t bend through the mesh. Then test in Play mode and tweak iteratively.
Can you just explain how i would configure this one joint so i can learn and apply this to the others? i really just want to know what the axis and swing axis should be for each one?
The main thing that causes the weird arm twisting is the joint setup:
Axis should point along the bone (shoulder to elbow)
Swing axis should be perpendicular to that
If that’s wrong, the arm will twist instead of bend.
Big tip: elbows shouldn’t behave like ball joints. Lock them down a lot:
Very small swing
Almost no twist
So they act more like a hinge
Also the ragdoll wizard isn’t perfect — it gives you a starting point, but you have to tweak:
Axis
Limits
Sometimes anchors
One more thing: keep your masses reasonable (heavier torso, lighter limbs), or it’ll get jittery.
That’s basically it — once the axis is correct, most of the “weird” behavior disappears.
For specifically this, Your arm is clearly going sideways (left ↔ right)
So the bone direction is along X axis
Fix it like this:
Axis: (1, 0, 0) ← along the arm
Swing Axis: (0, 1, 0) ← perpendicular
So for the left arm
Axis: (1, 0, 0) ← along the arm
Swing Axis: (0, 1, 0) ← perpendicular
& right arm
Axis: (1, 0, 0) ← along the arm
Swing Axis: (0, -1, 0) ← perpendicular
?
Almost but a small correction, use the same values:
Axis: (1, 0, 0)
Swing Axis: (0, 1, 0)
Because they are still using the same local bone orientation. Unity joints use local space not world space
Start with identical settings on both sides and
only change if one side behaves wrong
I have some enemies that keeps clipping out of walls (mesh colliders) even with dynamic continous rb
The most confusing part is that it only happens in the builded form (more fps)
has anyone came accross a similiar problem?
In 2D I had a problem of rb getting stuck in the wall on collissions sometimes. Had to change some default physics settings values, and believe it was because my world scale was smaller.
I first believed it was impossible to fix. Took me 1 year to realize. Using PolygonCollider2D on rb and EdgeCollider2D on walls.
How are you moving the enemies, code-wise, could anything be modifying its transform directly? Does it have an animator? What's the collider setup for the characters?
And are you sure that the wall meshes have valid geometry? "Watertight" geometry is usually the best.
Also, make sure to not have rigidbodies on the walls, not even kinematic
They have a navmesh which should be disabled during the noclip
What does "watertight" mean? I only know that convex normally do not have these problems compared to normal concave
It means no holes/open edges in the mesh
Convex makes it watertight though
But anyway, the most important question was how are you moving the enemies?
ty
Hello,
I'm trying to use ECS DOTS to do multiplayer game. I try to keep my project simple as I can.
Here I'm strugguling :
- I create a static object cube in a subscene
When I start the game I cannot see this gameobject in "Physics Debugger Tabs"
Any insight someone can give for making an NPC moved with Physics.AddForce not slide around like they're on ice, as well as an efficient way to clamp the velocity so their speed doesn't just increase exponentially the whole time?
add linear drag and/or friction
How hard is it to make realistic water?
define "realistic"
By realistic I mean water that looks believable and behaves believable. Stuff like reflections, depth, waves, foam, shoreline interaction, and decent movement physics.
All of that stuff is pretty vague
the answer is - hard
depending on how realisitic you want - harder
"decent movement physics" < what does this actually mean? You want a real time fluid simulation? That's stuff people do for their PHD theses
There are assets of course that do it out of the box that you can find and/or pay for. But they might not fully meet your exact needs.
kinda
Obi Fluid for example
Very vague question. Purely visually, water that looks good? Hard, but there are assets. For example, hdrp comes with its in built water system that looks good.
However, if you're talking about an actual fluid simulation as Praetor says, I really wouldn't do that if I were you.
HDRP has all that reflection, refraction, tessellation displacement and a billion other things built in, but it's not physically accurate, nor will it respond to someone's movement in the water
how would i calculate the reflection direction of a ball bouncing off a surface
hi guys i need a quick suggestion from you, i'm working on XR simulation of Transformers and i need to show the EMF ( Electromagnetic Field visuals) around the transformer coil. what should i do with that? any suggestion will help, i have tried the SPline but i don;t think it is working as it should be, i need arrows to animate according to show the directiion of flow also. what do you think?
Probably getting a line-drawing asset (or DIY’ing one) is your best option. You can try your luck with line renderer or splines, but, out-of-the-box, those aren’t exactly made for that use-case and will be somewhat annoying.
Thanks for the suggestion but i solved it using the Torus shape with shader graph showing arrows and making them animated using time Node. And its worked well and also optimized solution i guess. 🙃
Hello .
I'm new to Unity and to Game creation in general . I've started a month ago and i'm working on a tiny project to learn the step of the creation of a Game . I'm make a 2d survival isometric game and today I tried to make item drop of a tree when it's cut . I want to make the item pop out and fall on the ground , but I don't know how to simulate a gravity for an isometric world . If I add a Collider to the Tilemap , nothing can move , not even my player . And if I don't the Item just fall into void . Someone knows a way to make that ?
Physics simulation is overkill for that. Just make an animation
I'm working on the weaver "making bonehead" tutorial to help me understand procedural animations by animating a gecko.
So I need to make sure the axes are oriented correctly and if not I need to use "offsets" for each bone.
I've found two different methods and I want to know which one is generally considered cleaner since since the game I'm making will be mostly procedural animations..
One method was to create an empty game object and parent it to the bone that is not oriented properly and rotate the parent.
The other method was using quaternions in a script. Any help is appreciated!
"using quaternions in a script" is pretty vague. I can think of about 1000 different ways to use Quaternions in a script.
Sorry about that, I worded it wrong .Specifically the method talked about applying an offset into the rotation.
Don't cross-post. Pick one channel.
Um, guys
I was tryna learn the joints and stuff
But dis happened
Why did the stick go up just because i added a hinge joint to it?
And the yellow cylinder is spinning
consider using screen recordings instead of videos of screens
please don't crosspost
Isnt fluid mechanics bachelor stuff
It's PhD stuff
Or it was at one time
People building on the works of older PhDs may now do it at the baccalaureate level, not sure. I've been out of academia for 15 years.
Ill have fluid mechanics next semester in my ee class
there's a difference between learning the fundamental principles and building a convincing realtime simulation.
I hope so
I hope its not too hard
does anyone know how to fix the dress? I guess I should ask IS there a way to fix it?
The dress should have proper skin weights so it moves with the leg bones, and/or use Cloth physics with capsule colliders on the legs
yeah I added capsule colliders and have been messing with the settings, what do you mean about skin weights though?
Bone weights/skinning/weight painting
You'd use a 3D app (like blender) to weight paint the dress so that certain parts follow certain bones
Just like the character model's legs follow the leg bones. You'd do the same for the dress
It looks like the lower part of the dress currently just follows the torso/has no weights
IF you get the cloth to be stable then this might not be needed though.
Does anyone here know what this is?
At low speeds and slightly of center the discs keep pushing on instead of bouncing of/reacting
How are you moving the disc, is it just a single addforce/velocity set?
Try enabling continuous collision detection on the rigidbody
I doubt that's it though
Yeah it's just an impulse where I add force
How is that wiggling effect done?
Anyway figured it out, it was a DOTween function I set up to slow the discs down that interfered with the physics engine ... it now works fine again
https://youtu.be/aJZ3dYU2_WU
Have been working on refactoring code and separating functions ... as well as refining the look and feel, also made it a bit easier to score
how do i dampen my physbones make them move slower but not like for the return just when moving arround
is it cause my bones are really small?
Hello, I'm making a magnet-based game, and I'm having an issue where if the player is on the edge of a platform, using the magnetism power, it moves toward them slower than it would if they were in the middle, and doesn't push very well. I think the problem is because I'm using AddForce, and the x and z positions are locked, but i don't know how to fix it.
!code
📃 Large Code Blocks
Use links to services like:
https://pastes.dev/
https://paste.yunohost.org/
https://share.sidia.net/
https://paste.ofcode.org/
https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
based on your description the x component of motion is locked for one of the bodies, but you're applying a force with x and y components
The x component is basically gogin to be ignored
so you're left with just the y component. And the y component will be smallest the farther away from the center you are, since you're normalizing the vector
Think about two right triangles, both with hypotenuse length of 1 - but with different shapes like so. THink about what Y will be for each of them
the one with the larger x (ignored in your case) will have a smaller y, and vice versa
Would it be better to make a separate function, and use addforce just on the one axis?
the separate funciton is probably a good idea from an organizational perspective but it doesn't really make a difference to the logical issue here
Since you want this to only work "up and down" (you constrained the x axis) the real thing you need to be doing is just normalizing the y component - which means just finding if Y is positive or negative and using 1 or -1 times your force constant.
Would it be something like "if(player transform position x > transform position x)
Addforce up"?
we don't care about the x position, as far as I understand
Oh, sorry, i got the two confused
But, for the y position?
I will test at home when I can
you're freezing the x position you said, so I'm assuming whatever object this is only moves up and down
Yes, i am planning to do one for up and down, and a different for left and right
Hello again, and Thank you so much! I changed the vector to ///Vector2 directionToPush = (Player.transform.position.normalized - transform.position.normalized).normalized;///, and now, it pulls without slowing. only problem now, It reaches the player height, then goes up and down, and flies off Edit: nevermind, speed was too high, though it is still going up and down
Hello, I tried to make a spaceship to go right, left, up and down by using PID controller. But when I press left, my ship will go left and up at the same time, and vice versa. I know that there is problems on my FixedUpdate, but I don't know the type of problems. Can anyone help me?
What does controller.Update do?
I don't know. 😅 I'm a newbie who learn Unity for 2-3 months I think, that script is a reverse engineered-style from me. I change the horizontal.cs from (https://github.com/vazgriz/PID_Controller/blob/master/Assets/Scripts/Horizontal.cs) to apply into the spaceship. I tried to script the vertical movement (up, down) and the spaceship's movement went wrong
show your full script.
!code
📃 Large Code Blocks
Use links to services like:
https://pastes.dev/
https://paste.yunohost.org/
https://share.sidia.net/
https://paste.ofcode.org/
https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
hello, here it is. The code are messy because i reverse engineered the Horizontal.cs script and try to experiment with the new input system and others
This link doesn't work
Eh, it work to me.
does work for me still
btw, seems like your ide is not configured
!ide
If your IDE is not autocompleting code or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
PIDController is stateful, so you can't use the same one to handle both axes separately
you could have 2 separate controllers for each axis, though not sure how that'd go - you might want to consider making your own that supports Vector2s or something like that
Alright, I will try
MY MAN, THANK YOU, ITS WORKING. Your explanation are better than AI. You should be proud of yourself.
I use AI to check for error if I don't understand how to fix the problem and explain how the script work. For script, I follow the YT tutorial and look at other scripts in the Github.
"better than AI" is not a very high bar
you'd probably want to do this to make sure distances/velocities are handled well (and for ease of use), idk if it'd work as expected if you control the axes separately
it's working now. weird
Im making a character controller and when I raycast to a wedge downwards it goes through the wedge and hits the part below it. Any idea why this is happening? I tried enabling convex on the mesh and disabling
Either you aren't Raycasting in the place you think you are, or the distance is wrong, or there's an issue with layermasks, or your collider isn't where you think it is. You need to do some debugging
How would you check the collider on a mesh collider?
I already checked the collisions groups
Plus I debugged and it hits the wedge but then skips it and goes to the part under it.
What do you mean by "check the collider"?
And what do you mean by this exactly? What debugging steps did you take? How is it hitting more than one thing?
hey i wanna mess around with physics, i already have my eye on Obi fluid, soft body, and cloth physics and now i just need to find a good destruction physics system that preserves textures, any recommendations? i want it to work with character/skinned meshes too of course
I figured it out. I was using an raycastresult list and wasn't checking the distance of the objects passed and now it works
Is there a good reason you're doing a RaycastAll if you just want the nearest object?
Windows and enemy's
I use it for alot of different things. I am updating it tomorrow to use tagging to get enemy and thin objects like windows and fences
Plus for single objects if I get the closest to origin I can get the most close object whilst having data like if an object is being supported by another.
Then use the closest for floor placement and the other to manipulate the environment
Little question how could i set the velocity of a rigid body without moving it. For example while the rigidbody would be kinematic i would set is velocity to be = what it move in an animation and when i switch off iskinematic it would become a physics object and move in the direction i set
Calculate the velocity, set the rigidbody velocity after setting it non-kinematic. The velocity of an object is (position this frame - position previous frame) / deltatime
i mean my guess was pretty much that but i would have loved if you could directly put velocity while kinematic, guess not. still thank you for the velocity tip, save me some research
You don't gain anything from setting the velocity while it's kinematic because it doesn't do anything
Well it does actually afaik. For one, it makes other bodys colliding with it know the velocity and therefore makes the collision much more natural. It also enables interpolation. Haven't actually tried it this way but MovePosition does set the velocity which makes me believe that it would be what does the trick
I should try that
Oh, it gives the "Setting linear velocity of a kinematic body is not supported" message and does nothing, does not seem to work then
Would have been nice for conveyor belts and such
anyone?
Hi, I'm trying to move a ship using AddForceAtPoint and have the acceleration be gradual. Does anyone have any idea how to do it?
You'll have to tell what problems you're having with that and show your setup for anyone to help
A little car physics type question regarding traction. The car is flying through the air, and has just landed one tire on a stone block. I want the tire in this situation to "anchor" its position by applying a torque and force to the vehicle (using Acceleration/VelocityChange). I think I'm supposed to take the cross product of the red and blue vector in order to get the torque, but for some reason, the torque it gives me is way too much.
(Purple circle is center of mass and purple line is linear velocity. Blue line is the point velocity of the tire and red is the offset from center of mass)
My in game version of this is giving the green line (predicted torque to cancel out rotation) that is much longer than the yellow line (angular velocity of the rigidbody at this frame)
You can just use AddForceAtPosition to apply the friction and the torque will come naturally
The issue with AddForceAtPosition is that I need to apply the torque based on all four tires, not just one. I need the torque required to completely anchor a tire in one frame.
You can call it once for each tire
Using the appropriate friction calculations for the materials each tire is touching
Assuming this one has significantly higher friction, you'll see a net torque
Wait, does AddForceAtPosition take into account previous calls when calculating the torque?
I imagined I'd be wiggling since I'd be overcorrecting with four tires

Like if the car is spinning, and I use AddForceAtPosition() for each tire, wouldn't I be applying the red force (enough to stop it with one tire), when I want to instead use enough force for four tires (blue)
Vector3 planarWheelVel = Vector3.ProjectOnPlane(rb.GetPointVelocity(GetWheelPosGlobal(i)), rb.rotation * Vector3.up);
rb.AddForceAtPosition(-planarWheelVel, GetWheelPosGlobal(i), ForceMode.VelocityChange);
This does in fact make the cars freak out instead of stopping on a dime
they're all additive. The total reaction of the car takes into account all the calls. They are independent from one another though
Physx doesn't understand pressure points, right?
For example, it makes no difference to the engine whether a rigidbody sword hits something with the blade edge of blade face?
What exactly is pressure point and why does it matter? What difference should it make whether the blade or the face hits something?
Let's say, for example, you have a joint somewhere with a break force.
Is the same amount of force appllied to it regardless of which part hits it? I.e. do rigidbodies care about pressure in any way?
Pressure is not part of the equation. PhysX like most physics engines only operate on rigidbodies which do not deform or bend. If there was no deforming/bending, the pressure wouldn't make any difference in the real world either (I think?). PhysX also operates on contact points, not areas of contact. Therefore you could argue the pressure to always be infinite. You could think of it as if everything in he PhysX world was made of diamond, extremely hard material which never gives up. Forces (and torques) are what matters, not pressure
Yea that's pretty much all I wanted to know
How can I check if a Collider2D’s exact shape (including things like PolygonCollider2D) would overlap with other colliders at an arbitrary position, without actually moving or instantiating the object in the scene? I’m working on nav/path generation and simulating positions in code, so what I need is essentially to “place” a collider shape at a given position and test if it would intersect with the world. Using bounds isn’t accurate enough since it’s just an AABB, and the built-in OverlapBox/Circle/Capsule methods only work for primitive shapes, not arbitrary collider types. Collider2D.Cast also doesn’t quite fit since it’s a sweep, not a pure overlap check at a specific position. Is there any way in Unity to query overlap using the actual collider geometry at a given position, or is this not supported?
currently im thinking to instantiating the object in the scene anyway as a part of the nav graph building process then destroy them after the process is done, easier to follow this process too that way, but feels a tad bit inefficient
you could just move the collider to the place you want and use https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Collider2D.Overlap.html
then put it back when you're done
Moving one collider doesn’t really solve my case, because I’m not testing one obstacle shape at one position.
During navgraph generation I need the obstacle prefab colliders to exist at all their tile/world positions at the same time, because the enemy box can overlap multiple obstacle tiles at once.
Example: if two obstacle tiles are stacked/adjacent and each has a unique partial collider, checking only one moved collider can say “no overlap,” even though the enemy box would actually hit the other collider at the same time.
you would be moving the enemy collider (or rather, a copy) to the point you want to check and then Overlap would tell you all the colliders that would overlap
it's not testing whether 2 given colliders overlap
What Chris said. It checks against all colliders in the scene. I was referring to the enemy collider
I already know how to check using the enemy collider, I use it's bounds, I don't mind being limited to a box shape for the enemys collider, but in the scene, where I have obstacles tiles, which spawns prefabs, these prefabs are stored in the tile data, and do not exist in the scene because we do this during scene time, not playing time. There are no instances to check against when placing an overlap at the enemies calculated position. And it is that which I want to find an effecient solution for.
I have a method that can get all the tiles that we would collide in, and get their data, so if we collide with 3 tiles, 2 of which are obstacles, I'd be able to get their prefabs and spawn them in the center of their respective tiles, but each jump calculation can do up to 45 * (6/0.05) * 2 calculations/checks and for each frame of those jumps I place an overlap the size of the enemy so it would quite expensive to always instantiate a prefab, so yea, I need help with figuring out a more effective way of getting a unique collider shape to be placed where the tile prefab would spawn during run time, and then when checking each jump frame I do an overlap to see if we touched any of those unique colliders that we would be placing
You can reuse the instantiated object instead of instantiating it once per check
For me personally it would help if you show screenshots of the game/map to better understand your project's needs.
so this is a screenshot from the project, ive edited the picture to a hypothetical polygon collider for the obstacle tiles (the 2 spikes), and a blue outline for the "enemy" which is just a gray box with an arrow towards the direction its facing (a sort of whitebox for testing).
a singular instantiated object instead of instantiating it once per check wont work since in this example, the enemy "jumped" (we dont "place" an enemy when trying to find an optimal jump, we use its width and height from the "enemy data" SO to create an overlap box) in this instance, this would be one of the simulated frames (see image 2 for a real simulated path of the enemy, basically to find out if a trajectory is accepted is if for each physics frame, we place an enemy sized overlap box at the calculated position at that frame, in the second image, the enemy is in an arbitrary example position unrelated to the trajectory). so as you can see, in one of these simulated frames, the enemy might be touching 2 obstacle tiles of the same type, meaning if we only check using one, say we check the first/closest obstacle, you would see that we dont touch the collider (green shape) and that would then make the trajectorycheck think this position is reachable/okay, when in fact its not, because as u can see, it touches the second obstacles hitbox.
thats the reason one obstacle prefab that gets moved around, does not work.
and simply doing an overlap box does not work either because this is a navigation graph bake which is run before the game starts, not during run team, meaning those instances of those obstacle tile prefabs are not instantiated yet
we would simply instantiate all of them in the beginning as a part of the bake process, and then do our usual checks as the system currently does (it already relies on overlap box but as you know by now that didnt work for this particular situation) which now would work because we do instantiate the prefabs, which is sort of my leading solution
and then at the end of the process, delete those instances
but that seems like it would end up being costly to instantiate so many obstacles, becuase while i understand this process would take lots of times, especially due to how i calculate jumps, i dont want it to take forever, and if i can find a way to optamize this, that would be nice
frankly this seems like more trouble than its worth, usually no one uses such complex colliders for such things anyway
Is anyone able to give me some insight on my game? I've made these big rigidbody meshs made out of cubes, I give each cube its own box collider. every box collider for the mesh is stored in one GameObject to keep the editor clean. To keep the amount of active colliders down I instantiate the colliders with the collider disabled(boxCollider.enable = false) and as my player gets closer to each cube, the collider enables. This system works but when they enable, the rigidbody moves without me touching it. Are my colliders colliding with each other? they all definitely touch each other as their coordinates are always whole numbers. Is the solution really to give each collider its own empty GameObject? That is all I can find online.
The gameobject that holds all the box colliders is a child object of the parent. the parent itself has no colliders
does each hitbox really need to be managed on its own? would enabling/disabling them all at the same time be viable? i feel like that'd make more sense
you could use a composite collider for that i believe, though im not sure it's the typical approach
Have you profiled to make sure this optimization is required and works? Often when people do these kinds of optimizations, they end up being much slower than the optimizations unity has in place automatically. Enabling and disabling stuff on chunk basis (when chunks are used) can be very effective. Especially if every object has their own script instance attatched which checks for distances, that can get very slow very quickly
If we are talking of game similar to Minecraft, having a GameObject for each cube would alone be really inefficient
What kind of game is this
Hey everyone,
I’m working on a pirate game project, but I’m having a lot of trouble fixing player jitter while standing or walking on the ship in the ocean.
Right now, the character feels like it’s constantly shaking a little, and walking around on the ship feels pretty unstable. It gets even harder because the game is multiplayer, and I’m using FishNet for networking.
How would you approach this kind of system? What would be a good way to make walking on a moving ship feel smoother and more stable for all players?
I’m mainly looking for ideas or implementation approaches to reduce jitter and make the movement feel cleaner.
There is too much here to comment on. For starters, is the character a rigidbody? Does it need to be a rigidbody? If it does, how does it move and with what settings? What kind of movement are you trying to achieve?
For example, character controller is much simpler and has no issues with jittering. It all depends on what you're trying to achieve
im not too sure where i should ask this but, i have an object, that when rotated, stretches weirdly and uncontrollably while the collider stays the same. How can I fix this?(I tried searching on how to fix this but I cant find anything)
the size of the parent is 8.506345, 35, 1
i tried making an invisible parent (empty object) but this still happens
By the way, it happens to the little squares too.
@tender vapor @timid dove @unique cave
Chris- my game is a slop voxel game made of cubes. Think of Minecraft but spaceships instead of houses. My ship of 1000+ cubes isn't too much on the cpu, but i know when i have 100-150 players in a server its gonna get expensive real quick with all those box colliders unless everyone can only make a ship of like 900 blocks total. I have currently not tried just enabling/disabling all the colliders at once. I feel like this would have to be done with a coroutine to avoid a lag spike and would probably end up with the same result. Is there a difference between a compound collider and a composite collider? is there any difference when each hitbox is attached to its own empty object instead of them all attached to one?
AleksiH- The optimizations are more then required for what I want to do. My Spaceships are dynamic rigidbodys with a mesh. The mesh resembles cubes like Minecraft and is split up amoungst a couple sub-meshs for handling different materials. Basically, there is one ship parent object that does the checking if something is close to a block and turns on the correct hitbox, its a 5 radius circle of activation around the player. The script only starts checking when a player enters its activation zone, which is a giant circle trigger collider around the ship.
praetorblue- I am ripping off a game called Starmade. it came out a while ago and died fairly quick. It is a voxel game based in space. You build space-ships out of blocks like Minecraft, mine asteroids with your ships. and use those materials to make other things so on and so fourth. I would have just used a Mesh Collider for the ships but I wanted a dynamic rigidbody that reacts to forces instead of doing it kinetically. I might just have to bite the bullet and emulate the physics with a kinematic Rigidbody instead.
I’ve been racking my brain trying try to understand the sled physics in https://youtube.com/shorts/IX_whJmxnDI?si=4QGLjWs_V_8OXaz4
i have been working on a sledding game for a long time but its just riddled with ghost collisions I can’t get rid of
Does anyone have ideas for how to implement smooth sliding physics - a mesh ground and mesh sled? Something else?
I think if you really want to do this efficiently you might want an algorithm that can dynamically convert your set of voxels into a minimal set of box colliders. E.g. if you have a whole section of the ship that's a contiguous rectangular prism, it should be able to use one single BoxCollider for that whole section
yeah apparently composite colliders are a 2d thing so they don't apply here, mb
@timid dove So I was thinking about this. Based on the geometry of the ships that players will build, their ships could still end up with anywhere from 150-500 Box colliders. Would this really be that more efficient than like 50 non-convex mesh colliders attached to a single kinematic rigidbody? I say 50 because each chunk is its own mesh. I did this to avoid re-drawing the entire mesh of the whole ship each time a block needs to be added or destroyed. Edit: I also feel that with how fast i'll need blocks to be able to be destroyed, having an intermediate step that calculates, destroys, and re-adds box colliders every time will slow down the performance. With a mesh collider, it is destroyed and re-drawn without my shittly coded algorithim finding the optimal amount. Edit2: I see now that I cant have non convex trigger colliders, It seems my only option is to try your suggestion. ty.
You'll definitely want to use object pooling for the colliders too
Im having some issues with phsyics. I am making a pinball machine, but even tho i have a hinge limiting the flippers movement sometimes it just glitches above the ball or something and rotates in a way that shouldnt even be allowed by the joint.
These are my settings. I feel like in general the physics are just doing weird stuff sometimes with these flippers but this is the only thing i can relaly place (i feel like it sometimes doesnt give as much power but that might be also because of this issue)
Make sure your ball is driven by physics forces and not being overriden
i dont have any code for the ball its just a rigidbody with gravity
Also for fast moving objects you want at least https://docs.unity3d.com/6000.4/Documentation/Manual/ContinuousCollisionDetection.html
Check the joint manual as well, make sure it's properly limited.
i mean i have the axis, and its just moving outside of that axis
i dont think any other settings should allow for that to happen
Hello there!
I'm making my first game right now, and there is this issue I have with slopes.
So, I want my character to glide off slopes at a certain angle, but I tried a few things and none of them are working.
I'm doing a lot with ChatGPT, but the things it recommended didn't work, so maybe someone here knows what I should try.
Btw, the shown script uses the Input Action asset to get, well… the inputs. I'm using a CharacterController, by the way.
!code
📃 Large Code Blocks
Use links to services like:
https://pastes.dev/
https://paste.yunohost.org/
https://share.sidia.net/
https://paste.ofcode.org/
https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
CC.Move should only be called once per frame, btw.
oh the other Move has a return after it
oh my bad
man its really hard to not just complain about these physics when stuff is literally glitching through eachother even though i have stuff set as continues
make sure it's set to interpolate and you're actually moving using physics as well
interpolate?
i use a hinge motor
interpolation: interpolate
idk if that uses physics
ill try that i have none rn
on both the ball and the flipper?
mm i'm not familiar with that, but as a rule of thumb you have to make sure stuff isn't fighting over the transform
eg rigidbody and CC are mutually exclusive, if you have either then you shouldn't modify the transform, etc
i mean the only thing im using to move it is a motor which i think uses a rigidbody. as the whole joint needs one
thx this seems to have fixed it so far or at least improved it
ye it seems better
Interpolation is purely visual and doesnt affect the physics simulation, so if that really fixed it then the issue was just cosmetic
The Physics settings has some settings to improve joint stability (like Solver Iterations iirc), they are pretty low by default
A couple of other things that might help with stability are to use a smaller fixed timestep in the Time settings and to disable Enable Preprocessing on the joint
weird cuz it does seem way less now so maybe it was just visual then
ye i did bump up the solver iterations for some other bugts but it didnt help for this one
oooh this seemed to make it better too
idk all these things combined made it behave way more deterministic
so thats good
is it possible to make my own kind of primitive collider say a ramp?
Not a primitive but you can always use a meshcollider
(A convex one probably)
hey, sorry in advance if im asking in the wrong channel,
is it possible to calculate bullet drop and target leading in one equation?
im basically coding a turret that tracks targets and shoots at them, adjusting for the bullet drop (from gravity) and adjusting to the targets velocity.
the way im doing it right now is im using a simple ballistics formula from wikipedia which calculates the angle at which you have to shoot to account for bullet drop, and once i have that i calculate the time to target and then the bullet lead (predicted target position), and i iterate this cycle like 2-3 times
and it works pretty well but i was wondering if its possible to do it in one calculation?
is it even worth bothering to calculate it in one go?
I doubt you'd win much if anything by doing it all in one go. Unless you need pinpoint accuracy or the targets are very fast compared to the bullet speed, it might be enough to estimate the flight time (or use a separate formula for that) and predict the lead first, and then doing the ballistics calculation once
Yep, doing it iteratively might feel "dirty" but its often good enough for games
hmmm yeah all the stuff i read online is pointing towards a quartic formula, which looks like moon runes to me, so i think im gonna implement a dynamic iteration count depending on flight time
I would think that such iterative algorithm would converge really fast towards the right solution. By managing the iteration count you can find a good balance between performance and accuracy
i consistently struggle with ocd lol 😅
Would definitely set up a test to measure the accuracy. I would bet even with very little iterations, you would get so close it doesn't even matter if it isn't mathematically perfect
just did that, it seems first calculating the bullet drop, then the lead, and then drop again gives pinpoint precision with the least calculations, tho doing drop once then lead was very close in accuracy, so you were right to say it converges really fast
I am trying to upload a avatar to VRC and i cant becuase i keep geting this error? I do not know how to modle its my frist time just even coloring an avatar and i need help to know how to fix this!!
(also idk where to post this im trying my best!)
!vrchat
Join the growing VRChat community as you explore, play, and create the future of social VR! https://discord.com/invite/vrchat
I have a question about the Low Level Physics 2D api. What is the expected way to move a Kinematic PhysicsBody? Is there a Rigidbody2D.MovePosition equivalent? Should I just directly set the velocity?
Kinematic: Unity applies no forces or gravity, but allows collisions with Dynamic bodies. Kinematic bodies move only when you manually reposition them or set their velocity.
appears so
MovePosition works by calculating the velocity to get there anyways
private int weight;
private Ray ray;
private Vector3 rayPos;
private bool isGrounded;
private bool _CheckForGround() // Sends out 4 raycasts around the player to check if he is grounded, only sends a bool for now
{
isGrounded = false;
for (int i = 0; i <= 3; i++)
{
if (i == 0)
{
rayPos = new Vector3((transform.position.x + 0.5f), transform.position.y, transform.position.z);
}
if (i == 1)
{
rayPos = new Vector3((transform.position.x - 0.5f), transform.position.y, transform.position.z);
}
if (i == 2)
{
rayPos = new Vector3(transform.position.x, transform.position.y, (transform.position.z + 0.5f));
}
if (i == 3)
{
rayPos = new Vector3(transform.position.x, transform.position.y, (transform.position.z - 0.5f));
}
ray = new Ray(rayPos, new Vector3(0, -1, 0));
if (Physics.Raycast(ray, out RaycastHit hit, 1.1f))
{
isGrounded = true;
}
}
return isGrounded;
}
void FixedUpdate()
{
if (_CheckForGround())
{
// Make player jump if he wants
// depending on material can add footstep sounds
}
else
{
rb.AddForce(-transform.up * weight, ForceMode.Acceleration); // Pulling character down, simulating gravity
}
Vector3 LocalMovement = (transform.right * direction.x) + (transform.forward * direction.y);
rb.AddForce(LocalMovement * speed, ForceMode.VelocityChange);
rb.transform.localRotation = Quaternion.Euler(0, mousePos.x * Sensitivity, 0);
}
Hey guys, just wondering if coding a certain weight to a singular object is nessessary or is there a attribute system for gameobject's "weight" that I'm not informed of? If there isn't then here is my code and wondering how you guys would improve on it?
Gravity is famously the same for all objects regardless of their weight
Also rigidbodies have a built in gravity simulation, you don't need to make one yourself
Am I able to change the gravity for a singular rigid body from components or is that something I have to hard code in?
At first I thought changing mass would make it go down faster but I was wrong
It would be useful to know because lets say if the player goes into the water, being able to change it's weight to be lighter would be nice if weight is already an attribute for the rigidbody like Mass is. But I have to hard code the weight in the script above
Weight doesn't affect gravity. In water, what makes things "lighter" is buoyancy which depends on density
and in air what makes things fall slower is drag, which can be simulated with linear damping
Ahhh ok
I did a quick search and saw that messing around with linear damping could get what I want
Tysm for the help
To do it in a more realistic way you could apply an upward force to the object, with the length of the vector calculated from the depth of the object as well as the density. This could even be expanded further by taking multiple points on the object, and applying forces at those points, so it would bob up and down, and rotate when waves hit.
How deep underwater something is doesn't matter actually, only how much of the object is underwater (volume). Is that what you mean? If something is fully submerged, it doesn't matter if it is 1m or 100m deep, the buoyancy force will be equal
Good point!
That's not quite true. Buoyancy is lower the deeper you are
idk what the original question was lol