#⚛️┃physics
1 messages · Page 24 of 1
and apply it each time the object reaches this point again
Due to the fixed timestep of the physics simulation you likely won't have a frame when it's exactly at the bottom point
yes i know this
To do something similar you would do:
float differenceFromDown = Vector3.Angle(transform.forward, Vector3.up);
if (differenceFromDown < someThreshold) {
// it's close to straight down
}```
yeah how to make this threshold
just a constant
or defined in the inspector
it's an angle in degrees
we're saying like "if the angle is within 5 degrees of straight down" for example
and insert whatever number you want there
The whole approach is a little sketchy because depending on your fixed timestep and the max speed this thing swings, it's possible to skiup that whole window if it's too small.
But if it's too big you'll record the velocity at too large a difference from straight down
honestly... if this is suppsoed to be a swinging obstacle for the player to run past, I think it would probably be better to just use an AnimationCurve for this
you're close - but player should catch the moment and stop this thing to reach another platform
somethjing like:
public AnimationCurve curve;
float timer = 0;
float animationDuration = 5f; // seconds
void FixedUpdate() {
timer += Time.deltaTime;
timer %= animationDuration;
float t = timer / animationDuration;
float evaluatedRotation = curve.Evaluate(t);
rb.MoveRotation(Quaternion.Euler(evaluatedRotation, -90, 90));
}```
ah so it can't be kinematic?
i'm not sure what kinematic does
turns it into an unstoppable force that you can move via script but isn't affected by forces or normal physics in any way.
you would do that to use an animated version like my code example above
ok, well i see it is too complicated to make so i know - i'll use animator instead
animator would be the same
i mean i'll just make an animation for it
but what do you mean it would be the same?
it would be the same as doing a code based animation like I had above
in terms of not being aable to interact with it - i.e. stop it
i can add parameter to it, make animation speed to depend on this parameter and set it to zero to stop
@timid dove thank you for all of this
I had to solve a similar problem to this recently and what I found was that I needed to add a 'lateral-only' friction. If you get the dot product of the object's velocity and it's right direction, this will tell you how much of it's velocity is in it's right direction (conversely it will be negative if it's in it's left direction). If you then add a force to the object in it's left direction multiplied by the dot product you just calculated, this will immediately stop it from moving laterally but keep it moving in it's forward direction. If you clamp the amount of force you add then it will stop it moving laterally gradually, which is a more natural friction effect.
void Counteract()
{
Vector3 facing = transform.up; // direction that the body is facing
Vector3 heading = RBody.linearVelocity; // the actual direction of the velocity
Vector3 alignedVelocity = Vector3.Dot(heading, facing) * facing;
Vector3 lateralVelocity = heading - alignedVelocity;
lateralVelocity *= Mass;
lateralVelocity *= -1;
RBody.AddForce(lateralVelocity, ForceMode2D.Force);
}```
I will have to do some slight tweaks once the rotation becomes very close to where it's meant to, as it gets to an angle of something like 89.998
Success!
hey, so i have an object 1 and object 2, they are on top of each other, on object 1 i have oncollisionenter and exit. but when i destroy object 2 the object one doesnt trigger the oncollision exit function. how do i fix this please?
Whatever you were going to do when on collision exit ran, do it when you destroy the object.
I have a problem where this asset from unity stops in place while the walking animation is still playing, does anyone have any idea why this could be happening?, it seems to be in random places at random times he just gets stuck, I can show more parts of the code if it helps
Not a physics problem
yeah the thing is that the game is multiplayer and the other player can destroy the object and also the first object doesnt have to be on top of the second, it can just sometimes be there so this would be pretty much impossible
That's what the solution is. Change how your code works. There's no way to make OnCollisionExit get called in this circumstance
It's not clear why it should be impossible.
Nothing is impossible
yeah i mean im not going to change how the whole system works so i dont really know
I think you're overestimating the change you would need to make
i mean what i could do is check on the destroyed object before it getting destroyed if it is colliding with the first object and if it is then tell it to exit collision
but i dont know how i would check that
how do i check with if statement if an object is colliding?
You keep track of the objects it's colliding with in a variable
And see if that collection is empty
Usually not especially if multiple simultaneous collisions are possible (usually they are)
But you could start with that
Couldnt he be colliding with something? I'm still holding down the key, he just doesnt move
Just plays the animation
oh i didnt think of that
Let me test something
Sure, why not log something when you collide then
So that whenever the player's hitbox collides with another object's Box it sends out a message? But isnt he allways colliding with the floor
Is the floor one single object or made of many objects
What's the collider situation here
You gave no details
Oh yea, it's a tilemap so it's 1 singular tilemap collider 2D
Could the issue be related to these wall sensors aswell?
It's weird because the places and times he gets stuck are completely random
Are you using CompositeCollider2D?
You need that to merge the tilemap collider into a single contiguous surface
I dont think so, I just made the tilemap and attached the collider
I'll try using that do I need an asset?
But what does that do exactly?
But it also seems to give it physics like gravity
No, it's just a Collider
Since it needs a rigidbody or something
You're confusing it with Rigidbody2D
Yea but I need a rigidbody to have the composite collider
How do I make it not have physics?
Then just add one and make it static
Alr let me see
You need to check the "used by composite" box on the tilemap collider as well
This should do it no?
Oh ok thanks
Alr done
Btw it doesnt have that option
Is it the effector?
Composite operation
Merge?
merge is fine
He doesnt seem to be getting stuck anymore so thanks for that, but now he's always falling? any idea why that could be happening
probably you need to double check the layers on your colliders
after we messed with them
so that your grounded check works properly
something along those lines
impossible to know without seeing the code really
Ok I'll try that thanks
Hey, I moved the ground censor to allign with the Collider of the player and now everything works perfectly so thanks a lot bro, have a good day
I'm working on a VR Game, and I cant seem to get the net to interact with physics, its a Basketball Net colliding with ball, im not sure what the code to get it doing like that is, but i need help
Hello! Trying to make An axe chop a tree when it comes into contact with it, but dont know exactly the best way to do that. I want to make it where the axe leaves a bigger and bigger mark (based on the axe collider itself), just like irl, but i could also make it a square object that might be much easier to implement
any advice on how its normally done? (want to do it myself if possible to learn)
the physics system can detect when the axe hits the wood, but actually deforming it is out of scope
you'd need to generate a new mesh with a chunk taken out of it
(or have many small mesh pieces you can remove)
like having the tree where it's possible to be chopped to be divided into small cubes like .01mx.01mx01m? that way would seem to hurt performance alot because of all the verticles and different objects
i know a easy way would be to just, like use the vertex deforming feature of probuilder, but you would have to also change the material of all the faces affected
maybe i just need to look more into how to build a mesh for this purpose.
so I was working on making my enemies to have a set path but the moment I turned is trigger the enemy goes down at an angle and just clips through the wall. The wall and enemy both have box collider 2d so I am just confused whys its not working when i ticked is trigger on the enemy
Hi, I'm trying to create a crowd simulation using navmesh agents but I want to speed up the simulation by 30x or 50x while still maintaining the same physics behaviour as it would be at 1x speed.
I tried increasing the timescale and decrease the fixedDeltatime by the same factor like this:
Time.timeScale = customTimeScale;
Time.fixedDeltaTime = Time.fixedDeltaTime / customTimeScale;
But then the agent's movements are stuttering and the physics doesn't work as expected as the agents pass through the colliders. Is there are way to achieve this? I'm looking for a Timelapse kind of effect.
to get the same behavior as 1x speed you would just modify Time.timeScale and nothing else
Yeah -- if you double the timescale, you get twice as many fixed update steps per real-world second
By dividing fixedDeltaTime, you're getting a crazy number of very small steps
I also happen to have a "timelapse" feature of sorts -- I use it to rapidly test the game
I don't mess with fixedDeltaTime there
I do mess with it for the in-game "slow motion" feature
that ensures that I always get 50 physics updates per real-world second
Will Unity ever allow us using AABB character controller volumes? It is on PhysX, not sure why they don't expose it:
Not that I'm aware of
Hello, is there any way of blocking the character in place when he falls because of the ragdoll? Because as you can see, the ragdoll tends to do anything and I'd like to avoid this kind of problem.
You mean keep his position? Or what?
You don’t want to run into it?
Yes, I want to keep this position, as if he were frozen in this position after he fell, I want him not to interfere with the other objects and elements in the scene, for example I want that if I shoot him once he's fallen to the ground, the bullets don't make him move, or that if I step on him, he doesn't move either.
Just turn off the rag doll?
And the physics components
Or put it on its own physics layer
How do you do THE weapon Reccoil?
I've made a shooting animation, and when the animation plays I've made my character turn I think 2 degrees upwards, so if you only shoot without controlling the recoil the effect isn't incredible, but when you try to control it a little it gives this effect that I find rather nice.
hello im enabling a boxcollider when i do something ingame, and then using the boxcollider in calculations to place objects
why does it take 2 seconds for the boxcollider to be enabled?
what makes you think it's taking 2 seconds for it to be enabled?
because when its enabled, i have a object placed as well to show its enabled, then using raycast on left click to place an object if the raycast hits the boxcollider
You'd have to show the exact code.
Note that physics stuff generally needs to wait for the next physics update to take effect
tried to debug on my own first, seems to be its not reconizing the collider for a bit after enabling it
well first off your code isn't actually checking if the Raycast hit anything properly
you should do cs if (Physics.Raycast(...)) { Debug.Log($"Hit {hit.collider.name}"); } else { Debug.Log("Hit nothing"); }
the only object with the tag "Plot" is the space i want people to be able to place in). Checking if the hit is invalid is the same as checking whether it hit a gameobject ( ground is on seperate layer, not default)
it can hit other objects beisdes the plot, but cannot hit the ground
It's best to actually check if there was a hit in the code though
i do
right now your Debug.Log line will throw an exception if there's no hit
yeah it is, that was a test debug
it's also more performant to just use the return value rather than doing a separate nullcheck
and you're not logging anything when there's no hit
alright, ill use the performance instead, as it is better performance, but both should have same outcome no? is that really whats causing the issue
So it's going to be hard to tell what's going on
I think you want to first put in reliable and meaningful logs to get a good grasp of what's actually hapenning before we conclude what's going wrong.
if nothing hits, the first debug log throws an exception.
there, redid the code, thought it wasnt anything that could change.
There's actually a hole in the logic there
it's possible you're hitting an object, but the object you hit doesn't have the Plot tag
huh?
And you will get the "null" log here
but that could very well be part of what's happening here
if (hit && Tag == Plot) {Place} otherwise {print null}
yes so in the otherwise part of that is also included that there IS a hit
but the tag is wrong
ok i did debug it, and it has to do with my camera's view being IN the collider when i enable it
but they do after going outside, and back in?
oh nvm, you right. I need to do a check some way to store when the player is inside, but preventing placing outside
so ill work on that, thank you for the help
Hello! I've been tryin to make a script that scans certain trajectories to find a trajectory that an object can be launched at to reach its target. I made this script by following this forum:
https://gamedev.stackexchange.com/questions/71392/how-do-i-determine-a-good-path-for-2d-artillery-projectiles
The problem I've been encountering is that the object's trajectory is a bit lower than the one I predicted, meaning that I've either calculated a formula wrong from this forum or there is something about unity's physics system that I haven't considered that has been slowing down the object:
Here is my script,
https://scriptbin.xyz/ayesebilap.cs
Are you sure it's a "lower trajectory" and not just the fact that those boxes have width and height and aren't dimensionless points?
It looks like just the side corners are hitting the edge there as one might expect
It looks like the botom center of the box is directly on the trajectory line
well, in this case the lower right corner of this box should be following this trajectory
but it's slightly lower
Looks like the bottom center is following it
double check where the pivot of the object is
The other thing is make sure your rigidbodies don't have drag or anything
Another problem is this:
for (float i = 0f; i < t; i += 0.01f)
// loop through positions of the trajectory
{
// Calculate current position
Vector2 pos = position(launchPosition, launchVelocity, i, acceleration);```
You're using this arbitrary 0.01f value to iterate.
You should be using Time.fixedDeltaTime
And instead of this:
return startPosition + launchVelocity * t + acceleration * t * t / 2.0f;```
You can just use the exact calculation the physics engine is going to use
which is to track the velocity of the object and simply add velocity += Physics2D.gravity * Time.fixedDeltaTime; and position += velocity * Time.fixedDeltaTime
I think you're using the actual physics answer for ballistic trajectories which doesn't actually quite work in a physics simulation with a discrete timestep like Unity's
I double checked where the pivot of my object was, and I'm pretty sure it's correct
but I will try your other suggestions
I've switched over from a Rigidbody2D to a standard Rigidbody, and the rotational code that works fine in 2D, no longer works as intended. I've made sure that it uses the correct axis' like eulerAngles.z was eulerAngles.y when in 2D.
void ApplyTurnForce()
{
Vector3 dirFrom = transform.forward; // the direction the body is facing
Vector3 dirTo = transform.right * CurrentTurnAmount; // direction to the left/right of the body, perpandicular to the facing direction
// the two directions to rotate between
Vector3 targetDirection = Vector3.RotateTowards(dirFrom, dirTo, MaxRadian, 0f);
// rotate between the
float currentAngle = Mathf.DeltaAngle(0f, transform.eulerAngles.y);
// this is the current angle the body has
float targetAngle = -Mathf.Atan2(targetDirection.x, targetDirection.z) * Mathf.Rad2Deg;
// angle the target direction has
float angleDifference = Mathf.DeltaAngle(currentAngle, targetAngle);
// the difference between the two angles
RBody.angularVelocity = new Vector3(0, angleDifference * Mathf.Deg2Rad, 0);
}```
I feel like I'm missing something when it comes to updating rigidbody2d code to work in 3d, I'd assumed it was just a case of making sure it used the correct axis
for comparison, thats the old version that was for 2D
void ComputeTurnForce()
{
Vector3 current = transform.up;
Vector3 target = transform.right * CurrentTurn;
float maxRadians = CalculateMaxRadians();
Vector3 targetDirection = Vector3.RotateTowards(current, target, maxRadians, 0f);
float currentAngle = Mathf.DeltaAngle(0f, transform.eulerAngles.z);
currentAngle = transform.eulerAngles.z;
float targetAngle = -Mathf.Atan2(targetDirection.x, targetDirection.y) * Mathf.Rad2Deg;
float angleDifference = Mathf.DeltaAngle(currentAngle, targetAngle);
RBody.angularVelocity = angleDifference;
}```
Can you explain what the code is supposed to do?
transform.right * CurrentTurnAmount; doesn't make much sense to me
or I guess - It's not clear what CurrentTurnAmount is doing. A scalar will not change the direction of a direction vector
Oh I see - if it's negative you get left?
Anyway this:
transform.eulerAngles.y is pretty much always a bad idea to do, especially in 3D
you cannot rely on euler angles read back from a Transform like that
you especially cannot reliably isolate a single euler angle and expect it to be sensible. Euler angles come in triplets and generally don't have a reliable meaning alone
It's hard to say exactly what you're going for since you have a function named "ComputeTurnForce" which actually seems to be setting an angularVelocity not computing any kind of forces or torques.
I followed this suggestion and now it works like a charm 👍 thank you very much
#⚛️┃physics message heres the intended behaviour for the turning. Excuse the poor naming of the method and other things.
The way CurrentTurnAmount works is it gets set between -1 and 1, depending on the joysticks input so I can steer to the left or right. dirTo holds that direction.
targetDirection is found by rotating from the forwards direction, to the side direction. MaxRadian is used to control how tight the turn should be. The target is neeed so I can find the actual angle to set the angular velocity for.
To do that, I use the angle the body currently has (which rotates about the Y axis), and I take the targetDirection and find the angle it has. It's sort of the exact same idea as the first part of the method, whether there is redundancy for this, I'm not sure. But it's worked fine in the 2D version.
Once the target angle is found, its a matter of finding the difference from the current to target angles, this gives me the desired angle to rotate by. I set the angular velocity with that angle
right so - you're wnating to turn to that angle in exactly second?
because velocity is a matter of how fast you're rotating per second
So really since it;s always ghoing to be 90 degrees off your current facing, I guess you're rotating at 90 degrees per second
So I mean couldn't you just do:
Vector3 up = transform.up;
Vector3 angularVelocity = up * 90 * CurrentTurnAmount;
rb.angularVelocity = angularVelocity;```
the first part is more or less doing this. The larger you turn to the side, the greater the angle becomes to rotate by
I'm not at my PC anymore so I'll have to try it out tomorrow, but ideally I'd like to keep using the method I already have. It gives exactly the right type of movement I need, but for whatever reason, it just doesnt work with rigidbody
the only behavioural change I've done is instead of the 2D body moving on the xy plane, it's now a 3D body moving on the xz plane. All intents and purposes, I'm treating it like its 2D as I never allow it to move upwards
the question is that as long as my code has made sure to use the right axis with its various Vector3's, why would the rigidbody not behave as intended?
Because of the euler angle issues I mentioned above
Also if it's always upright on the Z axis you can just directly use Vector3.up
No need to worry about transform.up
I used euler angle just as it was the first thing I found that returns the actual rotation value the body has
How else could I find the angle difference between dirFrom and dirTo?
that's the fun part
you don't need to
for this type of control
If you did need to, you would use Vector3.SignedAngle but it's not necessary
it's honestly just:
rb.angularVelocity = Vector3.up * 90 * CurrentTurnAmount;```
I think all of your code just amounts to that one line really
huh! I'll give that a go tomorrow. Though part of me is a little sad to think all the work I put in could be replaced by a single line 😅
Hi, the head of my rgadoll curves into the body. How can I fix it? 1st shot is the parameter of the head, and another one of the neck.
one thing at a time, what does this even mean? how do you detect this "tunneling"?
Doesn't sound anything to do with raycasts does it? Maybe a video recording of this effect happening would help
I have no idea why you would use raycast for a ball
I wouldn't be here if I hadn't
yes?
like million things. does it matter?
Best to spend this time providing relevant information to solve your problem instead of interviewing people willing to engage.
I'm not in the mood to prove you anything. Whether it's me or someone else, it's hard to troubleshoot an issue based on half complete sentences alone. If you don't want help from me, I'll leave this for someone else with pleasure
Thank's
I'm making a 2d top-down rpg
How do I stop my player & monsters from "pushing" each other? I'm ok with a little push, just not too much.
I'd prefer both to just being unable to move through each other and stopping when colliding.
I'm setting velocity to move my player and using addForce to move my monsters.
Or would the game just feel much better if I don't make them collide at all?
https://docs.unity3d.com/Packages/com.unity.physics@1.3/manual/custom-shapes.html?q=mesh
why the Mesh & Convex Hull doesn't contain the center and orientation?🤔
Cylinder is the same kind of Convex Hull, but it has them
Is continous collision detection broken in Unity 6?
It seems to make things fly around in a tornado sometimes
Have you tried if the same happens in older version? If it doesn't, you should aim to create simple recreation steps to make simplified case where it happens and submit a bug report. There are also many other things that could cause that though, hard to tell without seeing more of the project
how do I make gravity and stuff for my 2d topdown game so it has depth and an efficient movement system?
I can't find a decent tutorial on youtube
hey what is the best (most performant and least complex) way to create a character controller that checks collisions with the environment, but needs no other physics functionality?
Ie no gravity (no jumping/falling, ground height is set directly from terrain data), no pushing objects. I really only want to be able to stop the player from moving through static objects with colliders. I'm currently using the built-in character controller component (which extends capsule collider) but I'm having to work around its api in annoying ways so I want to get rid of it.
I'm also not simulating physics anywhere in the game (except potentially particles in the future but they can just get their own gravity calculations) and I've pretty much disabled physics altogether. I can turn it back on and I suppose I would have to if I'd switch to rigidbodies.
I came across old threads saying that moving primitive colliders without a rigidbody is not as performant and I was wondering if this remains true, but then again, we're only talking about moving a single object in the scene. Rigidbodies seem to have a ton of functionality that I simply don't need, so putting a primitive collider on my player and moving it through transform.position seems most attractive, but let me know your thoughts.
Use CharacterController
What are the "annoying ways" you need to work around its API?
Sounds like it's exactly what you want
most annoying is that movement only works through the move method with relative movement, so I have to do an extra step every time to go from absolute to relative. most notably, straight up teleporting the player kinda messes with the controller component because it stores a position internally and I have to do this little trick to re-record the changed transform.position
(using move with _controller.Move(oldPos - newPos) is undesirable because I don't want to do any collision checks when teleporting the player)
but also yeah, this isn't too difficult to work with, only a bit annoying and obfuscating so if you say this is just what I need I'll stick to it!
Just make a little extension function to do this so you only need to write it once
You could also make a MoveAbsolute extension that just does the little subtraction
I think two tiny extension methods would be easier than switching to a whole new system
that screenshot is the entire body of my ForceMove(pos) function :) but yeah the extension methods are definitely easier
Hello, Im not sure where to post this but I believe its a physics issue, Im not sure why but recently my game has started Jittering with my players movement. Does anyone know what might be causing this and a possible fix
probably you did something in your movement code which is breaking interpolation
If you are ever modifying the object's Transform directly, that will break interpolation
It could theoretically also be a problem with your camera following code or setup
The whole vehicle is moving based on wheel colliders, and my camera shouldnt be jittering as its using lerp to get to its position
How does it rotate
Lerp doesn't guarantee a lack of jittering
True, its looking with a simple lookat function
These vague descriptions are no substitute for showing the actual code
oh yeah I got u mb
most importantly where is this happening. In Update? FixedUpdate?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
[RequireComponent(typeof(Camera))]
public class FollowCam : MonoBehaviour
{
Camera cam;
public Transform camPos;
public Transform target;
public float followStrength;
[SerializeField]
private Vector3 positionOffset;
[SerializeField]
private Vector3 rotationOffset;
// Start is called before the first frame update
void Start()
{
cam = GetComponent<Camera>();
}
// Update is called once per frame
void FixedUpdate()
{
transform.position = Vector3.Lerp(transform.position, camPos.position + positionOffset, Time.smoothDeltaTime * followStrength);
cam.transform.LookAt(target.position + rotationOffset, Vector3.up);
}
public void SetCamTarget(Transform targetPos, Transform targetLookAt)
{
camPos = targetPos;
target = targetLookAt;
}
}
Your camera movement is in FixedUpdate
of course it's jittery
I've used both fixed and normal Update and it dosent fix it
It's also not clear what this "camPos" object is
Anyway is there a good reason you don't just use Cinemachine?
I just dont have much expirience with cinemachine
Anyway camera movement code best goes in LateUpdate
But - we didn't finish the car movement investigation yet either
how does your car turn/rotate?
Ok - so if the car is moving properly via physics and has interpolation enabled I would try:
- Move camera code into LateUpdate
- Get rid of your Lerp code for now as that could be the issue
ok, Lemme try that
Just like:
transform.position = camPos.position + positionOffset;``` for now
yeah
Ok so after changing the Lerp function it seems like that fixed it
but i would still like a smooth camera, is there a different way to do that?
SmoothDamp would be more appropriate
Or better yet - use Cinemachine 😉
then you don't need any code
Fair, I should probably learn cinemachine, it just seems like a lot
Thanks for the help though
GUYS I'm facing problem using the mesh collider , im trying to give a cup mesh collider but the mesh keeps closing from the top and i cant put anything inside the mesh itself , i want to make the cup get filled with objects , does any one have any idea why is this happening ?
Does the cup need to be dynamic (move according to physics or is it static)?
Hey guys
thanks in advance. don´t know if this is the best channel.
I'm creating a 2D game, but instead of classic platforms i'm using slopes.
Thing is i've already set my basic movement script but the player is sliding down the slopes.
I've wrote some slide prevent script, but it still slide down the slope.
Wanna check this script and give me some hints?
yub , I know i unchecked convex and used kinematic but i faced this problem that i need to make the cup fall down and hold objects which is hard to do using kinematic and un predictable
The problem is that non convex non kinematic mesh colliders are not allowed so essentially the only way is to build the mesh out of multiple smaller colliders. Those could be box colliders, capsules or convex mesh colliders for example
This is an example of such compound collider that I made couple years ago to show it to someone: #⚛️┃physics message
first of all thank you for your help 💕 , but the problem that I deal with is a model looking like this which is hard to make out of compound box colliders
what level of fidelity are you aiming for?
not that high , but also it's for a chem virtual lab so it can't be low
so what are those used for? placing other objects inside?
yub liquid , particles , objects , it's a whole lot of lab equipment's so yeah it's hard isn't it ? 
getting decent looking colliders is not too bad but liquid sims are tricky ones. Not sure you would want to rely on colliders for that to begin with
is there any alternatives ? ,it's sad that unity doesn't support concave colliders
something intersting that when we used convex collider in some of these breakers they were open normally from the top but when we transfered them to unity 6 they stopped working normally
Not really I'm afraid. Static mesh colliders can be concave of course but if you need dynamic ones, you would need to use compounds
I don't think that's possible. Convex ones cannot be open from the top by definition
PhysX consideres convex colliders volumes, therefore making dynamic objects go inside is not really possible
how do i get more physics steps at the same speed?
like Time.fixedDeltaTime but it doesnt change the simulation speed
Changing the fixedDeltaTime doesn't change simulation speed, shouldn't at least. If it does, you are likely doing something wrong in one of you scripts that makes the physics become (physics) framerate dependent
oh.. i was assuming cause one of my old projects was doing it lol
ill try again
thanks
to setup a topdown game physics I use the same stuff from a platform game, like the same layers?
There is no canonical list of "layers" for platform games. Every game is different.
what about topdown games then?
what about them?
yea
idk how I make some movements work well in topdown, like gravity
and avoid making the player jump and fall weirdly due to colliding sooner or later than expected
All of that is specific to your game, and you need to design exactly the kind of movement you want
"jumping" in particular is very vaguely defined in a topdown game
how do i fix this? When im going high speeds my physics get wierd while sliding on something, and when i go in slow mo its fine
decrease your fixed timestep
(at the cost of more processing power)
i set the physics to the Update loop instead for a smooth camera.. is there another way?
You should leave it on FixedUpdate
using Update makes it inconsistent
i cant make a smooth camera then tho 0:
Yes you can
that's what interpolation is for
just turn on interpolation on your Rigidbody
If it didn't work there's something wrong with your setup
for example you might be breaking interpolation with something you're doing in your code
or your camera settings or script are not set up properly
very jittery now
If it didn't work there's something wrong with your setup
for example you might be breaking interpolation with something you're doing in your code
or your camera settings or script are not set up properly
they are setup normally tho
Define "normally"
There's no such thing
in a lateupdate loop
Show your setup
and show how the Rigidbodies are configured
and how they are moving etc
if there are any scripts
As well as your camera setup
what specificly do u need to see?
The things I just listed
yeah but what bits of the scri[ts
anything involved in moving or rotating the player or the camera
ideally just the whole scripts
turns out
i just changed it back to fixed update
and made the time thingy 0.05
and now its perfect
thanks 🙏
what if i put it to 0.001
LAG
The smaller that number is the more accurate the simulation will be, and the more CPU resources it will use up.
Using a rigidbody how can I make it so when I hold E when I am close to an object the player can grab the object and drag the object when moving.
Watch "ShootBallGame - Level 0 - Windows, Mac, Linux - Unity 2022.3.26f1_ DX11 2025-02-12 14-57-57" on Streamable.
You can do a physics query to detect objects next to you
And then attach that object to your character with a joint for example
what type of joint would be best for this?
When I grab and drag the object I want it to react with the ground when being pulled
Something like in a game called "Little big planet"
Configurable Joint exposes all the possible joint properties so you can do any joint with that
It's a bit more complex than the other joints
You can also look at other joint types and see which one constrains the item like you want it to
For those who are familiar with the ghost collision problem, do you know of any solutions that aren't one of the following:
- Using Havok physics to use their "contact welding" feature.
- Ensuring there are no inside faces to the world collision geometry.
- Making the rigidbody collider float slightly above ground.
- Using a capsule shaped rigidbody collider.
I've done a large amount of Googling about this problem and it seems like there is no good solve for it. I am kind of shocked, because I feel like objects sliding over world geometry without unwanted collisions is something I've seen in a bajillion games in my lifetime.
The best option is to merge those two green blocks into a single mesh
Do you know of any other solutions? It would be a difficult task for our team to bespokely model the entire world collision geometry to ensure no 'inside' faces. Is this just an unsolveable problem unless you perfect the world geometry?
Write a script to merge the meshes
Like a union boolean operation?
Hi, im trying to calculate the acceleration for a falling object but the acceleration keeps on jumping from a negative value that shoes its falling to some random positve value and the returns back it accelerating at the negative value
You'll have to show how you calculate it if you want someone to tell what's wrong
im currently calculating it like this in the update loop
// Calculate velocity
velocity = (transform.position - previousPosition) / Time.deltaTime;
// Calculate acceleration (difference in velocity)
acceleration = (velocity - previousVelocity) / Time.deltaTime;
// Update previous position and velocity for next frame
previousPosition = transform.position;
previousVelocity = velocity;
And what are you logging? acceleration is a Vector3 but the logs show only one number
Im logging the y value since I just want to see if its falling or not
You get that from velocity, not acceleration
in fact that's just transform.position.y - previousPosition.y < 0
Im not nesasseraly trying to see if its falling but how fast its falling
Im trying to make a simulation for someone falling of a building and trying to detect if they fall from a high height
The velocity tells you that
I guess but Im trying to simulate it as if its being read from an accelorometer which calculates acceleration only as far as I know
Gravity is famously constant so it tells you nothing about how long they've fallen or from how high
If you drop an accelerometer it'll show 0 all the way down
then what does it record?
there will also be a spike when you start falling so I am calulating when there is a fast acceleration that is suddenly stopped
either way do you know why it is giving me both positive and negative values?
There's not enough context to tell
But it's a dead end anyway, velocity tells you all the information you need
ok thanks
Dividing by deltatime twice is probably the mistake
How can i make tilemap colliders have collision? I've tried to use it on it's own, in pair with composite collider and both on single tile and on parent object of all my tiles but there is nothing. I saw few youtube videos and on them it look like i just should add tilemap collider and it will work from the start. If i use box colliders tiles really have collision but player randomly stuck/bounce while moving if i use box/capsule collider
I'm having an issue with a rigidbody player riding a moving platform. Funnily, the code I have works fine when dealing with rotations, even when standing on a long rotating platform where you orbit its central axis.
The green player object in the video is a rigidbody, there is zero friction or any other things at play, since I disabled them via a physics material applied to everything in the scene. The platform is a kinematic rigidbody, and is moving solely using MovePosition(), which I've found also sets its linearVelocity variable.
The code for handling the actual platform-riding is: c# private void RideObject() { if (isGrounded && groundRigidbody != null) { // Translate player according to linear and angular velocity of platform: Vector3 angularVelocity = Mathf.Rad2Deg * Time.fixedDeltaTime * groundRigidbody.angularVelocity; Vector3 linearVelocity = groundRigidbody.linearVelocity; Quaternion relativeRotation = Quaternion.AngleAxis(angularVelocity.magnitude, angularVelocity.normalized); Vector3 relativePosition = rigidbody.position - groundRigidbody.position; // Add rotation to player around Y axis only: angularVelocity = Vector3.Project(angularVelocity, Vector3.up); // Apply movement and rotation: rigidbody.Move(groundRigidbody.position + relativeRotation * relativePosition + Time.fixedDeltaTime * linearVelocity, Quaternion.AngleAxis(angularVelocity.magnitude, angularVelocity.normalized) * rigidbody.rotation); } } And yet, for some reason, the player stutters like shown in the video. My script-execution-order has the platform script execute before the player script, so I'd expect it to run its MovePosition() function first, and though I realize that this doesn't MOVE it by the time we get to the player script, I'd expect the same MovePosition() call in the player script to mimic the exact movement. Does anyone know what I am doing wrong?
First, do you have interpolation enabled on the rb?
Yes, on both of them.
When moving between path nodes of mine, the platform has a constant velocity of 3 units per second. When viewing it move from the sideline, it moves perfectly smoothly as well. I've tried increasing the fixed timestep value in project settings to something like 0.05 (so 20 times per second), which made the stuttering more pronounced. I'm considering trying switching the simulation mode to use the regular update function, but it would require a lot of changes everywhere in the code. I'm not even certain what physics-related functions work in that mode, such as MovePosition(). I've tried being very controlling of the physics, seeing as I only needed the system for the robust collisions.
Currently the fixed timestep is at the default (0.02)
Hi, what's the best way to make object holding system like in Amnesia: The Dark Descent? i thought about directly changing the object's velocity, but that would cause the object to fly when the player flicks their mouse, and it's not natural. is Configurable Joint fine for that?
setting velocity towards an imaginary point (or even an empty GameObject) in front of the player
alright, i will try that.
Is there a proper way to instantly set a rigidbody's velocity to X m/s in a given direction without touching the velocity directly
That sounds like a nonsensical requirement
Is there some actual restriction that you can't access the velocity property?
I'm just confused since some documentation online says you shouldn't set the velocity directly otherwise bad things happen, so now I'm confused since if you can't do that what other way is there
It means that you shouldn't rely on just always setting the velocity, for example for movement, because it can make it look unnatural and cause issues with collisions. But there's nothing wrong with just setting it once especially if the requirement is setting it to some exact value.
Ah alright, thanks
Better to understand what the "bad things" are than to take it as some article of Faith
There is actually, you can AddForce with a force that essentially sets the velocity. That doesn't help you though because those same "bad things" will happen regardless. As others said, there's nothing wrong in setting the velocity, it's just not very natural to instantly change the velocity of an object. In theory that would require infinite force which isn't obviously possible. In real world velocities tend to change over periods of time but if you need instant one in your game, you can just set the velocity
Hiya, I'm wondering if anyone here has setup a joint that can only rotate in 1 direction? Or would an additional script be needed for that?
I have a player with box collider and a cylinder object with a capsule collider which is a "Log".
I want the player to be able to climb up on the "Log", but I don't want it to fly with "momentum" as it does in the video. What may be the optimal solution for this?
Sorry for occupying here, apparently it was a problem in my code. It turns out I was multiplying gravity too, while sprinting
I'm not surprised. Such huge yeet definitely doesn't happen on it's own
So you mean an hinge joint that can rotate clockwise but can't anti clockwise for example? Like a ratchet? My first idea would be to enable limits for the joint and rotate the min and max of the limit dynamically (via code) so that one of them matches the current rotation all the time depending on the desired direction. Haven played around with it a bit, to me it looks like unity doesn't expose enough from hinge joints api to make anything useful with that approach. Other approach could be to directly restrict the angularVelocity of the rigidbody
Hey there! Im working on a bike shop like game, and im stuck at these colliders. I dont know what is the problems source, but when im parenting the objects, the physics going nuts.
What does "I'm stuck at these colliders" mean?
And why are you parenting objects to each other
What's the goal here?
The main issue there is that addforce won't remove the forces already on it.
That is true. One could of course use Rigidbody.GetAccumulatedForce but in the end it would all be very much pointless because the end result would be the same as it was with .velocity, at least I think so
Is there any way that editor vs. build can affect physics detection, e.g. with raycasts? I've found a really weird gamebreaking bug where my FPS enemies can sometimes see and shoot the player through walls, but only in builds and not in the editor.
So I can try things before going full scorched-earth and reverting all my recent commits
There are countless ways, but by default (ie unless you broke it), they are the same.
I guess I'll have to iterate through my changes then. Fortunately I don't have to revert my commits. I'm making separate new branches starting at older commits, and testing each of them for the bug, until I reach a batch of commits where the bug occurs.
Take a look at git bisect. If you have many commits to go through, it will help you a lot by halving the search range every time (binary search)
I mean i cant fix them. I want to parent these, to move them together. I had these problems before and still dont know why is it going crazy when parenting. Its like self-collision or something.
I dont know you know the game "My summer car", i want a similar part attaching system
Moving physics objects together cannot be done by parenting unless you destroy one of the rigidbodies
You need to use joints
Hey so I was watching this tutorial and I followed everything (I think...) and when I tested it out the movement is weird when I move right it moves the opposite direction and my player does not face the right direction and its very slippery when I move and let go of wasd my player still moves a bit.
Script: https://paste.ofcode.org/f6sCfQBi4kzWHcnbYJJv4E
Video of me trying it: https://streamable.com/jxeqoz
Video I watched: https://www.youtube.com/watch?v=Weu305NLMqo&list=PLyDa4NP_nvPeSosMrZ0Gv03v5s4k7Le7N&index=1&ab_channel=PrettyFlyGames
In this tutorial series I'll show you how to create an active ragdoll which works in multiplayer from scratch. Download complete Unity project 👇
https://www.patreon.com/posts/code-access-ep1-108262101
📍 Support us on Patreon and help us make more videos like this one ⏩ https://www.patreon.com/prettyflygames
In this episode we'll go through h...
In our 2D project where players can fly using jetpacks. We've found if players hit a collider above them at a certain angle (like 45 degrees), they kind of get a horizontal speed boost. I can't figure out what is causing it. The above collider has no physics material. The player has a zero friction and zero bonciness material
If I'm reading your case correctly, I think that's just how physics should work. If you move vertically and hit a surface at an angle, at least some of the momentum should convert to horizontal momentum whether you have bounciness enabled or not
i was kind of wondering that too
It's hard to give any suggestions though without knowing more about what the actual issue is (why the horizontal "speed boost" is an issue) and how you want your player to behave in different situations
Hey guys I just wanna ask a simple question. I'm trying to implement a wire sculpture simulation with VR hand interaction.
So the wire sculpture is basically the thing you can simply imagine which is to manipulate a single wire to make a shape of rose, man, or animals or whatever you like for example.
The point is that I have imported the meta SDK and I know how to code hand interaction with it. But other than that, I have no idea how to implement this wire manipulating simulation physically.
I've got to be able to manipulate the virtual wire with hand by touching it, and the manipulation needs to be seemed to be physically accurate, as if the real world's wire.
I'd like to appreciate you guys if you give me some idea on which components to use, or how to implement it, thank you!
How can I make the ground slippery? so as soon as my player goes on that slope the player rolls down the slope.
Did you set the friction lower for physics material on the slope?
yes still didnt work properly. Instead I just add a force when the player is on the slope instead
material on players's collider should effect it too, i see it defaults to average combine
I spent a day ripping out my charactercontroller to replace it with a rigidbody, because my character can carry a box and I wanted to prevent it from getting clipped into walls. The theory was I can connect the carried box with a fixed joint and it will prevent my character from walking into walls with it.. but it completely messes my controller. with the fixed joint the character starts turning or flying, even if I move it onto a different layer that's set to not collide with the player character.
I also tried simply parenting a boxcollider to the object with my player capsule collider and movement script and it also messes with movement.
so I applied the same script on both the ragdoll cow and ball, they both are supposed to bounce when hitting the platform
I used the cow spine2 bone as the rigid body that bounces off the platform, was I supposed to use a different game object to make it jump?
we don't really have enough context to understand what you're talking about here
Heya! So I made a 3D Mechanic like game and I used FixedJoints to attach the parts. I have a small problem. When everythings assembled, the physics goes nuts.
My guess is its because they are all colliding with each other.
hm, updating the limits is not a bad idea. I'll have a look at that!
So I'm stumped here... I'm using the physics system purely for the sake of solid collisions, and I'm dealing with forces versus friction/drag myself, so I've set my default physics material to have no friction, and rigidbodies have zero drag and such. This is so I can get the exact movement feel that I want.
Anyway, I have a rigidbody player that steps onto a spinning platform (kinematic rigidbody), and correctly applying the relative velocity between the player and the point on the platform the player is standing on, is not enough, as it produces this almost natural centrifugal force pushing the player away from the platform. This is even when accounting for any drag/friction from simply just standing there. I thought I could simply cancel this centrifugal force by calculating it and subtracting it, but that doesn't appear to work at all. Either I end up being pushed away as before, or the opposite force I introduced overcomes the centrifugal force so much that I get pulled inward entirely. Here's the code:
// Ride dynamic objects:
Vector3 relativePosition = Vector3.ProjectOnPlane(position - platformPosition, platformAngularVelocity);
// The velocity in the direction of rotation, multiplied by the "radius" (distance from the player to the center of rotation).
Vector3 tangentialVelocity = Vector3.Cross(platformAngularVelocity, relativePosition.normalized) * relativePosition.magnitude;
Debug.DrawRay(position, tangentialVelocity, Color.white, default, false);
// Centrifugal force: F = V^2/R, scaled into the normalized vector of relative-position so we get it as an actual force vector.
Vector3 centrifugalForce = (platformAngularVelocity.sqrMagnitude / relativePosition.magnitude) * relativePosition.normalized;
Debug.DrawRay(position, centrifugalForce, Color.blue, default, false);
Debug.DrawRay(position, velocity, Color.green, default, false);
// Accumulate and apply extra platform forces relative to our current velocity:
var platformForces = platformVelocity + tangentialVelocity;
rigidbody.AddForce(platformForces - velocity, ForceMode.Acceleration);
//rigidbody.AddForce(-centrifugalForce, ForceMode.Acceleration); // Opposite centrifugal force (does not work).
// Add movement friction/drag:
float moveDrag = isGrounded ? DRAG_MOVE_GROUND : DRAG_MOVE_AIR;
Vector3 hVel = new Vector3(velocity.x, 0f, velocity.z) - platformForces; // No vertical friction/drag.
rigidbody.AddForce(-moveDrag * hVel, ForceMode.Acceleration);
And here's a video showing the centrifugal effect pushing the player off the spinning platform. The green vector is the player's velocity, the white vector is the tangential velocity applied to the player from the platform's rotation. The blue vector is the calculated/expected(?) centrifugal force.
I've tried also just calculating the actual difference between the next position that the player ends up in during the next physics cycle, versus the "ideal" position that the player should arrive at, by rotating the relative position by the revolution per fixed-deltatime step. Then I take this as a force-per-second type deal by dividing it by fixed-deltatime, but this also does not appear to work.
(And yes interpolation is enabled for all rigidbodies. Only the kinematic platform uses MovePosition/MoveRotation, where-as the player's velocity is entirely force-driven)
sorry ye I just realized, basically I gave both object the same script, one bounces off the ground and the other (Ragdoll) did not, I don't know why it wouldn't bounce
https://youtu.be/ZFx9M0dY8Ag
nvm I messed up the mass 
Yeah, that was my guess too, I’ll get home I’ll try using layer matrix
i love ragdive agdolls
(active ragdolls spelled in a strange way)
anyone ever managed to make a self balancing ragdoll without external forces?
You'd probably need to simulate toe muscles properly
So, its not the collision, I turned off the self collision, and still theres the problem.
Hey! Im trying to make a 2d ragdoll fighting game using swords/lightsabers. I want both swords to be able to interact with each other like as if it's a real sword. I thought this was quite simple and to just use box colliders but they weirdly don't collide. I thought it may be because both are on kinematic so I switched the rigidbody2d to dynamic. The swords get weirly stretched out and dont follow the character. Does anyone know how to fix this or fix my original problem? (please ping me if you reply)
- yes kinematic bodies aren't going to collide with each other
- dynamic bodies will collide but controlling them via teleportation directly in code or via an animator is fraught with issues. They also won't follow parent objects - you would use joints to connect dynamic bodies to each other.
okay thank you very much. I would use something like a fixedjoint2d right? And while using a joint it should not be a child object of the limb
The way I would approach it would depend a lot on what kinds of interactions you need. Do you need collisions? Elasticity? Does the length need to be constant or can it be stretched/drawn?
I’m using Unity.Physics collision filter and I want to set the CollidesWith to collide with all layers. How do I set that?
it's a bitmask - just set all the bits
e.g.:
uint mask = ~(uint)0;```
Yep but what about more than one layer?
what do you mean
Collides with takes a bitmask. I’m guessing this bitmask only represents one layer?
no...
each bit is a layer
that's the point of the bitmask
the code I shared above creates a mask that will hit ALL layers.
Ooohh cool
because all bits are set
That has the distinct look of DrawRay being called incorrectly but it does seem correct... 🤔
I have just tried with brand new camera without changing anything still nothing..
Oh I think your problem might be the mousePos.z = mainCam.nearClipPlane; line
that doesn't really make sense for ScreenPointToRay
I would try getting rid of it
How did you assign mainCam?
drag and drop
there's no physics involved in the DrawRay though
the problem we're talking about is the DrawRay looking weird, yes?
Or something else?
No draw ray working fine. Physics.Raycast is problem after countless of debuggin.
the ray drawing looks weird to me... it's converging on some point it seems like
but uh - what object are you expecting this raycast to hit?
Show the inspector for it
you can give duration to it. It will stay still
Its in the video the ground and tiles.
Are thsoe objects spawning in at runtime?
Yes but ground.
Is your time scale normal, or set to 0?
Is your physics Simulation Mode normal (FixedUpdate)?
Timescale is default. Raycast is in Update.
not raycast
Project Settings -> Physics -> Settings -> Simulation mode
In fact can you screenshot the settings there?
Everything should be set to default.
yes... seems ok... 🤔
Can you try a Physics.SyncTransforms() before the raycast
just to check something
It is soo weird. I even backed up my project to 1 month old version. Still wasn't working. This problem has just started.
try using a large finite number instead of float.MaxValue? e.g.... 1000?
shouldn't matter
it's already set to float.max 😄
i was using it at 100 and was working till last night.
Are you using git?
so... what changed since last night according to git log?
As i said i have backed up the project to older working versions but it wasn't working.
Have you restarted your pc?
Did you print out actual value of variables you are using?
Yes, Input.mouspos and ray work just fine.
like maxDistance when you are using it. Is it serialized?
watch the video here.
You are missing something really obvious there. Create an empty scene and basic case with raycasting. Make sure it's working there. Then put it into your current scene and compare.
This didin't work too.
Ok.
It's Crazy..
you sure time scale is not set to 0?
can you show your Project Settings -> Time settings?
what do you mean?
Elements like basic colliders
a screenshot of the settings would have been sufficient
Yes, put the working model parts into your main scene.
its not working. See it on the console
In your original, your ray was not moving at all. This updates properly.
No, it was moving. Maybe angle of the camera was hiding the rays.
I even updated unity version.
Then it's likely physics settings. Compare them in both projects
Just tried it.
Found it. It's This. I don't remember messing with this settings at all. But this is the cause.
Thanks for your time guys. I couldn't figure this out for another week by myself. 
Just remember sanity checks next time if nothing makes sense. Test in clean environment and compare.
I've seen it when you ask that but i though that was the default option ://
i have a trigger below a player that controls onGround variable and for some reason when player walks on Terrain collider the trigger randomly stops working when it's clearly visible that it touches the surface, there's OnTriggerStay() that should continuously keep onGround be set to true
Trigger colliders are honestly worse than using direct physics queries for grounded checks in basically every way
The RB is probably falling asleep or something
anyway why doi you need OnTriggerStay
instead of just OnTriggerEnter/Exit
hey just letting you know that i was able to expand your "betterphysics" package to work with articulation bodies
so in my case I was able to make it so the "articulation bodies" for my VR hand fingers now no longer impart forces on grabbed rigidbody objects, so its a hell of alot more stable now
if you want the modified scripts just let me know
I would love to see them!
That's great
I'll send in DM
yeah i have all three methods in that script and for some reason it disables onGround at some moment
it never happened on mesh or box colliders
Hello I have this inner platform with in it little cylinders that have cubes on top which all spin
my inner platform can tilt and move up and down but whilst doing that the inner little cylinders don't move with the platform (look second picture) the cylinders have rigid bodies that have no constraints set to them what could I have done wrong
my hierarcy:
outerstructure
emptygameObject
innerplatform
innerCylinders
benches
fixed had a issue in my rotation script which is now fixed
How does friction work in physics material? Changing its value does absolutely nothing to, well, add friction when sliding down a slope
I want to make the object that is sliding slow down
it affects the friction force the object experiences when sliding against other objects
whether that matters or not will depend on your movement code.
what to you mean by matters or not? I have gravity movement of a ball without any scripts moving it
just dropping down
when it slides down a high friction slope, it behaves the same as if it were sliding down a 0 friction slope
because spheres don't slide
they roll
so it's not particularly affected by the friction
in real life they have something called "rolling resistance" caused by the deformation of the ball as it rolls
but in the game engine the sphere is perfectly rigid and doesn't deform
so there is no rolling resistance
So what do I actually do with the rigidbody? Increase damping and linear damping?
A simple analog for rolling resistance would be angular damping
don't exactly know what you said but it works for me
although the difference would be that angular damping operates while in the air unlike actual rolling resistance which is only present on the ground
the other thing would be to simulate rolling resistance with AddTorque when grounded in FixedUpdate
It's only during oncollisionstay
So it won't make a difference
what is
On collision exit I reset the drag values
gotcha
Does anyone have any idea why rigidbody.AddForce(force, ForceMode.VelocityChange); differs from rigidbody.linearVelocity = force + rigidbody.linearVelocity;? From what I know, and based on the documentation, ForceMode.VelocityChange applies a direct change in velocity, by just adding the given vector to the velocity (without accounting for mass). So overriding the velocity with a new value should be as simple as adding the new value and subtracting the existing velocity, right?
it would be rigidbody.linearVelocity = force + rigidbody.linearVelocity;
not -
why would you subtract the existing velocity?
Oh my bad yeah, I'll correct that.
Actually I think I meant to put the subtraction inside the AddForce method. But regardless, the two still have different outcomes. I've got these two lines for the player jumping, which is supposed to replace the Y component of the velocity with the jump force variable.
// The way I do it:
rigidbody.linearVelocity = new Vector3(rigidbody.linearVelocity.x, JUMP_FORCE, rigidbody.linearVelocity.z);
// The way I "ought" to do it:
rigidbody.AddForce((JUMP_FORCE - rigidbody.linearVelocity.y) * Vector3.up, ForceMode.VelocityChange);
AddForce is additive
linearVelocity = is overwriting
idk why you think the bottom one is how you "ought" to do it
though yes I guess it should probably work out the same?
what different outcomes are you getting?
a higher jump when using the 2nd one.
The difference is possibly due to you having other AddForce calls in your code
by doing linearVelocity = you are probably cancelling/overwriting some other pending forces
If you do Debug.Log($"Accumulated force : {rigidbody.GetAccumulatedForce()}"); before and after this code, what do you see?
I get all zeroes, before and after
Even when you do the AddForce way?
Nope, there it does seem to accumulate the jump force. Interesting.
yeah - AddForce doesn't modify the velocity right away. It accumulates it then applies it during the physics update (which is after FixedUpdate)
But my assumption must be correct then, with VelocityChange behaving that way. The difference must have come from the cancellation of the accumulated forces
I knew this yeah
Can you show the rest of your script?
I just figured reading from and writing to LinearVelocity would use the values already set from the previous cycle, and not fiddle with any of the internal accumulation state stuff.
No reason to, you helped solve my problem already :P
thanks!
Did I? good
not sure I caught the moment we solved it though haha
Or what the issue was
I guess maybe you have other code that further modifies the velocity later in your script or something
Not directly via assignment. Just another AddForce as acceleration.
anyone? please
I love a good crash course through raycast and vectors and getting / setting directions. Trying to make a ray from one collider, through another, and back is hard.
wdym "and back"?
to make a vector pointing from one position A to another B is just B - A
i need to get the face thats closest to where my collision starts, and the one thats the farthest away from my collider, of a mesh, to edit it using probuilder
have to use Physics.raycast because thats the only way ive found to find a mesh face without using my screen for calculation
i mean i just finished it, and it works! But had to learn quite a bit about vectors, direction is target-start, and i tried some other inefficient ways to do things, like trying a raycastAll or just using normalized vectors for direction instead of simple direction.
i need to get the face thats closest to where my collision starts
For this you can use Collider.GetClosestPoint, and then do Collider.raycast through that point
and the one thats the farthest away from my collider, of a mesh
This feels not very well defined to me. This might be different points for different parts of the mesh.
raycasting inside of a collider doesnt work, iirc? because closestpoint is in the collider. the backwards one is just a 2d version of find farthest face. because its for log chopping, i only have like 14 faces, and i need to find where the axe hit, and the opposite face of where the axe hit
raycasting inside of a collider doesnt work, iirc? because closestpoint is in the collider.
Yes I'm saying raycasting from the outside through that point
also is this 2D? I assumed you are talking about a MeshCollider
otherwise the raycast is not necessary
because you said you want to get a mesh face
Yes, using a meshcollider. Its not a 2d game, but the problem described is 2d because it throws out y in any calculation (uses mesh's center for all calculations
i have this log, and im trying to get the face hit by the axe, and start deforming a mesh according to an agorithm im creating that relys on health, dmg object does, and goal is to move the initial face back close to the other face, before destroying the object, and letting a tree fall. As more hits get added, the initial face falls back, uses Grow section to get other faces, deletes them, and continues.
ive gotten the in index and out, but i should probably use the colliders raycast instead of physics, to increase performance.
the problem im on is getting the quad face out of the triangle indexes, but thats a probuilder problem and i dont need help rn for that
honestly if you have a lot of knowledge beforehand about this log like how many faces it has, you can probably simplify this a hell of a lot. Just get the face you hit and then, just have a mapping of face -> face for opposite faces that you have premade and use that
like if this thing has 12 faces around the outside you can just add 6 and mod 12 to get the opposite face
as an oversimplified example
yeah, wasnt thinking about that as all, the code i was thinking id use was intended to be done on a full tree initially, which i was trying to sidestep mesh colliders and querying the face index using a world point.
yeah it could be done simply via taking the angle around the center of the chop and figuring out which "pizza slice" it lands in
thank you for the advice, that saves some performance. im really new to dealing with modifying/finding specific mesh faces, so i dont understand the last thing yet. i want to just make this logging feel satisfying to do, so alot of work, but ill get it done.
can i use the two sphere colliders as a grounded check? currently im just using one raycast out of the back wheel but that makes it kinda buggy
Why not two raycasts?
yea i did that lol completely stupid question from me xd
I made a rudimentary (I'm still extremely proud of it) orbital sim. Can someone please tell me why the orbiting object does not perfectly repeat its previous orbit? Is it a problem with my code or is this a real phenomenon? The code below are the only lines that manage the orbital physics
public static float Gravity(Transform m2Loc, Rigidbody m1Mass, Rigidbody m2Mass, float gravityConstant)
{
float force = (m1Mass.mass * m2Mass.mass) / MathF.Pow(m2Loc.position.magnitude, 2) * gravityConstant;
return force;
}
i.mass.AddForce(i.pos.position * -1 * Equations.Gravity(i.pos, planetMass, i.mass, gravity), ForceMode.Force);
The object does NOT exert a force back on the Earth
The pink blocks together is the trail of the satellite
And, any ideas on how I can make it predict the orbit path before it completes it?
i'm sure you seen this problem before. but my OnTriggerEnter is not triggering. I've checked the matrix, made sure the script is on the phsyics object. One of the colliders IsTrigger and has a rigidbody with IsKinematic. what is happening haha
i just tried 2d physics trigger and that works fine. 3D is not working.
i'll mention that ive installed Entities so maybe that has something to do with it
Reason: while ECS subscenes are open GO 3D physics is disabled
Hi, I want a rectangle rotate on the z "around" a sphere but rotate it like the hammer on getting over it, it's always attach to player
why is this coin not falling? it has rigidbody
The Animator probably?
i figured it out, i was using a box collider for my tilemap instead of a tilemap collider
I made a rudimentary (I'm still extremely proud of it) orbital sim. Can someone please tell me why the orbiting object does not perfectly repeat its previous orbit? Is it a problem with my code or is this a real phenomenon? The code below are the only lines that manage the orbital physics. The pink is the satellite’s trail. The satellite exerts no force back on the Earth.
public static float Gravity(Transform m2Loc, Rigidbody m1Mass, Rigidbody m2Mass, float gravityConstant)
{
float force = (m1Mass.mass * m2Mass.mass) / MathF.Pow(m2Loc.position.magnitude, 2) * gravityConstant;
return force;
}
i.mass.AddForce(i.pos.position * -1 * Equations.Gravity(i.pos, planetMass, i.mass, gravity), ForceMode.Force);
Has anyone else experienced ContactPoint.normal being inverted?
ContactPairPoint.Normal also seems to be inverted sometimes too.
That is to say, the normal sometimes doesn't point from ContactPair.OtherCollider to ContactPair.Collider.
If I'm reading the Physx documentation correctly, Unity's ContactPair.Collider and ContactPair.OtherCollider are equivalent to Physx's PxContactPair.shapes[0] and PxContactPair.shapes[1] respectively. It also states that PxContactPairPoint.Normal (seemingly equivalent to Unity's ContactPairPoint.Normal) points from the second shape to the first shape. But, this doesn't seem to always be the case with ContactPairPoint.Normal, which sometimes doesn't point from ContactPair.OtherCollider and ContactPair.Collider.
https://docs.nvidia.com/gameworks/content/gameworkslibrary/physx/apireference/files/structPxContactPair.html#d4482d0d718415fbbd0c5852994f139f
https://docs.nvidia.com/gameworks/content/gameworkslibrary/physx/apireference/files/structPxContactPairPoint.html#36ae08a170895b4b57eaa1f6488bcd05
No it's always been correct for me. What's making you say it's inverted?
By listening to the contacts reported via Physics.ContactEvent, the contact point normals don't always point from ContactPointPair.OtherCollider to ContactPointPair.Collider.
It would be the opposite.
OtherCollider is poorly named. OtherCollider is your own collider
Collider is the one you hit
The normal is correct. The names are bad
It's the same in OnCollisionEnter
(on the Collision struct)
But I get the normal in both directions. Sometimes it points from OtherCollider to Collider, sometimes from Collider to OtherCollider.
I should say I only get this issue if it's colliders both attached to rigidbodies colliding.
If it's a rigidbody and a static collider, the contact normal always points from the static collider to the rigidbody, and the static collider is always the OtherCollider.
Weird, idk then
The only thing I've found which seems like it might be related is this flag CollisionPairFlags.InternalContactsAreFlipped. But from what I can tell there's no way to see if a ContactPair has this flag enabled.
(Leaving this comment here in case anyone else encounters this issue in the future and finds my comment when searching for a solution)
Okay, it seems CollisionPairFlags.InternalContactsAreFlipped does indeed represent when the normals/impulses are inverted. I've solved my problem by checking whether ContactPair has that flag enabled in it's m_Flags field, and then just inverting the normals/impulses of it's contacts if it does. However, that field isn't public, nor is the enum type itself, so you have to get it's value via reflection. This was my code to get it.
var flags = (ushort)typeof(ContactPair).GetField(FLAGS_FIELD_NAME, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(_contactPair);
var isInverted = (flags & (1 << 5)) != 0;```
("_contactPair" is my field for the ContactPair I'm trying to get the correct normals/impulses of).
Do I need to adjust the collision matrix when I'm using 'include layers' in the collider? According to my understanding when I select to include only 1 layer I should only get triggers for that layer, but it's not filtering correctly for me. It works if I set the matrix. Do I understand the include layer setting incorrectly or and I missing something else?
Afaik, the includeLayers only specifies additional layers the collider should collide with. It doesn't cause the collide to miss any layers not specified in includeLayers. Have you tried adding all the other layers to excludeLayers?
I thought if I add a single layer to include layers it will exclude all others.
if I use exclude it'd have to be updated every time I add new layers too
I don't believe so. Any layers not specified in either includeLayers or excludeLayers fall back to the collision matrix behaviour.
Yes I think that's true.
I'm also not sure what would happen if you specified a layer in both includeLayers and excludeLayers.
iirc it exclude will take priority and it'll remove it
You could probably write a bit of code that sets it to exclude all layers other than the one you specify in awake.
Then you wouldn't have to update it as you add new layers.
i have a trigger below a player that controls onGround variable and for some reason when player walks on Terrain collider the trigger randomly stops working when it's clearly visible that it touches the surface, there's OnTriggerStay() that should continuously keep onGround be set to true
the script which is added to the trigger has all three methods (Enter, Stay and Exit)
Thanks George, figured it out. You put me on the right track, I did indeed misunderstand the include. Removing all from collision matrix for the layer and then adding just the specific one via includeLayers works as I wanted it to.
Anyone have any ideas why my projectiles might be passing through my walls? Providing images of projectile inspect, wall inspector, and projectile code, respectively
Your Rigidbody is kinematic and you're also not moving it via physics
You would need a dynamic Rigidbody and to move it via the physics engine if you want collisions
I don't want it to move through physics though, I want it to travel in a straight line at a constant speed
You can do that
With physics
But if you want collisions you need an actual dynamic physically simulated object
You can certainly move in a straight line at a constant speed
Oh ok I forgot about the gravity scale property. I got it now. Thanks!
Hello, i dont seem to get how this is working. I have a meshcollider that i instantiate within an object. once its spawned in, i cast a raycast hit on it to get the triangle index that was hit. However, when debugging, turns out that it gives me -1 as the hitindex, but it HAD to hit the meshcollider as thats the only one spawned in where i hit it with a collider, and it shows up on raycasthit.collider.name. https://paste.ofcode.org/qmU57k7RfeTLMPmGB6Us8m
That paste site isn't readable on mobile 😭
changed websites
I'm making a 2D side scrolling platformer. Here's my current script for character controls (cut out the unnecessary details) https://scriptbin.xyz/viwoxodura.http
RN, I'm using the RB.linearVelocity.x OR RunMaxSpeed for the Speed Difference situation, which ensures tight turning speed. This method is not ideal for transient forces like jump pads which are horizontal, and negatively affects other forces. I want to switch out the RB.linearVelocity.x part for a new variable: PlayerVel. However, I don't know how to increase or decrease this variable and where, in order for it to make sense? Because it's all Forces
Use Scriptbin to share your code with others quickly and easily.
I made a character and a ground and gave them the necessary components but when i click play the player hits the ground but the camera just continues to fall
this is my first ever project so im bad at this stuff
does anyone know why when I use an articulation body with a prismatic joint, the path of that prismatic joint follows the parent orientation, instead of staying in place
hi, quick question, when a wheel hits a wall, how could I make the wheel climb it, should I change the force direction or is there a way to simulate the physics
check if u accidently added rigidbody with gravity to the camera
thanks a lot it seems that was the problem
You'll have to change the force direction.
why does my sphere cast only sometimes hit the collider of the ground below?
bool hitSth = Physics.SphereCast(transform.position + new Vector3(0, .01f, 0), jumpCheckRadius, Vector3.down, out hit, distanceThing + .01f, LayerMask.GetMask("Ground"));```
everything is ground layer i sent a picture of one of the colliders it isnt hitting as well
the red ball appears when the cast sees a collision
Physics.raycast could hit with no issue with this code
A spherecast won't detect any faces of a collider that the starting position of the sphere already overlaps with. What is the radius of the sphere cast and how far above the ground does it start?
the radius is .7 so i should start it .7 above the ground?
It would need to be a little bit more than .7 to allow for some inaccuracies in the cast
Try starting it .8 above the ground if the radius is .7
alr
You would need to extend the max distance of the cast too though
In this case it would need to be at least .1, to account for the difference in height and radius
ty :)
I am making a active ragdoll and I have this issue where the player no longer stands and just falls. Any ideas?
Watch "Active RagDoll - SampleScene - Windows, Mac, Linux - Unity 2022.3.26f1_ DX11 2025-02-21 17-40-57" on Streamable.
I would probably try setting the hips rigidbody to kinematic just to see why the legs rotate backwards. If don't rotate back with the hips as kinematic, then it's likely that the spring force on them isn't strong enough. If they do still rotate back, then it's potentially something to do with how the limts or target rotation are set on their joints.
Btw, I think active ragdolls usually have a fake force holding them up off the ground. They don't usually actually hold themself up purely with their legs, as that is behaviour that is very difficult to achieve.
does anyone know why Physics.Raycast() doesnt return a triangle index on convex mesh colliders? it hits it, it can say the name of a mesh collider, but it gives -1 when giving the triangle index. i can confirm visually the point where it hits, and can confirm there is a visible triangle of the mesh collider where it hit.
The hips are kinematic and the legs rotate back too much is that why it falls down? isnt it because of the script?
Watch "Active RagDoll - SampleScene - Windows, Mac, Linux - Unity 2022.3.26f1_ DX11 2025-02-21 18-26-42" on Streamable.
this is the tutorial I have been following. I did what he did and it ended up like this 😦
https://www.youtube.com/watch?v=iNLQCwCHEBM&t=357s&ab_channel=HappyChuckProgramming
Unity Ragdoll Tutorial - Animation With Physics - Gang Beasts Style - Part 4
Hey Buds,
If you are having issues with copying the animation, please look at the reply to the pinned comment.
Welcome to Part 4 of the Unity Ragdoll Tutorial Series.
In this one I show you how to animate your ragdoll while allowing the limbs to be affected by physics...
There is a slight difference in your code compared to his. He is setting the target rotation to directly match the target limb's rotation.
Yes I had the same as him before his script made my player fall on the ground but someone in his comments pasted this script I have and it stopped my player from falling now the legs are just weird
Could you record what happens if you just set the target rotation to the target limb's rotation?
wdym? like put the limbs rotation of the animated model to my main player configurable joint target rotation?
Yes
cj.targetRotation = targetLimb.localRotation;
Try both .rotation and .localRotation
In the tutorial he uses .rotation but that surprises me, I would've thought it needs to be .localRotation.
I added this to my script my arms are now behind the player and my legs are nearly in the correct position
What do you need to do with the tri index? A convex collider's triangles dont match the original mesh it was generated from. So not sure how it is useful
Watch "Active RagDoll - SampleScene - Windows, Mac, Linux - Unity 2022.3.26f1_ DX11 2025-02-21 18-42-19" on Streamable.
You'll probably need to dig into how the target rotation needs to be transformed in order to make the joint match the target limb's local rotation. I'm not familiar enough with configurable joints to know how to do this, but the chosen answer to this forum post looks promising. https://discussions.unity.com/t/how-to-use-target-rotation-on-a-configurable-joint-to-make-the-object-point-in-a-certain-direction/45786/3
alright I will look into it thanks
i need to deform the mesh collider at runtime, with the impact point. i need a way to deform the probuilder mesh behind the collider as well, but if the hit index doesnt matter, that means you arent able to deform meshes at runtime unfortunatly, which is exactly what i need to do (deform mesh at runtime, with changing material of mesh. specifically i need to acess the mesh thats behind the meshcollider to push it to specific points, and raycast makes it super easy (if hit index worked)
Does the convex mesh collider need to be deformed or just the mesh that gets rendered?
both, and a change of submask/material
I think there's a few ways you could go about achieving this. One would be to simply find the closest point on the mesh from the raycasthit point and use that triangle instead. You can probably find an algorithm online to find the closest point on a mesh. Another way would be to have a second mesh collider that is non-convex, and either has no rigidbody or has a kinematic rigidbody, and raycast against that. This would give you a triangle index which you can use to deform the mesh, then once deformed assign the mesh to the convex mesh collider.
Hi i dont know if this is exactly a physics problem but i have a LookAt function but as soon as i added it my Enemy started leaning back and after 5-10 sec the enemy would be lying down atp so i figured it was due to the pivot point so i parented the enemy to an empty but it still leans ive spent 2 h on this problem and as yall can see in the screnshot how the one on the left is when it spawned but on the right is the leaned ones
this hapens both to box and capsule coliders
You're having the enemy look at a position above its pivot
Very simple solution is to just set the y component of the position you're looking at to the same as the enemy's
Thisisn't really a physics problem though
now that i think about its so obvius, my brain didnt even try to think about it cuz i set the enemy to have no rotations on x z and i thought it was about the enemys pivot point not the position im looking at so it would have never came to me. anyway thanks
constraining the rotation on the Rigidbody only affects physics
it doesn't affect your code
Also you shouldn't really be moving or rotating an object via the Transform if it has a Rigidbody
what do you mean via transform im moving the enemy with the move towards function
MoveTowards is not a function that moves an object
so i guess its using a transform
but I'm tlaking about the LookAt that you mentioned
MoveTowards just calculates a position
oh
so i should use a vector
You're going to be using vectors no matter what lol
You should be using the methods on the Rigidbody to rotate it
and to move it
ill see about fixing it am still preaty new to all this stuff i dont realy watch many tutorials so my code is bad but thanks for the insight
Can someone please help me interpret the parameters for this eccentricity vector equation? This is for orbits. I believe I understand how to use the equation, but what I don't understand is how some of these variables can be used as both vectors and non-vectors
The image on the left uses v as vector and also a non-vector. On the first use, there's no vector symbol above it. Is this not asking to square my velocity vector's magnitude? Or is it asking me to get the dot product of the velocity vector?
Pretty sure it's just saying eccentricity (a scalar) is equal to the magnitude of that vector
can anyone help my car is not moving when i press W
don't crosspost
what do you mean
don't post your question in multiple channels
sorry the name of the channel
i did that too in my first project
Hi, two questions how can I fix when it hits the ground, it get kind of stuck for a few seconds and how do I make it when it hits the wall it starts climbing it?
the wheel colider it's in the front wheel
im making a level for the first time, should each of the prefabs have a seperate collider or do i make bigger colliders for patches of tiles? not sure whats better for performance
hello, is there any way to acess the code behind BoxCollider.Bounds.ClosestpointOnBounds? Its stored in a external class but i cant get to it through the code or scripting api (i want to understand the implementation of converting a point in 3d space to a point on the outside of a box and thought unitys implementation would be helpful to learn)
It's native code, so no.
It's also closed source
i didnt get to the second one, so going to look at that. i did look at the first one before but i had a hard time wrapping my head around it. thank you blue.
wait also
ClosestPointOnBounds is also much simpler than this
DO you want ClosesPoint or ClosestPointOnBounds
ClosestPointOnBounds is for the AABB
im basically moving vertexes of a mesh on one side of a rectangler box, to a point on the retangler box thats closest in starting point. i already found out the direction for every point, just didnt know how to transform it
cloestpointonbounds is what i think i need.
ClosesPointOnBounds only gives you the closest point on the bounds
the bounds is a minimal AABB surrounding the boix
if the box is rotated at all off the world axes, it is not the same as the AABB
Closest point on the AABB is pretty much just Mathf.Clamp on each of the three axes.
Here's a good visualization of what bounds / AABB means: https://developer.mozilla.org/en-US/docs/Games/Techniques/3D_collision_detection/rotating_knot.gif
Ohhhhh, so if a box is rotated at all, then bounds doesnt work, because of direction, doesnt it work as long as all the bound points are in world space and theres 4 distinct points with 4 more directly them
yeah, i think bounds are what i need, the box isnt rotated at all and theres no reason for me to ever need to rotate it. at least for this implentation
this is the most work ive ever had to do for a progress bar XD
It's just Mathf.Clamp for each axis then
thanks bro for yesterday i did what u suggested and used my rigidbody to move my enemy and to rotate it in the direction of the object i want it to look at. I didnt know u schouldnt use transforms to move and look if i have a rigid body and phyisic but i know now
im making a level for the first time, should each of the prefabs have a seperate collider or do i make bigger colliders for patches of tiles? not sure whats better for performance
Hello, I'm coding a tetris. Here is how I created a tetris shape : I made a Square prefab, and used four of them to create a shape prefab (and square is the child of shape)
My question is : should I put the rigidbody in the parent or the child (as it is right now) ? because I think that the problem comes from that. also, should I use a composite collider, since I have different collider in the same shape ? as you can see in the video, the shape should not quit the grey rectangle but it does
If the problem is that it goes outside the gray area it's because colliders don't prevent you from going outside another collider when you're already inside. You should have 3 colliders for the play area (two for the sides and one for the bottom)
Also using a physics simulation isn't usually a good fit for Tetris. It's going to require a lot of tweaking to get it right for very little benefit
ok what do you recommand then?
Typically you'd have a 2-dimensional array that represents the board and it holds information if there's a block in that square or not. A falling block has coordinates that you can use to check if the block has reached the bottom or a filled space in the play area, and if there's space to move left or right or rotate. The movement is just animating with lerp at simplest
I'm sure there are a lot of tutorials for it
ok thank you for the advice
Hey all. I'm just wondering if anyone might know why my character is bouncing off walls slightly when jumping against them. The player has a material that has 0 bounciness and the wall does not have a material.
Show code?
hello, so here i have a box collider that covers this box. the problem is that when i check the bounds of this, its outside the actual bounds of the box. the problem is that the bounding box of the collider is not on the collider, even when at 0 rotation. (little boxes are at bounds min/max of code, and sheet is where box is) if box was at 0 rotation the bounds would be like 90 degrees parellel to the box) But, for some reason, ClosestPoint still works.
What do you mean by checking the bpunds?
Where's the collider gizmo?
And what does your code look like?
the collider gizmo is the exactly selected oranger area, its just covered bc i have it selected. https://paste.ofcode.org/34z8MugJ6uBy3R9ixbDpyiA
by checking the bounds i mean running collider.bounds.min, and collider.bounds.max
for this i basically need to get the outside most intersection of my mesh collider and the box collider repersenting the cube, to use for calculating where to put my mesh vertex points.
i got pretty close a single time, but the points were a bit more inside the collider then i needed
i tried using mesh collider with collider bounds, but the points were very off, using collider.closestpoint got me closer, but a bit off, i thought about taking a step back and turining the cube into a bigger cube that slowly grew to finish the entire area, but that wouldnt solve the problem with make the points turn back inwards after the middle
Hello, guys! I have a question. Does anybody know how to create climb up/down the stairs system using a Character Controller?
theres multiple unity articles on this / Forum posts
I've come across a lot of car controllers that tend to use wheel colliders, but when I've been writing my own vehicle controller, wheels arent something I've ever used. It's been more than enough to do a basic AddForce in the forward direction and to gradually rotate the game object as it turns.
I'm starting to wonder if wheels are actually something I should start using, I like the idea that they could make my own vehicle a bit more physically accurate, but I'm doing more of an arcade vehicle controller so it's not like I need something extremely realistic
suspension being one feature of the wheel controllers that isnt of any use to me
the main thing I'm interested in is if they could allow the turning of my vehicle to be physically accurate
Collider gizmos show in green. Orange is typically a MeshRenderer.
Are you sure you're using a BoxCollider?
Bounds are not the points of the collider itself, they're an axis aligned bounding box
The best/simplest option is to use a basic ramp shaped collider rather than stair shaped collider
i am sure, and im sure the boxcolldier is exactly as whats outlined in orange. (I think i might of figured out a way, will update if i didnt
Your object has this really degenerate 0.001 scale
You should just use a quad mesh instead of a cube, fix that scale back to 111, then adjust the box Collider instead of using scale
hi guys could you help me with my physics homework
Don't think so. Doesn't seem Unity related at all and also homeworks are meant for you, not for us.
ok aleksi you are right I apologize
I can not stop the flippers in my pinball game from clipping into the ball. I've set the ball and the flippers to continuous dynamic, but still, the ball will occasionally clip into the flippers, usually when the ball hits the flipper on the far side from the hinge joint. Any secret unity settings I should try?
I also have interpolate on, not sure if that should be on tho 😮
Well the main thing is to make sure that you are rotating them properly with the physics engine
how are you rotating/moving them?
I'm rotating them through these Hinge Joints. I don't really understand these, but pinball tutorials on youtube said this was the way. I was trying to just manually rotate them but the table is sloped, and me trying to figure out how to rotate them on a slanted axis like that was melting my brain.
{
hinge = GetComponent<HingeJoint>();
jointSpringPressed.spring = jointSpringReleased.spring = hitStrength;
jointSpringPressed.damper = jointSpringReleased.damper = dampening;
jointSpringPressed.targetPosition = hinge.limits.max;
jointSpringReleased.targetPosition = hinge.limits.min;
if (flipperType == FlipperType.LEFT)
{
FlipperController.instance.OnLeftFlipperActivated += ActivateFlipper;
FlipperController.instance.OnLeftFlipperDeactivated += DeactivateFlipper;
}
else
{
FlipperController.instance.OnRightFlipperActivated += ActivateFlipper;
FlipperController.instance.OnRightFlipperDeactivated += DeactivateFlipper;
}
//defaultRotation = rigidBody.rotation;
}
// Update is called once per frame
private void FixedUpdate()
{
if (isActivated)
{
hinge.spring = jointSpringPressed;
}
else
{
hinge.spring = jointSpringReleased;
}
}
Yeah I would probably be using MoveRotation personally rather thawn a joint, but this should be alright... at least in terms of clipping stuff
I was trying to just manually rotate them but the table is sloped, and me trying to figure out how to rotate them on a slanted axis like that was melting my brain.
I mean one easy way to shortcut this whole thing is to just make two empty objects in the editor - one at the "rest" rotation and one at the "activated" rotation. Then you can easily just MoveRotation to each of those positions
like:
bool isActivated;
public Transform restObj;
public Transform activeObj;
void FixedUpdate() {
Transform target = isActivated ? activeObj : restObj;
Quaternion targetRotation = target.rotation;
rb.MoveRotation(targetRotation);
}
void PressFlipperButton() {
isActivated = true;
}
void ReleaseFlipperButton() {
isActivated = false;
}
then you don't have to do or think about any rotation math
i'll give this a try. thanks!
Can anyone help me recreate the weld tool from gmod in unity? or just give me some good ideas? Cause im really stupid and cant come up with something good.
Attach the objects with physics joints
Thanks, ill try that.
How should i set it up?
Write code, using AddComponent, to add e.g. a FixedJoint to one object attaching it to the other.
Forgot to say, tysm
Hi, has anyone encountered an issue, after import of Unity.Physics, editor goes into infinite import loop. And knows how to resolve it? On empty project import of samples is fine.
https://docs.unity3d.com/Manual/class-PhysicsManager.html @simple token as youre doing pinball flippers physically, you'll want to increase the solver iterations. You will always get inaccurate results from having such a fast movement (like a 90 degree rotation over 2 frames), increasing the iterations will improve the accuracy
What about fixed time step? I lowered the fixed time step value and it seems to be working better, but idk if there are some unforeseen consequences I'll be facing further down the line
No more clipping in the flipper at least
fixed time step is required for physics, as the it keeps the duration for every physics tick the same, delta time in the other hand can vary by tiny amounts which could generally lead to an unstable simulation.
Iterations are substeps that occur within a physics tick, the more substeps you have, the more accurate the simulation becomes. See how in the image that the blue registers the collision immediately, the red having less substeps caused it to detect the collision but not as fast (less accurate), and the yellow didnt receive any collision and teleported through the wall
the trade off is that it becomes very expensive to have very high iteration count
thank you so much for the thorough explanation! would solver iterations be a more performant solution then?
From the way I understand it, Default Solver Iterations impacts the accuracy of the position after each tick, like how the red square will need to be positioned to be on the walls surface. This is probably the only setting you need worry about
Default Solver Velocity Iterations is purely so the velocity of everything is as accurate as possible at the end of each tick, same sort of principle as the image, but just imagine the red being a little too fast, and yellow being a little too slow. Simple example is slowing down over ice, you'd expect to slow down after X amount of time
reset the fixed time step and bumping the solver iterations to 8 seems to do the trick. thank you so much!
excuse me where would i go to ask questions about specifically the particle system. I really want to learn it and shader graphs but the documatation wasnt helpful or i misused it somehow
how would you guys make a ball bounce differently (less bounce, less speed, etc.) if it bounces on a different surface?
I basically want the ball to bounce lower if it touches grass and speed up or bounce higher if it touches concrete and slow down
anything less than Bounceiness of 1 makes the ball bounce too low in general... but I also want more control over the bounce itself
I know how to make the logic change based on a trigger/collision type... I am more concerned about what numbers to play with
Guys, I am running into this problem. Does anyone know how to fix it? I checked the 2D collider and Rigidbody2D—everything seems fine, but...
You should say what the problem is. This picture is meaningless to us
@timid dove The object is going inside the other object. It is supposed to come out quickly, but after the collision, it goes in and does not try to come out
It's happening when the collision is triggered, and there are some objects in between.
The objects in between are getting stuck in the merged object.
You would have to show:
- the inspectors for the objects (and colliders)
- the code that is moving the objects
I have a question, im not sure if this is the right place to ask, but here goes:
We have a project where we are going to simulate collisions in space and we want objects to be hit by smaller objects and cause some destruction. Lets say a spaceship is hit by some debris, and the hit part would be a bit destroyed and become debris. How would you go about doing this without paying for tools like rayfire. And also if we were to pay for rayfire, would everyone working on the project have to pay for it, or just the person working on the collision parts.?
Rayfire has a "per seat" license which means you pay for each person who directly works with the tool
as for the destruction - there are many ways to do it. You could have your ship made of many smaller MeshRenderers and when one gets hit you could replace that one renderer with a destroyed version (or nothing) and spawn some debris, for example.
Or you could go for a more advanced thing.
Ok, then rayfire might be an option. what we are doing atm is having 2 models, one whole and one cut-up, but im not getting it to work the way i want
anyone able to help me come up with ideas on this please?
Either using physics materials or OnCollisionEnter and a custom component with surface information on it
but what exactly do I change here?
cause physics material bounceiness has too drastic of a change... like anything less than a 1 and the ball just feels like it dies or I cant make it bounce more
Even if you did like .9999?
Should be pretty gradual
I can try .9999 but I usually feel like changes to the physics material bounceiness make it too drastic except for drag
Make sure you understand the combine modes too
Greetings. I have a bolt that can stick in walls with boxcolliders, but bounces off objects with rigidbody AND a collider. Why is that so?
Hi peeps, i was just wondering if anyone could help me with my npc character that moves around 2 feet off the floor on my terrain. Ive unchecked the gravity box on the rigid body which seems to work and not fall through the floor. but now he runs a couple of feet above. ive set the starting position directly on the floor by snapping it. but after a few steps he just levitates. if there is a fix to this that would be greatly appreciated 👍🏻
sounds like your collider is not aligned with the visual part of your character
look at your character in scene view when this happens and double check the collider compared with the renderer
thanks will do
Hello
I have been following along with this tutorial
https://sergioabreu-g.medium.com/how-to-make-active-ragdolls-in-unity-35347dcb952d
So the simulated doll is moving.. just not in the way that it should. It seems that the rotations are messed up
I'm stuck on this part, probably why
How do I set the axis and secondary axis? The numbers seem random to me.
like, is this facing the right way? How do I orient the axes?
Is there any documentation for what can cause a Collider component to recalculate its geometry? (3D)
Wdym by recalculate its geometry?
Are you talking about MeshCollider specifically?
Reduce linear damping to .05-.3 depending on surface
my main concern about changing the linear damping based on surface is then it makes it more difficult for players to aim and hit the ball since that would play a bigger factor than just it bouncing
I guess I could just always change the linear damping after a bounce and then change it back if it touches a players hitbox but that seems like it'd get complicated fast and is at a risk of failing eventually
I did change physics materials a bit such as dynamic friction and bounciness which is a good start but I need more improvements as well. But I feel like linear damping just makes things more... complicated
There’s only so many properties to play with here I think.
well I'm gonna try your suggestion and see how it goes
although the only thing I am running into right now is the ball doesn't seem to spawn with its default value
private void OnTriggerEnter(Collider other)
{
if (!(base.isServer))
{
return;
}
if (other.CompareTag("Hitbox"))
{
Rigidbody rb = GetComponent<Rigidbody>();
rb.linearDamping = 0.5f;
}
if (other.CompareTag("Clay"))
{
Debug.Log("Clay");
Rigidbody rb = GetComponent<Rigidbody>();
rb.linearDamping = 1f;
}
if (other.CompareTag("Hard"))
{
Debug.Log("Hard");
Rigidbody rb = GetComponent<Rigidbody>();
rb.linearDamping = 0.5f;
}
if (other.CompareTag("Grass"))
{
Debug.Log("Grass");
Rigidbody rb = GetComponent<Rigidbody>();
rb.linearDamping = 0.2f;
}
}
I have the default value as 0.5 on the prefab, but when the ball spawns it uses the value of something else. but its too high and far away from any triggers tagged these objects.
So hello people.... I ugh, may have been developing my own deterministic physics system thinking that Unity's physics engine wasn't deterministic. I was just recently told that it now is. Ugh... can anybody tell me what their experience has been?
https://docs.unity3d.com/Packages/com.unity.physics@1.3/manual/index.html <== Says right there, it's deterministic.
In the picture; a snapshot of the unit tests behind my system to make a deterministic physics model (2D).
namespace OmiGames.Numerics.Fixed {
using System.Diagnostics;
using System.Numerics;
using System.Runtime.InteropServices;
using UnityEngine;
[StructLayout(LayoutKind.Explicit)]
[Serializable]
public struct Fixed64 : IEquatable<Fixed64> {
public static readonly Fixed64 Zero = new Fixed64(0);
public static readonly Fixed64 One = new Fixed64(1);
public static readonly Fixed64 NegativeOne = new Fixed64(-1);
public static readonly Fixed64 Epsilon = new Fixed64 { _value = 1 };
public const int FRACTIONAL_BITS = 16;
public const long SCALE_FACTOR = 1L << FRACTIONAL_BITS; // 2^16
[FieldOffset(0)] private bool _signPart;
[FieldOffset(0), SerializeField] private long _value;
[FieldOffset((64 - FRACTIONAL_BITS) / 8)] private Int16 _fracPart;
// Constructors
public Fixed64(long integerPart) {
_signPart = false;
_fracPart = 0;
_value = integerPart * SCALE_FACTOR;
}
public Fixed64(double value) {
_signPart = false;
_fracPart = 0;
_value = (long)(value * SCALE_FACTOR);
}
public static explicit operator Fixed64(double value) => new Fixed64(value);
public static explicit operator Fixed64(long value) => new Fixed64(value);```
Here's the start of my "double" for some context as to the well of despair I might have set myself in.
"Unity's physics engine" is a bit of a misleading phrase, as there are at least 4 officially supported physics engines
So it depends what you're comparing it with
It also depends on your definition of "deterministic"
I'm making a game where the player is able to WallJump/Jump and shoot downards at the same time. My problem is when they shoot and jump at the same time the velocity in the upwards direction becomes way to high I've tried a bunch of things with limiting velocity and applying scaled amount of force depending on speed. But this is all extremely Janky any good suggestions to make this smoothly?
It's really pointless to suggest anything without seeing how your existing code works. Why would the shooting matter?
Hello guys, does anyone have a function to calculate time to cover distance by a rigid body?
Distance = rate * time
so time = distance / rate
What rate, sorry?
So let's say a rigid body 2D weight 1kg was launched 10 m/s with drag 5 was just launched. Now I want to know how long it will take it to cover 100 meters and if it will even reach it.
rate meaning velocity/speed
There's also drag, right?
the mass is irrelevant
rate is 10
drag matters yes
if you want to incorporate drag it's more complex
with no drag this would simply be:
t = d / r
t = 100 / 10
t = 10 seconds
with drag you need to know how Unity calculates drag which is kind of opaque, but people have reverse engineered it. It might be better to use your own drag formula though so you know precisely how it works.
I found this for the future position:
public Vector2 FuturePosition(float Time) {
// Starting position
Vector2 Position = RigidBody2D.position;
// Drag multiplier (friction)
float Drag = Mathf.Clamp01(1.0f - (RigidBody2D.linearDamping * UnityEngine.Time.fixedDeltaTime));
// How much velocity is added per frame
Vector2 VelocityPerFrame = RigidBody2D.linearVelocity;
// How many frames are going to pass in the given time
float FramesInTime = Time / UnityEngine.Time.fixedDeltaTime;
for(int Index = 0; Index < FramesInTime; Index++) {
VelocityPerFrame *= Drag;
Position += (VelocityPerFrame * UnityEngine.Time.fixedDeltaTime);
}
return Position;
}
But I'd also like to have time to coover distance and also how much total distance rigid body will travel.
I can add my own drag formula directly to rigid body?
Or would I have to use inheritance, or implement movement of everything myself?
you would write a script to apply the drag force
in FixedUpdate
why inheritance?
Yeah I was thinking more of virtual void ApplyDrag in RigidBody2D, so then I'd create a C# class, inherit from RigidBody2D and override that using the default physics formula.
But you say custom drag in a class, makes sense
Can I find somewhere where people reverse engineered it?

I thought you have something specific in mind
Wait, there's also a friction on the material?
So I took the formula of the next velocity: velocity = velocity * ( 1 - deltaTime * drag); from the forums. Does this look right:
public float? TimeToCoverDistance(float Distance) {
Vector2 CurrentVelocity = RigidBody2D.linearVelocity;
float DistanceTraveled = 0f;
int TicksToTravelDistance = 1;
if(CurrentVelocity.magnitude > Distance)
return Time.fixedDeltaTime;
while(true) {
TicksToTravelDistance++;
CurrentVelocity = CurrentVelocity * (1 - Time.fixedDeltaTime * RigidBody2D.linearDamping);
if(CurrentVelocity.magnitude < 0.01f)
return null;
DistanceTraveled += CurrentVelocity.magnitude;
if(DistanceTraveled > Distance)
return TicksToTravelDistance * Time.fixedDeltaTime;
}
}
Can you give colliders custom callbacks for narrow phase detection?
I need to be able to raycast against different points inside my gameobject, but creating a bunch of child GOs is really wasteful for my application
you can't do a custom physics shape implementation if that's what you're asking?
Can you describe the problem a little more?
Like I have this curved road object which can have its bezier manipulated using the 4 control points, currently these are child objects
for a city builder which needs like 10k of them to exist I want to avoid needing an entire gameobject per point (both because of performance and code complexity) Ideally these 4 points are just Vector3 in my road
I will later explore ECS for performance, but wanted to stick to classical unity for now
Are you not using the Splines package?
No, my own custom vertex shader
Let the physics engine handle the broad phase basically with a large crude collider for the whole road. Then you just have to do four ray-> sphere intersections to see if you hit one of the control points
I guess there's no way to raycast against 'procedural' colliders?
In general yes but not with Physics.Raycast
You can certainly write your own math as I am encouraging in my above suggestion
Yes, I suppose I will make roads selectable via my bounds and then just maually test against my points in the script
Alright, that makes more sense anyway
Interested to hear how it goes
Though I also wanted my road selection to work based on the bezier curves, but 10k mesh colliders would probably be too expensive
I'd like to use AABB for broad phase, then a custom ray-bezier_road test for narrow phase, but there is no way to somehow reject box collider hits based on a custom callback?
So I would have to implement it myself from scratch? BVH and all?
I would just give your curve a box collider and dynamically resize it to match the AABB of the renderer
(make sure it's not rotated as well ofc)
That's what I did, I'd like more accurate raycasting against the curve though, but not sure how to do that without generating a mesh for every single road
that part is just some spline math
And this is kinda why I mentioned the Unity spline package earlier. Because it has tools for this kind of thing already built in. Spline math can be complex.
- Do Plane.raycast (or sample your terrain or whatever) to find the point on the plane.
- Use https://docs.unity3d.com/Packages/com.unity.splines@2.7/api/UnityEngine.Splines.SplineUtility.html#UnityEngine_Splines_SplineUtility_GetNearestPoint__1___0_Unity_Mathematics_float3_Unity_Mathematics_float3__System_Single__System_Int32_System_Int32_ to find the distance to the spline
- if the distance is < a threshold, you can decide it's a "hit"
If you must use your own spline code then you'll have to figure out the math on your own. Here's Unity's implementation which might or might not be useful for you:
https://github.com/needle-mirror/com.unity.splines/blob/40d982dcb2b450c65170868d780536428a10f05a/Runtime/SplineUtility.cs#L680
How do I do that if I have >10k of these splines though?
I would need to manually build a BVH of roads first
actually, RaycastAll could give me all the box colliders so I can then manually compute the narrow phase curve intersections and pick the closest one
Well, what I really need is for some simulation with some initial conditions to remain consistent after some number of discrete changes.
Like, from state 0, if we move objects by some transformation A and then apply a transformation B, we get some result in state 1. If I replay this simulation again at a later date, we get exactly the same state 1, given state 0 and the transformations A and B.
consistent in what context? Is there a network involved?
If you're talking about on the same hardware, then all of the physics engines are deterministic
as there is no randomness in any of them
the main "nondeterministic" problem comes from floating point calculations across different hardware not giving precisely the same results
Yes, but for that I was going to use a lockstep or rollback solution with server.
I would prefer different machines give the same result - that was my main concern.
if you can always guarantee that it's the server that will be doing the same simulation then you have no issue.
as long as you only run it on the same hardware 😛
Yeah, my preference is to distribute authority and not use a server, but I was playing with the idea of rollback in a strategy game. My naive implementation was going to be lockstep, preferably with the simulation layer guarded so that I don't have to worry about different machines thinking up different results.
The network updates were going to be discrete and guaranteed to be applied in a certain order.
I was hoping to have a simulation that is robust enough to not require that positions of things need be reconciled.
public class Baker : Baker<UnitMovementDataAuthoring> {
public override void Bake(UnitMovementDataAuthoring authoring) {
Entity entity = GetEntity(TransformUsageFlags.Dynamic);
AddComponent(entity, new UnitMovementData {
movementStyle = authoring.movementStyle,
moveMaxSpeed = new Fixed64(authoring.moveMaxSpeed),
moveAcceleration = new Fixed64(authoring.moveAcceleration),
moveStopDistance = new Fixed64(authoring.moveStopDistance),
rotationMaxSpeed = new Fixed64(authoring.rotationMaxSpeed),
rotationEasingThreshold = new Fixed64(authoring.rotationEasingThreshold),
});
}
}```
I hope this gets my intention across - basically, I am using Unity as a presentation layer as much as I can and was going to try to own the simulation in pure C# as much as possible. The granularity that I actually need for this simulation doesn't have to be super-scientifically accurate so long as I know that the results will always be the same. For trigonometric functions, I was going to back some lookup tables to take the worry out of getting results that differ between systems.
I am wondering if this is necessary now, if Unity's modern physics is deterministic in the sense that I was needing it to be.
its stateless physics (not necessarily 'modern'), so probably
I was hoping for a distinct "yes" or "no" if anyone had had to check this out in the past, but likely the only really great way forward is to test. >_>

