#⚛️┃physics
1 messages · Page 77 of 1
How would I make multiple triggers react to randomly spawned objects (Without triggers)? The script with the onTriggerEnter2D is on an unrelated object. Someone said tags, but idk how I'd implement them when the script doesn't recognize any triggering at all
In order for Ontriggerenter2D to work:
Both objects need 2D colliders
One of which must be a trigger collider
At least one of the two objects needs to have a Rigidbody2D
Yes. But the script with the ontriggerenter has to be on the triggering object, doesn't it?
When optimizing colliders using multiple primitive colliders do you add the primitive colliders as a component of the game object? Or do you make a seperate collider in blender made of primitives and apply it to the game object in unity?
Huh? If you make those ”made of primitive” colliders in blender and import em to unity as mesh, they are not primitives anymore, they are just mesh colliders right?
yea that doesn't make sense now that I think about it
@flat palm yep. Very common way to optimize mesh colliders is to make simplified version of the model and set that to the collider so you get less vertices for physics object but maintain good visual quality. If your collider needs to change their shape runtime (for instance, hitboxes for moving character), use primitive colliders instead. Simplified mesh colliders are super cheap, theres usually no need to optimize them anymore
Is there a general rule of thumb for primitive collider counts on a single object? I have an object with 8,400 triangles or so and I removed the mesh collider and added in some box collidiers. I have roughly 80 box colliders on it right now which is 900 tris or so for the collision.
”tris” of primitive colliders doesnt exist. Primitive colliders doesnt use the ”mesh” of the collider to calculate collisions. Sphere collider for example should have infinitely high tris count (or super high), still sphere collider is lot faster than box collider.
That's interesting I wouldn't have guessed that, where are you getting that from? I've been trying to find something in the docs or collision optimization but can only find hearsay, nothing concrete
I dont have any specific reference. The order of performance is (usually) sphere > capsule > box. You can find some comparison videos from yt for example
forsure, thanks for the info I appreciate it I will look into it more and do some tests
@unique cave Wow! I was doing some test runs, I tested 2 of the same prefabs with different colliders attached. One constructed of 143 box colliders and one constructed of 148 capsule colliders. In each test run, I spawned 10 at random rotations and had them collide and watched the frame rate. On the Box collider test, I went down to 29 fps and at max hit around 80 fps once the objects settled. On the capsule test I stay above 300 fps throughout the whole simulation.
nice, the performancy highly depends on the exact situation, sometimes there's barely any difference between different collider types because AABB checks takes care of most of the collisions. in general capsules are faster than boxes because they are such simple shape mathematically: 2 points and radius, sphere is even simpler: 1 point and radius (cube has center, rotation and scale or smth like that). but yeah, capsule and sphere colliders are very cheap which is pretty nice. capsules are very good colliders to use for fps characters hitboxes etc.
mesh colliders are surprisingly cheap when building static scenaries with simplified collider meshes for example. it's better not to overshoot with optimization. you can use profiler to profile the cost of physics and if you get too high performance hit, you can try to optimize the performance with compound colliders etc.
Ok, I came here to simply to ask about mesh collider vs box/circle/whatever simpler colliders.
After reading mesh colliders are generally heavy I went all out to make all colliders of my teams' game's main building. The idea seemed simple enough, a block here, a block there...
After 29 colliders, I did it, it works, it isn't heavy in any way, I hate it.
So people actually do that, or am I doing crazy stuff?
It is just a four floor building and it seems like I overkilled it beyond recognition.
Does anyone have an opinion or insight/info on the concept of moving the world around the player instead of moving the player through the world in physics based controllers?
Well, while I get this was done in the past, with a game engine it seems harder to do because for me it looks like you will have to do many things from ground-up instead of doing like everyone does. But that is just an opinion, never tried.
what you did was make a compound collider from primitive colliders, which is the reccomended way of reducing the overhead of complex shapes
a box collider is basically just a center position and some offsets to establish its bounds, while a complex (and especially concave) mesh collider can be many thousands of vertices and other accompanying datas. Solving collisions on those complicated meshes can be even more of a problem
Ok, I get it. But is it worth it if you don't need it? I mean the game is retro anyway, low poly and all. I don't think we will have performance problems to begin with.
only add colliders if you have a reason to
And goddammit, doing 29 colliders, that is a nightmare to edit and I know I will have to do it later.
probably will end up nearish the 40s if I keep doing this
wouldnt a static mesh be even harder to edit?
not if you have someone whose work is literally this xD
doing a simplified version of the original mesh is trivial for him
for design and art, complex meshes are fine, it's only collisions you need to worry about
big box colliders for floors and walls are fine, and can be grouped together pretty much
static objects can be included under the same hierarchy, but you can separate them out to move them around easier (like blocks or staircases, etc...)
grouped together?
yea, you could either add many box components to the same object, or just have many copied + pasted box objects that you use to shape your stuff
there are performance implications in terms of simulation fidelity as well as computational speed
it's still worthwhile
even considering the way bigger games that even a phone can handle...? .____.
it's about physics sim
so this depends on how much you're stressing unity's physics systems
if you wanted high fidelity and repeatable stuff (like for networking) then there is benefit
if you want vert fast moving rigidbodies, that too
that is why I think this is an overkill, the game is not physics based in any way
well the character has to move and all
I mean it has basic physics
I mean I am not making stuff roll over or blow up
im guessing it's player colliders (capsules) moving around and shooting raycasts?
do they move with physics or is it a manual controller script
nope, not a shooter, but yeah first person
it does use physics to make it move
I am reading that static objects as mesh colliders are not dangerous to performance if not overcomplex
some meshes have millions of vertices
it's a qestion relative to the size and detail of the mesh, the way you're physics interacts with it, and the budget of the platform; you need to test
also, even if a mesh is high-poly, simplifying it is not that hard for this purpose
fair enough, but then it returns to my point, I don't believe we will ever be heavy enough to worry about performance in any common hardware, then if it comes to that, it seems more logical to do this later and not start doing this
I mean, if our target platform were smartphones I would at least be trying with my mid-range phone to see if it works, but in PC or any console I cannot see us comparing to any big title that actually kills framerate.
I am having serious collision issues
im not quite sure why, but basically i have a part of my game where the entire level starts rocking back and forth
and no matter what configuration of rigidbody collision types I use my player is quite literally going inside other meshes
I went into blender and even made the meshes thicker to no avail, which didn't matter anyway because i shoved a giant cube under this one part and the player is going inside the cube
now my only theory as to why this is happening is that I'm controlling the rocking using the animator which for whatever reason may be simulating at a locked 60fps even though my game is running at a higher FPS
hang on let me try locking the frame rate to 60
nope that did little to nothing
you did add a collision to the meshs right? be it box collision, mesh collision or any other right?
How are you rocking the level? If you just move it with the transform it's going to phase through stuff
You'd have to use Rigidbody.MovePosition for it to work properly with physics
the unity animator, i have the keyframes set to 60 but i assumed the animator didn't actually run at 60 and it smoothed between each keyframe
yeah they work fine until the level starts moving
the player is a sphere if that matters
a rolling sphere
the level is like a combination of box colliders I placed manually since I assumed I could garuantee better accuracy doing that, but there are some spiral staircases that I had to use meshes to make collision for
so for those I went and made sure the meshes were fairly thick
but I wouldn't be able to tick "is convex" on a semicircular wall
i dont remember what required that I had all mesh colliders ticked as "is convex" it might've been the rigidbody
I really don't think the meshs being tick help in anyway, so, the problem is that the stairs are being passed through? You did add the 3d mesh to the mesh collider's component's configs, correct?
if i didn't there wouldn't be any collision at all right
the collision works perfectly fine until the level starts swinging
2021.2.5f1 if that's relevant at all
of course, don't mean to offend. I don't know the level of knowledge of anyone I find here. I am not that experienced with unity, but as a programmer I have seen that sometimes programmers need someone else's view to see the obvious... I will always try to assume the easiest even if dumber solution first like "did you turn it on?" instead of trying to find some inner weird bug... anyway, I don't know enough to help you besides stating the obvious for now xD
Animator isn't designed for this
Like I said you need to move via rigidbody
Otherwise you're not moving the object you're teleporting it.
yeah fair enough i just wanted to make sure i was understanding you correctly
right ok ill give this a shot next time i open unity
Well, yes, you have to move via rigidbody but not using rb.MovePosition. MovePosition is same as rb.position but with interpolation (visual interpolation, the interpolation doesnt affect any physics calculations), it doesnt prevent objects from moving through each other.
Could you share video about the rocking effect youre doing? It doenst seem very good idea to rock the whole level. It would be much better to just rock the camera and add some forces to objects that has to be affected bu the rocking effect.
mm alright nintendo dont sue me please
ignore the ridiculousness of what you're about to see
the reason the whole level rocks is because i want the actual forces to affect your ability to move straight
like getting pulled toward walls and such
i could do that with code but it would take me a while to figure out how to do that convincingly
it would also have a knock-on effect with the other things that aren't part of the stage that is rocking
so the only reason the player isn't clipping there is because that box collider is huge
the other colliders it goes through with enough speed
i see but it still doesnt seem good idea to attatch rigidbody to whole map and move it using physics
i was usiong the animaator
rigidbody was cos i thought it would allow me to change collision detection type
animator is absolutely not the way to go. you need rigidbody if you really want to move the whole level but that doesn't seem good idea
Hey so I got 2 collider objects using gravity, but when i place 1 below the other they just start floating in the sky. Ive tried everything from using kinimatic and turning gravity off, im so stuck and confused. *** Fixed the issue, turns out had too many rigidbodys on things i didnt need them on.
Hey is it possible to desactive the LightReflection only with the an PrimitiveGameObject
Please ping me for respond
It is not the same. If you MovePosition a kinematic object it will push non kinematic objects out of the way.
If you MovePosition a non-kinematic rb it will not go through things
It is very different
I may be wrong idk. docs of MovePosition is very unclear. Atleast it doesn't take collision detection mode into account. If you move the object too fast, it will go through everything no matter what collision detection mode you have.
Ofc
if its an important distinction I'm rotating the object, not moving its position
Sorry, MoveRotation
same concepts apply
ah ok
I'm trying to detect if a capsule collider is intersecting with any other colliders, I've found CapsuleCast and RigidBody.SweepTest to be unreliable because they don't work if the starting position is already intersecting another collider. And CheckCapsule isn't useful because it does return any information about the colliders that were detected, so they can't be used for what I would need afterword.
I could use OnTriggerEnter (and not OnCollisionEnter because I'm trying to avoid the rigidbody physics system). But the only problem there is that it takes place after FixedUpdate, so It would be completely out of step with what I'm trying to do.
Physics.OverlapCapsule
ooo, that looks like it could work 😮
I think this is the right place to ask about this? My (Character Controller) character refuses to move in play mode, it's completely glued to the floor, and even teleports there when I press play.
I'm not directly dealing with its transform in the movement script at all. So what could be causing it?
Do you have an Animator
Yes
Try disabling it for a minute
OK. That works. What part of my animator could cause it?
If your animator is animating your player's root object
It shouldn't be. It should only animate child objects
Otherwise it's going to set the player's position as you're seeing
Interesting... OK I don't know how to actually fix that, but that gave me the idea to apply root motion, and now I can move the character with my controls (yay!)
But... only left and right. And the animation stopped working. :(
The way to "actually" fix it is to make sure your animation clips aren't key framing the root object's position
I wish I knew how. I'm just using Mixamo for animations.
This is probably more of an #🏃┃animation question than physics at this point
OK. Thanks.
Hi guys, i wanna make jelly physics like this can you tell me how , thank you
You'll want to look up the concept of soft body physics. It's not a feature built into Unity, and there's assets on the store that do it.
Yes, ive tried Obi Softbody but it doesn't work for me
It works. It's just not trivial to integrate into your game.
Another option is to use physics joints with several rigidbodies on a rigged mesh with SkinnedMeshRenderer
it's not as granular as something like Obi Softbody but it uses only build in Unity tools and if you don't have that many bones it performs fine
Hello, Im having an issue I've never faced before. I'm using Unity 2020.3.6f1
I started making a 3D scene of a racetrack. Building the environment is really the only thing ive done to this project. However, whenever I add a rigidbody and collider to an object they immediately start moving backwards. no other components are added. happens even with a basic cube. im seriously at a loss. any suggestions would be greatly appreciated.
It's either moving due to gravity or colliding with something
i've raised the object so it wont be colliding with anything at start and turned off gravity in the rb component, still happening
disable the collider
Question if i call upon ignore collision between object A and B and set it to true
then call ignore collision layer between A and B and set it to false
does it allow A and B to collide again?
no
so ignore collision has higher precedent than ignore collision layer?
All ignore collision layer does is set up the layer collision matrix in the physics settings
If you have explicitly set two colliders to ignore collisions, they are not going to collide, regardless of layers
disabling the collider does stop the movement, but i'll need it for the game
it means your object is colliding with something
You can put an OnCollisionEnter in your script and print out what the name of the object it is colliding with is.
that might help you track down the problem
good idea, thank you very much
yup, one of the prefabs i added had a giant collider attached to it. wow, you're a godsend
ok thanks
Hey currently i am moving my ingame character with rb.velocity = moveDirection; How can I archieve same physics but use something like AddForce, which is constantly the amount of moveDirection?
Vector3 currentVelocity = rb.velocity;
Vector3 targetVelocity = moveDirection;
Vector3 velocityDifference = targetVelocity - currentVelocity;
rb.AddForce(velocityDifference, ForceMode.VelocityChange);
What's the point though? The end result is the same
except now it's subject to floating point arithmetic error
Ty sir i will try again
Do i add a rigidbody to a parent of static gameobjects with colliders in 2D?
for example i have a floor that doesnt move, and a bunch of dynamic rigidbodies are moving above it
if the object doesn't move, it's fine to have a collider with no Rigidbody
but does it have any performance benefits if it does?
no
alright
Anybody got pointers in how you would rig up a "monowheel + character"? Using 2d physics. I mean how can I get the character to be upright etc. The wheel is probably just a "wheel joint 2D", the character is rigged with joints normally, but how can I get it to behave nicely when the wheel is rotated. I was thinking of negative gravity for the character or something...
Rigidbody2D.velocity being changed changes local velocity or global?
There's only one velocity for a Rigidbody, and it's relative to world space if that's what you're asking.
im getting weird velocity direcitons then 🤔
does calling MovePosition and then .velocity right after cause any weird issues?
for example if i try to get the direction using the transform position and target position
i was correct; .MovePosition has a delay so grabbing the transform.position right after that code doesnt actually grab the position that u want to move the rigidbody to
MovePosition doesn't actually do the moving until the physics update (which happens after FixedUpdate)
Also generally try not to mix Transform and Rigidbody concepts.
Have your code read the Rigidbody position, not the Transform position
ok so it either needs to wait a frame, or to use the actual move vector im using
or that 🤔
eeh since im using a vector3 i cant use rigidbody.position so ill stick to the vector 3 copy i do
why does having a lower fixed timestep , like 32 updates a second, an object moving have a stuttery constant velocity that seems to be in a repeated pattern every second?
you kinda explained it already... you have low 32Hz update interval that's running fixed rate so it's impossible to have it in sync with the main rendering, sometimes your physics updates will inevitably happen close to rendered frame timing and sometimes they will be further away
you could use interpolation etc to smooth it out if it's an issue
if you draw a timeline pulse of the fixedupdates and your game updates, the intervals you see probably make more sense to you
is there a way to allow for an object to move normally but not be pushed around by the player?
like basically i want the enemy to be able to move normally and use rigidbody for say jumping and other physics things. But i don't want the enemy to be pushable by the player.
you can put them on different layers and toggle collisions off between those layers
eye sea
so wait how do u avoid such issues if u have low update interval?
the thing is just a background visual of stuff passing by, it doesnt really interact unless i decide it can colider with eachother
@rugged lotus easiest solution is to just enable interpolation for simulated rigidbodies
and best solution?
just enabling interpolation for simulated rigidbodies
of course it all depends
but without knowing the practical limitations, that would be always my first recommendation
like, if your target is a game that runs locked to 30 fps, it could be beneficial to just lock physics steps to actual update rather than fixedupdate
i do try to make it as performant as possible, since im putting this project in a wallapaper engine so it runs in the background
wait what?
i assume the physics are running at 32 fps, right?
no
Unity by default has fixed timestepped physics so your physics will always be async to rendering even if you try to match those fixed timestep settings
🤔
but you can disable the stock physics updates from running automatically and call physics.simulate yourself whenever you want
aka each fixed update, for example?
I wouldn't recommend that route unless you really understand how this all works in the background though
well. sure if you want to but doing that each fixed update would beat the whole purpose of not letting the engine do that for you 😄
lol ok so its the same then
i dont get it why it doesnt update consistently then if i have fixed timestep on 32hz
if you look at Unreal Engine 4 for example, they run physics always at main update so physics is never async there... and they have separate substepping option for physics that just splits the physics updates between these frames if main game runs too low fps
scheme like that lets you avoid interpolation altogether
but really... simplest way to do this is to run physics as low rate as you can without it glitching and enabling interpolation
unless you can really see the interpolation costing you too much, you shouldn't worry about it
when u say physics, u mean the fixed timestep value?
in this case yes
you shouldn't really run anything but simulation (typically physics) at fixed timesteps even
alright so i guess ill just put it back to 32 instead of 50
oh, i have a coroutine of an AI moving but im not sure if i should be multiplying it by the fixed delta time, should i?
around 30Hz is still somewhat acceptable for physics unless you do really fast paced stuff... but you can find the place where things start to explode yourself
rig.MovePosition(rig.position + (moveDir * moveSpeed * Time.fixedDeltaTime * Vector2.right));
yield return new WaitForFixedUpdate();```
its an animated wallpaper, theres not really much stuff going on there
lower the value, more objects have time to sink into each others when they collide and more things will explode when physics engine tries to solve those situations
Howdy! Just a little question, if i may : I have colliders all setup and stuff, but apparently, they dont go well with anims. Is there any way to prevent player from clipping through boxcolliders (like on the pic), other then making them larger then the object itself?
her let me show u what it really just is
@rugged lotus I'd just... enable interpolation and lower the physics rate as much as possible, if it's slow paced thing you could get away with 20Hz etc
interpolation keeps the whole thing looking smooth
yeah but how much of a performance hit is there on that?
🤔
why do you need physics for that clip?
the AI interacts with the ball for example
nothing there looks like it should require any physics
you can calculate the ball distance yourself
the asteroids there im doing use rigidbodies to move 😛
as in?..
ok maybe use physics then 😄
heheh
the Ai also uses rigidbody to move and have gravity
probably not needed but it helps set stuff
I mean this isn't complicated math but I do get the appeal on using existing things
dont get me wrong, would love to just remove the in-engine physics system and just use my own
but u know...i dont know jack shit on how to do that 👀
that and URP already needs the package anyway so might as well use it...
no clue why it needs it but whatever
typically you'd just fake everything in such scene and write some quick pseudo-physics on the char movement
URP needs physics for it's volume system
ah, the triggers stuff?
I'm personally not very fond of that
it's silly because Unity also has bunch of other physics engines on DOTS side
on a rendering pipeline that they say is fast, it sure uses a lot of packages that dont seem to be needed
urp uses JSONSerialize, of all things
and UI
it does have debug UI you can toggle on at runtime on dev builds (and in editor)
no idea why they need json
and because of that it includes it in release builds
i assume they are needed for the settings
Renderer 2D Data for example
ah, I haven't really played with 2D side
but yeah they could be doing stuff like that.. I always assumed they just used some SO's to store things but haven't actually looked what type of data assets those are
¯_(ツ)_/¯
I don't think Unity has any mechanism for different built type requirements, so I guess this is something where you just can't win unless you manually remove the requirements using custom URP package
only ones that move dynamically
since ive noticed the AI also have a somewhat jerky movement even though its much slower
dynamically?
the meteors are kinematic, i just add velocity to them; still jerky
I'm not 100% sure which all configs get the interpolation with Unity, typically the bottom line is that if physics engine simulates the movement, it gets the interpolation. so if you move via velocity, it should interpolate
2D physics solver without any collisions are really trivial to code yourself too but I get if people hate math 😄
not hate as much as i cant xD
needless to say not the best at math
hell, i wanted to find out a formula that calculates how long it will take for the meteor to reach the out of bounds box from any location to any direction, but ye...
wouldve saved me an Update method for each object
but yeah, interpolation is just a setting on rigidbody... use interpolation instead of extrapolation for least amount of glitching
mhm
you get tiny extra latency with it since you are always rendering the physics sim like one frame late with interpolation but that doesn't matter for visualizations
even for most games that's a nonissue
hmm
i could probably make the timestep to 20 if interpolation works well
i do want to make the meteors collide with eachother later on , so im not sure how well it will go then
main limiting factor on your scene are the characters
they will start to sink in the ground and colliding get more wonky the lower you go
find some place where it's a good compromise with perf and visuals
interpolation cost is overexaggerated on docs... unless Unity does something super silly with it, it's very simple math that shouldn't cost much
it's literally just one lerp for position and slerp for rotation
(for each rb)
you can do thousands of these operations in single frame with most devices
mhm
so... just measure the cost before making any assumptions
using the profiler i assume
yes
i dont see teh AI sinking into the ground tho
to settle in on the ground 😄
but your ground is all leveled
the ball can go over the AI's heads
if 2 for example pinch it , it goes up and over
you can also just constraint some of the axis on rigidbody's physics settings
i could probably get away with no physics at all if i remove the ball from the equation with my current scene
already is
since the AI doesnt need to rotate
yeah, I mean you could just freeze Y too if you don't need them to move up/down
but yeah ill still need the physics for future updates
the thing is im lazy to see what height they need to be exactly so thats why i just let gravity to it's job
its not gonna be just this one scene, but this one is the most physics-heavy
ive got a forest one where everything (for now) is just a static thing, and its just the AI wandering around
@lapis plaza well that seems...bad?
are the spikes just the 20 fps timestep kicking in?
those are probably your physics steps
it doesn't do physics simulate each frame
just look what the profiler says :p
I mean, that's the whole point of using it 😄
huh, my coroutine's at fault maybe
i do have a yield return new WaitForFixedUpdate(); while its "wandering"
you really shouldn't worry about costs in this ballpark at all
none of this matters
if you really care about micro-optimization on this level, don't use built-in physics at all 🙂
but really, unless you have some badly performing part that costs you several milliseconds you don't have perf budget for, maybe then start to look into optimizing it
otherwise it's just all premature optimization for no good reason
hahah alright alright ;p
my reasons are that CPU usage is about 4% when its running so idk
its a free performance boost tbh; and gets rid of GC alloc- i just put WaitForFixedUpdate as a static in my manager script; saved me multiple calls per timestep that also allocate CG
ah, don't get me wrong, you should always aim for zero GC when possible, that comment was purely based on the perf impact
so question, this object had childs in its prefab and those childs have a collider each, as u can see in pic green lines, but instance itself doesnt have any collision, in course he said if u add rigidbody to gameobject it will detect the children colliders and it will work, but now when i add rigid body it doesnt work. any idea what i can do so game object detects prefab children colliders?
Having a Rigidbody at the parent will do it. Your object needs to move in a physics friendly way for it to matter though
If you're moving the Transform directly it's not going to matter either way
not sure if this is the right channel for this question, but here goes. I'm trying to make a simple 2D platformer with a tilemap that makes up the level. i have a tilemap collider 2d on the tilemap object, and a capsule collider 2d and rigidbody on my player. i move the player with rigidbody add force. as the player "slides" across the tilemap making up what constitutes a floor, the player will hit the corners or joins of the tiles in the tile map and either slow down temporarily, or bump up in the air momentarily before gravity pulls the player back down. is there any way to prevent this? i think i've read something about using Havok physics and "welding" joins together or something along those lines, but i'd prefer to use the built in physics engine.
gotcha; btw i managed to half my CPU usage, i think its because i reduced the timestep from 50 to 20
and interpolation made everything look prettier xD
not sure if i should make my AI's collision detection discrete or continuous though
the thing they interact with, the ball, is continuous; so idk if the AI also needs to be continuous
why just having rigidbody2D on an object makes it jitter even if i move with transform.position
and interpolation does absolutely nothing
moving with velocity makes it even worse and interpolation still won't do anything
tbh interpolation makes it only worse
updated unity and now its fine with rb on the object but still no idea how to get smooth movement with velocity
From left to right:
RB, Velocity, Interpolation
RB, Velocity
RB, transform.position
NO RB, transform.position
this driving me mad already
it seems to be absolutely fine in 3d, why that isn't the case in 2d?
unity uses a completely different physics engine for 2d and 3d. You should not expect anything to be the same between them.
interpolation is trying to guess where the rigidbody is going to be between physics frames. If you are updating its velocity yourself, it makes it so all of the interpolation guesses are wrong, which is why it introduces the jitter
moving an object with a rigidbody on it using transform.position is generally a pretty bad idea. It makes the physics system get out of sync and can introduce all kinds of hard to track down bugs
and just look bad often
I find Rigidbody2D.MovePosition is a good option when I want to manage my object's velocity in my own code, rather than letting the rigidbody work it out based on forces
I tried MovePosition and it was pretty much the same problem
In 3d tho setting velocity of the physics object with interpolation is buttery smooth
I believe Unity's 2D approach is Box2D and 3D Approach is PhysX right?
Did you mess with the fixed timesteps?
or iterations I think
I found a short-term solution by setting it to 140 updates per second
yes, if you use the built-in physics and physics2D
It's not a physics channel
There is no scientific discussion about physics
I need help...When I start my game the character just falls through the floor
Any know how to fix this?
Constraints are on, local center of mass is manually set (correctly), inertia tensors (both) are 0, I still get rotation on axis that should be 0.
localRotation.y == 0.001 (?)
private void Start()
{
rb = GetComponent<Rigidbody>();
rb.centerOfMass = Vector3.zero;
rb.inertiaTensorRotation = Quaternion.identity;
}
so i want to recreate something like an analog stick inside unity
how would i move it along a sphere(? i guess thats how its done)
and also restrict it to like that circle edge
imagine the transform would be uhh the top of the analog stick
idk maybe like this i cant really draw good xD
Ball/Sphere to show its moving not on a plane
Make the ball and stick one object and rotate it so that the pivot is in the middle of the ball
like it does in real life
so rotate the ball? 🤔
hmm good idea
but how do i resrict it like the analog example?
like i could say if you just turn it left/right you can check if angle < 30 && angle > -30 or something
but if its up/down AND left/right then you cant really do that since its a circle not a square so idk how to change the checking angle
Guys, I probably got it here with my questions. But there is one that has been haunting me for a couple of days.
There are enemies, I cling to them with the hands of my player with a cutter joint that hangs on the player's hand. The joint is default.
The problem is this: there are two options for my player (2 skins in fact). In one player, this bone, which I am hooked on, is rotated so that the Y-axis initially looks vertically, in another skin the bone is rotated differently.
When I use the first player option, I grab the enemy normally, nothing trembles. But when I grab the enemy with the second version of the player (where the axes are rotated differently), the mob begins to very much sausage in all directions, everything is set 1 to 1. Only the rotation of the bone is different. How can this be fixed? Someone worked closely with joints. THX
Many ways, but you can for example check transform.rotation.eulerAngles.magnitude which would be the angle in relation to 0, 0, 0 rotation
Hey everyone, so I have an object and I want it to go down a slide, but it just gets stuck when it hits the slide, it doesnt slide down. What do I need to do to make it "slidey"?
Use custom PhysicMaterials
that allows you to change the default friction settings
Any movement scripts you have for the object could also be potentially causing issues.
thank you @timid dove I found it out anyway, but thanks anyway!
I already typed this in another channel and was suggested to go here but
Im in a middle of different project so I haven’t started this, but I wanted to know how to make something like this in 2D: If you were to collide with a surface with a high enough velocity, immediately jumping off that surface would give you a higher velocity than you did before the collision.
Also if you wait too long, then you’ll lose that built up speed and your jumping will be normal.
The Collision will give you information about the relative velocity between the two objects. You can use that to make your determinations https://docs.unity3d.com/ScriptReference/Collision2D-relativeVelocity.html
Is there a relatively cheap way to simulate pools of water? I'm talking about having water conform to the shape of its container while also applying water physics to objects in its volume.
Obi Fluid perhaps?
https://assetstore.unity.com/packages/tools/physics/obi-fluid-63067
will DOTS physics ever support multi-platform determinism
the only possible way rn is using dots and SoftFloats/FixedMath
time will tell
wouldn't expect it to happen in following few years
they keep talking about it being some distant thing on their roadmap they are not focusing at all atm
@runic surge
here's a recent staff comment about it
you can read between the lines that it's firmly sitting in the backlog and has very low priority atm
same people used to give more optimistic estimates of this few years ago
it's just really clear it's not in any near term plan anymore
Alright
I built my own solution anyways
but it would be nice to have a DOTS solution
@lapis plaza thanks
Does anyone have a recommendation for a good tutorial that helps provide a thorough understanding of Unity physics including but not limited to Rigidbody, AddForce etc
@pulsar cypressI don't have any beginners tutorial to recommend, there this more in-depth talk that may give some insight to why certain things happen (but it's really geared towards people who've already used physics engines for a while): https://www.youtube.com/watch?v=NwPIoVW65pE
In this 2015 GDC talk, QWOP creator Bennett Foddy explains how to make your game feel solid without writing your own physics engine or breaking your entire game.
GDC talks cover a range of developmental topics including game design, programming, audio, visual arts, business management, production, online games, and much more. We post a fresh G...
Thanks!
do a PR 
It's not a good idea to involve Time.deltaTime when calling rb.AddForce() in FixedUpdate, right?
no
it's horrible idea, considering force itself as concept includes the time component already
that is unless... you actually want to recreate the force yourself with https://docs.unity3d.com/ScriptReference/ForceMode.Impulse.html (which makes zero sense but you can do it)
Thanks, wanted to just check my intuition 🙂
@pulsar cypress
Great tip, thanks!
this could actually be really useful for me, however i'm slightly confused as to which part of rb.AddForce you change accordingly
@wind quail forcemode is just the optional parameter in AddForce, there's no AddImpulse for example in Unity (like there is on some other engines), instead you just do AddForce(value, ForceMode.Impulse)
not sure if you meant that or something else
oh
that is what i meant
thanks :)
also, for my player movement, after my character falls for a certain amount of time the x+z velocity starts to decrease exponentially
and i can't figure out why
whats a PR?
my solution is heavily inspired from the first release of Photon Quantum/TrueSync
the easiest way to get cross-platform determinism right now is to use Fix64/SoftFloats with a modified physics engine (replace float math with fixed math and ensure stable sorting and no random number generation). I did it with a C# Jitter Physics port, but I could have also used DOTS
This github did exactly what I described but with DOTS https://github.com/Kimbatt/unity-deterministic-physics
oh, nice
how would i go on about simulating artificial gravity for player (that scales up as you fall down)
Just add a value over time
hello, I'm using AddRelativeForce and I see speed in the inspector but I don't know how to access it in code...
nvm
Why does my player sometimes get stuck?
that's probably the capsule collider hitting the edge at perfect position. what method you use to move the player? changing .velocity straight sometimes leads into physically incorrect behaviour. it would be better to use .AddForce instead.
hi, the obstacle looks very jittery ,any ideas on how can i make it look smooth, I tried interpolate (saw this after googling ), it did not work
How are you moving the obstacles
the obstacles are not moving, the player is moving forward with a constant velocity.
im having issues with uh hdynamic bones rn
two separate issues
created a dynamic bone for the hip and it only added one circle
and on the video im wathcing it says two
and then somehow my skirt/dress physics wont even work
even though i added exclusions
but like
if i remove them the legs become jelly
Then what did you enable interpolation on?
If I'm launching an object with the mouse, what system would be better?
Adding an impulse or angry birds style?
whatever works for your gameplay better
- is how I would expect such a mechanic to work. But what 0lento said is prob what you should do.
How do i create a contact filter 2D with Usetriggers enabled
Help! Fast-moving rigidbodies go through walls constantly. Setting the collision mode to "continuous" does not fix it, does anyone have a solution?
They seem to go through mesh colliders. Switching to a different type of collider is not an option. Does anyone know how to fix it?
Are you moving your object in a physics-friendly way?
Or are you just modifying the Transform position directly?
(MovePosition and rb.position are not physics-friendly ways either)
Also, quoting the documentation entry on the Collision Detection Mode...
Use this to set up a Rigidbody's for continuous collision detection, which is used to prevent fast moving objects from passing through other objects without detecting collisions. For best results, set this value to CollisionDetectionMode.ContinuousDynamic for fast moving objects, and for other objects which these need to collide with, set it to CollisionDetectionMode.Continuous. These two options have a big impact on physics performance. Alternatively, you can use CollisionDetectionMode.ContinuousSpeculative, which is generally cheaper and can also be used on kinematic objects.
https://docs.unity3d.com/ScriptReference/Rigidbody-collisionDetectionMode.html
hey quick question. I was using a raycast to detect if the character was grounded but a issue came up where the character would technically still be in the platform (part of the hitbox is still on the platform) but the center of the ground check is already off the platform. Is there a better way in which i could check for the size of the hitbox if it is grounded or not? I tried the check sphere but i ended up being able to check the "is grounded" of certain walls and angles where I wasn't meant to
@timid dove @unique cave I am using AddForce, I think that is physics-friendly. Do you know how to fix this problem?
I tested all modes, none of them worked. The rigidbody still very easily goes through mesh colliders, and using a different collider is not an option, do you have any solutions?
Are your walls marked as static?
Yep
Hmm, that is interesting. Do you have the possibility to share a project where this can be reproduced? Would be interesting to look at. I never had that issue with static geometry so it would be interesting to look at a case where it happens.
There's lots of possib ilities
One of which is that your mesh geometry is messed up
Otherwise, this sounds like your bog-standard tunnelling situation
it happens with every flat plane
Options to mitigate tunneling are:
- Use continuous collision detection
- Decrease fixed timestep
- Make your moving objects larger
- Make your static objects thicker
- Make your moving objects move slower
- Do your own custom raycasting to detect collisions pre-emptively
My understanding was that tunneling should not happen with continues detection and a static collider.
Well apparently it does happen, and very easily too. And I can't do my own custom raycasting
I'd like to use the built-in rigidbodies because my own raycasting solution would take too long
can't make them thicker because they're mesh colliders
I'm just listing the general approaches that work for mitigating tunneling
continuous collision detection is not perfect
But I'm kinda thinking you might just have a mesh with messed up geometry if it's happening so easily.
Surely unity has a way to have perfect collision with the built in rigidbodies? No, it happens with even a simple flat plane, so the meshes aren't messed up
Nope, nothing is perfect. Physics engines are one big tradeoff between realism and performance
How fast are things moving
and how big are they
And can you share your code
addforce 250, and its a cube thats 0.7 meters wide
"addforce 250" is pretty meaningless out of context
Which force mode?
How often is it called?
What is the mass of the body?
How long is it accelerating before the collision?
if it's a 1 kilogram mass, then a force of 250 will accelerate it up to at least 250 m/s after just one second
which is very fast
Mach 1 is about 350 m/s for reference
The objects go through walls VERY easily
For a pickup script it's almost definitely not be using AddForce
seems too finicky
I'd just use MovePosition to interpolate it into your hands
I just created a cube with size 0.01 xyz , added a script where in the start method, i do body.AddForce(Vector3.forward * 10000, ForceMode.Impulse); it does not go trough the plane
Yeah - show the code ideally
This script does use AddForce
I just added an impulse force of one million to my cube and it did not go trough the wall. Did you set your collider to trigger or something that makes it go trough walls? We are reaching the point where we need to be mind readers to help you. It's quite frustrating to have to try to drag information out of you just to help you.
putting this here for awareness: Unity added force getters for articulated joints (available on recent 2022.1 betas): https://forum.unity.com/threads/inverse-dynamics-for-articulation-bodies.1198696/
Honestly guessing going through the wall at this point is not related to normal movement of the body, rather it's something to do with your code after it's being "held" - where it probably is moving due to being parented to something or similar that doesn't obey physics
https://github.com/JuozasK/unity-inverse-dynamics-demo/raw/main/Demo_gifs/ID_DriveForces_Demo.gif
https://github.com/JuozasK/unity-inverse-dynamics-demo/raw/main/Demo_gifs/ID_CoriolisCentrifugal_Demo.gif
https://github.com/JuozasK/unity-inverse-dynamics-demo/raw/main/Demo_gifs/ID_ForcesForAcceleration_Demo.gif
I copied this script EXACTLY, with a standard unity cube and a standard plane.
Nothing else
Anyway show how your scene is set up
based on that tutorial there's no object anywhere that should be positioned somewhere that the object could go through
so like... give us a clue as to what's happening
There is something else than physic forces affecting the position of your object. I'm happy to help you if you share your project but I don't want to go trough a youtube tutorial just to help out. 🙂
The cube that i'm holding follows the point infront of my camera using AddForce, and when I move my camera fast against a wall the cube just goes through
Here's the code I'm using
This tutorial is awful
MoveObject() is the part where the rigidbody moves
If they're telling you to use AddForce in Update like that
What is holdParent that you set objRig to be a child of?
Which tutorial is good then? for picking up objects
holdParent is a point infront of my camera and its a child of the camera
just an empty gameobject
and the object should follow that point, and it does, but goes through walls easily for some reason
But if you set your picked up object to be a child of that point, it means your object will teleport with holdParent
Yeah another reaosn why this tutorial is bad
there's no reason to be parenting anything to anything
If holdParent moves that movement will affect your objects position without physics.
Ok but which tutorial is good then?
don't have one off the top of my head
What happens if you do not set it to a parent of holdParent?
One moment i'll check
Maybe we can repair this one 🙂
Wow, it works. I can't put the cube through the wall anymore it seems like. Thanks! 😀
Great to hear! And that is why you should share your code when you want people to help you find issues. Even if you're a professional programmer who spent 20 years coding there will be things you miss. 🙂
is it possible to add gravity to charactercontroller? i tried already rigidbody but it didnt work is there a betther way than scripting it by myself?
CharacterController.SimpleMove? (havent tried myself)
Why does character controller and root motion cause gravity?
What do you mean by cause gravity
If you use SimpleMove there's automatic gravity
var ray = new Ray(new Vector3(x, 2, y), Vector3.down);
Debug.DrawRay(ray.origin, ray.direction * 10, Color.red, 10);
if (Physics.Raycast(ray, out var hitInfo))
{
print(hitInfo.transform.name);
if (hitInfo.transform.name.Equals("Road"))
{
return false;
}
}
Why does this code ignore the Road?
some one know how to get the obj that the Physics.CheckSphere(transform.position, .1f) get?
Hi, I'm looking for examples of 2d top-down physics based controllers - ships, boats, cars, etc. Especially how to control AI
Does the road have a collider?
Yeah
Why when I set my fixedtime step via script 1/60 it laggs and when I set it in the time settings it doesn't?
any help
?
is there any way to make custom collisions based on models that work with rigidbodys in present unity?
What would be the best animation rigging constraint for dynamic pelvis? for natural animations on uneven terrain.
Yes MeshCollider
Wdym by "lags"?
I have another question when I have higher frame rate like say 120 do I need to make physics timestep lower as say 1/120 or no need for that?
in general is having high frame rate effect fixed update call cause it works fine for me at 1/60 at 60 fps if someone have say 120 fps will it be called less or at same rate?
If you set the physics time step to 1/60 then it'll always be called 60 times/second regardless of frame rate
They're not connected. That's the entire point.
No, there's no need to change the physics timestep.
Thank you
the circle around the player is too big so the box collider works like this
cravity is on how can I fix that?
resize your collider?
🙈 thanks
is there a way to disable backface culling for mesh colliders?
or at least make it cull front faces instead of back faces
flipping normals of meshes is not an option for me
i have thousands of objects with millions of triangles, it will probably take weeks to flip normals
For Mesh colliders? No.
MeshRenderer yes
WHY THE FUUCK
just write a script that does this?
already have a script for doing that in blender. but it still takes tooo much time
also... why you even have that kind of source material?
doesn't sound very game ready
im trying to import the map of an AAA game into unity. the tools for extracting the map of this game have only one problem: flipped normals.
these tools are not really built for being handy to import sketchy source material, assumption is that people import things that are designed to work in certain way so your best option is to just fix the material 🙂
there's really no reason why your mesh colliders normals would need to be inverted in normal conditions
but they added an option for culling front faces in materials
not much people would use that too
it's a rendering thing, there are real reasons for being able to render both sides
physics work differently
you get all kinds of physics colliders too, not just mesh colliders. there's no such thing as inverted normal sphere collider primitive for example
point being, having invert normals option only for some specific collider type could get confusing to users
also if you really need it, you can just write your own conversion tools to handle it, nobody would do that amount of asset processing manually if it's a repetitive task
the easiest way to do it that i can think of is, editing blender fbx exporter code to make it export everything with flipped normals.
I don't use blender but if it has any macro capabilities, you might be able to automate the normal flip and export on single operation
ok so i have this tileset in my game which has a physics material that has 0 friction, which is what i want, however, i do want there to be friction for a specific type of object in my game, but no friction for anything else. how?
ok i did it with this
gameObject.GetComponent<Rigidbody2D>().AddForce(-gameObject.GetComponent<Rigidbody2D>().velocity * FrictionMultiplier);
which is basically
f = μN
if anyone knows a better way to do it though lemme know
The other way to do it would be to use two sets of colliders on different layers with different materials.
i thought about that too but i feel like that would be less performance efficient
Create a material instance through script
How would that helpful
You would be able to set the friction for the specific item unless i misunderstood?
You can do that in the editor
i mean like the tileset has 0 friction
so no matter how much friction the specific item has its still 0 friction for some reason
Couldn't you have done it the other way around
Give tileset normal friction
Give the items 0
Yeah thatd be the proper setup
Unfortunately in 2D you don't get friction combine options like in 3D
2D might always use average or something which wouldn't work
the issue with that would be every time i make an object i would have to add the no friction material
so it would be less work efficient
Thatd be where an automated script comes in handy
putting this gameObject.GetComponent<Rigidbody2D>().AddForce(-gameObject.GetComponent<Rigidbody2D>().velocity * FrictionMultiplier); in on collision stay works really good so ima keep that ig idk
ok so how do i make a 2d object that can only collide with the bottom face of the player's box collider and only collides with it if the player is moving downwards
and also make it so that the player can fall through it if he presses S
like terraria platforms kind of
In this video we have a look at Unity's 2D effectors.
● Download Sprites: https://www.assetstore.unity3d.com/#!/content/73728
♥ Support my videos on Patreon: http://patreon.com/brackeys/
····················································································
♥ Donate: http://brackeys.com/donate/
♥ Subscribe: http://bit.ly/1kMek...
The platform effector is the one you want (8:44 in the video)
ok i did it but for some reason the player can still hit it from the side, is there a way to make it so that the player can only hit it from downwards?
bruh player can still collide with it even after i disable that in the collision matrix
how
So I'm tryna make very realistic physics, like Boneworks level for my VR Metaverse. Anyone got any good references that could help?
Are you looking for games to study, or something to read?
When I think of realism in unity, i think havok: https://www.havok.com/
I have Havok, was wondering if there is a way to make it better, or if there was something even better than Havok.
That, I don't know, sorry.
Alright. Thanks for trying though!
What's your definition of "very realistic"? Like what is missing from PhysX that you're looking for?
For example proper conservation of momentum or angular momentum or something?
Like I want them to be near real life level physics. It's hard to explain
Havok in Unity is DOTS setup, it's not really that useful today
Unless you actually are coding your gameplay in ECS
(would totally recommend against it today)
Well basically anything you run in a computer simulation is going to be an approximation. Nothing will be perfect. PhysX I would say is "near real life level physics". But it's going to be hard to help unless you mention some specific interaction or something that you're wanting the physics engine to support better. For example, are you looking for SoftBody physics or something? Determinism across varied hardware?
depending on your answer, there's different routes you should be pursuing.
I think I want the VR character to act like a human being, like it should have mass, you should be able to pull yourself up onto things etc.
would that still be physics?
or more vr?
unless you want to re-invent the wheel, search hexabody on asset store
Anyone has experience with implementing custom wheels or have a comprehensive understanding of unity wheel colliders forces formula?
I'm trying to write a custom wheel, but I'm stuck at the calculating the forces applied by the wheels/tires based on the slip of the wheel...
I don't have specific knowledge of unity wheel colliders nor have I implemented custom wheels, but a BS in physics is better than peanuts. I'm happy to lend a hand trying to muddle out the right eqns. What do you mean "based on the slip of the wheel"? Slippage should be determined by the forces, not the other way around, right?
Probably not perfect for what you're doing, but my favorite physics reference has an article on tire friction specifically. http://hyperphysics.phy-astr.gsu.edu/hbase/Mechanics/frictire.html
Hi! I'm executing Edit Mode tests that include physics by simulating the steps manually.
The rigid bodies are moving correctly but they don't seem to generate collision events when they collide with each other.
Is it possible to generate them on Edit Mode?
I need help
i have a capsule as a character but when i add capsul collider it keep flying
does it have a rigidbody on it aswell
yes it does
Do your scripts with collision handling methods have ExecuteInEditMode?
It's probably colliding with something
They didn't have. But I added it to them (also added runInEditMode = true to Start) and collision events are still not being called 😦
Start and Update methods are being called though.
Hi there, I'm brand new to Unity, but not entirely new to making games, so I've been going through some basics to get the hang of things and I am running into an issue with 2d rigid bodies and colliders. more specifically, i have 1 rigid body representing a player character that i've also assigned a 2d collider to. separately, i have another asset representing some ground for the player character to move around on that I've also given a 2d collider to. I am using stock settings on all of these components right now and both the ground and player character models are on the same sorting layer. despite that, my player character continues to fall through the floor whenever i hit play to run the game. haven't had any luck finding any answers in my own research / messing around with settings. any suggestions?
make sure you're using Rigidbody2D, not Rigidbody. Unity has two completely separate physics systems and they do not talk to each other. 2D components talk to 2D components and 3D components talk to 3D components, but 2D components don't talk to 3D ones. If the component has 2D on the end it is part of the 2D system, otherwise it is part of the 3D system.
yes, to clarify it is a rigidbody2D componernt.
is it set to kinematic or dynamic? Is either the player or ground collider set to be a trigger?
nothing on trigger, and the body is set to dynamic. should it be kinematic?
no, dynamic is right
What physics layer are the objects on? (just called layer in the upper right corner of the editor when you have the object selected)
sorry, I g2g. Hope someone else jumps in to help you debug
if anyone else has any thoughts, i am all ears. still haven't found a solution and I really have no clue what's causing it. T_T
@coarse willow
can you show a sreenshoot of both rigid bodies and colliders?
Hey guys, running into a physics issue with a prototype I'm working on and feel like I've exhausted most of my troubleshooting options, so hopefully someone can shed some light on this issue.
I'm currently prototyping a game similar to Katamari Damacy, where the mechanics involve rolling a sphere around an environment to pick up progressively larger objects. When the sphere comes into contact with an appropriately-sized object it should pick the item up and become attached to that sphere to make it larger, much in the way one would roll a snowball.
The issue I'm currently having is apparently something to do with the collision detection of child objects attached to the sphere. I'm able to detect collisions and attach appropriately-sized objects to the sphere, however the collision for the attached object seems completely off, as if it's colliding way too early. As a result the sphere will do approximately 1/2 of a full rotation and stop as if it has hit a wall instead of continuing to roll as expected. It's worth noting that if I disable collision for the object when it is attached to the sphere the sphere will roll as expected, however doing this defeats the "snowball" effect that I'm trying to achieve.
This is how I'm currently implementing this feature in code, not sure if this is somehow incorrect when dealing with physics and rigidbodies:
private void OnCollisionEnter(Collision other)
{
if (other.gameObject.CompareTag("rollable"))
{
other.rigidbody.isKinematic = true;
other.gameObject.transform.SetParent(transform);
}
}
Here's is a quick video demo'ing the issue since it's a bit hard to put into words
lol and of course after I type all of that out I found my answer apparently
(for anyone curious, apparently destroying the rigidbody component is the fix)
sorry for the delay there. here's what i have:
the first one is the grass with its collider and the second is the player character with its collider and rigidbody2d components.
@coarse willow
The Box Collider on the Grass is not a BoxCollider2D
well then...that makes sense. i feel silly for not having noticed that. though i do wish the 3d ones were just named rigidbody3d or collider3d. oh well. thanks!
anyone knows about wheel colliders physics? i want to make my car more responsive because it has such a delay steering idk how i can fix it
okay, 2D question: i'm trying to do something like this where an arm with a weight at the end drags behind as the object it's connected to moves, but i can't seem to get it to behave properly. how do i make this work?
tried doing something like this. The best I got is a car that acts like a hovercraft with sideways friction and proper suspension
custom wheel colliders in general is something that isnt on the unity forums
pretty difficult topic
Can you describe your problem more?
Sorry for the late reply. What I meant to say is how to calculate the final forces to be applied at the wheels/points where they touch the ground with respect to the slippage of the wheel.
basically i'm trying to have one object hanging from another
I've found a project on GitHub that attempts to replicate the old wheel collider from unity 4 I think. It works more or less, but the problem is that the forces to be applied are defined right in the friction curve.
so that when the main gameobject moves, the hanging gameobject drags behind
If only there was source code for the current wheel collider implementation,it would've been simpler...
mine is heavily based off of this
it's the only relevent thing I could find on the topic
I've seen this one, but it didn't fit my purposes.
Actually, looking at it again,it might be useful. Thanks for reminding me about it!
I only wanted a wheel that detects collisions at several points. The default wheel collider does only one raycast, making wheelies(on bikes) extremely buggy.
I managed to get that part down and suspension too, so there's just the friction part left.
like this
I ended up removing about 60% of the code and cleaning it up, since the friction stuff didn't seem to work well, or I just wasn't setting it up properly. Then I used some dot product magic to counter gravity on the left vector of the car, since it slides down slopes in a really nasty way
countered forward gravity too to prevent rolling on uneven surfaces
I will try to test this system myself and help you.
ok, thanks!
regarding the several point collision, how difficult is that to incorporate and get working properly?
It's always been on my mind but I never attempted it yet
try to use distance joint.
the moving object must have rigidbody too but you can set him to Kinematic
ah, i see, i'll give that a try. thanks!
hi there, i've got a weird problem. I'm using a raycast to shoot a projectile towards a target point, and when it intersects with the ground I create an explosion. This works perfectly in the editor, but in the build it doesnt. Any ideas why?
Not that hard - it's just getting several points on an arc with the wheel radius and casting rays down and using the closest hit as the contract point, but it's tied closely to suspension, so you'll have to make sure your suspension works properly regardless of which ray is selected.
hey i need help with rotation of the object in 2d
i want the yellow and green to also spin in same direction as orage (left and right rotation)
but they move in a weird y rotation
how can i fix this?
nvm i got it!
there is, it's based on physx and physx sources are on github
afaik Unity just implements some abstraction layer for this
If the wheel is slipping, the force applies should be the maximum possible kinetic friction force (uN, or umg in most static cases). Anything in excess of that accelerates the slipping, and if less force than that is applied it means that the forces being applied are not enough to overcome kinetic friction, so its not slipping.
If you're applying it at multiple points, a first approximation would be to just divide the force equally across all your contacts. Not sure how those results would end up. If you want a nonuniform distribution of force across the contacts, you could take the magnitude of the vertical component of each normal and use that for weighting how much of the weight is distributed to each contact.
The next step after that would probably be to start considering the torque applied at each contact as well -- that seems like it'd probably provide diminishing returns.
If you're trying to also account for the suspension's effect on this, then you're getting into systems of coupled ODEs land. That seems to be what the PhysX code Olento posted above is doing.
Soooo, I want to make pipe system that is similar to electricity circuits as works like lego blocks.
Here all important details:
https://github.com/bustedbunny/GasExpansion/issues/1
Any help with solution to this problem is appreciated.
P.S. no idea how to actually ask help with such questions, if you know I did smth wrong, let me know
I have a question that may sounds dumb but I'm still at the beginning:
I have a car that has a box collider (a simple cube) that when collides with another car (still cube) passes through it, like the collision exist but the forces it implies are necessary to ignore the collision. How can I solve it? I can send a little video if needed.
You have to move your cars in a physics friendly way
if you are moving them directly by setting their Transform positions, they will go exactly where your code tells them to go, ignoring all physics entirely
void Update()
{
// Get keyboard's arrows input
horizontalInput = Input.GetAxis("Horizontal");
forwardInput = Input.GetAxis("Vertical");
// Move player
transform.Translate(Vector3.forward * speed * forwardInput * Time.deltaTime);
Yep, you're moving it directly via the Transform
you need to move it in a physics-friendly way
You can't use that if you want things to interact with physics
you need to give your objects Rigidbody and move via setting the velocity or AddForce on the rigidbody
Thanks, I'll change that
anyone know the best way to get physics like in TABS?
Hey! I'm new to unity, been using c# for a few months now. I want to make a golf game, I found a ball flight physics model I want to use but it's written in python with numpy to do the math. should i re-write this in c#? can/should unity use numpy/python for this? does unity have a way to use 3rd party .net libraries or how does that work? Does unity have it own math libraries for this kind of stuff? i need to solve linear alg / calc / differential eqs
You can pull in DLLs from third party libraries but you also have to pull in all their dependencies. There are tools that make it less manual, but I would not really advise getting too deep into it if you're just starting.
What's complex about the flight model that requires it needing all this maths? Are you going for something more than a basic ballistics curve?
it's a golf specific model that takes inputs from measured data from a golf launch monitor, so you actually hit a golf ball and it measures spin, angles, velocity etc. the model takes into account wind speed and barometric pressure
i suck at math, i had to take pre-calc three times
numpy.interp(x, xp, fp, left=None, right=None, period=None)[source] One-dimensional linear interpolation for monotonically increasing sample points.
i need to do stuff like this
i would have to use numpy in unity somehow
Unity has interpolation functions in Mathf and in the Unity.mathematics package
Although that seems to include a bunch of other things like a periodic interpolation which you'd have to do separately, e.g with the % operator.
The built-in math functions are going to have less of a scope than numpy afaik. But you can probably find some .NET math libraries that will cover other things you need. Or even just C# versions of certain functions. I'd probably be more worried from an architectural sense. I have little familiarity with python, and if you have little familiarity with Unity/C#'s libraries then there might be confusion that will be very difficult to fix when manually translating between libraries
I've tried to port some things in the past, and you spend a bunch of work and get to the end and it doesn't work and you're like... 😐 okay but which part did I screw up
I read something about ironpython and unity? Would it practical to run python in unity? It's just a calculation for a single ball flight not complex physics like a "action" game so performance might not be a big deal
Can't speak to that, sorry. Might be worth asking about it in one of the code channels
Might save you a ton of development time if it's easy to set up and the performance is acceptable
Assuming the thing you need is ready to go in python already
ok thanks for letting me pick your brains, this community is huge!
how would you "grab" something in unity?
i made like a very simple hand but the item just falls off
- Make it a child of the hand
- attach it to the hand via physics joint
- use the ParentConstraint component
- manually move it in a script to follow the hand
Lots of options
If only I could understand what's going on there.😅
not sure if this is the right channel but im following a tutorial on making my enemy ragdoll when they die. Why is he not falling to the ground?
@plucky crag you can always run python standalone, take inputs, process them, and send them to an open unity application via sockets, or something like that
did that with face recognition a few years back, had no issues
unity was only used as a renderer
Did you use the ragdoll creation wizard?
it could be a number of things
check if the rigidbody is kinematic first when hes supposed to ragdoll and die
yea i figured it out
it's pretty basic raycast suspension but they compute unsprung masses bit weird there, it's also quite unnecessary as the rest of their implementation is so subpar it doesn't really need that. there's also substepping scheme built-in to the physx vehicle where they actually integrate the vehicle's main body movement on it's own substepping when needed (Unity probably doesn't use this since it's running physics at fixed timesteps anyway). I do mention the substepping because it explains why they did certain things there, like have their own physics integrators there
vehicle code is actually part of the more readable part of physx internals, usually that stuff is super cryptic there 😄
if you compare say, bullet physics and physx source code for readability, it's like night and day (bullet is actually human readable)
I'm more interested in the slip/tire friction/final force calculation. I've got the suspension working.
of course looking at the vehicle code without prior knowledge of the vehicle dynamics probably makes it more cryptic
all in all, their tire dynamics math is really simplified thing, you also won't get great experience with it but if it's all that you want I guess why not
they have this doc page that explains some of the concepts too, not sure if tire friction was one of them https://gameworksdocs.nvidia.com/PhysX/4.1/documentation/physxguide/Manual/Vehicles.html
have you seen this page? https://www.edy.es/dev/docs/pacejka-94-parameters-explained-a-comprehensive-guide/
that explains pacejka '94 algo, but he has like few dozen variants, that's just one
if you want to start with something simple, you could look at the end of that page and see the "Simplified Magic Formula"
it's not going to be great but it'll get you going, alternatively you could just draw the curve yourself with Unity's Animation Curves and just use that as lookup
basically you want some way to indicate that tire has more friction the more load it gets (more it gets pressed towards the ground) and that tire friction has some limit at some point where it starts to slip more
this is why you typically see graphs like these all around when talking about tire physics
if one wants to learn more about this stuff, there are plenty of good books on the topic, I've glanced over most of them so can recommend some of them
https://d1w7fb2mkkr3kw.cloudfront.net/assets/images/book/lrg/9780/0810/9780081000366.jpg
https://kbimages1-a.akamaihd.net/e89e8350-18a0-4166-85c9-7ed67528addf/1200/1200/False/road-vehicle-dynamics-fundamentals-of-modeling-and-simulation.jpg
https://images-na.ssl-images-amazon.com/images/I/71If-UnjZ9L.jpg
first one is really good intro book if you know nothing about the topic, and last two are "essential" reads if want to know more in depth about these topics, genta's book is kinda expensive though (but it also covers basic stuff too)
but if you just want arcade vehicle controller... just put some abstracted tire physics thing there and call it a day 🙂
@tender gulch
sorry for the wall of text (and images)
guys i created an object using 2d physics but it is crossing the collision depending on the applied force, how can i fix it?
he looks like a 5 year old that just got a no from his mom
xd
Explain how your objects are set up and the code that's moving them
What's the equivalent of the AddForce code when using a physics shape instead of a rigidbody?
Whats the difference between these lines? Why is the result different? ```
rb.AddForceAtPosition(rb.worldCenterOfMass, transform.forward * Input.GetAxis("Vertical") * speed);
rb.AddForce(transform.forward * Input.GetAxis("Vertical") * speed);
it's different because the parameters are the wrong way around in the first one
thanks, im stupid xD
Help! All rigidbodies fall slowly like it's moon gravity, changing mass doesn't change anything. My gravity setting is the default (real world gravity), and my world's and all objects' scale is just like in real life (1 meter is 1 unity meter). Anyone know what the problem is?
You probably have a script on your objects that's screwing with it
Or your timeScale is reduced
Changing mass will never affect the falling speed of the object by the way
Everything falls at the same speed regardless of mass
I'm trying to follow the unity physics basics, but when I press play, everything is invisible
Yeah, even in the editor view they disappear
Wdym disappear? Are they still in the hierarchy?
What's their position in the world when they disappear?
Are they getting disabled?
There's only a few possibilities:
- they moved
- they were destroyed
- they were disabled
They are still in the hierarchy ,they just don't render.
If they're not disabled/deactivated, then you've just moved them somewhere out of sight
I can't read the hierarchy in these screenshots but what am I looking at
The objects disappearing when I press play.
I'm not really sure how else to describe it.
They are there in the editor, I press the play button, they do not show up.
You can see that the sphere and floor are not there in the second screenshot right?
What's that whole ConvertToEntity script you have
I don't see the default object in the hierarchy anymore either
In the second one
The one they said to put in in the Unity Physics documentation.
So it's being destroyed
It seems like you're trying to use ECS?
Unity Physics is for ECS
Are you using ECS too? Pretty sure this stuff only works in ECS/DOTS
#archived-dots would be the place to ask about this stuff
Hello, im using Platform effector 2d
to be able to pass through the bottom but i cant pass from the borders.
what's up with this weird jittering?
your object moved by physics that run on fixed update which is async to rendering update
@bitter rose
ways to deal with it:
- not use physics or fixedupdate to move your game character
- use interpolation if it has to be physics based
Nope no scripts, just a rigidbody and a collider
Also that's strange because a heavy object falls faster than a feather in real life
How do I stop drag from effecting gravity?
When I turn up the drag to slow down my ball, it makes gravity really slow
You dont, that would not be realistic. If you have to decrease speed that fast, you could make the horizontal drag yourself
It's only because my main character is a marble, so friction doesn't so much to stop it.
I've made my own gravity script, and that seems to be working.
Oh, thats differemt problem then. Drag is not the correct way to slow down a rolling sphere. You should code the rolling resistance yourself. Rolling resistant is not same as air resistance
Probably, but that should only happen when the ball is touching a ground. Sadly unity/physx doesnt have their own internal rolling resistance implementation. You have to code that yourself
The solutions I've found only basically say to only apply drag when ball is touching the ground, yeah.
Or, to do it realistically, is that a way to make the friction on the sphere be calculated by a small area at the bottom of the sphere rather than the exact point?
not 100% sure this is the right channel, but anyways. I want to use the Unity Built in cloth component to make a cape for my character but I am facing some issues.
- When my player is accelerating the cape moves back as it should, but when the player reaches a constant speed the cape behaves as if the player is not moving
- My player has a character controller which has a capsule collider built in. The problem is that the Cloth component doesn't recognise that collider as a capsule collider.
How do these physics seem now?
Does anyone know why all rigidbodies fall slowly like it's moon gravity, changing mass doesn't change anything. My gravity setting is the default (real world gravity), and my world's and all objects' scale is just like in real life (1 meter is 1 unity meter). Anyone know what the problem is? And I don't have any scripts messing with anything either
Do I have to modify something on the rigidbody itself? It's all just default settings right now
Hi, (for the millionth time in gamedev history) I'm trying to "recreate" yet another pong clone lol but I have a slight issue...The force of the ball is increased if the ball hits a moving paddle instead of staying at a fixed speed... Is there anyway to have a fixed speed of the ball instead of it being affected by the force of the paddle?
(PS, in the version I'm trying to do, the paddle can move in all directions btw not just up and down, so if you hit the ball "running" towards it, the ball shoots off at high speed.
I think there's something wrong here...
Only due to air resistance, which is not present in Unity. In a vacuum a feather famously falls the same speed as everything else.
I think it's a mistake to use the physics engine for pong
hmmm any suggestions/tutorials that doesn't do this? Haven't found one that doesn't use rigidbodies
Think about how they probably did it in the 70s
There were no physics engines to be had
How to make some objects fall faster than others though?
agreed...I am however, very shite in math so... 😛
It's just objects moving at constant speed in a straight line and bouncing
I'd it's 2D you can use the gravity scale property on the Rigidbody
If it's 3D you have to apply your own extra gravity force
Just know that it's unrealistic, which is fine if you're not looking for realism
Wish me luck...let's see 😛 thanks hehe
? Unity does have air resistance a.k.a. drag
set a higher drag to objects that should fall slower
Unity's "drag" isn't actually air resistance at all
it's actually linear damping
them calling it drag is misleading too
It does but not in a way that would cause a feather to fall slower than a hammer
They would both be affected identically by Unity's drag
if you put higher drag on the feather it'll fall slower
It's set on individual objects, not globally
Well yes
Why is there no gravity scale option in 3d? I just want to make my objects not feel like feathers, in an easy way. Making a script is the only way? And I'd put an AddForce in the update method? That feels like it gets laggy real fast with hundreds of objects though
There just isn't one. Unity uses different physics engines for 3d and 2d
And no, AddForce would have to go in FixedUpdate
oh, @tawdry wave meant like per object
well.. then the only way to achieve that is to use custom gravity forces yourself
adding custom forces is not very complicated even
There's only a useGravity bool for 3D
Wait but what about the "drag" property? Does that not do what I want?
Ah ok that would be an easier method than to have to make a new script, I'll test that
Unity's "drag" is basically velocity = (1 - drag) * current velocity
if you omit some checks from it that is, but that's essentially the end effect it has
it's simply a multiplier for your current RB velocity
My collisions still seem fairly bouncy, especially when pushing boxes...
@young rapids adjust friction and damping for the object you are pushing?
I've been trying, to the point that if you push it from a running start, it keeps sliding for a while.
I don't really see "bounciness" on that clip
just it being more floaty than what one might want
It's more that it pushes it a little, then moves further ahead so I have to catch up with it, etc
Yeah exactly
remember than physics materials are using average of both sides phys mats by default
so if you ground has friction 0.5 and your object has 1, it will end up with friction of 0.75
in most cases you'd want to keep this behavior, but if it's some special case, you could just override the phys mat so it uses only one sides value
I've just found the issue, and it's a leftover from me trying to stop the marble rolling
The marble's friction is 20
Oh my god it's perfect now
Can drag be a negative number?
That feels weird math wise
Try it
Fixed the marble having 20 friction XD
It resets back to 0 when I try, so apparently I can't make the object fall faster than the default, looks like I need to make a script after all
why would you even want to have drag as negative?
You can just increase gravity overall
it would make your object accelerate even from smallest movement
Then give the slower things more drag
The object falls like a feather currently
just add extra downward force to it
Give it less drag
or that
It's already 0 by default
many games have 2x gravity because of that
It's a 1x1x1 meter cube and it falls like it's on the moon
and yeah also could be issue with scale and such
If you have really large objects... They might look like they're falling slowly
Sorta like a Godzilla effect
A 1 meter cube is quite large
How high are you dropping it from
Like I think your sense of scale might just be off
I feel like it's more about weird expectations on how quickly real world gravity works
Like 6 meters high
Hard to say without seeing it ourselves, but yeah just increase the gravity setting if you don't like it
I totally looks like a feather when it's falling
Alright I'll just change the gravity
it should fall like one second or so I think
in real life
I didn't do the math, just approximation
ok did the math, it's 1.1s
also tested on Unity and it takes... 1.1s
@tawdry wave
I've timestamped part of this talk: https://youtu.be/NwPIoVW65pE?t=264
In this 2015 GDC talk, QWOP creator Bennett Foddy explains how to make your game feel solid without writing your own physics engine or breaking your entire game.
GDC talks cover a range of developmental topics including game design, programming, audio, visual arts, business management, production, online games, and much more. We post a fresh G...
it discusses about the gravity in general
Not sure why the dice collisions are being like this
Their material has like 0.05 bounce, so that shouldn't effect it
too big timestep value for fixed update?
I don't remember setting a timestep?
Where's that
project settings->time etc
0.02 is the default... it results in physics running at 50Hz
you could try on 0.01 and see if it improves the behavior
it does come with extra cpu cost though
you could also try different collision detection settings
0.002 Has made it really smooth, but my acceleration seems to have also slowed down?
0.002 is total overkill
Yeah but when it's a small physics based marble game, I feel like it's ok to focus on the physics?
basically you'd always want to set the physics update rate as low as possible while the thing still feels nice
but yeah, it's all combination of different factors
also if the timestep change changes your physics behavior you have some math error on your movement code
or it's just possible the whole game slows down because your cpu can't keep up etc
there are small differences on the physics behavior if going from really slow update rate to faster but it shouldn't be huge difference at these speeds
My movements done entirely by adding force in a movement vector
It seems to run at 2 different speeds in the game view, and build view?
It's like the timescale's slowed down
@young rapidsyou use deltatime in your force calculations?
I was told with physics that's already built in to AddForce and stuff
it is, hence asking
Ah, no
but even that depends
if you move by ForceMode.Impulse, then you have to factor in deltatime yourself again
(which would be silly since you could just use regular force then)
it seems like the entire game timescale is lower. At the beginning when everything falls to the floor, it's slow.
Not just my code.
check your CPU load per core
if the cpu can't keep up, it will slow down the physics
How do you check per core?
just open windows task manager etc
Overall it's 12% use max
What's your timeScale set to
1
