#⚛️┃physics
1 messages · Page 69 of 1
Secure account and not post unrelated stuff on the server.
And be more careful what you do on discord.
I'm only applying two forces to the Rigidbody - thrust and drag - yet the rigidbody slows (accelerates in the direction of drag) even when the thrust is an order of magnitude greater than the drag?
The velocity goes up as expected, but then starts decreasing, even though the magnitude of drag never comes close to being equal that of thrust.
I should mention that I'm not using the builtin drag: I'm using a simplified form of the drag equation. "Drag" in the inspector is set to 0.
Max thrust = mass * max acceleration (which is serialized)
Drag coefficient = Max thrust / max speed^2 (max speed is serialized)
Then the drag itself is calculated as speed^2 * drag coefficient, so that at max speed, drag = thrust. I should note that this same code works fine in 2D. I'm going to work on getting the code snippets, but wanted to post this first in case there's some obvious explanation I'm missing.
Not seeing any glaring problem so far...
Those are pretty large numbers, but that shouldn't be a huge issue, especially if the mass of the object is also large
Mass is 50,000
The following lines are run in Awake (they're actually in separate methods which are called in Awake, but I'm consolidating them for ease of reading)
maxThrust = MaxAcceleration * rigidBody.mass; // MaxAcceleration is serialized
/*Fd = 0.5 * p * u^2 * Cd * A
* Fd = Force of drag
* p = mass density of fluid
* u = flow velocity relative to object
* Cd = drag coefficient
* A = area
* Simplify: combine p, A, and the constant 0.5 into Cd; Fd = u^2 * Cd
* Therefore Cd = Fd / u^2
* Fd = Thrust at max velocity
* Therefore Cd = Thrust / max velocity^2
*/
dragCoefficient = maxThrust / MaxSpeed / MaxSpeed; // MaxSpeed is serialized
The following lines are run during every FixedUpdate (again, as part of a method which is called as part of FixedUpdate)
currentLinearVelocity = transform.InverseTransformDirection(rigidBody.velocity);
forwardVelocity = currentLinearVelocity.x;
// Props
propThrust = Vector3.right * maxThrust * enginePower; // enginePower = 1 at max power, which is what is shown in the screenshot
// Calculate linear drag
linearDrag = Vector3.zero;
if (forwardVelocity > 0f)
{
linearDrag.x = -(forwardVelocity * forwardVelocity * dragCoefficient);
}
else if (forwardVelocity < 0f)
{
linearDrag.x = forwardVelocity * forwardVelocity * reverseDragCoefficient;
}
rigidBody.AddRelativeForce(propThrust + linearDrag); // Note that this is the only call of AddRelativeForce (or any AddForce at all)
This same code works just fine in 2D (the axes are different, and the vectors are Vector2 rather than Vector3), so either I missed an axis/vector conversion, or the problem is not with the code itself. Maybe Rigidbody and Rigidbody2D behave differently in some relevant way?
Seems fine at first glance
There may be a small improvement in floating point precision if you do a single AddForce with the sum of the two force vectors but that's not a big deal
🤔
Would that affect behavior during collisions? I guess not, since a collision would change the velocity and reduce the drag instantly.
Not really
Id there any chance there's something weird going on here like accidentally having two copies of the script or something
You're logging the two forces, and drag is smaller, and it's still decelerating?
And drag is definitely disabled on the Rigidbody?
And there are no other scripts applying forces to this object?
Yes to all those last three.
I opened every script and searched all open documents for "Force"; the only results are the ones in the script shown above.
Hmm the constraints you have are interesting
Sometimes rigidbody constraints are known to remove energy from the system
For example if part of the force is applied in one of the frozen dimensions
Would it be possible to try without the constraints for a minute?
Turning off the constraints solved the issue.
Oooh ok
That's odd, though, since this is the only force application, and it's only in the X axis, so there shouldn't be any energy wasted in the Y axis.
That said, it's an unnecessary constraint, since gravity is off.
So we have a culprit at least
It's the local x axis though right?
Does that align with the world x axis?
The constraints are world space axes AFAIK
It should, although I'm seeing very small Y-axis movement as well. I wonder if that's an issue with the torque, since I'm also having trouble with that - I'll comment out the torque lines (should be 0 anyway, since I'm not touching the steering, but who knows) and see what happens.
Well that's definitely where the missing energy was going at least
Still getting small Y-axis velocity even with no torque code.
Edit: The issue was that I had a TerrainCollider, and the bottom of the ship was just contacting it (no gravity). Removing the Terrain object fixed the issue.
Is there equivalent to Mathf.CeilToInt in Unity.Mathemetics.math? It returns the smallest integer greater than or equal to x
The library doesnt have intellicense commants to help what these functions
int CeilToInt(float val){
return (int)(val + 1.0f);
}
@feral pike
Thank you :)
There's a ceil function
ask ray if he wants to be played with first? @stuck bay
Anyone know why my wheel colliders let my vehicle fall through the floor? The wheels (which the wheel colliders are assigned to) are children of an object that has a rigidbody
continuous vs discrete collisions
also don't mess with the velocity directly
Anyone know why no matter what direction my Vector 3 is in, the rigidbody never goes forward/backward?
No value in the x, y, or z fields will make it go forward
you'll have to be more specific about what you're doing with this Vector3
I'm trying to apply forward force to a rigidbody. I'm using rb.addforce(vector3, float, forcemode) to do that
But it always either goes to the left, right, or down
what is fDirection set to in the inspector?
it starts off as 1 in the z axis
I see that in the code but - what is it set to in the inspector?
Also, it's the same in Update()
It's public, which means it's serialized
what's the same in Update()
This chunk of code. I cut it from Update() and pasted it in FixedUpdate() to see if would make a difference, but it didn't
2000
It barely moves it when under that
you could use transform.forward instead of fDirection if you want it to always be forward relative to the object
I tried that, but it has the same problems
right now it looks like it is applying a force in the global z direction, rather than the local z direction
If that was the case, shouldn't (1/-1, 0, 0,) or (0, 1/-1, 0) give me the result I want?
no. I'm saying it looks like the force is always pointing the same direction, regardless of which direction your object is pointing. If your object rotated 90 degrees, do you want the force to also rotate? Or do you want the force to point in the same direction as it was originally (before the rotation)?
I don't think you've really explained what the result you want is yet
You've explained in abstract terms with a vector and a rigidbody but what's the gameplay thing that's supposed to be happening here?
It doesn't really matter what direction it is in. I just want to know why changing either the x, y, or z values doesn't provide the result I want. Also, I haven't rotated the object at all.
I need to apply velocity to the rigidbody so I can test out this script that is a function of the rb's velocity
What's actually happening instead? This sounds like a pretty basic setup but maybe I'm missing something
You said it goes to the left - right - or down... like, directly in those directions, or at weird angles? what
Well, now there is a new result. I don't know what caused it, though. I only added a 0 to the force. @jovial wraith https://imgur.com/a/LWfqmZZ
It now only moves left and down
looks to me like it's trying to move but it's colliding with something
what's the collider for that thing look like
maybe disable any and all surrounding objects for a moment?
or move them away
Disabled the surrounding walls. There's nothing else in this scene that's not parented to the plane except for the walls and floor
what else is in the plane hierarchy
Like, things that are not supposed to be a part of a plane?
I mean...
the children of TheBomber0527
what do they have?
Any of them have Rigidbodies?>
....yes. BUT ONLY because I needed OnMouseOver() to work on some of them
All of them are kinematic
Except for the parent
Can you dry disabling them for a little bit
those child objects that have rigidbodies
Yeah, give me a sec
since they're kinematic I think they should be ok but... something is off about all this
Same thing. ALL Rigid bodies except for the cockpit have been disabled
make a new scene
make a cube with a rigidbody
put your script on it
see what happens
So, that works.
I want the simulation on the left. I want to simulate two objects and tell one to ignore the weight and velocity of the other object so that it passes through it undisturbed. Is this possible to do in Unity?
I need this because I want a car(blue box) to ignore the velocity of players(red sphere) but not ignore the force from explosions. Is this more complicated than enabling a simple setting on a physics object? Is it even possible?
Make the Blue box kinematic
But you will have to move it manually with MovePosition()
Is there an Ignore Collider Input setting?
Also will MovePosition() make the blue box behave like a simulating object?
Wdym
It will move it where you tell it to move and bump other objects out of the way
Because I want to have other objects in the world that the blue box collides with normally
But a kinematic rigidbody will not be affected by any forces
If you want it to act like a normal simulated object and still ignore particularly the forces from this Collision you may need to use the contacts modification API
Which is quite new
Lemme find a link
Hmm ok. I wanted to have a physics object in a full simulation that simply ignores the force/velocity of some other specified simulated objects but I guess I will need a kinematic body. Weird, this seems like a pretty important feature that I have seen other people requesting. The same thing is required if you have a character walking into a wall on a boat. If the boat is simulating physics and the character is simulating physics, the boat will be moved with the character, which sucks.
Hey so having a slight problem with my ragdolls, heres a quick video. This goes on forever, does anyone proficient in ragdolls know how to deal with this. It only happens when head is not colliding with something. Head has a box collider to prevent it from movinh like such on the ground.
Also one way to prevent it is to make head hitbox bigger, however that would pretty much be unfair in a third person shooter
don't necessarily have to use the same colliders for gameplay as for the ragdoll
That would add a bit of complexity though of course
understood, ty that makes me think of a possible combination 🤔. I'll see how a trigger and a different shaped collider that could collide and rest with the upper torso works then.
another option is also just resizing the collider when ragdolled
wish I had a better answer about why it's happening in the first place though
it's all good😅 Honestly it's such a weird problem. Resizing the collider has consequences to where if the ragdoll is not experiencing the problem, then the head floats off the ground because the collider is too big. I'll get it figured out eventually.
Perhaps this is a beginner question but I am struggling with it for the last hour :). I built a spaceship, as I want to move it around and apply physics to it I added a rigidbody to it. Now i want my player to move within the spaceship. I started off with a character controller to move the player but the player started to move with the rigidbody of the spaceship (even though it is a child component of the spaceship). So I tried to apply a rigidbody to the player, but to no avail as I do still see the player moving it's position when the spaceship is moving. How can I make sure that my player's rigidbody (which is a child of the spaceship), is not affected by the movement of the spaceship's rigidbody? Thanks in advance 🙂
these are my current rigidbody settings on the player. I tried to turn of gravity but then my player starts floating (as expected) when the ship is moving downwards.
Have you tried playing with Drag?
I have tried but to no avail, I will give it a few more tries 🙂
Hmm, maybe you could play with the masses, so the person inside is much more massive than the ship so the forces don't impact them much
It's not a great solution but might work/get you closer
Er sorry, you don't care about having a rigidbody on the player/having physics on the player, you just want them to stay in one place relative to the ship?
it's not beginner it's something that's very hard to accomplish. the way you describe it makes me think the charactercontroller had a rigidbody too.
children without rigidbodies will follow their parent so long as you control them in local space.
I guess I might be mixing up world space vs local space in that case. I will do some more reading in that area. Thanks for the answer
@terse gulch A suggestion via code, is you could increment the player amongst the x,y,z axis in accordance to their vehicle. Lets say the vehicle moves +5 amongst the x axis, then increment the player to move accordingly amongst the x axis +5 as well. Should work as long as the player is positioned in a desired place like a seat before such calculations are made. Just a suggestion.
Thanks @stuck bay . Will take a look at that.
is there any way to manipulate the virtual particles of a cloth mesh at runtime? I deeply desire to connect two moving transforms with a visual cloth tether, but it seems like there is no way to actually achieve it
i looked into this before but not too deeply...
I made sprite of a wire (2D), and now im trying to make this sprite look like a real wire, that connects to my character and moves with it and drag across the floor, someone knows?
children without rigidbodies will follow their parent so long as you control them in local space.
just realised how weird unity is without context
do you need to do something after checking/unchecking boxes in the physics collider settings? i feel like when i tinker around in there sometimes the settings arent taking hold, and things just start working again a little later on
nope it should update right away
im having a problem where my character controller isGrounded bool keeps switching back and forth between true and false
try and increase the ground distance variable
whats the ground distance var?
wait send me a pic of your code and then maybe i can help you
I want to say that the jump method is interfering with the CC collider https://pastebin.com/fcU2UcFU
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Im increasing the scale of an object at runtime (by 0.2), but then its velocity decreases. I tried to reduce its mass but that didn't seem to make a difference . So now Im trying to scale its velocity by the same amount m_velocity.normalized * 0.2F. This isn't quite right either, as it still suffers a speed reduction. What am I doing wrong?
basicaly I just want to maintain a constant velocity after I increase its scale
Don't cross post this much please
Alright so have a mesh collider (no rigidbody), and a moving capsule collider set as a trigger (with a kinematic rigidbody, though it's parent has a non-kinematic rigidbody). I'm only getting OnTriggerStay events when the trigger is on an edge of the mesh collider. If the trigger collider cross an edge and fully goes into the mesh collider I get an OnTriggerEnter (when it begins crossing over the edge), an OnTriggerExit (when it leaves the edge and is fully inside the mesh collider), and no OnTriggerStay events once it's inside. Is this expected behavior with mesh colliders/anyway to make it do what I want?
Is there a reason why, my rigidbody in my unity scene and when I build the game are different
they do not feel the same
the phyisic's numbers i set
the build version feels way heavier
You might have framerate dependent code
Or sometimes just playing in a different screen resolution feels different
experiencing occasional ragdoll stretching when colliding at medium speed against static geometry
preprocessing is off, projection is enabled
ragdolls are running this
foreach (Rigidbody rb in ragdollRoot.GetComponentsInChildren<Rigidbody>())
{
rb.solverIterations = 12;
rb.solverVelocityIterations = 12;
rb.maxAngularVelocity = 20;
}
Any thoughts how I could further improve to reduce stretching?
my enemy jumps high enough, but too fast
void JumpAttack()
{
float distanceFromPlayer = player.position.x - transform.position.x;
if(isGrounded)
{
enemyRB.AddForce(new Vector2(distanceFromPlayer,jumpHeight),ForceMode2D.Impulse);
}
}
jump height is 7 and gravity on the obejct is 15
Debug.Log
Wdym
ohh sorry I copy pasted the wrong message. Decrease gravity and increase the force for "longer/in time" jumps
you could probably also add/remove from velocity as soon as the player is no longe rgrounded
hey guys! so while writing my own custom character controller, I found a collision related issue I don't see any easy solution for. It's also present in unity's own physics system and it's the problem of objects going through slim corridors. Let's say we have a corridor getting slimmer and slimmer, and a capsule or sphere shaped object. As we apply force to the object, it starts creeping into the corridor deeper and deeper, a bigger force results in a faster speed. This is due to how unity handles collider penetrations. As it seems, it only calculates a vector for each collider intersecting, and tries to nudge the collider out one by one. The problem is, that if we have 2 walls facing each other, they are basically playing ping-pong with these two vectors, and only a little of the "nudge vector" remains, which is not enough to stop the object from going deeper (like, in infinitely slim corridors even.) So my question is, is there slower, but 100% accurate solution for this that does not require nasty approximations and multiple iterations? Thank you in advance, even if you just read my waay too long message 😄
(that nudge vector isn't correct lol it's late)
should be pointing from one center to the other
one kinda dirty solution I have in my mind right now is to cast the capsule backwards for like a really long distance, then from there (or where it hit something) cast it back towards it again and if it hits something, put it exactly there, but I'm hoping there is a more elegant fancy math way to achieve this
Would that be adjusting jump height? Or the player speed in general
Also, I tried applying force using an unrelated object's forward transform, and no matter what direction the plane is, it will ALWAYS apply force to its left.
I don't know what more information that presents, though
For my controller i check collisions using capsule casts before the capsule moves to anticipate collisions, then if needed I use overlaps
yeah that's what I do aswell, it allowes for more accurate force calculations, but I found that you have to have the capsule cast to be slightly slimmer than the actual collider, because if the capsule cast would be touching the collider at it's origin, it misses it
did you found a workaround for this? I also tried casting it a bit away from the actual player capsule, but I had trouble finding that "bit away" vector
i push the collider back a little bit to prevent that
and i use capsule cast non alloc incase the character moved into a collider behind
yeah that part I'm doing aswell, then I need to experiment with the capsule cast more, thank you! 😁 ❤️
np
this object can be replaced but i dont know to what i should change it
what exactly is the issue you're having?
they do not collide the one is in world space and the other is in canvas space
i cant make it a regular sprite, i can make the regular sprite a canvas object
should i raycast and then to worldspace and see if i hit the object?
solved
Do ridgebody.ignore collisions turn off trigger Dedections?
yes
assuming you're talking about Physics.IgnoreCollisions
I don't know of any Rigidbody.IgnoreCollisions
how can i check a box trigger for colliders manually?
i cant use a boxcast or anything because it uses cubes i think
nvm
What shape do you think a box and a cube are?
i needed a rectangular prism
but it turns out that it supports those
i was confused by the half extents parameter
If anyone is good with physics and ignoreCollision, please dm me. I just need 2 minutes of help.
I meant post your question here, not ask people to dm you 😅
I am really lost, the question would take too long to explain, I will just hope for the besr
best*
I know it is a simple solution I just can't find it online
if its going to take too long to explain its not 2 minutes of help now is it 😛
I suggest just posting it, that way multiple people can see it and help
the dot in the center refers to the dot product right?
yes (I think)
hey i am new and i am struggling with this the right flipper have range outside of intended area and i tried to change the angles and it is still there 😦 any1 knows what to fix it?
I have an issue with colliders and I don't understand what is going on. I have a Plane in the shape of a circular polygon, this plan has a Mesh collider and a rigid body on it.
There are moving objects (circles) which have sphere colliders on them.
When a circle enters, the plane changes it material to be opaque, if no circles are in the area then the zone or plane is not visible.
This issue i'm having is that the collider works perfectly, once the zone has been moved in the scene if if just one pixel. But before the zone is moved no triggered events are occurring and I don't understand why.
Any ideas what is happening here? If I start the plane(zone) prefab in the scene it seems to work from the get go. This happens when trying to instantiate the prefab at runtime.
hmm, no idea's offhand- can you show us the collider config for your zone object? looks like your NOT using rigidbodies.. is that correct?
I am using a rigidbody on the zone prefab.
See Image attached image for config.
Thanks
Note: The mesh gets generated in the start script. I did try Collision Detection continuous but that didn't seem to do the trick.
@worldly pawn and the spheres- are they ALSO rigidbodies? Sound like not..if so, does giving them RB's help?
Yeah the spheres just have Sphere Colliders, and no rigid bodies.
If I add a rigid body to the sphere's it doesn't seem to do the trick either.
In the zone script if I do the following in the Start function it works:
transform.Translate(0, 0, 1);
transform.Translate(0, 0, -1);
Seems like a hack, but it's something.
that is very odd- def should NOT be necessary@worldly pawn hmm does it also work if you disable then enable the collider on the zone (rather than moving it back and forth)?
(after assigning mesh)
@worldly pawn
I believe I tried that and just enabling and disabling the zone was not enough, it had to move. But I'll test it again to be sure. Will be in about an hour tho, just entering a virtual meeting.
@worldly pawn oh.. perhaps the cooking options? lots of deets on that here https://docs.unity3d.com/Manual/class-MeshCollider.html ok- ping me with update pls
Trying to further minimize ragdolls stretching, any ideas?
So far I have
- Disabled preprocessing on relevant RBs
- Enabled projection -- using default values
- Raised solver steps + solver velocity steps to 15 on all relevant RBs
- Increased colliders size, made sure they sink in each other by a decent margin
- Got rid of all < 15 degrees limits on joints
Okay, if I disable and enable the collider in the zone (via the scene ui), then it also works.
@dapper lichen That gave me a thought. Before I was creating the mesh and then immediately setting it to the collider.
mesh = new Mesh();
meshCollider.sharedMesh = mesh;
Then I would update the mesh with vertices and triangles.
So I tried setting the sharedMesh on the collider after updating the vertices and triangles and that seems to have done the trick.
Appreciate the support troubleshooting the issue. Thank you, I believe it's resolved.
Rejoice fellow physics enthusiasts ! https://github.com/NVIDIAGameWorks/UnityPhysXPlugin
hey, does someone know if Physics.Raycast is deterministic? - given the case: i move my sphere colliders that shall be hitted by the Raycast, with deterministic code.
Raycast doesn't do any physics calculations/simulations so I assume so
also when i want to get the hit.point? i am wondering because it uses Vector3 and not some deterministic types
so when i use the result and cast it to a deterministic Vector3 , the code will be deterministic?
I see that you are building an RTS and looking to implement deterministic lockstep
I hear Planetary Annihilation doesn't use this kind of an approach.
The server sends back something they call "curve", apperently it tells you the position of the entity and its tragectory prediction.(Which i believe is a simple curve on the surface of the planet, a start and an end position)
After server sends one of these for each entity, as long as the simulation follows the last sent "curve", server doesn't send back anything.
I might be wrong with a good portion of that though, so if you are interested maybe check it out yourself.
Anyone know how to make physics like Totally Accurate Battle Simulator?
Like the way the characters move and how they randomly trip up on the smallest bump.
And when they attack, they throw themselves at the opponent.
@stuck bay "Active ragdoll" is the keyword
Could you elaborate?
That would just give it the ragdoll effect, yes?
I mean, if you search for "active ragdolls" you will get some relevant info
Aight, give me a sec.
Your character is a ragdoll and limbs are controlled with forces to try replicating an animation.
Thats what it is. @stuck bay
I'm new to Unity, so could this work with any of the free assets?
Active ragdoll is pretty complicated
I'm sure the TABS guys spent many months perfecting it
Yay. Well, I gotta start somewhere.
@stuck bay Unity has rigidbody angular velocity limit on rigidbodies by default
You may want to disable that at some point, or you may not perform fast animations with active ragdoll
I think this might save you later on
Ok
This is a bad idea but I'm trying to make a horrorgame with crazy ragdoll physics.
Like the enemy ai can trip up and fall over while chasing you.
Or the other way around.
I think ragdolls give the game some randomness, taking the control away from in a way. And I don't think that's a good thing.
I had tried making a parkour game with ragdolls before.
I mean it's probably not a good thing if there's a good chance you'll trip over and player has nothing to do about that @stuck bay
That's the thing. Once you fall over and the enemy catches up, you'll have to get up and face him head on. Absolute beat the shit out of each other.
If you die, then jumpscare. But if you manage to win, you may knock him down for several seconds to get away.
https://www.youtube.com/watch?v=62TMK1ggaik @stuck bay
I did something like that to the best of my abilities back in the day haha
I'm just scared that the game would be comedic rather than scary :/
Yeah thats bound to happen
Well if it looks anything like T.A.B.S. ...
Googly eyes and all. May have to change a few things to avoid copyright though...
You better handle the "tripping over" with regular animations
Yeah
Some IKs, some head IK movement based on acceleration so it does body leaning as well
It should be good enough
How would you overlap animation with ragdoll physics?
Easiest way is starting with two characters
One with kinematic rigidbody limbs
One with dynamic rigidbody limbs
And each limb pair is connected via some kind of a joint
@stuck bay
So combine 2 characters?
You make the animated one invisible
I'll look more into it tomorrow.
I don't know how would that work though, i didn't try it myself
I don't think tripping over and falling will work nice with this
But you'd get the external impacts nice
K
thanks for your reply i read about what they do there a while ago, but i decided that deterministic lookstep would be an easyer approche for me since i "only" need to sync the input. right now i am working with this for vector math: https://github.com/Kimbatt/unity-deterministic-physics witch works fine, but its a little difficult do setup the physics for my needs. So i wonder if i just can use the std raycast.
how do i fix this mesh collider
Looks like you ticked "Convex" in the MeshCollider Component, if you didn't then I have no idea
i fixed it up
i added collision in blender and imported then mesh collider is behaving same as before
Where is the mechanics tab?
guys, when i apply the center of mass to my vehicle this happen:
car flip up, same code of the Unity Learn program
no trouble with the Unity automatic calculation, but i need control on the Com
I can't seem to get my character to even move.
I'm not sure if this is the right channel to ask, or maybe in 2d-code (?)
So I'm trying to build a prototype for a small roguelike-bla-bla-bla. Top-down view, aim with mouse type of game.
The idea is to be able to have the sword attached to the player with a joint (I used a relative joint 2d), so it can wiggle around and is not all stiff. I got it basically working, but at 90 degrees it does this weird thing:
Any help on how to get this to work completely? (Pls keep in mind that I'm very (read: extremely) much new to c# and unity in general.
Thank you all!
how high can i crank the default solver iterations and still have great performance?
can anyone tell me why my capsule is sinking to the ground?
Is your collider already clipping the ground when you start? It needs to be above.
I don't see the collider in the new images.
Do you have any other components on that object other than the three in your screenshot?
nope
So a code snippet for how you're moving your object.
The CC has it's own isGrounded check. My guess is that your manual check is failing and it's allowing the CC to fall.
Try the code from the docs instead:
https://docs.unity3d.com/ScriptReference/CharacterController.Move.html
ok
im getting some pretty big lag spikes from just a few simple shapes going down a track. anyone know how to fix this?
You appear to be in a physics death spiral
well that doesnt sound good
Physics calculation taking too long which leads to lower framerate which leads to more physics simulations each frame
And so on
Too many Rigidbodies too close to each other i suppose?
so by removing their ridgid bodies, that will fix then lag issue?
Well... And break your game I assume?
How are you moving these objects
Do they need Rigidbodies?
yeah, im using the rigidbody AddForce fucntion
Go find the physics section of the profiler
It will say how many bodies there are etc
Maybe you have a bunch you're not aware of
ok, give me a moment while i launch unity up
its telling me 30 active bodies
73 total
there are 30 enemies in this runtime, so 30 is the correct number
Hmm that really shouldn't be so slow
Is your computer weak or doing a bunch of other stuff 🤔
other than discord, unity is the only thing i have open, and i have a 24-core, 3ghz cpu, so that shouldnt be the problem
i mean, although it is 24 core, its only 3ghz, maybe its not utilizing all the cores properly?
i dont know much about software in that regard though
like, im looking at my task manager, and even though im lagging on unity, its only using up 13% of my cpu? i dont get that. why doesnt it just use more of the cpu to process more physics calculations?
Unity is single threaded
For the most part
I think the physics sim is at least?
Which means it can only use 1/24th of the CPU at best
could that be the problem then?
is a single 3ghz core not enough for 30 triangles and circles?
man, praetor not knowing something? thats rare lol. Im gonna try to look deeper into the profiler tomarrow and see if theres anything i can optimize. im gonna be real sad if my whole game idea is taken down by the fact that i cant have 30 basic shapes taking a corner
Are the colliders all simple circle colliders or triangle (polygon) colliders? Nothing wonky going on with accidentally having some super high vertex colliders or something?
the colliders are iether circle coliders or polygon colliders. the polygon collider ended up with a bunch of triangles instead of just one though. give me a minute and ill show a pic of what i mean
i couldnt figure out how to make it just one tri
What if you run it with 30 circles?
There's a tip here that might help making the collider simpler though I'm not convinced that will solve your problems https://forum.unity.com/threads/physics-collider-2d-triangle.100884/
sorry for the late reply, had to fix a bug, but yes, 30 circles ran very smoothly compared to 30 triangles, which could barely run at all
Yeah try to clean up the collider
In my experience, complicated polygon colliders absolutely murdered my physics performance for 2d
Oh wow this is definitely at least contributing to your performance issue
That's a super complicated Collider
@cold rivet Are you doing something in the OnCollision callbacks?
Oh I guess it is just the amount of geometry 🤔
I'm pretty sure that physx uses jobs now
I'm not sure about 2d
but in my testing I can max my cores out
during the physx calculations
That's news for me. Do you have a source on the topic ?
My source is putting a ton of objects onto a scene and profiling it
At the very least it's utilizing the jobs worker threads
Ooooh nice. Thanks for the info derekt
Hi, having a little trouble figuring out how to add a rigidbody and capsule collider to an enemy via script after a delayed timer.
I have an enemy that ragdolls on death via a script that turns the rigidbodies kinematics off on die() method.
After 5 seconds I want to disable the ragdoll, enable a capsule collider with it's own rigidbody to be used on the dead enemy instead. (I want to still be able to move the bodies on the floor, just not with all the fancy bells and whistles of the ragdoll.)
I'm not sure how to go about doing this without accidentally enabling all the same rigidbodies again. Any ideas?
Hi! I'm launching a gameobject (2D) by dragging it from a start position with the mouse and using AddForce() on mouse-releasing. Recently, I have added an EdgeCollider2D to the ceiling and side walls of my level to prevent flying out of bounds. However, sometimes the launched object gets randomly "stuck" in the ceiling and doesn't bounce off the wall. Does anyone know what I might need to change to prevent this from happening?
Did fixing the collider help on this? I need closure lol
oh sorry, i should have followed up. Yeah! the game is running smoothly now that the triangle collider is only using 1 polygon!
great! glad to hear
quick question, im using physics 2d with 2 colliders bouncing off eachother,
if collider A is 0.5 bounciness, is there a way to calculate (edit>) bounciness for collider B for a perfect, lossless, bounce
Unity's physics engine is built for performance and not 100% perfect physical accuracy
You can tweak it quite a bit, but perfect 100% energy conservation just isn't going to happen
np
I would like to add "slowing down the fall" after player is almost grounded, something like when rocketship is landing it starts its rockets to slow down the remaining of the fall until it can land safely. The distance from which the slowing will start will be contant, so the force applied to player will need to be higher when he is falling at greater speed so that the overall distance traveled from almost grounded to grounded will be "constant" no matter at which velocity the player is falling. I'm not using rigidbody but character controller, and after numerous tries I'm not able to get it working as intended... (To simulate gravity I basically just use Vector3 velocity.y and then CharacterController.Move() function)
Quick question I started my first Unity 2D project and made a Terrain with the Tile Palette tool now I added Physiks like this:
My question is now why is the player falling through the Terrain?
EDIT: Nvm it wasnt the collider, it's the actual oneshot sound that plays twice for some reason.
@spare oracle Static rigidbodies sometimes don't work the way you'd expect and I'm not sure why. Make it Dynamic but lock all the axes
Do you mean freeze the axes?
yup
How are you moving your character
are you doing something physics friendly or just teleporting it
"something physics friendly" would generally be a Rigidbody2D and only setting the velocity of that body or adding forces.
The Character has a Rigidbody2D
it's not enough for the character to merely have the rigidbody, you have to be moving with the RB's methods
Whats that?
This #⚛️┃physics message
Link is not working
It's a link to my earlier message in this conversation
I have a non-kinematic continuous rigidbody on a capsule collider that is my player. I'm finding it can pass through some concave mesh colliders with ease... is there something I might have missed that could improve this situation?
how are you moving the player
Addforce
when my player is going really fast, not even super fast just kinda fast, they will skid through a trigger and exit before the enter events can happen. both get called, but the exit trigger cuts off the stuff that should happen for the enter trigger
sounds like you need to keep track of the fact that the enter stuff is still being processed and not do the exit stuff if it is
ive tried every possible way to do that
OMG WAIT I KNOW
thank you
it just needed to be put into words
a simple toggle boolean is all i need
ill let you know how it goes
i really need to get a rubber duck
didnt work
i fixed it but i fixed it in a way specific to my purpose
ur fix should work for any other use
If im making my own gravity and movement for an object, should i multiply by Time.deltaTime or Time.fixedDeltaTime ?
You can always use Time.deltaTime
even in FixedUpdate?
Yep, it will automagically become Time.fixedDeltaTime if called from within FixedUpdate
hmm i see
Is there any scenario where deltaTime is better?
or are both frame-independent stuff?
Time.deltaTime is for update, Time.fixedDeltaTime is for fixed update
i cant believe i played around in unity for so long and still didnt figure out this lmao
Ok so if its each frame its deltaTime
if you use Time.deltaTime in the wrong spot (fixed update), it automatically converts it for you
alright so i just slap deltaTime everywhere 
mhm...
Oh @dreamy pollen one specific case...what about an event thats called in FixedUpdate, does it still get changed?
fixedDeltaTime is always this number
no matter where it's called
(fixed timestep)
yeah i found out about that in #💻┃code-beginner an hour ago xD
I just use the appropriate one for the job... fixed delta time is relating to the fixed timestep (simulation speed), ergo Rigidbody physics
yeah what im doing is physics rn
basically making my own physics for a projectile
all the code is running in FixedUpdate event though
When you say event, you mean like a delegate?
Yeah that'll be invoked probably 50 times a second, if you changed nothing relating to your fixed timestep
yup
any events that subscribe to it will be called effectively during fixed update
so normal FixedUpdate and deltaTime will be converted?
... no... not necessarily
🤔
Unity automatically converts it inside of FixedUpdate. Just use fixedDeltaTime
there is no reason to try and just use one
use the right tool for the job
It's good practice 🙂
Also is it even wise to have a delegate for the projectiles?
Its literally just the projectile class using that one
Because of that one post about the 10000 Updates
I don't know enough about your architecture to comment on that... doesn't really seem like a physics question either?
well im using a delegate to call FixedUpdate which is assigned to a projectile class which event calls a bunch of simulations
Is there a reason the projectile isn't using FixedUpdate() itself?
10000 Updates post
and since i have the potential to have hundreds of those projectiles ,maybe even thousands - i decided to go there
Oh, so you're using an update manager
That's totally kosher, in fact, I use an update manager myself
You can use delegates for that, yeah. They're very performant.
yup, nice ; so at least i did one thing right hehe
now only left to make the damn things to use object pooling, and then use the DOTS
@dreamy pollen should LateUpdate also use deltaTime?
Yes
alright thanks,s helped me fix several classes haha
You should just always use Time.deltaTime everywhere. Then you never have to reason about this.
This is not correct
They're invoking a delegate in an update manager

Any function called by that delegate would use delta time, but because the functions are meant to affects physics they should use fixed delta time
Unity would not know to convert this
I kind of remembered actually using deltaTime when i initially made it into a delegate and it working inconsistently
That's exactly why you use Time.deltaTime. If you do manual ticks through a callback it will be correct, no matter if the callback is sent from an Update or FixedUpdate tick.
that doesnt sound right
Thus if you have a method that could potentially be called from either an Update or FixedUpdate callback. The only way you can guarantee the delta to be correct is to use Time.deltaTime
They're not calling a function, they're invoking a delegate
If you use Time.fixedDeltaTime in a method that gets called in an Update callback it will be wrong
But if it is called in FixedUpdate it's correct
So using Time.deltaTime ensures its correct no matter which callback triggered it.
There is 0 reason to not just use the correct delta time. I never call functions from both update and fixed update
ill just stick to fixedDeltaTime everywhere that uses FixedUpdate 
it's always one or the other
^
I am a proponent of that. It makes sense to be intentional with your code
plus code consistency
Actually now that im here, might i ask about the gravity formula
velocityVector.y -= Mathf.Pow(gravity, 2) * Time.fixedDeltaTime;
is this the correct one , or do i put the fixedDeltaTime inside the mathf
"Therefore, to keep the number of FixedUpdate callbacks per frame constant, you must also multiply Time.fixedDeltaTime by timeScale."
but FixedUpdate arent supposed to be constant
I'm not sure what your point is, I'm aware of this fact. I exploit it to use slow-mo in my game
good to be aware of, for sure
oh wait, yeah
but it should be multiplied by Time.timeScale only if ur changing the timeScale
no?
Hmm it seems they changed the docs at some point regarding this
But they used to say you should always use Time.deltaTime
I know this is old as heck now, but here's from before https://docs.unity3d.com/560/Documentation/ScriptReference/Time-fixedDeltaTime.html
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
the example in that theres also fixedDeltaTime inside the Update
"For reading the delta time it is recommended to use Time.deltaTime instead because it automatically returns the right delta time if you are inside a FixedUpdate function or Update function."
yeah its also for unity 5.6
I'm not sure why they decided to remove this piece of docs, but it's worked the same since then
Okay? I'm not sure why you're so adamant about this. They clearly don't say that anymore. My argument is not invalidated by what Unity used to recommend
Without testing, I can't confirm this but I don't think a delegate event uses the correct delta time automagically
Why should it not?
A delegate is a direct method call. It's not like Unity could know where you are calling Time.deltaTime from.
it is a direct method call, but its not compensating for FixedUpdate, is it?
They only thing they could do would be to set Time.deltaTime = Time.fixedDeltaTime before invoking all FixedUpdates.
I just tested, you're correct -- it appears to return Fixed Delta Time
Anyway, in your case I suppose you could use what you think works best. Only reason I recommend Time.deltaTime is "because it (used to be) recommended". But that brings up another question, why was it removed from docs?
It was removed in the 2020.3 docs actually.
Someone actually asked that exact question and got a pretty good answer (for those interested): https://gamedev.stackexchange.com/questions/192411/time-fixeddeltatime-time-deltatime-in-unity
Im back from yesterday
So Im making a tool where you can simulate a ragdoll and you can stop the ragdoll when its well ragdolling but how do you take that data from the ragdoll position then send it to the actual game
thats where im having issues with
also, the tools uses run time but Im thinking is there any other way to simulate the ragdoll outside of run time
any help is appreciated
Could someone assist me in creating custom very simple wheel colliders for a car?
I don't need friction or anything advanced like that (I think, at least), I just need it to be able to go up ramps and go over potential bumps
I have no idea where to start
just curious, @wraith junco ... Why don't you want to use wheel colliders?
I'm starting a new project, undecided yet whether or not to use unity's physics / rigidbodies... thing is it is 2d/3d hybrid, 3D graphically, but everything is constrained to the surface of a sphere, unity physics would need to be constantly overridden by custom angle and position constraints... my main concern is that it might end up a fair bit of work to implement collisions properly if I want to do anything more complex than sphere colliders.
There seems to be an issue with my player's box collider. When i hold the left or right key against it, it gets stuck in place. Is there a way to make the player just slide off?
physx wheel colliders are awful for multiplayer
can't use them for prediction and such
need something much simpler
Why are they awful, just curious. Besides that, you could leave the physics for the client just to the wheel colliders and just send simplified data for collision checks over the network, so maybe just position and bounding boxes and do your own calculations on the server and send it back to sync with the clients.
Everything movement needs to be confirmed by the server, and then the client needs to correct the position
so it's always going to be off on the client, by a certain degree.
the other option would be to not do physics on the client, only the server, and just send the positions to the client each tick, but then you have input lag
regardless, I think I found a raycast wheel script on github that might work
Not sure you are trying to avoid things, that will happen anyway. But I am interested in seeing your solution. Its just my 2 cents, that syncing with server will always have latency and thats why some games smooth it out with an average of local and online and input lag is also just a common thing of multiplayer, if your server corrects the position, because the players movement is not in sync, it will feel like that exactly the same. Curious about your raycast script tho, can you share it? @wraith junco
This looks promising, however the wheels just fall through the map the second they touch the ground
so that's a problem
not sure if I don't just have the right settings or something, maybe someone else can give it a shot while I'm sleeping and let me know what needs to be done
could be that it's pretty old
Oh ye, 2016
I got raycasts working and everything, it's just I need a way to keep the car from gliding around sideways
I don't really understand friction or how to translate it into a computer, so hoping someone in here can help me
that github I linked actually might work. For some reason it was trying to force rigidbodies on the wheels, which was odd
removed that part of code and it seemingly works
still don't understand friction though, I just wish there were more simple examples of this type of wheel stuff
Btw, wheel collider is basically doing the same as your custom wheel raycast script, using one raycast to check for ground and stuff. https://forum.unity.com/threads/simulating-a-wheelcolliders-suspension-w-out-using-wheelcolliders-multiplayer-vehicles.479678/
Hi, there is a problem where when I shot a bullet, sometimes OnTriggerEnter does not detects a collision. Sometimes when I stand still and shoot it detects every single shot, but when I move my camera a little bit, or move player it does not detects collision. Is there any fix?
post ur coded
lol sorry no one got to this and I have to answer 12 hours later
how are you moving the object
what are the properties of the collider and the object it's supposed to collide with (floor?)
controller.Move
sry i was doing something im not sure what u mean by this
I mean you haven't shared any information about how your objects are set up other than that video
like:
- What components are on the objects and how are those components configured
thats the level
the entire level is one single mesh i made in blender
this is the player
all of the collapsed things arent relevant
You need a rigidbody to have collision
thats included in the character controller
Oh it's a giant blender mesh?
🤔
all kinds of things could go wrong with that
that particular section of floor might not actually be solid
Does the wall have any depth to it? Or it's paper thin?
Which way are the vertices for those triangles oriented? inwards or outwards?
its a plane
but ive never had issues with this before
honestly the normals are all over the place and i wasnt sure how to fix it
so i just ignored it and turned off culling in my shader
my level is a maze so i need the planes to be 2 sided
as you see - you will run into more problems than just rendering when you have walls that are just planes
you need geometry on both sides of the walls
sure
There's probably a way to do that and make actual solid, two-sided walls
but I'm not enough of a Blender expert to know how
maybe ask in #🔀┃art-asset-workflow
i cleaned up the mesh but still used planes (i just kept going from the vid i sent) and it works now
so thats nice
How to solve this, this is happen when the player collapse with some object or try to do jump
are you objects far away from the world origin? (0, 0, 0)
I bet you got a NaN or Infinity into a transform position
via some divide by zero or LookAt operation that looks at Vector.zero or something
I won't go over how multiplayer works, but when data comes in from the server, you need to be able to directly modify the friction, spring values etc to match the server
can't do that with unity/physx wheels
Id say you get the position from other cars and unity physix doing the rest locally
the client has to be in sync with the server
so it has to keep updating values and re-simulating the car on the clientside to be in sync
basically every time a tick comes in, server gives the client his position, etc and basically all of the car info if that's what you're doing
client has to go back to that point in time, set the position, velocity, spring data, friction data, etc, and then replay all of the movements until he's back at the present again
since the client is ahead of the server for my matter.
but yeah I would love to use the built-in wheel colliders but unfortunately cannot because of that
nope
might be what Praetor said then
I dont really get it. I just testing movement using rb.velocity
no errors at all?
the only errors is when I already run the game adn did the jump or collapse to some object I put on the stage
what are the errors? you should probably fix those before anything else
Hi. I made a Raycast to check if player can go to a position but if the player goes to some points, He can pass the collider and go to the other side. i tried multiple types of castings but none of them works.
That sounds like more than one issue here. So what is the desired behaviour you want? Does the raycast miss the collision check or is your player just travelling through walls?
How does AddExplosionForce force decrease with distance? Is it linear?
The explosion is modelled as a sphere with a certain centre position and radius in world space; normally, anything outside the sphere is not affected by the explosion and the force decreases in proportion to distance from the centre.
Trying to make an explosion damage script and I wanted it to behave similarly to the explosion force
so if the distance is equal to half the range, it's half the force?
Sounds like, its a quote from https://docs.unity3d.com/ScriptReference/Rigidbody.AddExplosionForce.html
the collision is calculated good most of the times. but some times when the player is going to some sharp edges he can pass the collider somehow
Then the raycast might start behind the wall? Or maybe you are moving the player in the wrong place inside your code, before physics happen or you might transform.position move the player instead of velocity, a lot of things that could be
the player is moving to the right place. but he is standing like half in one side of the collider and half in the wrong side. I tried to use offset but it didn't work.
How are you moving it? @inner carbon
i'm working with client and server. the problem is with how the server is calculating. every time the player needs to move, the server puts the simulated player in the position he needs to check the collision from. and returning to the player if he can go there or not.
you can think about it like every time the player is in a new place and he needs to check collisions from his place to the point he wants to go (mouse position). if there is no collider in the way, the player can go.
But you are moving the player himself without actual collision checks, right? You are just using the raycast without any volume on the player?
yes.
So you need to add your volume of the player to the collision check of your raycast or the positioning, otherwise, you just set the player position at the point where the raycasts hit and therefore your player would be half way inside any collider
Thanks. I'll check about it. And why can't I just put the player in the place minus some pixels and get the same result?
Well if you know how the collider looks like, you might be able to calculate it, but if its for example a corner, you have two edges touching the player for example. You could try to move the player at the point, check if it collides with unity physics engine and then offset it depending on your colliders, but thats some math you gotta do there.
Hello guys, i am wondering if there's a way to make a 2dBox collider (or colliders rather) change in size and position per Animation sequence? example : my character throws a kick, his hurtbox (a bunch of 2d box colliders) changes the form according to the animation, if there is a way to do that can you please be kind and share that with me, or at least help guide in the right direction, i thank you in advance
hmmm... yeah. Thanks for helping!
how is this done
please
how to make the collider's shape change with input/event conditions
You can maybe change it with animation. so when the kick animation happens, the collider will be fitted the sprite
i mean i already created the animation for an attack
and i want a transition from the "idle" animation's collider
to "attack" animation collider
and i kinda have no idea how to accomplish that
actually! i have NO idle animation collider
i have a player object collider
and idle animation happens to be the entry animation in my case
how to I counteract current velocity to force a particle into a destination location? So it all particle burst when spawed. I then apply a change of velocity towards a target but that will overshoot in most cases.
directinoToTarget = (Target.position-particle.position).normalized;
particle.velocity = particle.velocity + directinoToTarget * Time.deltaTime * 15f;
Is the direction absolute or relative to the velocity of each particle?
its relative to the velocity of each particle
And you want to add the velocity to it?
I want to make it fly towards player and actually "hit" player
This line will add up the velocity by itself every frame
particle.velocity = particle.velocity + directinoToTarget * Time.deltaTime * 15f;
this line
I am sort of trying to apply force, but that doesnt seem possible 🙂
Did you try to use AddForce?
doesn't exist for particles afaik
Oh right, no rb there. So you want to let the particles fly to the player, so the destination is the same for ever yparticle you affect?
exactly
when they spawn the burst outwards in a circle
then should start turning and then rush towards the same destination
this is what happens now, trying to take a screenshot at the correct time 🙂
this shows the inital spawn
I would stop using velocity as soon as you want to take that affect place and just move them smoothly with script of bezier and slerp
feed the first bezier point with the velocity of your particle and the second being the player as target
yes
just take out the right parts and you get your bezier curve ready, ignore the drawlines if you dont need them , just for developing it
Ill see what I can do, thank you (might need those lines as well just to know what is going on:D )
yeah not wrong to use them, but as long as you set the first bezier somehow to the velocity, it will look smoothly translating to the destination 🙂
had to take a brake from this but had a thought, will this work if the object moves while the particle has begun moving?
As long as you feed the direction to it, it should work, yes. Just try it out 🙂
recreating the curve at each update?
yep, and then just lerp the position to the next updated one on the curve from 0 - 100 length along the curve
if a plane is described by its normal (n) and the coordinates of a point (p) on the plane, how can i find the closest distance (d) from a point outside the plane (e)?
That question does not make sense to me, distance from e to where? p?
the closest distance to the plane from e
the plane is described by a normal and some point that lies on the plane
i want to find the closest distance from e to the plane which is the distance d
then you take e, shoot a ray down the normal vector of your plane by also checking if the max and min vertices of your plane are inside that rayshot range, if not, adapt the vector to at least hit the planes farthest vertices
phew, good luck with that, but you are in physics here 😉 Might be a better #archived-shaders question I guess. tbh, I think you need to calculate the distance outside of the shader and then pass it in as a value you need in there
no i just need the equation
there is an equation to find the closest distance from a point to a plane for a plane described by its normal and distance from origin
but i need one that works with the normal and a point on a plane
no the plane is infinite
3d
Was wondering if I could get some help with trying to get a circlecast detection working for a Homing Attack system For unity. I can get the targets properly but I'm struggling to filter out walls and plat forms. This is what I have
{
RaycastHit2D hit = Physics2D.CircleCast(targetPoint.position, 3f, transform.right, 10f);
if (hit.collider != null && hit.collider.gameObject.tag == "Enemy")
{
distance = Vector3.Distance(transform.position, hit.transform.position);
if (closestObejct != null)
{
float currentDist = Vector3.Distance(closestObejct.position, hit.transform.position);
if (currentDist > distance)
{
if (closestObejct.Find("Target(Clone)").gameObject != null)
Destroy(closestObejct.Find("Target(Clone)").gameObject);
gcs.currentTarget = hit.transform.gameObject;
closestObejct = hit.transform;
}
}
if (closestObejct == null)
{
closestObejct = hit.transform;
gcs.currentTarget = hit.transform.gameObject;
}
}
}
Does anyone know how to make the player move up the slope normally? So like the surface is touching the slope and not the edge.
Heres an example
can you use layermask to filter?
20 bucks???
You want people to offer you their hard work for free? Make your own if you think the amount of time you'd spend trying to figure out is less than $20. My guess is, it isn't.
Well, could have a look online for tutorials on how to achieve it.
ok
Unity 2D soft body tutorial using rigged sprites, rigidbodies and spring joints. Here I demonstrate how you can create a 2d soft body shapes and use it for your awesome projects. Can be used for Jelly simulation, car tyres, liuid blobs, goo you name it!
Download project: https://drive.google.com/file/d/1RbXJUETBJGwlLFV9Rmnz2AiXLKl7wrgp/view?us...
dunno about performence though but looks freaking awesome
Use raycasting it has a normal function which you can assign your z axis to
is there some formula i can follow to figure out how fast i can move projectiles without having collision issues? i have a bullet that was 120 speed and having issues regardless what i set the rigidbody to. i lowered it to 50 and it works fine now. i dont want to have to keep testing each value though. my fixed timestep is currently set to 0.01111111
Should just be d = |e.n - p.n| (assuming n is normalised).
yeah: if the distance your projectile will move per fixed update is greater than the width of the obstacle minus the length of your moving object along the direction of travel, you will have problems
Hey folks, math question here. Since we don't have a dedicated math section I figured this channel might be most relevant.
https://stackoverflow.com/questions/68108170/how-to-scale-matrix4x4-around-point
#archived-code-general is probably more relevant? don't think many people are using linear algebra here
I tried there a bit back but it gets flooded out within minutes and I expect more people familiar with linear algebra here than there.
Ok thnx
https://i.imgur.com/01HmHsS.gif why can i just exist inside a rigidbody
screenshoting from beginner help now that i realise this is a better place to get help
try setting the player to continous dynamic and the pole to continous
are their collision layers set correctly?
If I make a bunch of stuff a child of a single gameobject, and then rotate that object's transform around X, will the gravity within all those objects rotate too (ie staying relative to the root GO's "down")?
If you rotate with transform.rotation you will just "beam" it to new positions, ignoring physics. If you add a velocity/force to it, it might affect the child ones
Thanks. I just want to rotate a game board to look up a bit, but I want gravity to suck all the child objects to the board. Is that doable?
how do i add bigger hitboxes for this one? i want to be able to hit it even with a slightly bigger because sometimes the hits don't register regarding its animation
You might want to use smaller colliders and combine them into one to get collisions for hitting stuff and then just have one big one for the surroundings to work with the animations extend, but tbh, even best games have some clipping sometimes. Another approach would be to use IK and or FK to drive the animation dynamically, but thast another story
In your capsule collider component, you can edit your collider size
oh i forgot you can add that
Hi everyone! I'm having an issue with a boat .io game where it tips over after being driven around. I tried to make it have a very low center of gravity but that didn't seem to fix the problem. I'd appreciate any help on trying to fix this! Thanks! (PS. Please ping me when you respond so I see it)
There's the "angular drag" setting for rigidbodies which would dampen rotation
I used a stabilizing script to just keep an object upright like this
void StabilizeTorque()
{
Quaternion deltaQuat = Quaternion.FromToRotation(rb.transform.up, Vector3.up);
Vector3 axis;
float angle;
deltaQuat.ToAngleAxis(out angle, out axis);
rb.AddTorque(-rb.angularVelocity * dampenFactor, ForceMode.Acceleration);
rb.AddTorque(axis.normalized * angle * adjustFactor, ForceMode.Acceleration);
}
wdym
everything is activated
if i dont go so fastr it collides
and if the mass is low enough i go through the object but then it realised i collided and then moves
settings
hrm, not sure why the continous setting isn't helping then
Hey. Anyone know the best way to out a 2d trigger collider on a 3d player? I dont want it to rotate with the player.
Hard to imagine the best way without knowing your system
Ive got a third person controller on the player, but obviously it rotate, so I'm wondering if I should just have a seperate object that references the players 2d position
Assuming your player is moving in 3D space, attaching a 2D collider to it is prone to causing weirdness
Yeah...i ve definitly experienced that. capsule collider2d seems to be a line
You could set the position of the collider to player's position, or make it a child and set its rotation to neutral every frame
But mixing 2D and 3D physics is really not going to work out
Yes. You are right
I should use a 2d controller
is there a good standard one somewhere?
nvm im sure my package manager has some
so im doin a zipline thing, but i want it to work in either direction...i'm thinking, a mesh with a rig thats kinematic on it, and a mesh collider, and like, an existing block with a spring joint on it attached to this, but that will be invisible without renderers. and when i approach said cable, at any point and try to interact, ill just snap my invisible slidey (hook? not sure what to call it but my GO that slides along it's long axis) snap into my players hands position and then connect a config joint from hand to slidey thing onit. Am i approaching this with a good mindset here? is there a more performant way? also, is this something that dot tween is especially suited towards, i've never used it but i do have it
Use rsycast between previous and current position . At least that is what I use for my very fast moving bullets
I'm a bit of a noobie, do you have any examples of code doing that I can see? Or what it would look like roughly
void Shoot()
{
Ray ray = cam.ViewportPointToRay(new Vector3(0.5f, 0.5f));
ray.origin = cam.transform.position;
if (Physics.Raycast(ray, out RaycastHit hit))
{
hit.collider.gameObject.GetComponent<IDamageable>()?.TakeDamage(((GunInfo)itemInfo).damage);
PV.RPC("RPC_Shoot", RpcTarget.All, hit.point, hit.normal);
}
}
[PunRPC]
void RPC_Shoot(Vector3 hitPosition, Vector3 hitNormal)
{
Collider[] colliders = Physics.OverlapSphere(hitPosition, 0.3f);
if (colliders.Length != 0)
{
GameObject bulletImpactObj = Instantiate(bulletImpactPrefab, hitPosition + hitNormal * 0.001f, Quaternion.LookRotation(hitNormal, Vector3.up) * bulletImpactPrefab.transform.rotation);
Destroy(bulletImpactObj, 10f);
bulletImpactObj.transform.SetParent(colliders[0].transform);
}
}```
thats networked with photon, but, the raycast theories is all there
https://www.programmersought.com/article/23974992156/
Explains it I believe. Dont have access to my code atm
Unity-object speed is too fast to detect collision, Programmer Sought, the best programmer technical posts sharing site.
Thanks
Hello everyone! ✋ Here's an interesting case we've been facing these days:
We are trying to cut down the velocity towards the walls when the character is close to the walls to make the movement easier on such maps. We check in which joystick direction is closer and set the velocity to that direction.
It is working as intended expect on the wall edges. A little glitch happens whenever the character follows an "L" shape towards the walls. You may find the related code part and a visual representation below. All helps and suggestions are appreciated and thank you in advance! @wooden tangle
private void OnCollisionStay(Collision other)
{
if (other.gameObject.CompareTag("Wall") && _joystickMoveVector.sqrMagnitude > 0.01f )
{
Vector3 left = Vector3.Cross(transform.forward, Vector3.up);
Vector3 right = Vector3.Cross(transform.forward, -Vector3.up);
Vector3 parallelVector = Vector3.Cross(other.contacts[0].normal, Vector3.up);
float angle = Vector3.SignedAngle(parallelVector, _joystickMoveVector, Vector3.up);
if (angle > -90 && angle < 0) // ccw
{
if (!Physics.Raycast(transform.position + Vector3.up / 2f, right, out RaycastHit _, 0.75f, _layerMask))
{
_moveVector = parallelVector.normalized;
}
else
{
_moveVector = Vector3.zero;
}
_moveVectorOverridden = true;
}
else if (angle < -90) // cw
{
if (!Physics.Raycast(transform.position + Vector3.up / 2f, left, out RaycastHit _, 0.75f, _layerMask))
{
_moveVector = -parallelVector.normalized;
}
else
{
_moveVector = Vector3.zero;
}
_moveVectorOverridden = true;
}
else
{
_moveVectorOverridden = false;
}
}
else
{
_moveVectorOverridden = false;
}
}```
Can you explain the issue a bit more? Hard to tell what's going wrong from the video and description you gave
At this very point the character makes a full right turn (90 degrees) and then corrects its rotation. We're trying to achieve a smooth turn
Assuming your character's collider is circular, perhaps you want to create parallelvector using the delta between the contact point and the character position instead of the surface normal?
Did you consider rotating the camera instead ?
Giving it a try, thank you for the suggestion!
Greetings, i have a game items that i need to place around the world, their origin is not on the bottom of the item.
What i simply want is a "fall to ground" option or button. Clicking this will make a collider fall to hit another collider and sit ontop of it.
I had this back in the oblivion creation engine editor. It's just to place items.
I'm not sure if this counts as physics or not, but its largely about just a box collider needing to check where floor is.
There's an asset, physics place in editor or something
ok thanks
Somethings wrong with my ragdoll rig. It gets stuck in place when i attempt to move it. Does anyone know what to do to fix this?
nevermind i fixed the issue B)
I’ve got a skybox and scenery that I want to stay level. Anyway I just need to Google this, it must be possible.
Updated:
I have a question about rigid bodies in 2D. I discovered that 2 kinematic bodies cant collide with each other but how can i make bullet rigid body that should be kinematic and an enemy that will move freely up and down left and right using rigid body velocity?
Kinematic and dynamic can collide but I want to have full control over the movement
This is probably a stupid question but still
This is really helpful thank you! Also quick question about the addforce / addtorque functions, Are they meant to be run every frame? Just once? and in what method? I've just been a little confused about them recently. Same with Time.deltaTime haha
Depends which force mode you use
ForceMode.Impulse and ForceMode.VelocityChange are generally meant to be "one-off" forces
ForceMode.Force and ForceMode.Acceleration are generally meant to be "once-per fixedUpdate"
The latter two implicitly multiply the force you pass in by Time.fixedDeltaTime
the former two do not
Check out the matrices at the bottom of this page: https://docs.unity3d.com/Manual/CollidersOverview.html
they explain exactly what will and will not cause OnTriggerEnter and OnCollisionEnter messages
gn
i want to get consistently the last position of some moving object, but sometimes, when colliding, my the last position register as if it went through the collided object for some instant
pic of issue (check transform position and Player component last position)
this happens very randomly, sometimes it works
the rules are the same for 2D
You are likely moving your object in a non-physics-friendly way, such as transform.Translate or transform.position =
by doing so, you're bypassing the physics engine and it means objects will freely pass into each other until the physics engine catches up and depenetrates them
im using rigidBody.velocity = new Vector3(direction.x,0f,direction.y)*speed;
in FixedUpdate
ahhh ok my life makes sence now thank u
All physics alterations should go into FixedUpdate
You can use any of them every frame, but the functions that set forces or velocity to some value, rather than add or subtract them might yield unrealistic results if used continuously. Unrealistic isn't necessarily bad though. Refer to documentation for more info
Time.deltaTime is simply the time since last frame. As Update() can run any number of times in a second depending on framerate, multiplying by deltaTime allows you to get consistent change over time.
FixedUpdate() runs always a specific number of times per second, so you don't need to multiply by Time.deltaTime.
Time.fixedDeltaTime is that specific interval. It's always the same value as defined in project settings, so you don't need to multiply by it
(Unless it's changed or my memory is wrong) Physics functions that affect the rigidbody don't run until the next physics step anyways, so there's almost 0 point in using them outside of FixedUpdate() unless you want to queue something up like with input. From the docs:
Applied Force is calculated in FixedUpdate or by explicitly calling the Physics.Simulate method
why my sphere got blocked when I give sphere collider as istrigger collider to the enemy
Solved I used navmesh to control my character and seems like the ray hit the collider
Hey everyone! Quick update on our previous post:
When we draw rays in the direction of collider contact point, normals around box collider corners are a bit tilted compared to the normals on surface.
We want our character to walk parallel to the walls. We are currently calculating a perpendicular vector the these normals and have our character move in that direction.
Since the normals are a bit tilted, character also tilts a little bit when crossing each piece of wall as you can see in the following video.
Ps: Character has a capsule collider. Walls have box collider, and they dont have space between them. We don't want to merge all walls and have one big collider.
All helps and suggestions are appreciated and thank you in advance!
Here you can see the normals drawn by unity in red
How can I make something like this?
is there any material or reference I can refer to?
Like a force directed graph? Try this https://towardsdatascience.com/3d-force-directed-graphs-with-unity-587ad8f7dff
Perfect! Thanks alot
when I use tiles with box colliders that are snapped together, I end up bouncing between tiles, but on a single collider it's fine .Anyone faced this before ?
oh yeah
this is an ooooold problem
Cries in Unity 2018.3 cus Unity hub refuses to work
I've never found that these settings work perfectly though
I wionder if the new contacts modification API might be able to help with it though
Ah here's the super old thread I remember
Is this prevalent in Unity 2019 and above as well ?
What would you do if needed multiple tiles in a floor though ? XD
the high tech way would be to programmatically merge the colliders somehow
Lol just take a look at the 4th previous message 😄
I bet you can hack something together with this though https://forum.unity.com/threads/experimental-contacts-modification-api.924809/
brrrrrruuuuuuh
Just set the "Default contact offset" to a really low number from Physics settings
While changing the number it gets set to 0 momentarily so don't mind the warning
if you are having specific problems with your approach, feel free to ask for help.
I have this line: closestPoint = (transform.position - movementPoints[i].position).sqrMagnitude; but how do I get the co-ords of the closestPoint?
The coords are movementPoints[i].position if I'm undersanding your code correctly. So when you find a new closest point, just save the current value of i, or the position, then you can retrieve it later.
You should use a separate variable to store it
closestPoint = (transform.position - movementPoints[i].position).sqrMagnitude;
closestPosition = movementPoints[i].position;```
or yeah - i
i is a bit better in that you can get the Transform itself with i
but if it's in a for loop will it not get overwritten every time?
or maybe it will get overwritten anyway witht he closest as it goes
for (int i = 0; i < movementPoints.Count; i++)
{
closestPoint = (transform.position - movementPoints[i].position).sqrMagnitude;
print(closestPoint);
}```
Yes it would
So you want to actually store in the "closest" only if: current magnitude < previous stored closest
var closestPoint = null;
for (int i = 0; i < movementPoints.Count; i++)
{
current = (transform.position - movementPoints[i].position).sqrMagnitude;
if (current < closestPoint) closestPoint = current;
print(closestPoint);
}
// use closestPoint
``` smthg like that
how did I end up in this channel
random said earlier you only need that current < closestDistance closestPoint = current; thing if you are checking if it's within a certain distance rather than just seeing whichever is closest
BUt how would you know which one is closest if you don't compare ?
THe idea is that you iterate every pos with your for loop
closestPoint = (transform.position - movementPoints[i].position).sqrMagnitude; was to find which is closest i thought o-O
each time checking if your closer than previous one. At the end, you get the closest
(because you assign only if closer)
Nope, it's literaly the squared distance between two points
you don't know if it is smaller or greater than previous or next one
thus the capture variable closestPoint
to help you keep track of the best one you found until you reach the end
oh you're right, that's just to get the distance not check if its close
yup 👌
is doing var closestPoint = null; okay?
like i thoughjt you weren't supposed to do something = null
I would rather initiate it with smthg like float.MaxValue for a distance
for a pos i dont know, yeah null looks okay to me
naaah i'm being dumb, this won't pass the first check haha
loll
if (current < closestPoint || null == closestPoint) closestPoint = current;
here you go 😛
you get the idea
I appreciate the help thankyou im gonna try it out
You're welcome, happy coding
not sure happy is the word :p
You need to embrace the challenge, you'll be proud in the end 😉
😛 truee
hi, i don't know if there is a known solution for this situation but: i have a projectile moving in a direction and i check for collisions using Phyisics.SphereCast. But if another object is moving in the opposite direction, they will miss each other sometimes cause the other object moves faster than the projectile and is never in the middle of a spherecast. Any ideas on how to go about solving this situation? thanks
damn that's a tough one
how many such projectiles will you have in the scene at a time?
I can think of a few solutions but they wouldn't necessarily be performant
from 0 to 50 i would say
they definitely need to collide with each other?
not the projectiles
but for simplicity, let's say there is a character and a projectile
that are moving towards one another
oh there's other moving objects the projectiles need to hit, gotcha
so are you not using RIgidbodies at all?
mmm not right now.
but mostly cause i use navmesh and i don't want my characters to collide
but i guess i can make them collide only with projectiles.
yes - you can give your navmesh agents kinematic rigidbodies
after i posted the questions i made it work with kinematic rigidbodies
yeah exaclty
👍
np
i really don't understand why this is happening.
i have an FPS controller and for some reason it just falls off the map after 251 units?
it just goes through the box collider of the floor
i initially thought it was maybe because of velocity (sometimes my controller falls off the map because of speed)
but i moved it within the editor and it's the same issue
this is on any scene
i've switched from a probuilder cube to a default unity cube and it's got the same problem
Heya, would anyone be able to help me with Raycast detection? Been asking some questions about it over various places including here but I'm stuck
I'm using a Circle cast to try and detect enemies ahead but feel like the implementation isn't right as when I have the filter on it does only detect Enemies but leaves me with the issue that I can detect them through walls which is not what I want.
Removing the Filter allows for other stuff to be detected but due to that it means it messes with detecting the Enemies as it detects everything else too and will not go on to the enemy like I want it to. It will see the Enemy for a second but then focus on another object
Here is my current code:
{
RaycastHit2D hit = Physics2D.CircleCast(targetPoint.position, 3f, -transform.right, 10f);
if (hit.collider != null && hit.transform.gameObject.layer == whatIsEnemy)
{
Debug.Log(hit.collider.name);
/* distance = Vector3.Distance(transform.position, hit.transform.position);
if (closestObejct != null)
{
float currentDist = Vector3.Distance(closestObejct.position, hit.transform.position);
if (currentDist > distance)
{
if (closestObejct.Find("Target(Clone)").gameObject != null)
Destroy(closestObejct.Find("Target(Clone)").gameObject);
gcs.currentTarget = hit.transform.gameObject;
closestObejct = hit.transform;
}
}
if (closestObejct == null)
{
closestObejct = hit.transform;
gcs.currentTarget = hit.transform.gameObject;
}*/
}
else if (hit.collider != null && hit.transform.gameObject.layer != whatIsEnemy)
{
Debug.Log("No target");
}
}```
Can Overlap detect triggers?
Yes, if you define it in the last parameter of the overlap call.
Ok.
Why dont you also add walls to the filter, then just check if the object you're hitting is an enemy?
I'll try in a sec, but I can't help but feel ill get the same result
It's detecting the Enemy but it's still through the wall
Doesn't even trigger this else if (hit.collider != null && hit.collider.tag != "Enemy") { Debug.Log("No target"); }
do the walls have colliders and are they on the same layer as enemies?
I added them to the whatIsEnemy LayerMask Variable I have
RaycastHit2D hit = Physics2D.CircleCast(targetPoint.position, 3f, -transform.right, 10f, whatIsEnemy);
Scratch that just saw that in the screenshot lmao
lol
Well it sort of a works, seeing that it works depending on whats in the CircleCast first
Hmm or not. Soon as I moved the wall it keeps on the Enemy. I'll add another check
That's kind of annyoying, the wall has to be completely out of the Ray before it can find the enemy
what did you want it to do instead?
Set the player to static so I can keep him in the air for my trigger
you can use the other version of Circlecast that returns an array of colliders
Basically when I jump I want it to target the closest enemy within a set range/view of the player. It's so I can do a Homing Attack similar to sonic stuff. So meaning if I jump it will see that wall and remove that target
then check if one of the colliders is an enemy
it would cause your earlier issue though, since your player would be able to see through walls
currently your circlecast returns the first thing it hits
which is why you're having this issue
Right, I know I used CircleCastAll based on a suggestion from some else before but I'm not sure how well it would work. I got the base system working with that and been messing about trying to get another implementation since
Just trying to figure out how to get it so it will target when the enemy isn't hidden behind the wall
Which makes sense given why it keeps saying "No Target" when it's over the wall and the enemy
getting 2d poses translated to 3d isn't trivial, also this might belong more in #🏃┃animation
still don't see how its #⚛️┃physics related... did you mean #archived-machine-learning ?
what exactly are you trying to do right now? EasyMotionRecorder is 3D, so you are going from 3D -> 2D -> 3D again?
are you trying to train your own NN or what?
you probably should ask #🏃┃animation at this point
How should I modify PhysX collisions to make them sticky?
toyed with some stuff but I cant seem to get it right...
essentially I want colliders to stick together with some variable amount of force at their contact points....
inverting the normals turns colliders into black-holes, which is funny
not super useful though....
I cant seem to get it right with velocity....
@lapis plaza Hey sorry to bother you, but would you have any idea how to trick the collision system into performing collisions that "stick"? I feel like there should be a fairly simple way, but I can't quite make it work well... Nvidia even teases sticky collisions through contact modification, but never says how!
inverting the normals, and using an internal shape to keep the objects from fully penetrating, very nearly works
my objective here is to make sticky, but not absolutely constrained, finger physics for joint based VR hands
should I assume this will only ever work well with sphere on sphere colliders?
I guess you might have to fiddle around with joints that dynamically change their position based on the collision hit point @mighty sluice
Thanks for the suggestion, but I'm actually already using that as a standard grabbing system. For this I am looking for a lighter and more dynamic sticky finger mechanic
I really like configurable joints so i dont fear them, but for friction across16 colliders per hand would get extreme
Okay wait, whats the problem you are having right now? 😄 from the clip it looks not that bad
it's just not reliable enough to be used on fingers
it tends to send the collider in strange directions and doesn't apply friction right
Oh so you want like all fingers to affect that collider of boxes for example?
i need the solver to force the rigidbodies to come to rest at the collision point, but right now im just ham fisting them at eachother
precisely
Phew, thats something hard to do considering all unity physics querks and stuff. could you do a convex collider dynamically created by the fingers?
i have a hand made from joints so each finger has 3 rigidbodies
possibly yea, but the goal is to allow for robust digit-object manipulation
this contact system is meant to give the fingers more gripping power
like light adhesion
I can already articulate the hand pretty nicely, the issue is just the collisions and friction
on the right is the 3 fingered hand im testing with
I have also had a similarish problem with my physics agents not having enough gripping power, or cases where i want their feet to be outright sticky
using joints for these cases is sort of nightmarish, although barely feasible
Out of my scope I guess, sorry if I cant help more here
i need to look into exactly how unity generates collision normals (for contact points)...
it's quite alright. not many people ever need to get this deep into the engine... 0lento is basically the only person I know of that I expect to have insights lol
yeah, its quite special, but I am looking forward seeing your progress. Are you using VR controllers ore magic leap or quest built in hand tracking? Just curious
I am using quest controllers at the moment but there's nothing stopping me from making full blown physics hands like nobody has seen before lol
I just need to get the hand tracking working in unity without resorting to the oculus integration API
Already have a ton of neat functionality. Might as well show it here given it's all low level physics
this is gliding (with a booster), or falling with style....
it's using some primitive aerodynamics on the hands for glide control, and a full blown radial playspace which is pretty interesting
(the spherical playspace requires custom gravity, which is fairly trivial)
the hands are simply joints attatched to the main body, which is rotationally constrained but not kinematic
Dang I would love to fly around with that controls
the low level physics also allows for all manner of physics-y stuff integrated directly into the player
some primitive grapples...
flappy bird was fun (a precursor to gliding) https://i.imgur.com/YBHJsSv.mp4
this system uses runtime joint creation for hand grip https://i.imgur.com/Lev1GDL.mp4
also for holding objects like swords...
the mobility is extreme
and of course, this full blown physics VR controller was made almost entirely for the purpose of interacting with these things https://i.imgur.com/4lD9Y8G.mp4
physics based robot-like machine learning agents
each centipede is over 100 joints, and there's not a kinematic body in sight, which is just nuts
in a nut shell: physics