#⚛️┃physics
1 messages · Page 39 of 1
for networked physics - their new unity physics seems a lot more preferred but its a work in progress
@quartz wyvern Is that some type of physics streaming capability?
yeh but unity physics is deterministic across architectures so you only need to send inputs - no more syncing of objects
- Built-in 3D physics which uses PhysX
- Built-in 2D physics which uses Box2D
- (DOTS) Unity Physics package for 3D Physics running on ECS
- (Paid) Havok integration (it should have been here already but we are still waiting) for 3D physics
- (DOTS) 2D Physics package running on ECS
also, Unity Physics (DOTS) is not crossplatform deterministic yet
it's the grand plan but it's not the state of it today
in fact whole DOTS physics is still very alpha today
yeh like most things
in unity in general 😛
i still wonder what limitations will exist in DOTS though for it to be cross platform
i have feeling it will be limited compared to physX
main limitation is that... Burst compiler that actually makes the deterministic float compilation happen doesn't support it yet
and Unity has pushed the ETA back for a long time already
right now they estimate it would arrive next winter
but they said the same for past winter...
they focus on too many things at the same time
even their navmesh components from unity 5 isn't completed
https://ctrlv.tv/R5se
What I do wrong?
When I remove the boxcollider, the object falls straight down (that's how I want it ), but then it falls through objects off the map. When I leave the boxcollider there and assign Physics.IgnoreCollision (Handgun.GetComponent <Collider> (), GetComponent <Collider> ()) to OnStart; so it behaves like a video
Okay, exactly which behaviors in the video do you want help with? It looks like there's some weird settings on the material - little or no bounce or friction. Or is it the drop not going the direction you want?
Looks like maybe it's colliding for one frame?
I've had good results using IgnoreCollision to ignore the source of an object, so I'm not sure what the problem might be, there; maybe some timing issue, maybe not getting all the relevant colliders, I dunno.
I just want it to drop the object straight down
I tried IgnoreCollision and didn't ignore it at all
Maybe OnStart is too late. (What is that, anyway?) Try putting IgnoreCollision in the same code segment that instantiates/activates the GameObject.
Also, make sure you're getting all the relevant colliders, if there's more than one.
Alright, let me know how it goes. Unity does a lot between Instantiate and Start so this might be one of those effects.
Physics.IgnoreCollision(lEmptyMag.GetComponent<BoxCollider>(), GetComponent<BoxCollider>(), true);
lEmptyMag.SetActive(true);```
Still nothing
Try putting SetActive(true) before IgnoreCollision.
Same
Hmm.
Checking my own working code. Having trouble seeing where there could still be an issue. I'd probably throw some events in and see what's actually getting called and against what. Is it really colliding with the exact collider we just prevented it from colliding with?
Buuut...
If you really want to fix it right now, there's a couple other options.
One simple one is to have the collider start as a trigger and only become a non-trigger collider one frame after OnTriggerExit.
Another possibility is don't even enable the collider until, say, 0.2 seconds in.
A third possibility is to use the collision Layer matrix so that it doesn't collide with the gun at all in the first place.
I no longer want to go to sleep today
but the trigger collider I actually put there but that is so unsatisfactory.
I understand tomorrow I will look at it, and when I write. I'm really going to sleep tonight. GN
@sly violet Mabye I could remove the box collider from the gun once I held it in my hand... maybe it could be better. I'll try when I get home
Anyone know how to create a separate physics world in the new system?
edit: seems they are created automagically with the duplicated system, so my problem lied elsewhere^^
@sly violet Okay ... I solved my problem ... I forget that I created imedietly a new one object in same position ... IgnoreCollision is wroking 😃
Heh. That sort of thing is why I wanted you to check what it was actually colliding with. Glad you fixed it!
Has anyone tried creating a rope in Unity that can collide with objects in game i.e could wrap around a column and apply tension? If so any tips on a good way to go about it?
Rope is a notoriously difficult computational physics problem. There's a reason that most games that have rope, fake it. There's a number of rope-handling assets in the asset store, but AFAIK all of them have issues.
Thanks for that, thats good to know before I commit too much to this project as its a big aspect of what I’m working on.
I was hoping a series of configurable joints with raycasts between them might work
And trying to fake the physics from there
HELP
@stable plover : This is a bit complicated because that red pivot point is the location of your transform; sort of the "real" location of your GameObject. You'll have to figure out why it's off and fix it. Most likely it's the pivot point of your Sprite, so you can change that in the Sprite Editor. Once that's in the right place, your Collider will end up offset, so you'll have to zero out the Colliders offset. That's a good way of knowing you've succeeded, though.
Hey guys! I'm having issues with an FPS controller on a rotating platform. Basically I'd like the FPS controller to be facing the same direction relative to the platform as it rotates, but it stays relative to the world instead. I can't find any tips for this online
It's position is already updating correctly? You should be able to simply rotate the controller the same distance as the platform rotates.
The position is only being updated because of the friction of the player. I'm not a math major, and I haven't tested it, but I don't think I can rotate the player the same as the ground because that becomes distorted, especially the further away from the focal point that the player is
Actually, a wheel rotates at the same revolutions-per-second anywhere on the wheel, as does anything on the wheel. Don't overcomplicate a simple situation.
THAT BEING SAID, I smell a fish. If the player is moving by friction... Then they ought to be rotating by friction, too. Most controllers aren't that physically accurate, intended towards playability instead, which is what I thought you were talking about. You might simply need to... Stop preventing it from rotating.
Hey, I have a question about colliders. Can I ask here?
I'm making a 3D game, where the characters are 2D sprites standing and moving around in 360 degrees within the 3D space.
I've made a sprite renderer for my character, and I need the sprite to be hittable by raycasts. However, the sprite has transparent parts. The ray must only react to non-transparent parts of the sprite.
How do I perform a raycast across the 3D room, and have it hit the sprite only when it's hitting a non-transparent part of it?
Well, typically you would make a collider (or set of colliders if need be) that conforms to the opaque portions of the sprite. It's not impossible to check the sprite color alpha, but I wouldn't recommend that approach unless absolutely necessary.
Youd want to blit the texture, store it and check the raycast hit against the coordinates of the texture
Nice thing about it is you can blit the texture at much lower resolution than the visible one
heya, i have a question about Unity Physics, i'm moving many child objects by rotating their parent, using ConvertToEntity and the built-in transformation systems from conversion. But the issue is that Unity physics is not picking up the change when made to the parent.
If i move each object directly instead then it works fine and i can see from the debug display mode that it is in fact moving the colliders. So yeah, is there a trick to get these updates to be found with the parent-child setup?
In play mode a child object with a Rigidbody doesn't automatically move with its parent. I wouldn't screw around with trying to get around that rule, especially if you've already got it working another way.
Hello friends I have a quick question about unity I’m trying to create a slippery icy floor affect for a 3-D game. I’ve searched far and wide throughout YouTube google stack overflow in numerous form boards. My question is I create the physics material I set the friction down to zero however I don’t get the desired effects does anybody have any sort of advice to replicate the slippery icy effect that you would notice in Mario games please and thank you dms well appreciated
And what effect do you get from setting it to 0 compared to the one you want?
@stray apex
The slide effect works however I’m trying to accomplish on a flat surface
@stray apex I don't really understand, it works? But you want a flat surface?
Physics material allows me to add the sliding affect but only on a angled surface I’m trying to replicate That on a flat surface as you would see in a Mario game
@stray apex And how are you moving your player?
I don't see why it shouldn't work as you want if you are using forces, have limited drag, and no friction on the floor.
Let me check
@sly violet Unfortunately, manually making a collider that conforms to the shape is absolutely not an option, because if I did that, then I'd have to make hundreds of them. I need this to work with a huge amount of sprites.
@narrow quiver What does it mean to blit the texture? Also, it's a sprite and not a texture, so is this possible to do with sprites? (RaycastHit.textureCoord always returns (0,0) if there's no mesh)
No you just make a box collider but then you ignore raycast hits outside of the blit
Oh wrong comment lol
Cant you use raycasthit.point, convert it to the nearest point on the plane of the sprite then perform the blit
I'm using a sprite renderer, so there is no mesh or plane.
I have tried adding a capsule collider like this:
But when I get a raycast hit from it, there doesn't seem to be a way to compare the point in world space to any point on the sprite, because RaycastHit.textureCoord always returns (0,0) if there's no mesh.
Is the game 2D?
No, it's 3D. Here, let me re-post my explanation from above:
I've made a sprite renderer for my character, and I need the sprite to be hittable by raycasts. However, the sprite has transparent parts. The ray must only react to non-transparent parts of the sprite.
How do I perform a raycast across the 3D room, and have it hit the sprite only when it's hitting a non-transparent part of it?```
Doesnt raycasthit.point return a world space coordinate
Yes, it does.
You could use that to convert to texture location with some geometry
Like I said, RaycastHit.textureCoord always returns (0,0) if there's no mesh. So, since there isn't a mesh present, how do I obtain the sprite location?
You use the point, not texturecoord
So I have the point, in 3D space...
And what do I do with that to get the location on the sprite?
You perform some vector geometry to convert them to eachother
How is that done?
Vector3.ProjectOnPlane(raycasthit.point, raycasthit.normal) might be needed if the point is slightly off
Then you rotate the point as much as it takes that the plane normal aligns with one of the axes
And I suppose you'd need to take the size of the sprite, move the plane towards 0,0 in whichever corner is your preferred sprite origin, set rotation to a certain value such that it matches the blit results
Then you convert your x,z coordinates or whatever coordinates to the coordinates matching the size of the sprite/texture and see if a (preferably stored) blit of the texture contains alpha value above 0 at that position
Interesting. This seems like a fairly involved process. Is this something that can be done every frame for a dozen sprites at 60fps?
Depends on the size of the blit results you store, I'd expect it to take negligible amount of time for only a dozen sprites
I used blits to convert 256x256 sprites to 64x64 arrays for a library of about 2000 sprites (I reckon) and then traverse all blit results to find the minimum and maximum alpha values, crop away all excess transparent pixels and store the resulting new image sizes
and it takes I'd say less than half a second on game startup
your use case wouldn't need to traverse the full array, just look up a single point (4000x less), you'd be working with 100x fewer sprites and your sprite sizes I don't know, but it'd probably be 400,000x less time taken
definitely can be computed within a frame
My sprite sizes are around 2k. It's a detective game with very crisp sprites, where the gameplay involves zooming in close to characters to look at small details on them. You can see a person's whole body, then zoom in towards (for example) their nose, and the nose will still be relatively clear.
So I will probably need at least a somewhat high resolution for the blits, as each character will be a lot more data than a typical game sprite.
It's important to note that the hitbox sizes really don't need to match the source sprite sizes
you could test how well the hitboxes match the sprite by doing nearest neighbour resizing in graphics software
say 2k --> 64px and back you see how rough the edges are and if you're fine with them
Hm, alright. Sounds like fair work to make it run well.
Can you explain Vector3.ProjectOnPlane to me? I'm not that experienced with vector math, and am struggling to visualize it, or what it's intended to return.
yea not sure either what it would return
Hm... I really don't understand this math that you're describing. I get that I need to make blits of the sprites first, but I don't understand what I'm supposed to do once I have my RaycastHit.
uh
so Raycasthit.point will be in worldspace coordinates but you want it in "texture coordinates" even though they don't really exist of course
I'm not great with vector maths but that's the idea
I understand that much. I know that the goal is to get the world coordinates in texture coordinates, and then get the corresponding pixel of the texture and see if its alpha is 0.
My problem is I don't know how to get the texture coordinates, once I have the world coordinates.
Step 1: Move point to relative coordinates
That's exactly where I'm lost.
Can you get the center position in world coordinates and the size/extents of the sprite relative to the center?
Yes, I can.
probably you'd want to remove transform.position from Raycasthit.point, such that the point is normalized w.r.t the center
then you'd rotate the point around the origin such that Raycasthit.normal aligns with one of the three axes
then shift the resulting point by the extents of the sprite in the two free directions and you get a point w.r.t one of the sprite corners
And this is using a capsule collider?
Ah.
Then you'd want to project the point on the plane first yeah
do the sprites rotate towards your player camera or so?
They rotate towards the camera, so that they appear to be facing you wherever you're viewing them from.
is it multiplayer?
No, it's not.
then you can assume the raycast hit normal will always face the player?
or are the raycasts for slow moving projectiles or something
They're for the mouse pointer. Here, let me try making a quick video of what I'm trying to do. It'll take a few seconds.
ah so the collider is more or less the width and height of the sprite
then you'd want to rotate the impact result such that Raycasthit.transform.position - player.transform.position aligns with an axis (instead of Raycasthit.normal)
Can I DM you the recording?
sure
I've got two cylinders that I'm pushing around with another object. I've got colliders on both cylinders but when I push one against the other hard enough they will move through each other.
This is using the bottom cylinder to lift the top one
but if I push enough it will push the bottom cylinder through the top one
How can I make it so they don't do that?
I'm not sure I can tell players "don't push hard!"
No, but you can limit the amount of force they can impart.
...I'm actually a little surprised the top cylinder doesn't "squeeze" out and go flying off in a random direction at ludicrous speed.
oh it eventually does
Lol oh good. Getting back to my original question, though, is the pusher kinematic?
Because ultimately the only solution is that the object doing the pushing has to "accept" that it can't push them anymore, it's getting too much resistance.
yes, the pusher is kinematic
I was thinking there's got to be some way of "stopping" the cylinder
or the pusher
That's the point of being kinematic - it just goes where you tell it.
It probably needs to accept forces in return.
which part?
One thing you might try is have the kinematic object not have a collider at all, and then make the pusher connected to the kinematic object with a very stiff, very dampened spring joint.
the pusher has to be able to move and interact with other objects
That will in effect give you an upper limit to how much the kinematically controlled object can affect other objects in the scene.
so I can't attach it to the cylinder
I didn't say anything about attaching anything to the cylinder.
I'm saying you replace your kinematic pusher with two objects. One is kinematic, and has no collider. This is the "ghost hand". It interacts with the scene only through its strong spring joint connection to the pusher object, which is no longer kinematic.
Make the spring joint strong and dampened enough, and it mostly won't seem to be two objects, but when you try to push it "super strong" like that, it gives and won't do it.
I'm not sure if that would work for me
I'm trying to wrap my hand around what you are saying though lol
I would have two pushers in the same space, they would move together and everything?
but one isn't visible and it has a spring joint connected to the visible one?
Basically instead of having your pick be the force of god where it can go anywhere and do anything forcefully, you have that object be a target for a physics-driven pick that's constrained to it via forces or springs or whatever you want
Think of it like VR hands, where you've got your real hands which can't actually interact with the world - that's your driver. Then you have these physics-driven versions which pull away when you push too far and can't intersect objects and stuff
it's a bit painful to get right tbh
I don't understand the settings on the spring joint
it seems like any changes I make do nothing
I can set spring to 0 or 100 and it's the same
or damper to 0 or 100
I can still lift the pick just as high
even setting the max distance to something like 0.00001 doesn't seem to actually do anything
I'm giving up for tonight, this makes no sense
Hmm. A Spring Joint set to 0 should do nothing at all, so probably something else is wrong.
I think my movement script is overriding the spring joint
I figured something like that was probably going on. The movement script should be on the kinematic "ghost hand" object. The object being moved by the spring wouldn't need a script at all (unless you're catching collision events or something).
@sly violet so the ghost hand is moving under the other object. Both are locked on the z axis and the ghost is locked on the x axis. If I'm not actually moving the other object how do I get it to lift to interact with the cylinders above it?
I'm also wondering if it would be easier to just stop the cylinders from moving positive in the x axis when the top on collides with a hidden cube above them
Maybe wth something like this
rigidbody.isKinematic = true;
rigidbody.velocity = Vector3.zero;
okay that works... but I can't get the cylinders to fall back down lol
I've set the isKinematic back to false
but what would I set the velocity to to make them fall again?
okay things are happening!
What I've got so far is the bottom cylinder sets a bool called isPushed to true when the pick touches it, when there's a collision with the top hidden cube it checks if that bool is true and if it is it sets the cylinders to kinematic
so I thought that I could turn off kinematic when the Collision exits, but if I'm holding the cylinder up with the pick it just switches between kinematic on and off
like it thinks the collision is exiting when it's not
do I need a onCollisionStay?
I think the cylinder is not colliding with the pick for a second when kinematic is on so it gets set back to kinematic off, just over and over again
HAH! I found a simple hacky way to do it... don't let the pick move higher than a certain y 😄
Okay I've got a new issue if anyone is around
the top cylinder in my stack has a constant force of -200 so that it pushes down on the bottom cylinder after I lift it. But that's causing the cylinders to drift slightly and slide around. How can I get rid of the sliding but keep the top cylinder pressed against the bottom one and pushing it down constantly?
Maybe with a joint?
Nevermind, I just increased my game's global gravity.
Hi there - I have a question that's probably super obvious
but I've done my due googling diligence and have yet to come up with a good answer
will a trigger fire if the incoming object has a box collider on it, is set to kinematic, but is just a child of a parent object? (and the parent object is the one being moved)
Eg - I have Player Object, and a child of that is "Ship Object" - if I put the box collider on the ship object, but I'm moving the player object's transform around - will that normally trigger a OnTriggerEnter event if the static collider is set to is Trigger?
@hushed sable Yeah, a collider on a child is treated little different from one on the parent with the Rigidbody - so long as the child doesn't have a Rigidbody of its own.
Ahhhh
So that may be the issue?
when it's transforming the parent the physics engine isn't registering the change in the child?
If a child object has a Rigidbody, then any colliders on it or its children belong to that Rigidbody, and don't belong to its parents' Rigidbodies.
Got it!
so assuming I set all the colliders and the rigidbody on the child, if I move the parent around - the child should still set stuff off?
I'm just asking for your opinion, I will test it out, of course 😃
Is it kinematic? Moving the parent of a Rigidbody may not operate as you expect it to. It will tend to operate based on its Physics instead of slavishly following the parent transform. But yeah, once it's there, it should set off triggers normally.
Yeah, I was going to set the rigidbody kinematic
also just a quick thank you, too, you're being super awesome and I appreciate it 😃
This make my player pickup rigidbodies
var force = (gravityPole - attracted.collider.transform.position) / Time.fixedDeltaTime * 0.3f / attracted.collider.attachedRigidbody.mass;
attracted.collider.attachedRigidbody.velocity = Vector3.zero;
attracted.collider.attachedRigidbody.AddForce(force, ForceMode.VelocityChange); ```
However i have a lot of jitter when moving, any idea why ?
@sly violet Just wanted to thank you again, I went back and checked the code, cleaned it up vis a vis the rigidbodies, etc, and then I realized when I did OnTriggerEnter2D I was using "Collider other" instead of "Collider2D other" - so it's working! thank you so much 😃
Uhmmm i think you mean some1 else
whooops
but no problem 
hah
sorry it brought up Pyrian's name but it must have switched right before I hit enter
2019.3.0a10 upgraded physx to 4.1
Hi everyone, I have a small question. I'm currently developing a 2.5D platformer game with mechanics like jumping, ledge grabbing, wall climbing, pole swinging. Implemented everything so far, I'm just stuck with the pole swing. The controller that I'm using is rigidbody based and 90% of the physics is managed by code. I tried using hinge joints to constrain player movement and then applying forces based on player input, adjusting damping factors and masses, lowering or raising applied forces, tried almost everything without any decent result. Most of the time the player is swinging very slowly or really fast, with no momentum or too much. Can't find a stable situation. The swing that I want to achieve is the same as the one you can find in super Mario games when he grabs horizontal poles. +-90 deg of freedom with smooth deceleration and swinging speed accumulation. Does anyone ever encountered this problem? I just need some tips, not already made code or lame stuff, I want to learn. Sorry for the wall of text and eventually English errors, it's not my mother language. Thanks in advance to everyone that will spend time on helping on that, hope to learn something new about that 😄
Hello, I've got this code for a missile: Vector3 direction = (target.transform.position - transform.position).normalized; Vector3 deltaPosition = speed * direction * Time.deltaTime; rigidbody2D.MovePosition(transform.position + deltaPosition);
But I don't want to have a strict angle, I want an inertia when it turn, do you have any idea how to do that?
You could use a PID controller to rotate it towards the wanted direction, but first I would try to just use forces instead of moveposition
Moveposition does what it says, it's not using forces or inertia
I think I can provide you a code for a vector 3 PID controller, then you can just adapt it to your needs
I never heard about PID controller before
@wraith palm Scaling up the mass might help with stability, then applying drag to balance it will have more subtle effect.
I tried to manage it with AddForce and Rotate (like my controller) but I'm not able to fully manage the rotate depend of the target :/
@frigid pier thanks for the feedback on that, should I raise the drag linearly when it comes closer to the maximum wanted angle?
It should be somehow linked to the angular velocity
@stuck bay I don't have access to my code stuff right now, in a couple of hours I'll give you some tips on how to solve this and get a smooth result. Already had this headache my friend 😀
oh yea, it will be using angular drag and torque in this setup. So using those. But angular drag may not have to be modified. It will serve as limiter for maximum angular velocity.
thank you @wraith palm 😃
I will try to pump up a little mass scale and play with the angular drag. Also what do you think is the best forcemode to use in this case?
I think I'm using a velocity change right now, not sure coz i don't have code right now
changing velocity directly would ignore drag though
I should use either Forcemode.Force or Impulse in order to get it working with mass n drag
If it's a swing, depending how you present it visually, if character does one push or allow to influence gradually.
You can build realistic model with just forces
Yeah it's a one go push, needs to be timed by the player to make it swing properly
drag should be minimal though to conserve momentum, mass should slow it down at high points
I've never built such a system though
I've dealt with regular forces, and they can be quantified precisely enough 😃
Yeah, unfortunately this is not the case 😂
Something might be interfering. Because a swing left to itself would behave quite naturally.
But a swing left to itself would not need any speed increase, it will just either swing forever or slowly go idle
The issue here is that if I try to add some forces with the keypresses I will reach an unstable point
By the way it needs to be something like uncharted swing or tomb raider
I'll just try to tinker with the values that you pointed out, I'll let you know how it goes
Thank you very much!
If you want a natural limiter you can manually add angular drag past certain point, and then reduce as it slows down and returns. Then it will have enough momentum to swing to the other side.
Hi!
Recently I have made a OnCollisionEnter callback for a compound collider. the callback is called on the rigidbody for the compound collider, but not on the sub colliders. The way I got the compound subcollider that is participating in the collision was by collision.GetContact(0).thisCollider.
Now when I have the OnCollisionExit callback, there are no contacts anymore and I am not sure how to determine which child of the compound collider was participating in the collision exit event.
Does anyone know how to determine the subcollider that was participating?
Not sure if that is the expected behaviour, but I didn't get the collision callbacks to work on the child colliders of the compound collider, but only on the compound collider rigidbody
@frigid pier I tried raising angular drag as soon as i'm in the desired position and the angular velocity is positive compared to player facing vector, if the angular velocity is negative to player facing vector i decrease the drag by half of the increase value. This seems to work and have a smooth "dump" effect on the player. Just need a little bit more time on it to play with values and stuff, but this really made the day, thank you very much!! 😄
Also while increasing drag i'm disabling player input
Vector3 gravityPole = (Camera.main.transform.position + Camera.main.transform.TransformDirection(Vector3.forward) * 2);
var force = (gravityPole - attracted.collider.transform.position) * 20;
attracted.collider.attachedRigidbody.velocity = Vector3.zero;
attracted.collider.attachedRigidbody.AddForce(force, ForceMode.VelocityChange);```
Im trying to hold a rigidbody with this, the problem is that i get jitters due to the camera and player movements being framerate dependent any idea how i could remove the jitter ?
Might just need to turn on interpolation.
Hi guys, I have one stupid question. How do u use CollisionFilter in the new Physic package? I'm trying to have two layer of colliders, and then raycast on a layer or another.
new Unity.Physics.CollisionFilter() { GroupIndex = layerIndex, BelongsTo = (uint)layerIndex, CollidesWith = 0xffffffff })
Or maybe something more useful : how can I debug the package? Each time I'm trying a step in the raycast through the debugger (no burst, and even local package which is the exact same as the official 0.2.0), well I just can't go inside...
Hear Shawn McClelland (Product Manager at Unity) and Joel Van Eenwyk (Field Application Engineer at Havok) explain how we partnered to build on top of the DO...
Ok, i need help in transitioning my transform-based movement system into a physics based one. In my current movement system, i move player by a certain amout (velocity) in a certain direction(depnds on player's input ofcourse). Velocity cannot exceed maximum_velocity. Maximum_velocity also changes depending on player's state. Question is, how can i have such control applying force to a rigidbody
Why do you want a rigidbody?
if i transform into immovable rigidbodies character launches into the air
and have you considered a character controller?
ok now im just confused with unity. Turns out bumping into enemy spawner (that is
considerably smaller than wall and also immovable) seems fine but a wall? nah, launches up when you touch it
ok, i figured out that bumping into rigidbodies is bad if they immovable, in my situation. problem solved i think. enemy spawner didnt had rigidbody in it
Can anyone recommend good material (for beginners) for learning physics concepts useful for game dev? I've started the Khan Academy course but I'd like something else too, preferably with a slight sense of humor/not too dry.
I'm struggling with some (what should be) relatively simple code to pick up and carry a cube in front of my face, Portal style.
I've tried a number of different solutions, but none seem to give me the results I'm looking for. Right now I've distilled it into it's most basic form:
if (isHeld) {
Vector3 targetPos = player.position + playerCam.forward * holdDistance;
thisRigidbody.MovePosition(targetPos);
}
}```
but the cube easily moves through any collider it is held against.
I've tried with isKinematic set to true and false, with Collision detection set to discrete and continuous, with Interpolate set to None, Interpolate, and Extrapolate. I've even tried the DontGoThroughThings script from the Unify wiki: http://wiki.unity3d.com/index.php?title=DontGoThroughThings. No combination of these has solved the issue.
I've googled this and pretty much unanimously people have stated that Rigidbody.MovePosition should respect collisions, and I don't work with Unity physics often, so I'm really looking for someone to point me in the right direction here.
Oh and I've also observed this when holding the cube against both thin planes and thick cube colliders, the result is the same, the cube passes through with almost no resistance.
Is you player a rigidbody as well? Else parenting the object to a hand transform and setting isKinematic to true should do the thing, if you player is a rigidbody, not sure how hierarchal rigidbodies and colliders interact, but try isKinematic to true and disabling the collider?
Hi guys. My server build in ubuntu doesn't seem to detect hits physics (animated sword etc).
It works fine in windows build as local server, and the offline version (also windows), and editor. Is there anything particularly different in linux?
Actually to be exact, physics works but the sword length seems to be shorter (what should be a hit in any other platform, needs to be closer distance in linux)
Weird. Could it be some kind of frame rate issue?
Ok just checked, the problem is server build.
Tried windows build, server build, and the "short sword distance" is happening too
Hmm, i dont know how to even debug this...
If you have rendering on your server as well you can render the collision boxes?
And you're sure it works in editor?
Do you see any errors in your logs?
It's only "shorter" in server build, which means there's no rendering too. So i can't even visualize it. Currently just trying to debug everything it hits (reusing some old debugging efforts). And other than it's hitting itself (which i already filtered out), it's just not hitting the enemy unless they're 1 step closer than they should
You can find your player logs here https://docs.unity3d.com/Manual/LogFiles.html depending on OS.
I would also do a quick search for the UNITY_SERVER define if you're using it somewhere which might modify the physics
Yep. The logs are in cmd, i'm logging everything extensively now. Even logging the sword's pivot position per frame as it swings, and see if it's even correct
Also make sure your physics are not done in the Update function.
(I'm running it with cmd as i need to do launch arguments with it for server)
The hits are in OnTriggerEnter stuff. Unless they're also affected by server build?
And the movement?
All i can think of is it's either, server build's affecting:
- the size/position of the physics in relation to animation
- the quality of the collisions that for a "longer, wider" swing, it just goes through it. Explains why a shorter distance swing might have much more chance to hit
Are you doing these things with animations?
Which movement? The player movements are all done with tween and they're looking correct. Timing wise, it seems correct too even though i can't see it in server build, the "start" and "stop" time of a player move is correct
Yep the sword swing is driven from animation
And animations are from Update loop if I'm correct
Hmm... yes but...
Does this mean, server build just don't process Animators and the result of its movement?
Well brb i'm gonna do the log sword pos per frame, this'll tell it
think of what difference framerate might do to your animations, of where it will be in comparison to your fixed Updates
Building...
I mean, i did say that it works when the enemy is literally "body to body" close. But at this point the size of the sword collider is big enough for them to touch without even needing to move
You're using rigidbody? What Collision detection are you using?
But consider you're not having a lot of resources on your server, the server might skip a few frames, and in turn animations, to catch up on fixedUpdates.
Ugh, yep. Throughout the whole swing process, the sword pivot's not moving at all which means the Animator's not even running
Woah, this is a problem hmm...
I guess this is a Animator problem, but bringing this to the #🏃┃animation channel is kinda unrelated too because it's about server build..
Hmm, not sure if the Animator is removed in server build.
I guess it would make sense in some cases.
And i can't believe there's no google hit at all about this use case
Unless i'm doing something wrong, and it's supposed to work
Becauase well, how else should the server do its own "hit detection animation" then?
Animator.UpdateMode = AnimatePhysics
Cool, neat to know! : )
Wait no, still doesn't work
ALthough i mentioned that because i did do that for another case in the past, and i really thought i already did that for this case too (apparently not)
WOOT now it works with "Always Animate" in the culling mode. I guess server build means everything's culled because well, no camera/rendering..
Can someone explain like im 5 the concept of colliders2d shape being attached to rigidbody?
first time creating a game
I understand its purpose; that these are shapes to kind of detect future collisions depending on direction
but that's about it
Typically in a 2d game, a GameObject has a Sprite, which displays where the object is to the user, a Collider2d, which determines the shape of the object for physics calculations, and a Rigidbody2d that holds its physics characteristics (weight, velocity, physics material, etc.).
The simplest consequence of this arrangement is that two GameObjects run into/bounce off of each other when their colliders intersect and not necessarily when their Sprites intersect.
@sly violet ah thank u
then what is the purpose of this function? https://docs.unity3d.com/ScriptReference/Rigidbody2D.Cast.html
wait sorry my question is off
i understandt he purpose but
i don't understand the results array
and why if we're using collider2d shapes, our results is in an array of RaycastHit2D[] (since raycasts talk about shooting projected lines)
Rigidbody2D.Cast is a super nifty function that lets you see if you're going to hit anything if you go to a certain location, taking all your relevant colliders and their positions and rotations into account. Particularly useful for kinematic controllers and the like.
The reason you get an array of RaycastHit2D is so you can find out not only what you "hit," but also where you "hit" it. It might've been clearer if RaycastHit2D was just called CastHit2D, because it's by no means limited to casting rays in particular.
@sly violet ah. so the integer that it returns, is kinda an indicator on how many points the rigidbody has come in contact with? (how many rays are being hit by another collider)
Anyone have any resources or tips on Joint Drives and the rotation weirdness?
Whenever I add to (not set) rigidbody2d.velocity or AddForce with ForceMode2D.Impulse, it resets my velocity to 0 right afterwards.
I'm trying to have my character instantly move by directly adding velocity in FixedUpdate, but I also need the character to dynamically react to being knocked back by my enemies. Whenever my enemies apply knockback force either by adding to velocity or by using ForceMode2D.Impulse, the character stops moving instantly because the addition of force in FixedUpdate overrides it instead of adding to it for some reason.
The only time my character can both move and be knocked back is when I use ForceMode2D.Force for my movement, but that isn't what I want, as it causes my character to take a while to get up to speed and then has a deceleration afterwards.
What do I need to change to fix this? I can post code if that would help.
Hmm. My honest recommendation is to just use ForceMode2D.Force and tune it to taste. Maybe increase the force, divide by your velocity in the direction you're going, and increase the drag.
But if that's not an option, you'll have to figure out what's resetting your velocity back to zero. Offhand I'd guess that something's seriously amiss with your code that "...add to (not set) rigidbody2d.velocity...". Maybe post the code. It shouldn't be doing what you're describing.
How would I correctly implement a min speed?
I don't want my character to be accelerating so slow
I used the code from unity tutorial
I've taken classes on coding, I'm just more lost on the logic side on how i should do it
nvm i got it
An update to my problem posted yesterday:
Here's an abriged version of the FixedUpdate that the player uses
void FixedUpdate()
{
// Calculate movement speed based on active effects
float speed = character.effectManager.CalculateStatValue(character.speed, EffectType.MOVEMENT_SPEED);
Vector2 inputSpeed = inputDirection.normalized * (sprinting ? speed * (5f / 3f) : speed);
Vector2 inputSpeedDifferential = inputSpeed - rigidbody.velocity;
if (inputSpeedDifferential.magnitude > 0)
{
rigidbody.AddForce(inputSpeedDifferential, ForceMode2D.Impulse);
//rigidbody.velocity += inputSpeedDifferential;
}
}
and in my enemy's script I have
void OnCollisionEnter2D(Collision2D collision)
{
Debug.Log("Enemy collision with " + collision.gameObject.name);
if (collision.gameObject == player)
{
Vector2 pushDirection = player.GetComponent<Rigidbody2D>().position - movement.rigidbody.position;
pushDirection.Normalize();
Debug.Log("Pushing player: " + pushDirection);
pushDirection *= 3.0f;
player.GetComponent<Rigidbody2D>().AddForce(pushDirection, ForceMode2D.Impulse);
}
}
These are the only places in the codebase where I ever use Rigidbody2D.velocity or Rigidbody2D.AddForce, so I know I'm not mistakenly setting the velocity to zero elsewhere.
When, in FixedUpdate, I use ForceMode2D.Impulse, or use velocity +=, the velocity stops completely whenever the player stops input.
No matter what, unless I am using ForceMode2D.Force, the AddForce in the enemy's collision check never actually does anything.
@stable plover ...Well, yeah, that's exactly what your code does. You take the difference between what your speed is and what you want it to be, and then "add" that difference (whether by impulse or by +=). There is absolutely zero difference between doing that and simply setting the velocity directly equal to your input in the first place.
Let's say your velocity is 4,0 and your input is 0,0. What your code does is subtracts 4,0 from 0,0, resulting in -4,0. Then you add that -4,0 to the existing 4,0 velocity, giving you a new velocity of 0,0.
You're doing a little dance with the numbers, but the end result is that you're just flat out setting velocity equal to inputSpeed.
Ahh geez.
I was working on making it so that the player's input would only take effect if the player wasn't already going their max speed in the input direction, and got sidetracked to working on the knockback.
I kind of missed the forest for the trees I guess.
Thanks for your help, the second pair of eyes does wonders
@sly violet, thanks for your help earlier with that, but if you have some time I've got a new problem I've been trying to figure out for the past few hours.
I'm trying to set up my character movement so that I can accomplish a few things:
- When there is input, move the character instantly (so using ForceMode2D.Impulse instead of Force)
- Be able to push the player around with explosions, knockback, or any other external force
- When the player is being knocked back, allow them to still move, so that they can do things like slow down after being pushed, or steer the direction of the push
My issue is that all of the things I've tried so far fail at #3. I'm pretty sure I'm just overcomplicating it though.
Things usually fall apart around the fact that I want the player's input-related movement to be instant.
My best solution so far is to use ForceMode2D.Impulse when the player is below max speed, and ForceMode2D.Force when the player is above max speed (presumably only when an outside force has acted upon them). But it feels super inconsistent in game to have both. I can post my current code for the movement if you want.
@stable plover Yeeeah this sort of thing is why I usually advise people to just use normal physics and make it work instead of trying to control everything; what you're doing forces you to cover all the edge cases.
So, here's what you do: Place the direction and severity of each hit into a Vector variable in your Player. In fact, ADD it to this variable. We'll call it "externalForce" maybe. Have this variable drop by a fixed amount each fixed update (to a minimum of zero).
Then add your "externalForce" vector to your input vector after getting the input, and use THAT for your new velocity. So your velocity is always taking into account both the input and any recent hits/pushes. You're just tracking them in your code instead of relying on the Physics system's momentum.
Here's what that might look something like:
private Vector2 externalForce;
private const float externalForceDropoff = 1f;
public void TakeAHit(Vector2 hit) { externalForce += hit; }
void FixedUpdate() {
externalForce -= externalForce.Normalized * Time.deltaTime * externalForceDropoff;
// usual stuff
inputSpeed += externalForce;
rb.AddForce(inputSpeed, ...);
}```
I had considered that, but was wary about it because it's effectively adding a second velocity and drag variable, right? I guess my pickiness about the input means I have to make some concessions.
Ugh, I forgot, you also need to make sure externalForce doesn't drop "below" zero. So if it's smaller than what you're subtracting from it, make it zero.
yeah, that makes sense
If you won't let the physics system handle it, you have to handle it.
When you say to have the physics system handle it, do you mean there's a way to get the kind of movement I'm looking for with just that? Instant-acceleration/deceleration and all? I'm early enough into the project that I'm more than willing to scrap a few things to have this stuff easier to work with going forward.
I dunno. Just conceptually, instant deceleration and knockback don't really play nice with each other; there's literally no way you can have both of them without letting knockback override the instant deceleration.
A lot of the time though when people want "instant" they really just want "fast" instead of slow and floaty like naïve implementations tend to end up. Just cranking up the input force and the drag may be enough, giving you full acceleration/deceleration in a fraction of a second. But to get the feel just right people usually adjust the acceleration based on the speed, too.
I'll play around with using the more powerful force, and if that doesn't work out I'll fall back on having the separated velocities. Thanks so much for your help.
@sly violet From the earlier conversation ... Yes, RaycastHit2D was inherited from 3D physics as a result structure and I have personally loathed its name since I started. CastHit2D would certainly be better or just PhysicsHit2D or Hit2D.
i would like to hold a rigidbody, now i found how to do it but it jitters a lot, i guess its from the player movements and camera movement being based on Time.deltatime causing jitter but then how could i counter this problem ?
@austere vine each fixed update i add force to the object based the direction and lenght of the object towards a point of my camera
So i have a question, if i do a Linecast/Raycast in Update, that raycast is on sync with the physics?
For example if i've a bullet and the collision is detected with linecast, it's better update or fixed?
It should be in update because the physics update is a lot slower that the normal update plus you dont act on the physic with a raycast so it is safe to use it like it
Fixed Update and Update is up to you, if you wanna make it frame indipendent or not
Fixed Update is not slower that Update function, it's just handled in a different way
The update function is totally based on frame rate and is played once per frame, Fixed Update can be played once, zero, thousands of times. It just depends on the settings that you have on the project
@frank orbit put it in the fixed and sync if with the addforce, if you put it in the normal update the projectile could clip before you stop to add force
Yeah but i guess in his current setting the physics must be slower + if he shoots a raycast in a fixedupdate he might miss where he wanted to shoot because it might be different from his camera update
It doesnt hurt to raycast in the update at least you are sure it will hit 😄
Right now i move the transform and make a linecast where it was before and where it's now
I don't have any collider nor rigidbody
So if you handle the clip by yourself, you can put it in the update as @inner cloud said.
What i'm worried about is if the colliders are moved in physics and it's not updated yet on screen, the player can end up shooting stuff that it's not there actually
For example if the game is running at 10-20 fps
I guess they both scale equally but im not sure of it
That's right @frank orbit, but I think that it will be unnoticeable even if you run at 10fps
@wraith palm wouldn't you happen to know how i could fix some jitter with a addforce on a framerate updated position ?
You mean that you are manually moving the transform inside the Update and then Applying a force inside the Fixed?
Like i am trying to hold a object Amnesia style so i addforce on the object by a vector that is the direction of the object to a point from my camera transform it work great with the collision but when ever i move the player or move the camera i got jitters
Okay thanks then 👌
@wraith palm Nah i'm moving the transform, i don't have any rigidbody
So i don't have anything to apply a force on
I was asking to @inner cloud 😄
@inner cloud it could depend on several things, have you got some gifs about the jitter? Wanna c what's happening there
I don't even know how you manage camera and player movement
Is the cube movement handled into the update?
Or it's handled by using forces inside the fixed?
If think that you could easily lerp the position of the cube inside the update to make it sync with the camera update instead of using addforce
The addforce is in the fixedupdate
I originaly did this but then the collisions wont work
Yeah that's totally the point, you are moving the cube N time per frame and then updating the camera once per frame as it should be
You can make the rigidbody of the cube kinematic, remove the use gravity and if it's hold you lerp it's position
Then on release you activate the use gravity/deactivate iskinematic and put a force onto it
But as long as you keep it I would make it kinematic and manage it's position in sync with the camera update
Thats exactly what i did before but.. I wont have collisions anymore
Collisions while holding it?
Yeah
It was going through walls
Because you set the position
There was no physics involved so no collision detection
Thats why the addforce aproach works
It pushes the object
So if wall => i push hard but cant go further
Yeah that's clear to me
You could just use a raycast to handle this while you are holding it
I don't think that there's a way to sync this, it's just the normal behavior of the Update/Fixed Update functions
Instead of just lerping it's position you could Raycast before moving it and void it clip into walls
Or just update your camera position inside the fixed
You could use a function that is calculating camera position in the Update and then applying it inside the FixedUpdate
A function in fixedupdate that gets the camera position ?
Say that you create a vector3 storing your wanted camera position. You calculate and update that vector inside the Update function and then apply it inside the FixedUpdate function
So you are still calculating camera position at frame rate but updating it in sync with the phisycs engine, maybe this could work
I dont quite get it i should make a var that store the camera position in update and then use it in fixed update ?
That's it, like a virtual camera position
Do you think i will be different than using it raw ?
It could be, instead of moving the camera inside the Update function you are doing it inside the Fixed Update so this should be in sync with the phisycs
BUT still calculating it's position frame rate based
Oh yeah i forgot i didn't implement the rigidbody based movements
For movements its ok then but doing this in update foe the camera wont it be janky ?
You have to try it, actually I have a rigidbody based char controller and the camera is working like I said, calculating virtual bounds and position inside the update and applying it into the fixed
It's butter smooth
Interresting but when you say "applying" you mean that the function is ran in update and this function sets a var in the fixed update ?
Isn't i the same as using the camera position direcgtly ?
Are you moving the camera based on a target?
Uh no i am moving the camera like for a fps with incrementing rotation with inputs and the position being handled by the player being its parent
So right now the position is from a char controller it will change but the rotation with always be input based
I was having troubles aswell with that setup, I just removed the parenting and managed the camera position by myself
And yes, I think you are right. It's the same thing as setting it directly but I make some calculations in the middle so I just made it like this. Maybe I could put the apply of the camera even inside the update without any problem, didn't tried it yet
Yeah well thx i'll try idk what is this problem for
I would definitely try to unparent it
Well i guess if i change the movements of the player with rigidbody movements it wont be a problem anymore cause the camera will hinherit the players movements but as for the rotation idk if i can get away with using the fixed time step for it without it behing lagging behind
Has to try too
You could use an addtorque function with an error calculation/compensations to make it rotate to the desired angle. But i think this is just too complicated for the needs. Try to update by yourself the camera rotation and position
@inner cloud what if you put addforce inside the Update? 😂
Actually in my setup if I parent the camera with the player it will jitter and stutter like hell
I have a rigidbody char
Then if I make the camera just follow the object by code inside an update function it's really smooth
Dunno why
Follow like with a lerp ?
I have both ways flagged, either with lerp or instant follow by setting the position
Actually i changed the player movements and the camera movement scripts to FixedUpdate and there is no jitter anymore 😄
Idk what repercution it will have but it feels so gud like this 😄
It will fuck it up at low fps I think
Like you will move while camera still not rendered the frame
Ah...
Wait you sure ? Because im pretty sure the rendered works faster than the physics
If you move something and this movement is not bound to the frame rate but faster, the if you are at 10fps this means that in the short time you are not rendering the frame you are still moving
So I think that at low fps you will like "lag" and teleport a little, you should try capping your fps rate and see what happens
It should be like online games, locally the input it's updating but if you have slow connection it will result in teleports and blinks
Really huh ?
I think so, yeah
Ok then i'll find an other solution
Idk it kind of feel a bit jittery on the movements like this even built
Try to unparent it, this will fix it for sure
Go for one easy test, just detach the camera from player and disable the camera movement script and move the cube
If you have a steady camera and you still have the jitter effect while cube is moving than it's something else
I'll try after
Bon appétit
Buon appetito 😀
@candid walrus how this question is related to physics
Uh, sorry, I'll delete
Hi guys, I am new to here. hope everyone is doing good.
I have a question about the difference of Unity embedded physics and Unity Physics preview from package manager.
The embedded physics , https://docs.unity3d.com/Manual/PhysicsSection.html
The preivew Unity Physics, https://docs.unity3d.com/Packages/com.unity.physics@0.2/manual/getting_started.html
I heard Unity's physics is from Havok and PhysX. but how to know which is from Havok or PhysX and their version.
gameobjects use physx, ecs uses unity physics(a collaboration betweennunity and havok)
@fallow gorge how can I know which is PhysX and which is Havok? and their version ?
uh are you familiar with gameobjects?
I don't have deep research about them, but I know I can create gameobjects.
so the new ecs physics(havok related) is in super early preview, you can only use it if you install the appropriate package for it
otherwise everything regarding 3d physics in unity is physx https://docs.unity3d.com/Manual/PhysicsSection.html covers it in good detail
do you mean the Unity Phsics 0.2 preview from package manager ?
ok to slightly complicate things: that package is Unity Physics(for unity's data orientated tech stack aka dots)
it is a collaboration between unity and havok
havok will in the future release their own physics integration with dots that you can use (in dots) instead of Unity Physics
which will likely cost money but be more fully featured
ok. thanks
otherwise everything regarding 3d physics in unity is physx https://docs.unity3d.com/Manual/PhysicsSection.html
which version? 3.x or 4.x?
i am personally not sure, havent touched it in a while
where do you get those information? any doc to explain those physics system background and version ?
for DOTS physics? the package has its own documentation but its a bit thin https://docs.unity3d.com/Packages/com.unity.physics@0.1/manual/index.html
if you want to learn more about dots theres a pinned message in the entity-component-system channel that has good info there
ok. thanks. can't see Havok version, that's a old famous engine used by many famous games.
yeah its not released yet and theres basically no info about anything concrete other than it should be a drop in replacement when it does arrive
about the default embedded PhysX, still need to know its version and roadmap. do you know where to find them?
physics subforum probably has that
oh dear, it seems like an adhoc team on an adhoc fix for such serious system. 😉
Thanks @fallow gorge for your information.
yeah, I was just about to tell that 😄
(that's my post)
I can give full timeline too
basically:
Unity 4 -> PhysX 2.8
Unity 5 -> PhysX 3.3
Unity 2018.3 -> PhysX 3.4
Unity 2019.3 -> PhysX 4.1
Unity 3 probably used PhysX 2.8 but can't remember that far back, @maiden prism 😃
Hi!
I have some issues with the target rotation of the configurable joint...
when I set x to its max limit it looks like this (which is what I want):
when I set y to its max its this (which is also what I want):
however, when I set both to their max I get this:
which is actually what I wanted if y was max and z was changed
when I set y to its max and z to its max I get this:
which I would actually expect for y's min value and x max value
so when I use two dimensions x and z somehow get switched..
my primary axis is (1,0,0) and my secondary is (0,0,-1)
how do I have to configure it such that it does what I want it to do or can someone explain to me how to the joint coordinate system works?
Is it common to make the ragdoll on the same object with the animator on, or is it preferred to make a copy of the visual character object, put the ragdoll on there and if you want to activate it you set the animator visual object inactive and the ragdoll gameobject active?
if someone has an answer, pls tag me, otherwise it is alright, I think I already have an organization.
In my case it makes sense to not separate the objects since the ragdoll colliders should also be active during the usual gameplay to receive collision events
I think I got my answer, seems that the copy approach is good for performance reasons if you don't need to have the limb colliders active during regular gameplay.
does a rigidbody2d just ignore the z coordinate of an object?
Most likely since it stores a vector2 which only has x and y
The z coordinate in 2D is mostly used to bring objects in front or behind
kay, thanks
Hi,
I'm just started with Unity. I'm following this tutorial: https://www.youtube.com/watch?v=IlKaB1etrik
But I have problem with physics. My red cube falls through the white Road object.
Make sure both of them have colliders and none of them have is trigger checked in the collider component
Thanks a lot, now it's working fine 😃
oh i think the yr wood floor is not solied to make it
select the floor
and than
prees
type box
and prees
prees box colider 2d for 2d game floor
and box collider for 3d
Anyone know how to properly add a collider (child) to a dynamic body in runtime in the new physics system?
you mean a parent child relationship or just to add a collider to a mass?
either way the ragdoll shows you how to add colliders at runtime, but its not through a child relationship. i think you could have a rigid joint in place but i dont know how the new system handles child stuff specifically with physics if at all
Yeah, through a parent child relationship. When it converts it from start the collider seems to be placed on the parent (if in the scene is set at child), but if I instantiate the child and set its parent, the collider seems to be set on the child and not work properly. I'll try see if I can find something in the ragdoll examples
Nope, haven't found anything helpful. Guess my answers lie in the BaseShapeConversionSystem.
Hello everyone, is there an easy way to fetch or print all physics contacts between all colliders in scene in a current frame at runtime? I'm trying to write a tool to help me optimize collisions in a large scene. specifically I want to group all contacts by layers to have something like the collision matrix, each cell being a number of active contacts between layer A and B.
what do you mean not work properly? from what I know the physics system uses translation exclusively for position, so the localtoworld and localtoparent components that the transform system uses will not work properly. you will need to set the translation of the child entity manually to match the parent's
or use some sort of rigid joint to mimic this
Ok, maybe I'm going about this wrong... but is there a way to... inflate a collider (capsule collider in my case) then get, not just the colliders it overlaps, but their contact points too?
Physics.Overlap only gives me colliders, and a zero distance sweep wont properly give me contact points for anything already overlapping.
I need to know if the character is standing against a wall, and exactly what direction that wall is, as well as the contact normal
Like this?
{
ContactPoint contact = collision.contacts[0];
Quaternion rot = Quaternion.FromToRotation(Vector3.up, contact.normal);
Vector3 pos = contact.point;
Instantiate(explosionPrefab, pos, rot);
Destroy(gameObject);
}```
I've also done it through raycasting before for medical software. But that sounds like what is already exposed through collision
Can the transform of an object be modified in code if the parent of that object has a rigidbody? I know you cant do it because of performance problems on the sam object but what about a child of the object.
@fallow gorge Hmm I see what you mean. So a rigid joint or transferring the colliders to the "parent".
you could also try removing the physicsvelocity havent tried that personally though
Hmm, what I did since the parent doesn't have any collider is to simply move it from the child to the parent. If I understand it correctly from the conversion system, in these child parent relationships they are made to a compound collider on the parent in the conversion.
the rigidbody on the child object has no collider
im simply rotating the child object, its the turret on a tank
I ended up using a Physics.OverlapCapsule check with an "inflated" player collider, then running Physics.ComputePenetration on each returned collider to get the direction of walls being touched. Using the direction info, I can do a simple raycast / capsule cast to get hit points and surface normal data.
I don't know if this is much cheaper than just doing a bunch of raycasts every frame, but so far it seems to work well.
Ok so, the transform can always be modified (rigid body or no rigid body) and afaik, there aren't any performance impacts. The bigger problem is the rigid body is manipulating the objects position and rotation and it just interferes with that process if you aren't smart in your approach
But yes a child can be manipulated via script under a parent that has a rigid body
I have a problem
So i made a cylinder and made a script for it to walk
and i did some terrain
and added a rigidbody
But if falls
on the ground
cuz my terrain has some bumps.
how are you moving your rigidbody?
I'm pretty sure you have to use forces in your script to make it behave correctly.
If you are and it still clips through ground, try setting the collision detection to continuous in the inspector of the object.
thx
I have a strange problem, I used Math.Smoothdamp to smooth the retation of a turret on a tank and while it smoths great, once it reaches the target orientation it kinda judders up to 1-1.5 degrees left and right. Any way to solve this?
Maybe a value is not clamped? I had a similar issue with math.lerp, i had to clamp the progress value.
Yeah, you're probably overshooting the target rotation each frame.
Rigidbody or character controller?
Which one is better for 2.5d game?
Character controller is really just an input extension to rigidbody
Howdy yall! I've got a question that I'm really struggling on finding information on.
I come from an extensive background in programming 2D games and I'm very comfortable with writing player physics on my own; in fact I prefer it over any built in systems as I like full control of my code.
Although it seems to be the norm to use Unity's built in physics engine?
What do y'all think about it?
(sorry for the terrible art work) why is my player in different place then in scene
@amber gulch is the scene view in 2d mode ?
The use case for using .material over .sharedMaterial is that it implicitly creates a new material, so the solution for that lack is to explicitly create a new material.
🤷
That's what happens when you use .material in 3d.
They don't normally clone the material. That's a feature of .material that's built on top of the underlying API, so to speak. You may not want to create new materials all the time, but that's exactly what you're doing when you access material clones through .material.
Just cloning the material in code and using it in sharedMaterial is equivalent, if slightly more verbose.
I just told you the equivalent.
Do you think that there's some "instance material" that's maintained in addition to the sharedMaterial? Because there isn't.
When you use .material, it creates a new Material, which becomes the sharedMaterial.
It's not actually shared at that point, but it could be.
are the points of a polygon collider 2d always going to be in counter clockwise order?
I kind of doubt it? Especially given that you can use SetPath to set whatever you want. I mean, a polygon collider 2d can even have multiple paths.
i have a question about configurablejoints, but I put it in general code on accident.
how can i make both the connectedbody and the gameobject rotate around? the way configurablejoints work is that only the gameobject can rotate, but i want both the connectedbody and gameobject to rotate
Um, what? Configurable Joints are configurable. You can a wide variety of relations between the objects, including fixing the relative position but leaving the rotation free or vice-versa.
Anyway, not sure exactly what you're trying to do, but the XYZ Motion and Angular XYZ Motion are where you set how the joint connects them in position and rotation respectively.
How about for both objects? I want to leave the rotation free for both the connectedBody and the gameObject
Joints define a relationship between two objects. They always affect both objects, unless one is kinematic.
Leaving the rotation free is as simple as not defining any angular restrictions. But what are you having restricted? Distance between?
@copper karma Sounds like you might be best off with just a Spring Joint. Set both the min and max to the distance you want and you have a distance joint in all but name. And then if you later want to make it act more tensile, the other settings are right there.
Yes, but I also need both the connectedbody and gameobject to rotate freely
@sly violet
@copper karma Yeah, Spring Joint's don't constrain rotation at all.
Really? So they are not like FixedJoints.
Thanks @sly violet for the help. If it works, I'll be really happy
I tried it out in a project I have, seems to work fine. Each piece of debris here has mass of 5, and I set the Spring to 1000, left the rest of the settings at their defaults.
can hinges in unity anchor to world space?
Hey @sly violet, I did what you said, and you're right. SpringJoints don't constrain rotation of the gameObject or the connectedBody, but I should have been more clear. Is it possible to rotate the joint itself? I am trying to create a simulation of atoms, and in order to do it accurately I need the joints to be able to rotate freely around the atoms so that they can go into their most stable positions.
i dont understand anything here
@normal lynx : All you have to do to anchor any joint to world space is not have a connected body.
@copper karma : I don't get it. What does "rotate the joint" even mean, independent of its connected bodies? What is it not doing? If it did "rotate", how would you even tell?
@sly violet The problem with the springjoint is that the position the springjoint is connected to is locked. I need it to be able to freely move/rotate around a point
How is that different from simply using the centerpoint in thhe first place?
Anyway, the only way to have something freely moving by physics is to have a rigidbody. Doesn't have to have any colliders. So you could have a joint to a virtual rigidbody, and another joint from the virtual rigidbody to the other body.
Those sorts of constructs behave pretty strangely, though. Just like in real life. You should probably just be using the centers as your anchors instead.
Hello iam new here and new to unity, is there a dedicated room for help?
@shy zodiac if programming help, all programming rooms are for help. If you can't find an group by name that your problem belongs to, go to general-code ^^
Aight, cool! Well like i said iam really bad and new to Unity. I tried to make a moving character and i get him to move. smoothly but only i freeze his position and rotation in his rigidbody
But when i do so hes not affected by gravity, so when i uncheck these things he just glitches around everywhere
This is when i unfreeze his position.
@shy zodiac When you freeze rotation/position you say that these should not be affected by physics. If you are using a rigidbody you should use forces e.g. rigidbody.AddForce(), or set the velocity rigidbody.velocity = ... .
if you don't want to use forces, or set velocity. You should try a character controller instead.
@autumn jetty Alright thanks! Had no idea!
hello, I'm manipulating meshes at runtime up to around 20k vertices at a time. The meshes are intended to act as colliders. In order for the actual colliders to sync with the updated vertices PhysX bakes them via "Mesh.Bake Physx CollisionData". Does anyone know if this is necessary? And if so, can the baking be at least multithreaded? When manipulating about 5k vertices there is already a 5ms spike.
random question for the gurus... why is there no Physics.IsTouching method (for 3D, like there is in Physics2D)?
Nope.
but why?
Just not implemented. 2D & 3D physics developed separately. Feature parity hasn't always been maintained.
I see, thanks, melv!
It would be a great feature to have including the "GetContacts()" stuff and I know it was discussed but I guess priorities etc.
I'd want to modify those contacts as well :p
but yeah, at least Unity Physics package got me covered on that one
(I know it's not trivial thing to expose with c++ interop layer in place)
i'm having a problem rigging a robot "hand"... it's like a clamp that has one joint that can rotate along the twist axis, and another that can bend along an axis. i'm trying to drive this via ConfigurableJoints that are reading an orientation from a Touch controller.
getting the positions to all match is easy, but the orientations are killing me. i can't seem to get the joint's angular settings to do anything properly.
So I have 2 colliders in the same object acting as triggers
the problem is that OnTriggerENter/Exit gets called twice, one for each collider
WHat is the way to go about it?
Just tested this
https://assetstore.unity.com/packages/templates/systems/rayfire-for-unity-148690
As a first look, it works really well! First of all, it just works. Everything as expected, shatterying any mesh according to physics. AFAIK, this is first such system for unity which REALLY works
Does it works with SkinnedMeshRenderer?
@quick ginkgo is this another of these "hidden" ads? 😉
how can I make this cloth not move in the +Z axis that much
I tied adding an external acceleration in the -Z direction but it doesn't help
and also the cloth seems to 'stabilize' after a while and not move as much
this is a bug with the cloth component maybe?
I have seen some people on the forums have similar issues
I'm on 2019.3 if that helps
How to reproduce: 1. Open attached 'project-1173813.zip' project 2. Enter Play mode Expected result: cloth stays relatively still Ac...
that's too bad really
Hello, I am working on my first unity project
and I downloaded a free car from the asset store
but the wheels are all part of a single object
the 4 wheels are "Cylinder.002"
shouldn't those be split into 4 separate wheels to make them work?
Any word on Havok physics going live? ETA I read was 'summer'.
I am working on a first-person shooter. I want the collision physics for my character to be able to collide with walls and objects without it being jittery and clunky. Basically if you run into the wall I want you to stop instead of it stuttering
I can send a small video example if I need to
Nevermind, I figured it out, it just took a little more googling
Hello. Is 2D physics more performant than 3d physics?
I suppose so, one less axis to worry about
Using the new phyiscs system, would it be bad for performance to have colliders in the same area that have different layers that won't collide with eachother?
The reason for this strange question is that the physics system uses Translation for positions, hence childed object Translation is in comparison to parent. In my case I want to have objects following with parenting other physics objects but only collide with objects that are also childed (i.e. a spaceship ). So one idea is putting each interior in it's own layer, but for the physics world that would mean they are roughly in the same place but on different layers. Is this a valid solution, or will there be performance problems?
i'm searching for some free dynamic water for unity 2018. Someone got a nice one ?
I have a few prefabs that are all connected together via ConfigurableJoints. They're meant to be attached to the user's hands (VR). When they collide against each other, the joints are mostly holding up, but they're not quite stiff enough... they tend to wobble or bend in strange ways as the prefabs press up against each other.
How can I make these things feel a little more "solid"?
Hard to say without more information. Off-hand, it sounds like it might be the sort of weirdness that occurs when you introduce "infinite" forces to the simulation. Are any of the objects kinematic or otherwise being set directly rather than having forces acted on them?
If so, one solution that sometimes helps is to make the "infinities" less infinite by making them invisible and collider-less and connecting them via a spring joint or something with a large but decidedly not infinite force. This will keep the kinematics from overwhelming the other joint's stiffness.
there's no kinematic RBs. the object is comprised of a bunch of different pieces, but the main parts are a shaft (the "arm") and a swivel on the end that has a kind of grasping hook
when i push the hook up against the other arm, the collisions are basically working, but the shaft "disconnects" from the swivel a little bit while it's trying to resolve the collision, and i'm not sure what i can do about it.
the driving action is all ConfigurableJoints. i'm reading the touch controllers and setting the targetPosition and targetRotation based on those inputs.
How are you moving them?
ConfigurableJoints
Hmm. That should be relatively robust.
the swivel piece is more or less the "wrist", i'm setting targetPosition and targetRotation based on Touch controller input, and the rest of the pieces are connected to the wrist via additional ConfigurableJoints
it's mostly working but there's a sort of springy disconnect that happens when i cross the arms or push things into each other. i was hoping i could remove some of that.
Might just have to make the target-based forces significantly weaker than the forces holding things together.
Maybe post some video.
not sure i'll be able to, it's proprietary stuff for an employer.
ah, by the target-based forces that would be the xyz drive spring forces, right?
hey ! Is there any way to avoid an object to fall through another object like a ground when activating "Is Trigger" (from box collider 2d component) ?
and keeping gravity from rigidbody2D enable
put another non-trigger collider
But you usually want this setup when making trigger collider slightly wider to capture events before actually hitting the physical collider
okay, thanks a lot ! 🙂
Is there a way to debug view colliders runtime in new system?
Jaws can you please add to that?
@lament stirrup Using the new ECS physics system, I want to be able to see the colliders in Scene window. I might not have renderers/displaced the colliders from renderers.
A second question, how does collisionFilters work? If I have lets say a Ball, belongs to filter A, collides with B. And a ground that belongs to B but only colliders with B. Is it always if positive, go positive? Or dependent on what PhysicsBody it is?
Or simply both need to approve collision.
Anyone know how I can update a CollisionFilter on a PhysicsCollider from a system?
hey sorry for the late response looking into it
If I find a solution I will DM u @autumn jetty
Hi, I've got a question
I have a very simple raycast car and suspension made with the help of Blinkachu's tutorial series that unfortunately got delayed because he had no more free time
And I'm trying to implement sliding mechanics so that the car doesn't turn without understeer and oversteer
Because currently despite the car rolling too much (I need to also develop an antirollbar system) the car turns perfectly and does not slide one bit
With that being said
How would I go about applying Pacejka magic formula to the system?
There are a lot of examples/tutorials for the basic pacejka 94/96 implementation, I guess it doesn't matter which one you choose, I found this one on google really quick
https://nocakenocode.com/unity-drift-simulator-tutorial/#toc8
Edy has a page where he explains what every single parameter does, over here:
https://www.edy.es/dev/docs/pacejka-94-parameters-explained-a-comprehensive-guide/
Seem to be getting quite a big level load performance hit due to "Mesh.Baked Scaled Mesh PhysX CollisionData" in a development (non-editor) build. Looks like it's caused by a few rock formation prefabs. Isn't that supposed to be built at compile time? Is there anything that could confuse Unity into doing it at level load (or other point in runtime?)
I'm trying to apply haptic feedback to Touch controllers based on how "hard" the user's hand is colliding against something, but I'm having trouble finding the right mix of attributes to use to determine this. The Collision.impulse property returns zero on low-impact collisions, and Collision.relativeVelocity seems to always return the same number no matter how hard I'm whacking the other object with my Touch controller.
ideally, the more "pressure" i'm applying on the other object, the higher my value would be. But I'm not sure how to get this value.
When I work with impulse, I find I have to add up all the impulses between two FixedUpdates.
how could you addForce without building momentum ? i would like my player to be able to do sharp turns
You can set their velocity to Vector3.zero before adding the force
(or simply lower their velocity by some amount, if you want to retain a little)
Or just set the velocity explicitly
Anyone have any idea how I can loop over the children by this code?
public uint NumColliderKeyBits => (uint)(32 - math.lzcnt(NumChildren));
public unsafe bool GetChild(ref ColliderKey key, out ChildCollider child)
{
if (key.PopSubKey(NumColliderKeyBits, out uint childIndex))
{
ref Child c = ref Children[(int)childIndex];
child = new ChildCollider(c.Collider) { TransformFromChild = c.CompoundFromChild };
return true;
}
child = new ChildCollider();
return false;
}
i may be totally wrong, but wouldn't you be able to do something like, foreach (GameObject gameobject in ColliderKey.GetComponentsInChildren<Collider>()??
any thoughts on the new solver in 2019.3?
you mean the temporal thing on physx 4.1?
there are experiences on the forum thread for the experimental builds for physx 4
some people found it less stable on their use cases but it's designed to be more stable
so your mileage may vary
I'd always just test myself if I needed to see if it helps on anything
it's just simple toggle on the settings after all
I was wondering how games make it so that terrain such as mud or dirt deform under player's feet
Any ideas?
Or maybe they somehow change terrain's normal map textures so that it seems like it deforms
Procedural mesh deformation. There's examples made by Unity on the Asset store @stuck bay
Thanks
So, I've got a number of questions about the particle system's physics...
I'm using particles as projectiles and so I need to build an accurate ballistics table. I know I could make it way simpler by dropping drag, in fact I've done that in other areas, but for this application I'm willing to do all the extra work to get this.
Basically, I want to know how Unity calculates a projectile's path with drag and "multiply by velocity" turned on. The fact that you can skip to points in playback makes me think the particles "run on rails" rather than being numerically solved. So it has some kind of analytical solution? I think you can do that if you assume linear (with respect to velocity) drag?
Can you just run a pre-simulation in advance to get the result?
if you can jump in time
It'll still be a lot of tedious work to make ballistics tables as opposed to if I could just refer to some equation(s), but yeah.
Still would be fantastic if someone knew what equations the particle system uses. I tried some generalized kinematics equations for linear drag, but those were very inaccurate.
it'd be nice, but the last time I tried something like that I learned that unity won't even return the particle ID of a collision
Looks like that's the rigidbody calculations. I think the particles use something analytically solved since you can enter any time on the particle playback and get it instantly.
Ah
Well
You could test it
Place particle system at 0,0,0 , set it's x velocity to 10, ignore gravity, set up the camera so it looks at some point and try few times
And also have a timer
I've been taking the particle system out to a range and testing its ballistics. I got my data table.
That's how I was able to tell that the equations I found didn't work.
If you have lots of data then you could just make a equation out of it with Excel
When I use Rigidbody.AddTorque do I need to multiply the force by fixedDeltaTime?
Gotcha, thanks @frigid pier. Are you implying other force modes require multiplying by delta time inside Fixed Update?
Continuous modes are applying given force over period of time, and Impulse uses it at once.
Is there a way to have a sort of partial collision reaction? Like making the collided object sway as something passes through it instead of blocking it(maybe with some resistance)?
I'm thinking, maybe, having ignorecollision in the collision event, and then applying some small multiplier of the collision force as a force instead?
Why not use a trigger?
Well, triggers don't return any sort of force or direction information, do they?
Like, I'm thinking a... permeable collision. You can pass through it, with some transfer of force
dunno if that makes sense
But not sure how to explain better
I suppose not, but you can use the trigger to then do some other operations to figure out whatever you want. What you're saying makes sense, not really sure the best way of doing it
They have effectors for 2d, but they are one-way; they affect the things that enter them but are unaffected themselves
Is there a way to rotate the Buoyancy Effector 2D surface level with the game object?
can i ask for help here?
its a character controller issue, i think that counts as physics?
anyway my controller is getting stuck when i jump up ledges and i have no clue why, I've used character controllers in the past and never had this issue. heres a video
@manic heron This may solve your problem
https://youtu.be/n-KX8AeGK7E
Source Code Available on GitHub: https://git.io/fNwNI Finally, after all this time, a video with a jumping FPS player! Today I cover: - Creating an FPS const...
of course it was the last 30 seconds of the video lol. thanks though, it helped me fix it
What would be the performance impact of using physical invisible particles to simulate radiation damage from a source
Depends on the number of particles. About ten years ago I wanted to do a UE3 mod that used particles for explosion damage on certain weapons (including giving doors health so they blow off the hinges, etc.)
Never got around to it :\
I used particles for fire simulation in my previous project, it worked ok
it was still probably the worst way to do it performance wise though
Hi I would need to generate a position at an angle from the NPC backwards. How do I do that? (On NavMesh)
Not sure if this belongs specifically in the "physics" section but:
I have a physics based player using a few child objects with hinge joints and rigidbodies in 2D. My issue is that I can't make my sprites rotate 180 degrees to turn left or right because the quaternion rotation completely breaks the hinge joints. Is there some non-hack that I could use to rotate my parent gameobject to turn left or right?
I'll link two gifs, the first one is without rotating my parent gameobject:
https://gyazo.com/085473cc10bdc81a94c0bd428430336e
and the other one happens as soon as I run this line of code on the parent gameobject:
transform.eulerAngles = new Vector3(transform.eulerAngles.x, 180f, transform.eulerAngles.z);
https://gyazo.com/f8536fec06583b137b86f75cd43c1c62
All the player's joints become dislocated and no longer function.
I don't really know what that entails
In my game I just multiply the localScale of the parent object by -1 on the x axis
though I'm not using rrigidbodies
Or rather, only one rigidbody for the whole character
I'll try it but, using hinge joints are weird. Pretty much ANYTHING you do to them that isn't specifically rigidbody based just makes them completely dislocate
Sadly no dice
Thanks though
This was the result, if you were curious lol
https://gyazo.com/ac367982f6b9ef269e30907a6f9d8e10
weird, I just tested it myself and it seems to work
At first I thought this was just that I had angle limits on my hinge joints, but I disabled all the limits and it did the same thing
It must have to do with nested rigidbodies or something, but it's really bothersome that I can't simply make my character turn around
forgive the rather... silly puppet, I just threw some rigidbodies on a sprite that wasn't designed for them
well, all I can really say is that I wish mine worked like that
It's hard to create an isolation case of my situation because my player has so many things happening at once
Try parenting it to another object and flipping that, see if that helps?
Yeah, I can see that
My parent gameobject already has no rigidbody or anything like that
Or it does but it's kinematic
I'll try that just in case though
that's actually proving a little bit difficult because I have to mess with my network settings, so it might take a while
good luck!
All I'm using to flip my player is ``` public void flip()
{
facingRight = !facingRight;
Vector3 lScale = transform.localScale;
lScale.x *= -1;
transform.localScale = lScale;
}```
which is probably childishly bad but it seems to work with no problems
It almost works for me, but after switching directions multiple times it gets more and more mutilated
I also can't realistically parent this gameobject to another one (easily)
It sounds dumb, but I'd have to change like 20 scripts and then change them all back just so I could remove a network identity
ah, I haven't even touched networking
Um, crazy stupid idea, could you just make a left facing copy and swap between them?
I suppose if I copied the current velocity to all rigidbody components that might not be too bad
I'm kinda curious how you set the legs up
does he have a walk animation?
Or just hopping?
Walking is pretty janky right now because I just rewrote most of the underlying code but
he technically does have one
It's not something I want to show off right now though
I've only been working on this for like 3 days so there's a lot of room for refinement
as for how they work? I essentially (through trial and error) found some good standing angles for his limbs to be at and I use this to keep them generally in the right area:
{
rb.MoveRotation(Mathf.Lerp(rb.rotation, angle, lerp * Time.deltaTime));
}```
When landing I use the current velocity angle and move the legs to it to simulate bracing for impact
ooh
Everything is lerped to give it a realistic and bouncy feel
Here is a better example of it
It's not just forwards though since it's based on the velocity
I do want to tweak the backwards feel a bit though
Anyway, thanks for the help. Hopefully somebody comes by with a perfect solution, but I doubt that's going to happen
I had the weird thought that maybe you could destroy and recreate the joints when flipping
So there'd be no degradation over time since they'd be sorta reset
Good luck! It is looking really cool.
Hrm... or create an empty gameobject, parent to it, flip, then unparent
The issue with anything involving parents is that it needs to have a network identity and other components for it to be functional on the server
Sadly I think it will have to be some kind of hack like that if I want to get it working ever
I cry at the lack of information about this on google
Either that or rebuild it with another level of parent I guess -_-
Man, I know, it can be really hard to find hard answers to 'what is unity doing under the hood'
good luck, and good... morning:D
Again, thanks for the help
I'll keep fiddling with it because I really don't want to end up giving up on this project
Don't give up!
i shtere a way to change the physic2d's properties through code, or say a key press
i just dont know how you would change it
You could maybe just put in a line that says something like Physics2D.gravity = [value] but i doubt that would work
Im not at my PC so i cant test anything
okie thx
why is my rigit body is jumping / skipping when i walk forward ?
_body.transform.localPosition += _target.transform.forward * axis.y * _speed * Time.deltaTime;
here is what i use to move the player
@torpid prism : Probably has something to do with your "axis.y" term. That looks like a strange thing to have in there.
Typically you don't move a Rigidbody through setting its transform position.
Can cause issues.
Rigidbody has its own equivalents.
I'll try adding force then
Or you could use a CharacterController.
If you want something that basically respects physics but still does simple movement, a CharacterController is the easy way to go.
AddForce is great but can take a lot of tuning to get just right. If you want it to act similar to a directly setting position (instead of a floaty acceleration/deceleration), it's usually a good idea to have a high drag value.
@sly violet thanks I'll keep that in mind
If i spawn an object within a sphere collider, or spawn a collider around an object will that activate OnTriggerEnter or does it have to enter from outside the collider?
Yeah, it'll activate.
One, spawning something in will activate OnTriggerEnter on both bodies.
Two, sphere colliders are volumetric, so detect things inside and not just things crossing the border.
thank you
@manic heron For 2d at least there is a setting you can change for that
naw its 3d
I dunno then, there might be a setting for that though
Is there a way to get the current position of a joint?
in other words, the distance to the target position of a configurable joint
Huhhh. I don't think so, short of just calculating it yourself.
Why when removing a child rigid body from the player ( who also has a rigid body ) the child collider can effect the parent rigid body ?
But when both the child and the parent have a rigid body, only the parent collider can effect the transformation of the rigid body ?
I got the following setup:
- Player ( rigid body + collider )
- - sword ( collider )
using the following setup allows me to push the player away from the wall when using the sword collider
where sword position is updated in real time following the VR controller coordinates
@twin sonnet did you check out camera collision and clipping tutorials on YouTube ?
yes @torpid prism
@sly violet where can i find that CharacterController ?
Hi, gravity could be influenced in project settings > physic 2D and also on my character by his rigidbody. I suppose it's not the same thing. May someone explain me that please ?
@flint tendon : So, there's a global gravity which you set in the project settings and a gravity scale that can set by rigidbody2d. The gravity a given rigidbody2d experiences is just the global gravity times its own gravity scale.
@torpid prism : A child with its own Rigidbody is effectively a separate object as far as physics calculations are concerned. A child with a collider but no rigidbody has its collider assigned to being part of its parent's rigidbody.
Thanks
@sly violet ok thanks a lot 🙂
gravity scale is influenced by Gravity in Project settings > physics 2D
@twin sonnet can you restate the question?
Wadim, you can just set the child rigidbody to Kinematic instead of removing it, that would make it still be treated as a separate object
@torpid prism are you applying the location change in FixedUpdate?
I have two gameobjects that have rigidbody, colliders and navmeshagent components attached to them, yet when they collide it doesnt get detected with the OnCollisonEnter method. Ive googled and it hasnt helped me
@bleak wedge i was but it didn't help much, doing too much wizardry with the transform hierarchy
Gonna try FPSWalkerEnhanced maybe it will stop the anomalies
Anyone have Bullet Physics experience? I'm trying to learn how to achieve different friction/bounce combines like PhysX
I want one object to bounce different against different object types
Why not use physX then?
@coral mango Because my game is a networked physics based game and I need a deterministic physics engine
I have a really strange problem. When I move my ball (physics-based game) forward, it moves normally. However, when I move left, right or backward, for some reason it starts levitating.
{
if (Input.GetKey(KeyCode.W))
{
rig.AddForce(cam.transform.forward * moveSpeed);
}
if (Input.GetKey(KeyCode.S))
{
rig.AddForce(cam.transform.forward * -1 * moveSpeed);
}
if (Input.GetKey(KeyCode.A))
{
rig.AddForce(cam.transform.right * -1 * moveSpeed);
}
if (Input.GetKey(KeyCode.D))
{
rig.AddForce(cam.transform.right * moveSpeed);
}
}```
@stable fog is it from the camera stuff? Your camera angle is gonna mess things up
Anyone knows a tutorial to get started with the new dots physics ?
I did see the demo projects, was hoping there is a quick overview for the structure
( And please don't link me Sykoo videos )
Hello! Im new to unity and Im having a little problem. I want to push this box but when I push it, it never stop moving. How can I solve this? I want to push it but will stay put if im not pushing it anymore. please help a fellow
@lost quarry looks like you can use some friction
How to do that? Sorry for asking this. I tried googling it but I cant simply understand how they do it
@lost quarry have you seen this https://docs.unity3d.com/Manual/class-PhysicsMaterial2D.html ?
@lost quarry The PhysicsMaterial2D stuff is used to affect forces from contacts. For top-down you're typically not in contact like that so you need to use what is effectively "air resistance". Use Rigidbody2D.drag (for linear motion) and Rigidbody2D..angularDrag (for rotational motion). Both of these are available in the inspector for the Rigidbody2D.
Thank you so much guys!!!! I tried following and experimented a little and bam! You guys are awesome
I just successfully migrated from PhysX to BulletUnity. Just putting it out there for anyone else: It was way easier than I thought and I'm enjoying the improvements it's made to deterministic server/client network simulations
Good to hear! I've been wondering about that
Hey @strange raven I was thinking of trying to make a physics-animated character, thinking a super top-heavy guy who can be knocked around with physics
Any thoughts on making a 'mostly stable' topheavy character?
@coral mango Well, I still wanted some decent control, so I used MoveRotations and Lerps to make it attempt to go to a certain angle, while still interacting with the physics system
Alternatively, you could use the hinge joint's motor, if you enable it. I haven't used that at all though
Yeah. I'm thinking what I can do is have a fairly normal character for the lower body, with a large capsule for the top that would 'try' to remain rotated upright
rb.MoveRotation(Mathf.Lerp(rb.rotation, desiredAngle, lerpTime * Time.deltaTime)); is what I did
So you could have desiredAngle be 0f and then it would attempt to remain upright
woah
Might make the torso bigger/legs smaller
I really like the legs on that
When he sees you, he charges frantically, but he can be knocked over or dodged
That's terrifying
Yeah, the artist did a great job with the combination of skinny and massive
So yeah, I would just do a rigidbody for the legs (as one object) and then a rigidbody for the torso, and have the torso just doing rb.MoveRotation(Mathf.Lerp(rb.rotation, 0f, 10f * Time.deltaTime)); all the time
oh
hinge joint between them too
almost forgot
The initial test seems to work well!
👍
Though it seems to always want to lean to one particular side
Even when standing completely still?
Yeah. I think I might have not placed the joint perfectly maybe
Or maybe I need some 'stay upright' force on the lower body too
hrm, this is tricky
Yeah, physics are wack
How should I move him? The lower rigidbody(the feet) or the upper one?
I'm thinking having the feet do the moving, with the torso acting as a weight that weakly tries to right itself
But initial tests are only so-so
I really don't know what would be best for that
if you moved the legs, you could change the angle that he uprights to, as in angle it slightly more in the direction he is moving so his torso doesn't just flail behind
I'd kinda like it to trail a little, and then bounce forward a bit when he stops maybe.
Unless he goes too fast, and then...
I am using the new 2d IK, and have a 2D rigidbody on the goal object that I am moving using MovePosition()
The motion works fine but the IK is jittery as hell.
Is there a way to make them play nice?
Good Morning fellas.
So I'm new to Unity, currently working my way through an online course.
I'm building a brick breaker thing. Now I have a ball with RigidBody2D and CircleCollider2D, with a PhysicsMaterial2D attached to the RigidBody2D component.
The issue I have is that if I set the bounciness in the PhysicsMaterial to 1, I'd expect - as the documentation says - that the ball will keep it's energy bouncing off my paddle (which does not move at all right now).
However for some reason it jumps higher everytime it bounces off, so somehow there's energy added.
I was wondering if anyone knows if there is a known issue or experienced similars and knows that I can do about this.
Thanks in advance. :)
@twilit hamlet Try setting the collision detection on the Rigidbody2D to continuous
Hmmm, try setting the linear and angular drag to zero. And also no friction
all done already.
if I set the bounciness to 0.99 it indeed looses energy.
if I set it to 1, energy gets added.
Just setting the collision detection to continuous should have worked, as discrete can have some inaccuracies due to it only checking for collisions in physics updates...
This was at the bottom of the physics material documentation
@twilit hamlet What's your interpolation setting?
none
yeah I mean
it's not like minimal deviations.
it's like
50% of the balls size more height after the first bounce
and it gets more and more with each bounce.
Does your ground also have bounciness on it?
well there is no physics material added
it's just a sprite with a CollisionPolygon2D added.
err
PolygonCollider2D
info tells me it has bounciness 0 and friction 0.4
the paddle that is.
It seems that people are stumped by this on forums posts and such
It's usually resolved with some hack like setting the bounciness to some really specific decimal
And besides that, they say setting the collision mode to continuous fixes it
Sorry, I'm out of ideas
I'm really trying to give Unity a chance but man it doesn't make it easy for me.
Well, thanks anyways. Since it's for learning purposes only it' won't be too bad if energy is added.
It's just about getting familiar with how things work in this engine.
Yeah maybe it's my godot install being jealous and messing with unities source to make me come back. :D
@twilit hamlet you can try setting the velocity explicitly after collisions
You know how much you should have, so if the velocity goes above or below that...
Okay so...
it seems I fixed it by moving the ball to a different start position.
ahahahaha
very odd. :D
anyways, it's solved, thanks again.
Hey, if it works
is it even possible to have from 25k to 250k objects2D flying and colliding without writing custom physics?
in 60 fps
If they are particles maybe
So is there a way to use MovePosition() on a Rigidbody2D without affecting the(non physically connected) parent?
A Rigidbody2D only writes to the Transform on the GameObject its on. It doesn't modify hierarchy above it.
I figured out what the actual problem was
The child was violently impacting the parent, and moving it that way, even though it was supposed to be ignoring collisions with it.
I fixed it with joints
Guys i am working on a project where i need to implement water diffraction effect (Physically correct).
Link to see what i am trying to achieve : https://www.youtube.com/watch?v=BH0NfVUTWG4}
I am not able to find any way to solve this problem, one of the friend suggested me to go with Navier-Stokes equations. any one can help me on how i can achieve this effect? or any steps which i can take to proceed further to achieve the solution.
Andrew Norton shows what happens when waves pass through apertures of different sizes. (Part 3 of 5) Playlist link - https://www.youtube.com/playlist?list=PL...
How physically correct do you need?
I want waves to be reflect as per the effect it got after colliding with objects, refer to video you get more idea of what i am trying to convey.
@fierce coral you should research work done by matthias-mueller-fischer, it's probably what you need.
Hello 🙂 I'm having a hugeeee brainfart (i think, or just not smart enough Pog) while working with forces and ragdoll
https://gyazo.com/366490381d4667baa463119723348231
https://pastebin.com/WtZQXSRj
When i click the player, i want it to fly up and ragdoll
But now the model just falls down to the ground, and 2 seconds later he flies up
Please tag me in the solution! 😄
Hey guys, i'm starting on a game, new to game dev but am a software dev by career.
I'm starting on a fighting game and am wondering if anyone has advice on whether to use kinematic or dynamic rigid body? I want to go more the style of say Guilty Gear where hits in the air suspend the character in air, and i think i'm leaning towards kinematic but didn't know if anyone would be able to give advice on their experience?
Thanks.
As someone who is making a beat em up platformer you definitely want to go kinematic. Rigidbody only for deco/debris, or code your own kinematic if its gameplay important
thanks for the insight and advice
How can you get the current position of a configurable joint's attached object?
myJoint.connectedBody.transform.position
yes but relative to the joint anchor
I want to know when it moves certain amount away
I would like to implement my own limits in one axis so I break the joint manually
@lime iron I don't know exactly why it's doing that, but try making the AddForce method an impulse instead of force, so change
GetComponent<Rigidbody>().AddForce(Vector3.up * force); to GetComponent<Rigidbody>().AddForce(Vector3.up * force, ForceMode.Impulse);
(you might need to tone down the amount of force if you do this)
Also I'm pretty sure you need to turn off all the gravitys on the child rigidbodies, or else he will just fall immediately, as shown in your gif (because they have just accumulated gravity the whole time but aren't ragdolls yet)
So you would need to do this inside the for loop in DoRagdoll: col.GetComponent<Rigidbody>().useGravity = isRagdoll (it might need to be col.gameObject.GetComponent, I don't have my IDE open)