#⚛️┃physics
1 messages · Page 30 of 1
fixed it on my own
what happened lol?
I would guess a script setting the vertical velocity to 0 each frame, that's the usual cause
Anyone able to help me debug my Client Prediction setup for my game, Im currently predicting the entire scene, this includes water, bouyancy and the boats, Meaning that almost everything you see as a client is ahead of the server, the clients then receive updates from my server, client then resets to this update and re-simulates back up to its current frame, continuously realligning the client with the server. im specifically stuggling with the boat destruction and im getting some jitter when splitting boats which indicates a difference in state, Im reappling joints and resimulating the destruction for clients which i believe is potentially causing this jitter, wondering if theres any experts out there which know everything there is to know about adding/destroying joints specifically fixed joints.
Hi, does anyone know of a clean way to move a non-kinematic rigidbody character on a moving kinematic-rigidbody platform? I currently have the platform using a spline so that it loops around smoothly in FixedUpdate.
Here is the script for the moving platform currently:
public class MovingObjectParenter : MonoBehaviour
{
[SerializeField] private Rigidbody rb;
[SerializeField] private List<Rigidbody> collected;
private Vector3 prevPos;
private Vector3 _velocity;
void Start()
{
prevPos = rb.position;
}
void FixedUpdate()
{
Vector3 _distance = rb.position - prevPos;
_velocity = _distance;
for (int i = 0; i < collected.Count; i++)
{
collected[i].MovePosition(collected[i].position + _velocity);
}
for (int i = 0; i < agents.Count; i++)
{
agents[i].Move(_velocity);
}
prevPos = rb.position;
}
private void OnTriggerEnter(Collider other)
{
if (other.TryGetComponent(out Rigidbody _rb))
{
if (!collected.Contains(_rb)) collected.Add(_rb);
}
}
private void OnTriggerExit(Collider other)
{
if (other.TryGetComponent(out Rigidbody _rb))
{
if (collected.Contains(_rb)) collected.Remove(_rb);
}
}
}
It "somewhat" works on the player, but the player slides around too much during the movement. Any help is appreciated. Note: I move the player rigidbody using AddForce.
Here's how it looks like
How much does your game require you to stick to platforms like that?
None so far because I hadn't figured out a good way to do so haha. But if I can get this to work, I had an idea for a level designed to be entirely moving
Unless I can figure out an alternative way to "fake" that movement I guess
my game is above we move entirely on moving boats
What are you struggling with?
It's mainly keeping the rigidbody player on the moving platform. Either the player just doesn't move fast enough with the platform or he slides too much in the direction of the platform's movement
How are you moving the platform? does it have physical movement with a RB? or are you just moving its transform.position?
It's using an asset called Dreamteck Splines which moves the platform's kinematic rigidbody with MovePosition along the spline in FixedUpdate
Sounds strange, gets a bit more difficult when you use RBs on your platforms also, i dont think you can match velocity here because not sure if MovePosition updates velocity
It does update the velocity and is the way moving kinematic platforms should be implemented as far as I know (if one wants to use the physics system)
If i were you i would make a child object of the platform, with no physics & i would set the players rb.MovePosition(ChildObject) each frame
you can then apply player movement to the child object which will automatically consider the movement of the platform
Is it possible to add IK to joints in any meaningful way? Or, joints to ik.
ideally, they would behave the same like normal IK but be reactive with the environment?
Or do I have to forego the animator and write some kind of movement system for the joint that would emulate ik movement?
You may want to have a look at the animation rigging package and see if it can do what you want https://docs.unity3d.com/Packages/com.unity.animation.rigging@1.4/manual/index.html
I have already used anim rigging extensively. I'm trying to figure out if and how I might combine it with joint behavior or some other kind of rigidbody type physics behavior because rigidbodies DO NOT like animations and vice versa
Well, they are fundamentally opposed concepts. To make them cooperate you need some sort of negotiation mechanism like Ubisoft‘s IK Rig discussed here https://youtu.be/KLjTU0yKS00?si=ORFMo95zwygaAhmh
In this 2016 GDC talk, Ubisoft's Alexander Bereznyak breaks down the basics of IK Rig technology for animators, and explains how it can be used for everything from video games to feature films.
Register for GDC: http://ubm.io/2gk5KTU
Join the GDC mailing list: http://www.gdconf.com/subscribe
Follow GDC on Twitter: https://twitter.com/Officia...
from a glance, it seems like that isn't even exactly what I'm talking about, it wouldn't achieve the same goal
the closest thing to what I'm trying to do is puppet master but I've also tested that in a number of ways and it didn't work in my case
maybe I should remake puppet master with my own rules and joint types and logic etc.
hey i'm making a 2d platformer game and just started making the prototype and almost finshed the movement script done but i have a bug where my rig or player is sticking to the edge of a box collider 2d here my code using UnityEngine;
using UnityEngine.InputSystem;
you will not get credit when i realse the game
because i will forget your name or username https://paste.mod.gg/cuvicopulcbs/0
A tool for sharing your source code with the world!
What is this video showing about the issue? All I see is a player moving forward (or the environment moving backwards)
If your character was moved by recalculating the velocity each frame, it'd be easy to just add the current platform's velocity to the final velocity before applying
The platform is moving forward and I'm applying its velocity to the player, but the player slides forward without me touching the controls
I'm using rigidbody.MovePosition to apply the platform's movement change to the player
My physics is in simulation mode: script for networking purposes, and ive realised that interpolation does not work when in this mode for some reason, does anyone have any fixes for this or know of any workarounds to get some interpolation, otherwise my objects just move at the fixedUpdate rate which is only 50fps
I have an ik chain for my player's arm which grabs the environment and pulls the player forward when moving (or at least that's what it should look like).
It works well but it doesn't have reactivity with the environment that I would want.
I turned off the animator and rig weight and tried building a chain of configurable joints. It gets me the reactivity that I want (i.e. player extends hand forward but is blocked by a terrain piece jutting out, so he bends the arms inward) but I find this hard to control.
It also only works if it gets stuck there for a bit, otherwise it just moves forward through parenting.
I have problems transitioning the animation to the next iteration of it because my hand just gets stuck behind the player.
Bare in mind, I'm talking about crawling through tight tunnels and pulling myself forward with the hands. Even if I manage go get the hand stuck on terrain (purpose being to make it appear like he's grabbed the terrain, it gets left behind the player when he moves forward and there is no space to bring it back.
I've been thinking of some kind of system that combines joints and ik but it's tough to make that combo work I think. Does anyone have any ideas on what I could do here?
Making a dual rig is another options without joints, just rigidbody colliders but I'll have the same problem pulling it back
Working with an fps movement system i created based on dani's old movement tutorial but heavily adapted to my needs. Everything works great the only problem is the fundamental issue of applying external impulses (such as an explosion force) or a knockback.
The system doesn't use unity's friction (friction on all objects is zero) and instead uses a custom countermovment logic, the problem is that when a player recieves a horizontal knockback while grounded they barely move, compared to while airborne they go flying.
This seems to me like a fundamental flaw in the movement system I created, but pivoting to a whole new system is kind of impossble right now unless absolutely neccessary.
Any other advice and feedback regarding the code is also very welcome!
*Main movement lines are 700-800
This is for an fps parkour game
For additional reference, the player should not be able to surpass their maxspeed with their own input (walking, sprinting, etc), but things like external impulses (explosions, and such) should allow the player to go far beyond their max speed
I haven't read your code (on mobile) but it sounds like you're probably doing something like setting velocity explicitly while grounded which is overwriting the changes made by any external forces
im almost sure the problem is coming from the countermovement block which is used to keep the movement snappy and also stop the player when no inputs are pressed and they are grounded, the problem is how the countermovement is programmed is contradictory to letting external forces be applied and i don't really know how to still keep the movemeent snappy but also allow things like explosions and impulses to affect the player
perhaps i could have an external script handle the forces applied to the player applied by explosions, but i don't even know where i would get started
From also not reading the code (on mobile too) it just sounds like it works as it's supposed to. On ground the friction is gonna be much higher than in air
You can modify the counter force in air to make it a bit better
hey so I'm turning gravity on in a rigidbody via a script like so:
public void Interact() {
if (Player.Instance.HasBeerCup()) {
//Player is carrying a beer cup
BeerCup playerBeerCup = Player.Instance.GetBeerCup();
playerBeerCup.SetBeerCupParent(this);
int beerCupTableLayer = 7;
beerCup.SetBeerCupLayer(beerCupTableLayer);
beerCup.transform.GetComponent<Rigidbody>().useGravity = true;
float beerCupPushForce = beerCup.transform.GetComponent<Rigidbody>().mass * 2 * (tableLength / Mathf.Pow(timeForBeerToGoToTheEnd, 2));
beerCup.Push(transform.right, beerCupPushForce);
}
}
but for some reason, despite me turning gravity on, the rigidbody still won't fall
I already checked if it is kinematic, which it wasn't
has anyone encountered this before?
this interact function is also only called once; when the player clicks the interact button
but for one, it seems like the rb moves forever
and two, the y value never changes--so the gravity isn't working
I've also tried adding a friction physics material to the surface but that doesn't seem to stop it either
Have you checked if it actually isnt kinematic and IS using gravity in the editor?
After u cause the script to change them ofc
And change it manually to see if it's a problem with the script or with the rigidbody
Hey, I am trying to make a pong clone but I am a bit unsure on how to handle the physics. I made the two player paddles by locking the X and Z axis, and moving them up and down with rb.MovePosition(). Still, when the ball hits one of the paddles from up or down, that paddle it's pushed because of the applied force.
I tried using Kinematic body type but now learned that it doesn't interact with other objects. Is there a way to create a body that cannot be pushed by other objects but still be stopped by static ones or push other objects?
You can increase the mass of the rigidobies and they shouldn't be pushed by the ball
But really, the best way would be to use kinematic rigidbodies and manually code the ball movement as it would only require using reflection vectors and no other calculations.
I see, I like that approach. Just one thing, that's I limit the paddles movement by having a static object with two edge colliders on top and bottom to stop the paddles from going offscreen. Is there any way to detect this thing by code?
My first guess would be to establish a max and min y in a variable and not allowing the paddles to move further if they are already there, but I wonder if there is a different aproach
That's the best approach
I see, thanks!
@tender gulch #💻┃unity-talk message
that does not seem to work
I double checked all colliders, main one have a layer not included in mask, all other colliders have layers included in a mask, and everything have rigidbodies
code samples in case
Physics.Raycast(shooting_barrel.position, mob_ai.target.coords - shooting_barrel.position, out RaycastHit hit, test_mask_of_shooting);
RaycastHit[] hits = Physics.RaycastAll(shooting_barrel.position, mob_ai.target.coords - shooting_barrel.position, test_mask_of_shooting);
foreach (var ht in hits)
{
Debug.Log("RaycastAll hit " + ht.transform);
}
Debug.Log("Raycast hit " + hit.transform);
Maybe Unity don't allow parent collider exclusion?
Raycasting all hits everything, Raycasting one hits only first biggest collider (parent)
Try logging hit.rigidbody.gameobject.
As well as hit.collider.gameobject
they are the same
all that looks right
I mean I can just use RaycastAll and pick what I want but I don't understand why Raycasts hitting everything
Just to be sure, what type is test_mask_of_shooting?
And can you log it's value along the raycast as well?
As well as the layer of the hit object.
Also....
Can you put the normal raycast log right after the raycast and not after raycast all?
it's a LayerMask
seems like logging out LayerMask doesn't work
try casting it to int and logging
640... whatever that means
I ve heard of bitwise operators or something but it looked like LayerMask type allowed me to bypass that
that might be it!
I mean issues with a mask
It's 8th and 10th layers I think.
or rather index 7 and 9
So, RaycastAll showing that it hit layer 8 must not be using the layermask🤔
Yeah, it's probably used as the max distance:
public static RaycastHit[] RaycastAll(Vector3 origin, Vector3 direction, float maxDistance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal);
And probably same in the single cast as well:
public static bool Raycast(Vector3 origin, Vector3 direction, float maxDistance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal);
So you're just not using the layermask as a layermask
guys im trying to use character controller for my player but its not applying collisions so it just phases through the floor and falls, but when I try to put a BoxCollider it says it conflicts with the character controller
CharacterController does not support extra colliders. It acts as a capsule collider for itself
So the issue is in your code or object setup
Does the floor have a proper collider?
it has a boxcollider
Have you confirmed that it is the correct size
If yes, then it's probably a code issue
Your character movement code
the movement code is literally just this
btw after messing up some properties, now the player just get stuck in the same y position instead of falling
oh god
that's pretty embarrassing
thanks for saving me
If this is your movement code I wouldn't expect any vertical motion at all. Are you also using a Rigidbody?
you can't use CC together with RB, they will fight each other
praetor's question wasn't a suggestion
with a CC, you need to apply gravity yourself
and how I do that
well, normally, you'd store the vertical velocity yourself, apply acceleration, and then combine that with the horizontal velocity in the move (1 move per frame)
(with extra logic - if grounded, apply a fixed grounded vertical velocity)
i don't know how much, if any, of that changes with the context of network
though, on that note - i do notice that you're using FixedUpdateNetwork there? if that's analogous to FixedUpdate, then that'd be the wrong method - CC expects to work on Update
and how I apply collision with anything I want, like walls, and the other players from the room as well
i believe that's handled by CC, assuming your Move calls are set up correctly
PhysX docs says that you should call Move only once per frame
Can anybody explain articulation bodies to me?
Loke, I tried chaining joints to one another for something, but it was unstable and jittery when constantly colliding with stuff.
All I understand is that art. bodies are supposed to help with that. Maybe? What is the feature that makes them more enticing that joints?
the rigidbody's velocity stays at zero, even though it's explicitly marked as nonkinematic and has a velocity change of 250 being applied to it
the fragments that come off. they're visibly moving, but they should be going extremely fast. currently they just fall
it is. debug messages, and even changes to the rigidbody besides velocity all get correctly applied
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
rb setup:
waiiit 3d rigidbodies do have info..
indeed they do
why was it missing here lmao #💻┃code-beginner message
use force impulse on your rigidbody 24/7
don't do that.
ok fine add an input command first then do it and become superman
impulse isn't a continuous force
multiply it by 100
that's not at all relevant to what i said
where's force coming from?
its a rigidbody command
have you tried debugging the overall force you're applying, eg force * mult * 100
variable. i've already debug logged this and it's set properly to 250
though i guess you'd just have to debug force, it's the only possibly-zero one there
and you've debugged that it's indeed velocitychange?
yes
are you doing linearVelocity = ... anywhere?
well, that's all my ideas
Are you sure this code is running? Maybe hitRB is coming back as null
yes, the code's running. no null errors
ok, it looks like destroying the fixedjoint before adding the force fixes it. the only problem is that i don't want to guarantee that damaging the thing will kill the joint...
I didn't say errors. There wouldn't be any errors if that variable was null
i’d assume there would be a null reference exception, which i would definitely consider an error
Why would you assume that? Your code is explicitly checking the variable with an if statement. There wouldn't be an exception, it would just silently do nothing.
oh right, i forgot i had a check in there. either way, yes, the code runs
what's the best way to check how much distance a raycast/linecast "spent" in a collider? i have an idea to just raycast in two directions (first raycast from A to B, another one from B to A), check their raycast hits and calculate the distance between their points, but maybe there's a better way to do that?
hit.fraction
tells you the fraction of the ray to the hit point
the other part is past the hit point, which you could assume is inside the collider
it gives an answer from 0.0 - 1.0 so youd have to multiply by ray length to get the actual length
if you want something more complex, like also being able to tell when the ray leaves, I would use RaycastAll
itll give you all the points, and you can feed that into some system to figure out how much distance the ray was inside the collider. Its probably kinda complicated tho
since there will be multiple points
im also unsure if you would get the exit point actually
you may have to raycast in the opposite direction
alright, i'll try that. though if there's no other way to get the exit point, then i'll probably stick to my 2 ray solution :/
or i could also raycastall from both points (A-B and B-A), collect all the hits, sort them by dist from A and then create pairs from that (if a linecast between two points finds an obstacle, it means that these two points are probably start/end of a line IN the collider) and check the dist between two points in each pair.
that is the solution
there may be edge cases, but im not 100% sure
well, i think it should be quite accurate but there may be some physx quirks that i dont know. but it should be ok
if i have a question about colliders and how the Collider.bounds.Contains works, do I ask it here?
yep
okay so, super simple question, and the docs are all telling me that I'm right here but just checking, if I have a mesh collider with two cubes stacked on top of eachother, with the second cube on top being much bigger, and im checking the meshcollider's bounds.Contains, what is the actual bounds of this? is it gonna extend the small cube's bounds when calculating to the bounds of the bigger cube? i dont know if this makes much sense lol
basically, if the mesh collider is the black part, is the bounds.Contains simulating the inside as the green part?
yes, the bounds of something is just some rectangular cuboid that encompasses the entire thing.
in the case of unity, Bounds is an AABB, an axis-aligned bounding box
collider.bounds.Contains doesn't check for something being in the collider. it gets the bounds of the collider, and it checks if something is in those bounds
thanks for the clarifications :p
Can I calculate a rigidbody's velocity so it moves around a point in an orbit?
yes
How exactly?
I tried some methods, but they all involve also rotating the rigidbody, which I dont want
compute it tangential to the vector between the rigidbody and the center and then keep updating it
that's basically how circular motion works physically
As in, the perpendicular vector of (rigidbody-center)?
In kinematics, circular motion is movement of an object along a circle or rotation along a circular arc. It can be uniform, with a constant rate of rotation and constant tangential speed, or non-uniform with a changing rate of rotation. The rotation around a fixed axis of a three-dimensional body involves the circular motion of its parts. The eq...
mb, i combined "tangential to the circle of orbit" and "perpendicular to the vector between the rigidbody and the center" lmao
your interpretation is correct
@tender vapor thank you
if you don't want to rotate it, then you can't or shouldn't use velocity, make it kinematic and just calculate an orbit position (which is simple trigonometry) without using force simulation.
how are those 2 things related
you can just set the linear velocity for a dynamic rigidbody just fine
that wouldn't be related to the position, so im not sure
a kinematic rigidbody (or no rb at all) might be easier to work with depending on what the overall goal is, but i'm not seeing how that decision relates to rotating it or not
like a kinematic rb for an obstacle that shouldn't stop for anything, as if it had arbitrarily high mass
maybe you can give a bit more context. Do you actually want a physics simulation regarding motion of that orbiting object or do you you just need that object to have a trigger? why is it a rigidbody? this would illuminate which approach would be the most practical for your project.
Ello, I'm currently trying to figure out how to test if a box intersects with a Concave mesh repersented by an SDF. If you need to figure out if a box overlaps other things without direct physics methods, do you just raycast 12 times(1 along each edge of a box) to figure out if something is intersecting without containing the box? (ps: if a sdf contains 1 vertex of a box, but not all of them, then it has to intersect.)
How much of a wizard must one be to get rigidbodies not to shake and jitter with precise movements and frequent collision?
There are a lot of cases where the physics might appear unstable and jittery. Do you have a specific example in mind? In order to be fast and stable in most cases, the physics system can make some assumptions about the "general use case"
out of the box as long as you're using interpolation, it shouldn't be jittery
well it is for me
I am trying to make dual rig: animation + IK => rigidbody + joints
it even works with addtorque and addforce, it tries to get there, but there is just a whole lot of shaking
the issue is the hands (what I'm trying to rig like this) scrape along terrain etc. and I can't get them to be stable
you've done something wrong then. Hard to say what without seeing your project.
animation + IK + physics is almost certainly the issue
It's not something I've ever worked with so I don't know what steps you need to take to make that work, but it's a complicated setup
how
the animation ik and rb are completely unrelated in this context
those are two completely different systems competing over setting the pose of the objects
well how would I know that?
Point is, I do the logic for the IK. The animations play and all that.
Then I have a completely separate hand model that just gets the transforms and rotations of each of the components (arm, forearm, etc) and use AddForce and AddTorque to match that transform, but with physical collisions and reactions
so the fact that animations and ik are used is completely unrelated to the rigidbodies
But even before this, I tried a simple test. I didn't use animations or IK or anything. I literally just stuck a hand with configurable joints that was anchored to the player, that's it. And even that would jitter and shake.
Like, I just cannot get rigidbodies to not shake when they are doing constant collisions and trying to move (in that instance, the joints were trying to spring back to the default position)
@pulsar canopy Do you mean really fast jittering (direction changing ~each frame) or slower oscillations/wobbliness?
You might just need to add some damping to the forces to avoid overshoot
Joints and physics also have a lot of settings that can help with stability
that might help, I will try
joints yeah, I fiddled with a lot of settings
what about "physics"? Any settings I should know about?
defaultSolverIterations, defaultSolverVelocityIterations come to mind
https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Physics.html
And ofc Time.fixedDeltaTime
ah, that. To my recollection, I did increase solver iterations
But I'm still unsure if you're having an instability issue or a damping/overshoot issue (or both)
A video could help
but I actually didn't know about velocity iterations. However, I use force, so that might not come into play?
Forces are just another way of modifying velocity
It can't really be an overshoot issue because it jitters back and forth even before it reaches the target (the force direction being the target)
Just to rule one thing off, are you making rigidbodies children of other rigidbodies?
also, I made it so that forces stop being added when it reaches .1 of the position, and at that point my hand (last in the chain), just turns off like a circular saw, spins a couple of revolutions and stops lol
yes
And are you moving any of the rigidbodies via its transform (i.e. transform.position = , or an animator controlling it directly)?
no, ofc not
That's problematic
strictly addForce and addTorque
A rigidbody being a child of another rigidbody (unless kinematic i guess) counts as its transform being modified
Because a child tries to follow its parent transform
Are they all supposed to a separate game object that just follow via code?
So avoid rigidbody parenting. Have them as "siblings" instead
Yeah
ok I will try that
That's how i've done my active ragdolls
You can still have them under an empty parent "container" object so they aren't just loose in your scene
(And don't move that parent)
a little while back, I tried using puppet master for this very thing and it had the same issue of jittering and shaking. Couldn't get it to be stable.
That also automatically set it up so that the rigidbodies are in the default armature chain
and used character joints, but that's unrealted
yeah ok I understand that much...
Yeah I'm a bit confused because IIRC unity's built in ragdoll wizard also creates joints that are parented to each other. But I've never had good experiences with rigidbody parenting
yeah. So the implication is that you've also had issues with parented rbs?
Definitely, I'd say you should never do that
well then, I'm confused as to why they're done that way but ok
also, I find the character joint to be the most stable. Other ones behave weirdly for me.
Maybe character joints are good too but they don't have a force driving them back to the default position, so you use them as ragdolls (they are limp like fish)
But I suppose if I'm just adding forces towards positions and rotations, they should work ok for me?
Idk, I opted for ConfigurableJoint because it exposes all the properties and can do everything that other joints can do
It's obviously more complex
But I'd say you can do most of it with forces/torques too
Here's some good helper code for setting target rotations of a ConfigurableJoint if you'll ever use that
https://gist.github.com/mstevenson/4958837
That's how I make the ragdoll bone follow the animated target bone's rotation
So have made dual rigs before?
I figured out the code, I just didn't add any damping
should I just damp the force based on proximity or something?
I think you'd usually do damping by taking the current velocity into account when calculating the force
I just used builtin damping of ConfigurableJoint springs
oh
yeah I do use damping there tbh
I guess I'll have to play around there. But I'm curious whether unparenting will solve anything for me
Yes and it was a lot of work, especially if you need somewhat realistic motion
For goofy games it isnt that bad
Unparenting seems to have solved the jitter, which is great
I need to solve other problems. Probably change the physics material to low friction and some logic, then modify a lot of the values
Just saw 6.4 beta launched. Does anyone know when this is coming 👀
did they elaborate on what they mean with the physics improvements
pretty sure it was talked about more in the video where this was announced
improving their DOTS Physics quality
I guess PhysX (game object physics backend) still more stable
physx and unity physics also solve different problems, the latter being a deterministic (non-iterative) solution that is, because of that, simpler and easier to sync/parallelize than iterative solvers like physx, it also likely means that its not as complete on the solver side and can't solve complex constraints as robustly as physx.
Hey everyone. I just encounter an issue can anyone help me?
when i shoot or fire shells at my tanks it flew far that's shouldn't happen but it happened..can anyone tell me what i did wrong?
or how can i fix it?
that's nowhere near enough info to help
something like this?
and sometimes it flew far like.... alot far out of the arena.
anyone?
Still not enough info. What objects have rigidbodies and what type of colliders do they have? Like maybe the shell's rigidbody and collider is pushing the tank. What does your code do, etc.
if you're not doing it already, you can try applying the forces in FixedUpdate
that can fix some inconsistencies with physics forces
not sure if this is the right channel but how can i possibly fix this
okkkay
ok i'll try that
it's prefabs from the tutorials i'm just doing as they instructs us to do
you can see that on unity hub learn
the tanks have rigidbody and box collider
shell have rigidbody and capsule collider?
is this an issue ?
//add groundSpeed, positionVelocity and the platform's velocity
rb.linearVelocity = groundSpeed * (Vector2)getTransformVec(Vector2.right) + positionVelocity + platformRBVelocity;``` This is my movement function. groundSpeed is the player's regular speed, and it has acceleration and deceleration. platformRBVelocity is the velocity of a moving platform, and it is added to the overall velocity to keep the player moving with the platform. As you can see in the video, it works normally when the player is moving in the same direction as the platform, but because groundSpeed is larger than rb.linearVelocity.x when moving the opposite direction, the deceleration makes the player move slightly to the right.
How do I fix this?
ah so you have applied the acc/dec to the combined velocity not just the player
couple of options - make sure you subtract the platform velocity before applying the acc/dec calculation
or you decouple the groundspeed entirely so it's never influenced by the platform
Technically, this is what happens
groundSpeed and acc/dec happens before applying every other needed velocity
ah no, groundspeed is being updated by the final velocity which will include the platform
So, what exactly do I do?
I still need to make the player move accordingly with the platform
i'd separate them out
do the vector 2 calc: groundspeed * etc
then add the platform in on the next line down
rb.linearvel = player + platform
Same thing happens
what's the new code?
//add groundSpeed, positionVelocity and the platform's velocity
rb.linearVelocity = groundSpeed * (Vector2)getTransformVec(Vector2.right) + positionVelocity;
rb.linearVelocity+=platformRBVelocity;```
@arctic echo Again, groundSpeed is unrelated to the platform's velocity, its just that the linearVelocity is composed of groundSpeed+platformVelocity
yeah so replace groundspeed with relative speed and then add a float first step reset relativespeed = groundspeed
relative speed?
then the prior value doesn't stack and re-enter the loop
yeah just a placeholder variable that ticks up each time
float relspeed = ground speed
relspeed = { xxxx}
vector 2 playervel = { yy}
and then the linervel
Where am I supposed to to use relative speed then?
everywhere except the first line
Even in the accelDecel function?
yes
Wouldnt this render groundSpeed completely useless
lol no you need to replace that with the calculation for it - ie. linearvel - platformvel
placeholder variable
Im just confused on what xxxx and yy supposed to mean
like is xxxx just my accel
the content of your existing code
i'm trying to avoid doing a copy paste solve for you :p
Honestly a copy and paste might be better than this guessing game
so long as you get the idea - make the two vel calculations separately
float relativeSpeed = rb.linearVelocity.x - platformRBVelocity.x;
relativeSpeed = generalStaticFuncs.accelDecel(
relativeSpeed,
maxMoveSpeed,
groundAccel,
groundDecel,
groundFriction,
dir,
Time.fixedDeltaTime,
isGrounded
);
// 2. Convert to world velocity
Vector2 playerVelocity = relativeSpeed * (Vector2)getTransformVec(Vector2.right) + positionVelocity;
// 3. Add platform velocity LAST
rb.linearVelocity = playerVelocity + platformRBVelocity;```
where is groundSpeed then
its been replaced by the explicit calculation in the first line
groundspeed = linearvel - platformvel
Again, groundSpeed is already UNRELATED to the platform's velocity
it's its own variable, with its own calculation
that's in theory but you need to decouple them in practice to avoid these artifacts
does anyone have an idea as to how I can keep the player momentum during a jump without them having control over it? this is my current code and the problem right now is that the momentum is based on where you looking
if(isGrounded && velocity.y < 0f)
{
velocity.y = -2f;
}
if(isGrounded)
{
x = moveA.action.ReadValue<Vector2>().x;
z = moveA.action.ReadValue<Vector2>().y;
}
mouseX = Mouse.current.delta.ReadValue().x;
mouseY = Mouse.current.delta.ReadValue().y;
xRotation -= mouseY * settings.Instance.mouseSensitivity * 0.5f;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
cam.transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
Player.Rotate(Vector3.up * mouseX * settings.Instance.mouseSensitivity * 0.5f);
Vector3 move = transform.right * x + transform.forward * z;
// x = horizontal movement, z is vertical movement
rb.Move(move * speed * Time.deltaTime);
if(isGrounded && jump.action.WasPressedThisFrame())
{
velocity.y = MathF.Sqrt(jumpheight * -4f * gravity);
}
velocity.y += gravity * Time.deltaTime;
rb.Move(velocity * Time.deltaTime);```
if possible I would like the character model to still change the direction it's looking without it impacting the trajectory of the character
i mean cant you just disable the player movement control while in air?
if thats what u mean
it's what I have right now, it was the first solution I thought of.
wouldn't a dynamic rigidbody handle this pretty easily
but now you can still controll where you're going with your camera
might want to consider that if it's viable for your usecase
ah thats cuz ur adding the transform.forward to the equasion probably
otherwise, you'd want to affect the velocity rather than recomputing it just from the input every tick
so there's an effect of momentum
wait, is this a CC?
why is it named rb
it's C# and it's called rb because I was lazy and had already named the character controller variable rb
that's not what Rigidbody.Move takes, so assuming it is a CC - make sure Move is called once per frame for consistent results, you have it being called twice here
fun fact, IDEs have multiple features to remedy this
there's the obvious find & replace, but there's also commonly rename symbol that's more intelligent, commonly F2
(also, i'm aware it's c#, cc is short for character controller.)
ah okay, didn't know that
ngl i have never used cc's i dont even know what they are to be exact
i always just used a rigidbody
for this I'm guessing I need to fill every vector of the velocity before the second time I'm calling the rb.Move and can remove the first?
yeah just add the gravity calculation to the movement one and call Move once
from what I know it should be easier declaring what angles it can walk upon and control some other stuff, but it's also a first for me
yeah something else is happening now, but now it's always walking the same direction and the camera doesn't do anything as to what direction I'm going in
you do need the transform.forward bit
you might consider, for example, applying it as an acceleration instead assigning it as the velocity
if that feels too slippery you could add drag or counterforces to oppose momentum when you try to go a different direction
Hey, I’m making a VR sailing game in Unity using the XR Interaction Toolkit and I’m stuck with a physics/joint issue.
I have a rudder GameObject with: Rigidbody, HingeJoint (limits set, connectedBody = boat Rigidbody), XRGrabInteractable set to Velocity Tracking
When I grab and move the rudder by itself, it works fine. But when it’s connected to the boat, grabbing it makes the boat accelerate insanely fast and it starts spinning/torquing like crazy, even on axes that are frozen in the boat Rigidbody constraints. I also tried unparenting the rudder outside the boat and connecting via HingeJoint connectedBody and it still happens. It feels like the grab velocity/forces are getting transferred through the hinge into the boat and injecting huge impulses.
Has anyone dealt with this?
can you tell me how? trying it a few different ways and it is constantly changing something for the worse
might want to step back from the code and design/analyze it in terms of physics first
Are you using a Rigidbody? That Move function signature looks suspiciously like a CharacterController
it's a CC
If it's a CC please tell me you didn't name the variable rb 😢
yeah #⚛️┃physics message
you need to actually keep a variable around keeping track of the current velocity and use that to move when there's no input.
Right now you have a "velocity" variable but it seems to only be handling vertical velocity. You're also calling Move twice per frame which is going to cause bad jittering when you touch objects while jumping
but yeah currently your code is always directly applying the input to the velocity, so there will be no momentum
will be changed, but it made sense when I started with that script but was to laze/busy with other stuff to actually change it
it's 4 keypresses
CC.Move(velocity * Time.deltaTime); here it's changed
if (Physics.Raycast(LFrontPoint.position, -LFrontPoint.up, out RaycastHit hit2, 0.1f))
{
Vector3 PointLeft = BoardRB.transform.forward;
Debug.DrawRay(LFrontPoint.position, hit2.normal * 2, Color.yellow);
//cross products
Vector3 left = Vector3.Cross(hit2.normal, Vector3.up);
Vector3 down = Vector3.Cross(hit2.normal, left);
Debug.DrawRay(LFrontPoint.position, left * 2, Color.green);
Debug.DrawRay(LFrontPoint.position, down * 2, Color.blue);
//flatten
Vector3 planeNormal = Vector3.Cross(left, down).normalized;
Vector3 flattenedEdge = PointLeft - Vector3.Dot(PointLeft, planeNormal) * planeNormal;
Debug.DrawRay(LFrontPoint.position, flattenedEdge * 2, Color.red);
Vector3 LFrontV = BoardRB.GetPointVelocity(LFrontPoint.position);
float sideSpeed = Vector3.Dot(LFrontV, flattenedEdge);
Vector3 sideV = flattenedEdge * sideSpeed;
Debug.DrawRay(LFrontPoint.position, sideV * 2, Color.magenta);
Debug.DrawRay(LFrontPoint.position, LFrontV * 2, Color.cyan);
//calculate the force
Vector3 CalculatedForce = (sideV * TEMP_FrictionFunction * (1f * 9.81f * 0.4f));
float forceX = Mathf.Clamp(CalculatedForce.x, -3, 3f);
float forceY = Mathf.Clamp(CalculatedForce.y, -3, 3f);
float forceZ = Mathf.Clamp(CalculatedForce.z, -3, 3f);
Vector3 fullForce = new Vector3(forceX, forceY, forceZ) * -1;
Debug.DrawRay(LFrontPoint.position, (fullForce) * 2, Color.black);
BoardRB.AddForceAtPosition(fullForce, LFrontPoint.position, ForceMode.Force);
}
I have this script which rotates the board to face down the hill. problem is that the front point (which is this script) rotates the board backwards and goes down the hill backwards. its not accidentally rotating backwards cuz it stabilizes itself after it has done so. all of the axis are correct since i checked with the 1 million debug ray's. basically this front point is acting like the rear.
this script might be confusing but any help will be appreciated since im not good at math and stuff
it's hard to understand what you mean by "the board" and "the hill" etc without any context
I'm realizing now you probably mean like... a snowboard or something?
Anyway this code doesn't seem to rotate anything
it only adds a force
unless the rotation is coming from the torque generated by adding the force off center
Yeah probably should've given more context: yeah it's a snowboard and the force is added on the front of it in order to turn
I can give SS's and more details tmr if needed
Oh and btw BoardRB.transform.forward is the left side of the snowboard not the front. Just cuz of how it's rotated
I'm going to guess there's probably a bunch of confusion and bugginess happening due to this
I think the best course of action is to go in and fix your 3D model so that forward is actually forward
then your code can be simpler and easier to think about
alr i'll fix the rotation and add some notes in the code to be easier to understand what it does
When it comes to physics I know when using addforce.force gives you better physics, does the same apply when using addforce.acceleration?
force is acceleration times mass. applying force takes mass into account. applying acceleration does not.
that's all they differ by
Better compared to what? I don't think there is much if any difference whether you use .velocity or .AddForce with a force that instantly adds up to the same velocity. It is just that objects generally don't change their velocity instantly but rather over time which is easier to do with .AddForce but I don't think there is anything in there that makes it inherently better or worse
hi, has anyone ever tried the limits of determinism in unity?
And by determinism i mean only the physics. Considering a simulation that requires no user input, and considering that it only needs to be deterministic on one platform/architecture, how much can we expect from Unity?
what is the "main axis" in a joint? If it's allowed to move in 3 axes, what makes the main axis the main axis? I don't understand what changes there.
Furthermore, if the joint is locked in 1 axis, does that just mean that it's rotation/movement is locked while trying to move/rotate directly in that axis?
It has got to be able to move via translation of Eulers, right?
unity uses physx, which is not deterministic
Hello
I want to check if there is a collider in front of my object, so can be my player or an enemy.
This method is :
public static bool CanMove(Vector3 direction, Vector3 currentPos, bool isCheckObject = false)
{
// True if no obstacle in the direction, otherwise false
int layerMask;
//Get the bitmask and not the index of the layer (so 0010 0000 instead of 6)
if (isCheckObject)
{
layerMask = LayerMask.GetMask("Obstacle", "Object");
}
else
{
layerMask = LayerMask.GetMask("Obstacle");
}
//Start the raycast at the center of the object
Vector3 rayOrigin = currentPos + Vector3.up * 0.5f;
Debug.DrawRay(rayOrigin, direction, Color.green, 1f);
//If nothing is hit, can move
return !Physics.Raycast(rayOrigin, direction, 1f, layerMask);
}
And its call in the player class here :
private void CheckToMove(Vector3Int targetGridPos, Vector3Int moveDirection)
{
if (!Toolbox.CanMove(moveDirection, transform.position))
{
Debug.Log(moveDirection);
StartCoroutine(BumpAnimation(moveDirection));
return;
}
StartCoroutine(MoveCoroutine(targetGridPos));
}
When I go in front of a wall or not, the CanMove method return always true, meaning the raycast return always false. Why ?
There is the screen of my drawRay going through my wall with the properties show
deterministic has a multitude of definitions tho. im aware that its not cross platform deterministic but it is algorithmically deterministic
ive read the docs and on a single platform and architecture say 64-bit intel processor running windows 11, every run should be deterministic
ive been testing and playing around with this stuff for months and i just wanna see if anyone else has some findings related to determinism so i can compare my results to theirs
one kinda dumb question - can you show your physics settings?
Especially these two
How can I make it so that the x and y axes switch? I have tried EVERY possible combination of axis values but none of them can do it
I can actually get close to it, but it seems impossible to get there
ofc I get it after right after I posted, even though I've been trying for a while...
I had to switch the secondary axis
I forgot to put the GameObject SDK to PhysX 🫠
But in simulation mode, what is the difference between fixed update and script ?
FixedUpdate is the default and most likely what you want
Script means you manually call Physics.Simulate in your code
In which context you want to simulate physics only on code ?
When you want full control over it. Could be for a simulation-style game, or a non-realtime game. It is also useful for networking frameworks when the physics engine needs to be syn ed up with networking stuff.
In your game it's potentially useful if your game is not realtime.
it would mean simulating physics only manually when you want to instead of it happening automatically all the time
Okay I see, thanks for the explanation 👍
Hey guys. I cant seem to work this out even though it looks like it should work. Maybe a second pair of eyes will help.
I want to have a knockback on the player when they get hit from a moving object.
Scripted on moving object
private void OnTriggerEnter2D(Collider2D collision) {
if (collision.CompareTag("Player")) {
hitDirection = (transform.position - collision.transform.position).normalized;
StartCoroutine(KnockBack(collision.gameObject));
}
}
IEnumerator KnockBack(GameObject player) {
player.GetComponent<Movement>().canMove = false;
player.GetComponent<Rigidbody2D>().linearVelocity = Vector2.zero;
player.GetComponent<Rigidbody2D>().AddForce(hitDirection * hitForce, ForceMode2D.Impulse);
yield return new WaitForSeconds(0.2f);
player.GetComponent<Movement>().canMove = true;
}
And this is my movement script
void Update() {
if (canMove) {
moveDir = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")).normalized;
if (moveDir != Vector2.zero) {
Quaternion toRotation = Quaternion.LookRotation(Vector3.forward, moveDir);
transform.rotation = Quaternion.RotateTowards(transform.rotation, toRotation, rotationSpeed * Time.deltaTime);
}
}
else moveDir = Vector2.zero;
}
void FixedUpdate() {
rb.linearVelocity = moveDir * moveSpeed * Time.deltaTime;
}
As you can see this should work? shouldn't it?
The movement script sets the velocity to zero every frame that the knockback is in effect
of course cause that is there to stop the player still moving when a shop is open. Thank you
That actually still doesn't work.
But in saying that adding the condition to the fixedUpdate to only run while im allowed to move did work.
Told you a second pair of eyes always works
Unrelated but velocity shouldn't be multiplied by deltatime
Is that because its physics based?
Velocity is already a frame-independent value (units per second) so it doesn't need to be converted
Ah no worries. Thank for that too.
Is there a way to make collision sounds that works for objects that are already colliding ?
Like for example a very tall plank that falls over wouldnt trigger OnCollisionEnter because it is already toutching the floor, but if i use OnCollisionStay it just plays sound every frame, is there a proper way to make this work or should i just use a cooldown or something like that between sounds?
Use OnCollisionEnter and OnCollisionStay but actually check the relative velocities and impulses in the contact points
Play the sound when they exceed a threshold, and/or modulate the volume by that threshold
yeah thats what im doing but it does still play every frame if the object is dragged/ is sliding across a surface
Well first off I would expect that to make a sound
Second, like I said you need to vary or modulate the sound based on the impulses and velocities of the contact
You can see if the motion is parallel to the contact surface and play a dragging sound instead of an impact sound
All of the information you need is in the Collision object
oohh thats a good idea, ill try
thanks!
Could anybody help me figure out why my Physics Debugger won't show collision meshes? Unity 6000.3 Neither Scene or Game view show them, Gizmos are on, "Collision Geometry" is checked.
All of the colliders are Default layer convex mesh colliders.
but not even cube colliders or the ground (quad with mesh collider) are showing.
where are the box colliders supposed to be?
The quad is a concave mesh collider IIRC and those don't ever render AFAIK.
Cube offscreen. Same deal. The quad is set to convex which seems to work but let me know if there's something wrong with that
Cube is here just to see if the collision geometry just wasn't rendering for my vehicle. It's not rendering for anything.
But it does have a cube collider.
Box collider rather
I can see the collider on the left
And I see the tank colliders on the right here
Thats because I'm selecting them
Previously when I have collision geometry selected with the physics debugger it renders them all the time, and with a translucent shader instead of wireframe
I don't think I've changed anything but the debugger has stopped working on even archived versions of the old project where I use it.
Drawing contacts/forces does still work, just not collision hulls.
The shot with them shown is just to show that the colliders are there.
hmm...
It's not working for me either... trying to see what I'm missing
Thats bizarre. On 2022.3 (old revision of project) it worked for me, but even on that archived backup it doesn't work anymore.
I was worried it was my machine. I'd think it's a unity bug but since it stopped working? I really have no clue.
trying to do a char controller with movement a bit like octodad
I've got a rigged character with iks on legs
was going to try and use those to move him around and use ragdoll generator for the rest of the rig
dunno if that will work but regardless of that the physics is super whack for some reason
everything just kinda spazzes and slides about
no intersecting colliders
any ideas?
Would have to see what that means
And the setup of the character
yo, I'm trying to get this sort of floppy driven-by-IK locomotion working in 2D, anyone got any pointers? https://youtu.be/ZRLibDF-JGQ
Developed by Free Lives
Swing bats and throw balls through the intertwined histories of humankind and cricket in this one button, physics-driven game. Over a thousand years ago the human race teetered on the edge of extinction. Our ancestors were helpless against the mighty behemoths of the land. And then, salvation…the game of cricket was in...
just make like a 2d active ragdoll with ik legs
shouldnt be too hard to replicate i think
is there an inbuilt way to have strong gravity, but after the player jumps around the peak of their jump for a bit longer and then accelerate downwards
because my movement is server authoritative it wouldnt be good for players to calculate on script by themselves
"inbuilt"? Now, this is a highly bespoke behavior you need to write the code for yourself.. You can certainly do it using the tools the physics engine gives you.
The physics engine provides basic newtonian physics.
Also the premise doesn't make sense, it makes no difference to server authoritative if it's custom or built-in physics
yes that is what i meant sorry
o yeah
nevermind then thanks
Dumb question but why is there include and exclude layers on colliders ? why not just include or exclude ? what happens if something is on both include and exclude ? or neither ?
The Layer Collision Matrix in the physics settings is what defines which layers interact with each other. The Layer Overrides can be used to override that behavior for specific collider. Includes are layers that the given collider can interact with even if the collision matrix says they shouldn't interact and exclude layers are ones that should not interact with the given collider regardless of the collision matrix. You can check this page https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Collider-layerOverridePriority.html for more information on how conflicts are resolved if two colliders collide where one should and the other shouldn't interact with each other.
I did not find any information of the situation where you put the same layer on both include and exclude layers. Since that is a contradiction by nature, I would not recommend doing that. The behavior might be undefined and differ between editor versions.
Basically LayersThisColliderInteractsWith = LayersInCollisionMatrix + IncludeLayers - ExcludeLayers
Ohh i forgot about the collision matrix ^^'
Thank you, this is all i needed
cinemachine camera following zooming out and sometimes zooming in of following target, i just want it to follow the target at a specific area
i have changed the update mode to fixed
the target its following is an aircraft btw so it can get pretty damn fast
#🎥┃cinemachine has manual and tutorials pinned, you should find there how to limit camera to a fixed range.
I'm trying to make a bike script, everything works well except the steering of the wheels since it just flips over instantly like the bike flips and becomes upside down. https://paste.myst.rs/8i3y4tyg that's the code and I also attached the input asset and the values of all my components.
a powerful website for storing and sharing text and code snippets. completely free and open source.
You can try setting the rigidbody's center of mass to an (unnaturally) low point so it's more bottom weighted
I mean like way below the rigidbody itself
Been a while since i worked with wheelcolliders tho
Also a joint or corrective forces/torques can be used for balancing
I fixed it by making the turning a bit smoother and disabling z rotation
hi, I have two objects with a rigidbody and they both have 2 colliders, one with a non-trigger collider and one that's a trigger. they belong on 2 separate layers. how can I make them go through each other (non-trigger colliders get ignored) but have their triggers still interact with each other? or something that produces this effect?
what i had done originally was create a child object just for the non-trigger colliders and that child object would live in one of the two layers that i want ignoring each other. the trigger collider would then reside in, say, the parent object that lives on default or something so its ontriggerenter can run. is there a better way of doing this?
example: i want my player and enemy to move through each other (enemy layer and player layer ignore each other) but i still want their triggers to interact with each other so they can do stuff like inflict damage
yes, put the colliders on different objects which are on different layers and set up the layer collision matrix appropriately
tyvm!
I have this ragdoll human. I'm working on a bicycle rage game that will have 2 people on this bike but the ragdoll sometimes gets loose and ends up under the bicycle which results in the bike clipping through the map. I have fixed joints on his feet and hands, I want him to move a bit with the movement but not too much. Also sometimes the hands start to jitter alot in place which isn't too much what I want. How can I fix these issues?
recorded a video to display the problem a bit better
Why is the capsule collider shown in physics debug smaller than the character controller capsule?
Any idea why the textures look so weird when importing into unity?
are you sure that's the CC and not a separate capsule?
yes
CC might use a "normal" collider internally to interact with the physics system but it's an implementation detail, not really something that's useful to dig into
Got it. I was a bit worried I messed up somewhere. Thanks.
Can someone please help me with this when i play the game the character stucks in the ground like this whats the issue @everyone
You should not try to tag everyone
just post your problem.
Check the positions of your colliders and/or your animations
Sorry
Ok, but can you please give explain further to
Click on the object that has the collider
make sure gizmos are turned on
and see how the collider is situated relative to the visual elements of your character
Ohk
I made geometry dash physics
hi, if you're just showcasing your work that would go in #🏆┃daily-win or #1180170818983051344 , this is a help channel
whoops
mb
sorry about that
What is the practical difference between acceleration and velocityChange?
I am currently using acceleration for some rigidbodies to follow and rotate towards some other objects (better than ForceMode.Force).
Would VelocityChange make a practical difference and why?
i mean acceleration is the change of velocity so idk if that would make a difference
VelocityChange is meant for instant velocity changes and acceleration for continuous change over time
acceleration multiplies the value you put in by Time.fixedDeltaTime before adjusting the velocity. It makes your input represent an acceleration rate rather than a direct velocity change of that amount
They both effectively do the same thing (adjust the velocity), just by different amounts
Force: body_velocity += (your_force / mass) * Time.fixedDeltaTime
Acceleration: body_velocity += your_force * Time.fixedDeltaTime
Impulse: body_velocity += your_force / mass
VelocityChange: body_velocity += your_force
(note that you can change physics update rate from fixed step to dynamic step so in that case instead of the Time.fixedDeltaTime there will be Time.deltaTime)
(never do that though)
(yep)
(btw Time.deltaTime in FixedUpdate method is equal to just Time.fixedDeltaTime, nice unknown feature!)
ah ok so acceleration is best in this case
is it wrong to move and rotate something in a coroutine, and the follow it with rigidbody force movement and torque towards it in fixed update?
Should I move everything to fixed update?
How are you moving and rotating? And at what cadence?
The details matter
If you're modifying the Transform directly that's wrong to do anywhere for a dynamic Rigidbody
Torque and addforce, every frame
you should not addforce/addtorque with continuous forcemodes in the update loop
It'd need to be at physics update cadence
You can use yield return new WaitForFixedUpdate() to do that
Oh
Didn't know that
Thanks
There is some jittering and overshooting
Might be out of sync
It's fixed update
you said every frame
every fixed update tick, whatever
these details are kinda important lol
I did say in the message above that I'm using fixed update
and my recommendation was in response to a message where you said it was not in fixedupdate...
No you asked about a coroutine
Maybe if you just showed the code...
No, I'm moving something (by transform) via coroutine.
Then I have fixed update where some rigidbodies follow the stuff that moves in the coroutine.
ah, i see. you didn't make that particularly clear
but yeah that won't have too much of an issue. generally you'd want to have stuff happen in Update regardless, because that's when frames are rendered - that's what interpolation on rbs handles
with a transform you'd definitely want to be moving it in Update
Oh, that's useful. I should then move it to update and rewrite the stuff from the coroutine probably
Cause the occasional jitters I get might be from the lack of interpolation? (I use interpolation on the rigidbodies)
oh the AddForce should be in FixedUpdate
i meant there should be something in Update, not everything in update, i didn't phrase that well
(in the case of rbs, that's handled for you with interpolation)
Bonjour
oh lol so I can leave it as it?
cause that's how it is now
addForce and addTorque are in FixedUpdate
the source objects that the rigidbodies move to move via transform in coroutines
it's technically going to have different behavior based on the framerate this way but whether that's a problem or not depends on the details of your game
doesn't deltaTime mitigate that? Or does it not work for coroutines?
deltaTime works fine for coroutines but no, multiplying by deltaTime is not enough to mitigate the effects of having a non-fixed timestep when there are second-order physical effects in play
there's a reason the physics engine uses a fixed timestep
well I don't understand the problem if the rigidbodies move in FixedUpdate. Is it still an interpolation problem?
think about where they are moving to
you are moving them towards the Transform object
since the Transfrom object is moving with a non-fixed time delta, its exact position per physics frame is going to vary depending on the framerate
if the object was moving with a fixed delta it would move to the same exact series of positions every time you do it
it's not necessarily a problem for your game, but your game will not be deterministic.
right but I don't think this should make a difference in my case, as it moves with a constant velocity
Basically, I don't see how it might cause issues
it really depends. It could be the difference between the rigidbody hitting a corner and squeezing past without hitting it, or something
but if the rigidbody itself is interpolated, isn't that an impossibility? Cause I move them by addForce and rotate with addTorque.
Isn't that taken into account?
rigidbody interpolation isn't relevant to the topic really. It's just a visual thing. It doesn't affect the motion of the Rigidbody at all
the actual physics happens with a fixed timestep
so I have a setup when I have an origin arm object that moves via animation + IK.
Then I have a puppet rigidbody object with configurable joints.
I made it so that the puppets move and rotate towards the origins via addForce and addTorque in Fixed update.
I was trying to solve some jittering there. There are always some jitters. I've tried various settings.
However, AI is telling me to simply get the rotations of the origin joints and update target rotation in the puppet joints, rather than adding forces. Is this correct? Could this reduce jitters?
is there an API to specifically toggle on/off collision between two colliders?
I think I found one to be able to toggle collisions off but I need the opposite
to describe the whole story I decided to make a jumping mob but then realized that it shouldn't be able to jump through targets
intuitively I could just make it collide with all it's enemies
but there are multiple factions and I am not sure if making a layer for each faction is a good idea
and if they wont' have own layers it would get stuck while jumping from within friendlies (agent without avoidance)
are you in 2d or 3d?
3d
ah, rip. if you were in 2d you could probably use the oncontactfilter thing
i guess you would use this then?
https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Physics.IgnoreCollision.html
yeah this one.... can only be set to ignore it seems
no?
I ll try, tho I read one forum post describing that this API couldn't help them
did you read the signature/docs for that method
it's ambiguous tbh
it really is not
"Whether or not the collisions between the two colliders should be ignored or not." like if it's not ignored does it mean that layers matrix still applies or not?
they do apply
it's just "is this ignored or not"
if it is ignored, no contact
if not, check further
so like
that's what I meant by
can only be set to ignore
there is no option to enable collisions ignoring matrix
it can be set to not ignore too
sounds like you'd want layer overrides instead
if that's the case what you said is wrong
no I don't
what part lol
no wait you weren't
I fail to pinpoint miscommunication spot
full story short I want to enable collisions between two colliders
IgnoreCollision don't seem to do that
unless I manually disable all unwanted collisions... which is kinda pita
yeah i think the overall philosophy is to filter out unwanted stuff rather than specify wanted stuff
i imagine you could get the control you want with this, but that's for 2d, and given the different engines the 3d engine may just not support that regardless of unity's decision
do you know perhaps a good way to imitate collision through code? assuming I don't care about y dimention and good precision
currently I am detecting the intersection through OnTriggerStay and do RigidBody.MovePosition... kinda rough, maybe I could polish that but is there a better way?
basically what I do now looks like a headcrab which only collides with it's target
probably a SweepTest? that would kinda mimic what MovePosition does
https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Rigidbody.SweepTest.html
no I mean I detect collision with a target and push away the mob which is unsurprisingly not working well
I mean borderline acceptable but I don't really know what am I doing and why so much jitter
public void OnTriggerStay(Collider other)
{
if(is_in_jump && other == target_collider)
{
float y = body.position.y;
Vector3 direction_away = body.position - target.position;
direction_away.y = 0;
if (!is_dropping)
{
is_dropping = true;
body.linearVelocity = new Vector3(0, body.linearVelocity.y, 0);
distance = direction_away.magnitude;
}
distance += Time.fixedDeltaTime * step;
Vector3 new_pos = target.position + direction_away.normalized * distance;
new_pos.y = y;
body.MovePosition(new_pos);
Debug.Log("Teleported");
}
}
still jittery (interpolation set on extrapolate)
right, I am moving it each fixed update afterall
Instead of applying addForce and addTorque to a desired position and rotation for a configurable joint, I tried just setting target rotation(yes, I used inverse).
I figured it would achieve the same thing but maybe more stable. It doesn't, it just rotates to an unpredictable direction.
Is this because target rotation is aware of joint constraints so it tries to rotate in weird ways to reach thay position? While addTorque brute forces it and somehow manages to do it?
Hello! Im trying to make a sausage that behaves "realisticaly" (Basically, it shouldn't be a static capsule, it should be able to bend a little). I tried to make it by joining multiple capsules with configurable joints, but they easily clip through other colliders (apart from other weird artifacts when bending). The rigidbodies are set to interpolate and with a continuous dynamic collision detection, but they still clip. Is there a solution to this with/without joints?
This image is when the pan is static. If I try to move it it easily clips through
how are you moving them?
the capsules in the sausage are rigidbodies, none of them is kinematic. I move the pan with a fixed joint. The pan is not kinematic either
@timid dove
I am using configurable joints and I am trying to make the arms floppy and not rotate too much. I want it to rotate but if you watch the video it rotates too much and looks weird how would I limit the rotation?
configurable joints are immensely complicated and I can't cover everything, but first you should start by setting the three angular motions to limited, rather than free
and then you define the limits to which they can rotate
there is a solution with joints too. Hard to tell from a picture. Maybe you can also try articulation bodies; they are better for chains
I was able to somehow fix it kinda with configurable joints. I've heard about articulation bodies, but I heard it works better if the root is fixed, which is not the case
Hello!
I'm trying to figure out how to implement collide and slide (for walls only) for a kinematic character controller.
It mostly(?) works, but there's some strong jittering when I try to move directly against a corner.
The jittering only happens when I push into a spot between wall A and B in such a way that the slide pushes me back from A to B (and vice versa).
It stops as soon as the movement points await from the range that pushes me back into the previous wall.
I'm hoping someone could point out the (maybe obvious) mistake I'm making or give any kind of suggestion
Here's the code https://paste.myst.rs/9pyy3sah and a video of the jittering
a powerful website for storing and sharing text and code snippets. completely free and open source.
I have been having this issue for the past few days. I tried thinking about how to solve this, but can't rly come up with a solution.
I genuinly don't know what the problem even is...
I actually just found a possible solution, even if it doesn't fix 100% of cases (some small jittering still happens if using a gamepad to walk directly into the corner, but it stops after a few iterations)
Section F in this article is the source https://arxiv.org/ftp/arxiv/papers/1211/1211.0059.pdf
this is my implementation of it https://paste.myst.rs/vgmsq2vi
a powerful website for storing and sharing text and code snippets. completely free and open source.
using a very small skin width also helps in this case
You need to make your raycasting and sliding iterative
you're only doing one raycast
you're not accounting for if that slide brings you into a second wall
Check if your newly calculated trajectory hits any wall and repeat the process
until you run out of movement distance
or until you reach some present number of iterations
isn't it what I am already doing? (lines 11-21 in the paste)
I capsuleCast from the new position towards the slide calculate in the previous iteration
I mean the paste to the message you replied to
wrong paste, hold on let me look closer
sure
actually, I can just paste the new version with what i was talking above
a powerful website for storing and sharing text and code snippets. completely free and open source.
I'm pretty sure this calculation was just wrong:
Vector3 movementInsideWall = movementDisplacement - movementDirectionToWall;```
actually nvm
they should both represent the same unit
but it's 100% possible I did mess up some calculation
I'm not that good with doing vector math
this + projecting on the crease works for the jitter, but this causes the character to sometimes get caught in corners that shouldn't visually stop it until the input direction points away from the second wall
I checked it out but the thing is, this doesn't rly explain why more than one collisions aren't detected when I am manually moving the ducks. Cus if this jitter was triggered while using spline animate, there's no reason for this to not be triggered when I manually do it
I didn't check out what your specific problem was before but, looking at it now, this might not apply to your problem
we're probably talking about 2 different things
OOF
Ya, ur talking about a sphere colliding with a corner, ima talking about triggers being detected between a circle and a box collider
Kept working on this and my guess is that walking inside the right wall slides the character into the up wall, which then slides it back again towards the first wall on the next frame.
I'd appreciate a lot if someone could point me in the right direction on how to solve this.
The current fix, as mentioned above, is to simply stop in a corner that is (arbitrarily) sharp enough, but it doesn't feel like a good solution since it causes a lot of sticking.
Here's the current code: https://paste.myst.rs/ee0mmmaq
a powerful website for storing and sharing text and code snippets. completely free and open source.
The sticky corners are most likely caused by the sweep (green lines) hitting the same wall until the input (blue line) is angled in such a way to the sweep completely points away from the left wall and only towards the front wall
I have a 2d phyisics material attached to a set of circles connected by a spring joint, yet despite setting the material to max friction, they slide around
So I’m trying to make a physics arm like one armed robber where the arm lags bevind and kind of like swerves around and it’s kind of working but I can’t seem to get it stiff I set spring to 125000 and the arm and bones in it still swerve around really hard, any help would be greatly appreciated
is it okay to do a spherecast on a per-frame basis
my game isnt running that well already so im not sure if i should use it over raycasting, raycasting is buggy for me

it's probably not gonna be much different perf wise
compared to other stuff
What are your settings and what kind of joint are you using?
Configurable joints
Between every bone
Ok but configurable joints have 5928582 settings, show them
You need to be a rocket scientist to set them up correctly
What do you recommend me to do for a physics arm
I want it to kind of lag behind and bend when going into a wall
With some overshoot
I use mine fir joints but the purpose is a bit different.
So you want it to move towards a default rotations, but have some springiness?
You don't want to move it forward etc?
Exactly
ok can you screenshot the settings, so I can see where to begin?
Ok guys, do you think it is possible to eliminate all rigibody jitter this way:
I have a ghost object matching the rb's rotation and position every frame. I let it detect erratic shifts in velocity direction by, for example, matching the rotation/position only if the rb has had a consistent velocity for the past 3 frames.
Basically something like that. Do you think 3 frames is enough? Does that idea sound legit?
If you're dealing with jitter, why not just use interpolation on the rigidbody?
I am
Imma be real you're probably doing something quite wrong then if you have interpolation on it and still dealing with noticeable jitter
Hey, can anyone tell me how to import the fbx file of a cloth animation from Blender to Unity?
Problem Statement: The Alembic file is working perfectly. In the fbx file, model and animations are getting downloaded, but animations are not working in the scene, they are shown working in the animator, but in scene the cloth is not at all moving.
Can someone please let me know what is happening?
this is the physics channel, perhaps ask #🏃┃animation or #🔀┃art-asset-workflow
that's an insane thing to say
I'm saying it for the sake of you are potentially handling the rigidbody movement incorrectly if you are noticing jitter. It's not a jab at you, I'm just saying the setup is likely misconfigured
Can it be the camera movement that is causing the jitters?
If you're doing any transform movement for example, that'd very likely be a large cause of it
Can you show what you're doing perhaps?
I made a dual rig (like puppet master) where I have a source rig playing animations with ik and a puppet rig where the rigidbody joints try to match the position and rotation of the original rig with addForce and addTorque
It works pretty well, I added damping and everything, but there is jitter when constant collisions happen
there is no jitter when in mid air, but for example, when my origin rig has a wall grabbed, there is jitter in the final position (possibly due to constant collisions with the terrain)
When the character is animating and you are colliding with any object? Or only certain types of objects
just the terrain
to be clear, the animated rig doesn't collide (it only raycasts), the rigidbody following rig collides
Interesting, I mean using heavy forces with joints is likely to cause jitter so I do apologize for the original misinterpretation, I thought you were using a kinematic rigidbody or something of the sort. The most ideal way to work with joints is through direct target rotation / target angular velocity but that goes quite deep into config joint knowledge haha
I actually tried just that but it didn't work for me
it always tried to rotate to a rotation I didn't specify
and I know joint space is different from local space is different from world space
I basically did double Quat inverse to specify target rotation but it just didn't work. I don't know
Yeah it goes deep, I've run down this rabbithole and do it for my hobby projects and day job, I would not recommend it lmfao
but what makes it a rabbit hole? It's a fkn Vector3. What makes it so hard?
The edge cases you have to account for :P
This may be somewhat of help https://gist.github.com/mstevenson/7b85893e8caf5ca034e6
I did something exactly like the first method shown there
Wait, could it be because the target rotation is a vector3, rather than a quaternion?
Ah yeah, it's just shown as a vector3 in the inspector
all quaternions show like that yeah
Elaborate?
The third rig would just be a skinned mesh with nothing attached and would match the position and rotation of the puppet rig.
However, it would wait for a few frames to detect erratic changes in velocity of the rb rig. For example, if dot product of frame 1 movement and frame 2 movement is low, don't update position and rotation.
If dot product is high for 3 frames in a row, only then update. Does that make sense?
Yeah I understand what you mean, but I feel eliminating the jitter entirely would be a better alternative. Trying to drive the joints directly could be good but also difficult ofc
I mean I've really tried that but couldn't
I wish I could
Hm got it, then you could attempt what you're talking about, you could also try bumping up your physics project settings solver iterations, or anything else to help with joint slop
I have increased all of that. I mean, I could try increasing it more and more but there's a point where it becomes unreasonable
it may also just be due to the fact there are many colliders
Yeah, anything above 32 for a single rigidbody is overkill
I have joints on each of my fingers (yeah I know)
so it may be impossible to achieve stability with just rb
That will create joint error for sure
You can try simply boosting your inertia tensors too
I actually have 3 joints per finger lmao
I considered switching them to an articulation body but they either don't work or idk how to use them
you mean drag and angular drag?
That'd prob be a good idea
No, inertia tensor, in 2022+ it's a setting directly on the RB, else you have to do it in code
You could just simply multiply the whole vector by 2 as a test
I didn't even know abou that
I will check
but they can't be parented to RBs
essentially I'd need to make another rig for fingers that follows the rb rig
but I tried doing some articulation body tests and they didn't seem to work, idk
I mean, if you so want you could build your entire rig out of articulation bodies
nah, the player himself is a rigidbody. I would need to redo everything and I don't like that
hey, sorry for the ping out of nowhere. i was skimming through old messages to see if anyone's experimented with the limits of determinism in unity. Seems like you did just that. Did u get anywhere with ur tests?
Anyone know which version of physx Unity uses?
Depends on which version of unity
6.3
I think its 4.1
https://www.reddit.com/r/Unity3D/comments/1q138sx/what_physx_version_is_unity_63_running/
Yeah not exactly shouted out by Unity is it! I think they are well behind as maybe license changed for v5
It seems they changed from physx 3 to 4 already in 2019 and haven't changed since
Back then I think they had a blog post about the changes at least
sounds like PhysX has much improved and has 3d wheel colliders now so don't know what happened but maybe is a big leap to change to a different physics setup
seems v5 was a major change in direction to simulation and GPU
I assume it's quite much to integrate, still bit surprised they haven't upgraded yet. Maybe their physics teams have been busy with DOTS physics stuff etc.
Yeah Unity Physics is annoying to me as built for ECS/Dots (do not use) and may be a long project to complete
its more about being scared of breaking changes, they have a history of tiptoeing around improvements cause it could break legacy projects on upgrade, on one hand its nice to have a relatively simple upgrade most of the time, on the other hand it stops progress right in its tracks sometimes and led to things having 3 different implementations at a time cause they didnt want to remove the old one
Well beats removing the old one before the next version of it is remotely ready 😄 (looking at you, Unet)
ooo i will be reading down this thread
they're using 4.1 for wheel physics as can be seen stated here explicitly: https://docs.unity3d.com/6000.3/Documentation/Manual/wheel-colliders.html
I'm not sure if they're using just 4.1 vehicle sdk for wheel physics and stuff and the rest of the physics engine runs on some other version, but i just assumed that it's 4.1 overall :/
6.3 is PhysX 4.1.2
Anyone know the differences here between these 3 ways of setting my boats position & rot to the server Authed state before resim? The top one directly setting transform has worked best for me but it comes with a bit of a performance cost as all colliders need to be re-synced, from reading the other two are maybe what i should be using and seem to be cheaper but they ruin the re-sim somehow as my boat become super jittery and clearly don't align
the 1st one is "incorrect" for physics, as it causes a desync
the 3rd one is the "correct" way to do the 1st one, it's a teleport like the 1st but it maintains sync
the 2nd one does a sweep to the new position, simulating collisions in between, rather than teleporting
iirc for one of (2d, 3d) but not the other, MoveX is only interpolated correctly for kinematic rbs (as that's what it's intended for), that may be the cause of the jittering
if this is for "resim", do you even need physics? couldn't you just set the value every frame/tick manually (or maybe with kinematic rbs to get interpolation, if you're using the fixed time step)
also,
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
that's a very small screenshot that's hard to read
Hmm, okay well it seems like the 3rd one would be the one i want however it produces different results compared to 1st one, any ideas why this would be the case? id love to get some of that performance benefit.
Yeah i kinda need physics.
is the jitter just due to network desync of the simulation
is the rb kinematic or dynamic?
Probably better to show you, hold on
Its NOT kinimatic
would breifly setting it to kinimatic first maybe solve it?
am i understanding this right that you have some simulation on the server that you want to sync to the client?
Yeah essentially Server and client are running physics simulation for my full client prediction setup, server sends snapshot of world to my client, client then updates everything with these stale values and resims frames to catch back up to updated position
are these snapshots every physics tick or less frequent?
1st video uses Transform.SetPos&Rot(Nice & smooth but costs performance), 2nd video uses Rb.position/rot =(Jittery, but better for perfomance)
as you can see the rb.position set causes the boats resulting position to be wrong compared to servers, not every tick, server sends snapshot to client every 5 fixed frames.
Clearly rb.position results in a slightly different outcome compared to directly setting transform, does rb.positon update the position of the object immediately? or does it require another physics step before its truly updated to this position
If you change the position of a Rigidbody using Rigidbody.position, the transform will be updated after the next physics simulation step
apparently yeah, it takes a step
if you're doing this in FixedUpdate, the step should be immediately after though
Due to the nature of the simulation im running physics in script mode, that will explain the issue then
is there any way i can force it to update immediately, or does this require running physics.simulate()?
im running physics in script mode
what do you mean by that? i don't think ive heard of that
You can set physics.mode to script which means physics does not automatically run after fixed update, physics must be explicitly called using "Physics.Simulate(Time.fixedDeltaTime);" This allows me to preform multiple frames of physics during a single frame
huh, interesting
rb.position != transform.position
im assuming your boat is a rigidbody and you're trying to set it's position and rotation and want that change to be respected by the physics engine, in which case you should be using rb.move https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Rigidbody.Move.html or rb.moveposition if the boat is kinematic https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Rigidbody.MovePosition.html
in your case where your physics is running in script mode, you can use PublishTransform() after modifying the rb pos and rot directly for the rb and transform to sync
is Move not just a shortcut for MovePosition+MoveRotation? i assumed it would be since other "move pos + rot" methods say so but i'm just noticing now that Move doesn't say kinematic in its docs 
rb.move is different from transform.moveposition and transform.moverotation
This could be promising, i was just doing Physics.Simulate() after setting the rb.position and that seemed to work but obviously required me to run an extra step with everything kinimatic
rb.move and rb.moveposition are kinda similar. Ive used both on kinematic rbs and non-kinematic rbs. Didn't see any difference
does publish.transform() need the rb to be kinimatic?
i'm referring to rb.Move being rb.MovePosition+rb.MoveRotation
the docs dont explicity state that rb.move is to move non-kinematic rbs, but they do state that rb.moveposition is for kinematic rbs
but ive tried rb.move on kinematic and non-kinematic rbs and rb.moveposition on kinematic and non-kinematic rbs and i didnt see any difference
is your interpolation setting set to none or interpolate or extrapolate?
i don't have any rbs to test right now, but from what ive heard from helping here, MovePosition breaks interpolation on dynamic rbs (though, that might be for 2d) so i'm curious as to whether Move has the same behaviour
rb interpolation is frame rate dependent. im not sure how it affects multiplayer setups but interpolation can give different results on the same machine since every run would be at a different frame rate
move and move position respect the interpolation settings btw
says so in the docs
empirically, MovePosition does not respect interpolation on dynamic rbs
i'm not referring to this specific multiplayer set up. i'm referring to the behavior of rb.Move in isolation
Thank you both, Think ive made some good performance gains there ❤️
What's the good practice when it comes to making colliders for a whole level (low poly but not dumb simple geometry?
Inserting many many boxes?
Using meshes as colliders?
Making and importing simplified meshes of level geometry and using them as colliders?
Also how bad is the idea to make a huge bounding box alike collider as one mesh?
mesh colliders are very expensive if they are not convex, because you basically need to check the collision for each triangle. non convex also can't be simulated by rigidbody etc. it's usually better to just use many box colliders, as it's a simple AABB/OBB test
so like to make a cupola roof.... I meant to make it from pieces?
yeah, just use primitive colliders for that. the complexity will depend on your needs - if it's a parkour object, it will probably require more details in terms of collision because it can be interacted with.
tbh this is confusing because it feels like in every game there is many mesh colliders everywhere
Static mesh colliders are generally fine, as long as there's not too many of them in one place. But you want to generally use a simplified mesh and not the same one you use for rendering.
It will also of course depend on the complexity of the scene and the target hardware
what will happen if an object happened to fall off the map
do I expect some crashes or issues due to some overflows or I can just safely ignore that that may happen?
as far as i know, unity will just throw an error if you have a rigidbody on an object with non-convex mesh collider and won't simulate properly
it won't crash the editor
it was new unrelated question about
indefinite time freefall of a rigidbody
oh, sorry. thought you're talking about the mesh collider :P
if an object falls out of the map, it will eventually fall so far from the origin that there will be problems with floating point precision because of how far the object is. generally you'd have some system that would just destroy the object if it falls out, but that depends on your game
so I actually have to take care about it, huh
yeah, that would be the solution. i guess the object is not that important if you let it fall of the map?
yeah I don't mind them being deleted
of course I assume such can only happen during some extreme physic interactions
yeah, e.g. if the player has the ability to carry objects (like in R.E.P.O.) and there's a hole in the map
but like is there a game where a prop not suddenly getting mach 10 speed and fly through something
I don't trust those terrain/mesh colliders to be 100% impenetrable
i mean, if an object is moving extremely fast then it can just phase through another collider. rigidbody's continous collision mode does kinda solve it, but i'm not sure if it's that reliable
you'd usually set the collision detection mode to Continous if an object is very important, e.g. like puzzle elements in amnesia the dark descent (i remember when a pipe just fell through the floor and i had to load last save 💀 )
as I read about collision modes it's either fail to detect phasing through or fails to detech phasing through if big angular speed and weird trajectory
sometimes, given high speeds, but anyway, nothing is 100% impenetrable
true. i think you can also make a linecast between the last pos and the current pos - to check if the object didn't just penetrate through something
gee I guess
maybe worth it for puzzle elements
but in general I discuss about some random minor items
then i don't think why it would be worth the struggle. this linecasting thingy can get very expensive for many items
I would expect unity to outright delete objects extremely far or something
but I guess I have to do it myself?
toggle off some project setting 🤷♂️
now imagine how many of these kinds of problems maybe exist
That's just... such a bespoke thing that it's not worth being part of the engine
and how many toggles would exist
The engine should not take opinions on most things
it's easy to implement, e.g. every N seconds just check the dist from 0,0,0 and destroy the object if it's over some threshold.
It's part of why I dislike Unreal engine. Unreal practically begs you to be making a first or third person shooter game, and you have to start changing settings to make any other type of game.
I can't, luckly I havent sumbled upon anything like that yet
But What If The Thing Phases Through It
dont make things that fast
it just sound like the thing that may cause a savebreaking situation one time out of a billion or something which is still bad
dont worry about one time out of a billion
anxiety noises
For fast things there's a continuous collision mode for the Rigidbody.
Actually several of those
I wish I had a link for that Unity's(?) page comparing them
even dynamic one might ignore angular collisions
I suspect that may lead to some object getting stuck in geometry and potentially falling out
Long time ago when there was just one continuous collision option and I was making a bricks game it wouldn't be reliable enough at high ball speeds, even with very thick border colliders, so I had to handle it myself placing ball on the last position it would've been when it went through collider.
I mean the current one might be good enough yet not impenetrable and inevitably in a usual goofy game with props and stuff setting where rigidbodies even sometimes spawn inside each other or some random stuff like that some thing will get outside
or at least this is what I believe
Continuous speculative uses rotations:
https://docs.unity3d.com/6000.3/Documentation/Manual/speculative-ccd.html
Continuous and Continuous Dynamic do not use rotations:
https://docs.unity3d.com/6000.3/Documentation/Manual/sweep-based-ccd.html
exactly that page, yes
so what if we got a compound collider on a sweep based detection rigidbody flying into a wall with a high angular speed?
I suspect one of colliders might get through and something terrible will happen leading it to phase through by one end or the other
Probably not robust
The rotation stays the same during the sweep
Ok, so let's say I have a camera with a FoV of 60 degrees rotated along the x axis at 30 degrees. I want a given subject's transform point to appear at a viewport point of (0.5, 0.3). How would I go about calculating where to place the camera?
I'm not sure I worded this well, so here's a diagram
This isn't a physics question, but the answer is to just use cinemachine - the viewport offset you're asking about is something you can just set up with a few clicks
I wasn't sure where else to talk about things related purely to math
Also I'm not sure how I would use Cinemachine that way
Position Composer | Cinemachine | 3.1.5 https://share.google/3sydWqDxktwjncrj7
Literally just by setting the "screen position" property in the inspector for the Position Composer
Can it be done in code? Because I'm trying to set this up at runtime
It could be but there's probably not a reason to
Unless you need to adjust those values at runtime a lot
But yes anything can be done in code
so im using rigidbody to make this item can be thrown but on specific scene this object somehow broken and before i think it because mesh collider but i copy the area to testing scene it somehow not broken? is im doing something wrong in my game scene using the same rigidbody setting it just bypasse the collider and fall
not enough information here
but also - moving it around via the gizmo in scene view at runtime isn't really a test of anything
Heyy SUPER new noob question. I'm trying to learn about different joints and I'm watching a youtube tutorial for it. In the video the guy sets up a fixed joint with one cube connecting to another one. With the fixed joint, he's able to grab and drag one of the cubes to make them both move.
When I added the fixed joint, I am not able to make the both move, but when I got to play mode I can see the cubes fixed and hovering. How is he able to make these physics active while in Scene view?
joints are only active in play mode (the whole physics engine is)
So you would enter play mode and look at scene view during play mode
Ohhh! It's that easy??? thanks man
you can even set up your editor so that you can see game view and scene view side by side at the same time
just drag the windows around however you want
i wish unity adds a cylinder based character controller by default instead of making a custom one using rigidbody
i mean making a custom one is easy
working with a custom 2d physics engine, none of the scripts have any code in OnEnable or OnDisable, but a bug i have gets fixed when i disable and enable the gameobject with the bug. So basically lol im just trying to figure out exactly what does unity do internally during these events.
You'd have to share more details.
why do you need cylinder?
there is few source projects i was working on that had multiple issues with some jumps not being possible unless you adjust the map or just make a custom collider
yeah true its very easy to do
its ok i did a bandage fix i will never know the cause
will have to live with it
A collider or controller? Because you can't use anything other than capsule as your collider
you cant?
i mean why would u want to anyways
Not everyone is making the same game
I had to use a horizontal capsule for my game, so I had to switch from char controller to something else
Hello i am creating a billiards game in unity and i am having some problems seeing realistic break physics. I have tried plenty of friction, bounciness material combinations however it just doesnt look right. Do you think this is a limitation of the physX engine and should i rather try implementing my own simulation physics? I can also provide footage how it looks now if it would be of any help.
Just don't use physx honestly
Billiards physics is pretty simple you'll be better off with custom physics.
How should i go about implementing something like that. Because i found an article that seems promising (https://ekiefl.github.io/2020/04/24/pooltool-theory/). I really never did something like that myself so yeah.
All the objects involved are spheres, which are the simplest possible shape. You can even continue to use physx for the colliders and spherecasts and just do the motion part yourself. It's all just linear motion and vector reflection off collision normals
so this would mean using unity's On collision events and then manually calculating the movement based on current linear and angular velocities?
Seems like moving the object while still using the collision system can be achieved with the Rigidbody.MovePosition() method. Any thoughts on using this?
No
Spherecasts
I am sorry i dont see how i would use a sphere cast in this way. Would this run in realtime or would i have to precalculate all collisions?
Or is every ball gameobject sphere casting on itself and seeing if it hits another ball?
you would run it every fixedupdate
to see if there will be any collisions
so you are checking to see for next frame what happens
sorry my bad every timestep right cuzt this is not the regular Update method
Wouldn't this get really resource intensive calculating every next position with fixedUpdate for every ball in the scene?
not really. There's only like 15 balls right?
yes
Okay so with this system i calculate a sphereCast that is where the ball will be next time FixedUpdate is called. This means that i should calculate a position, rotation every [timeStep] seconds, having it as a function of time?
AddTorque changes the angular velocity of a Rigidbody
It's the rotational equivalent to AddTorque
Not sure what you mean by "only visual"
Can someone help me find out why my dude just falls through the map?
I'm following a ragdoll physics tutorial. Each piece of mesh has a mesh renderer, rigidbody, and a joint connected to the relative part of the body. The cube I have stays but not my model. I also put a rigidbody and mesh collider on the full model to try and stop this but it didn't work.
With physics based movement you need to use physics methods properly with FixedUpdate frames, so it won't get pushed through colliders and interact correctly. See physics movement tutorials
You cannot use a concave mesh collider on a dynamic rigidbody
for an animated character especially you should not use a mesh collider at all. Generally a character like this uses a capsule-shaped collider for the basic world movement/interaction
Let's say that I have a rigidbody sword and a rigidbody axe split into handle and blade part.
I make the axe more top heavy due to the blade having more mass and I make the sword bottom or mid heavy.
Now, if I apply torque with the hilt being the pivot, does physx understand that the axe applies more force on impact, but takes morw torque to spin?
Is this something physx thinks about?
I make the axe more top heavy due to the blade having more mass
How did you do this exactly?
Awesome thanks for the heads up, I'll look into FixedUpdate frames as well
How many Rigidbodies are involved?
If it's a single rigidbody the only way you can distribute mass is with the shapes of colliders. And all colliders are assumed by the system to have uniform mass.
What you can do is set the center of mass manually by disabling "automatic center of mass"
I reiterate, I split is into two rigidbodies, hilt and blade. Blade has more mass in the case of the axe.
I might need to unparent it and use fixed joint and all that, whatever
ok you didn't mention multiple rigidbodies before. YOu will need to connect them with joints yes
and the yes the masses will be taken into account when applying torques and forces
I did mention two parts. I guess I didn't specify they are both rbs, I thought that was imied
the parenting doesn't make a difference if they're dynamic bodies
That is cool tho
Doesn't the transform interfere with force propagation?
the physics engine basically will ignore the hierarchy. Joints are the only way to connect multiple dynamic RBs
it may interfere/fight with it. It's best to not have them in a parent/child relationship ideally
What's the end goal here though? I expect this is probably more complicated of a setup than you need/require
Yes, that's what I did (unrelated to this, but also with joints and rbs)
a single rigidbody with a custom center of mass may be a better solution
I'm just spinning up a new game idea with actual physical weapons and forces
No, that's not a proper solution
I mean it depends on what the game actually needs
Shifting center of gravity would work in the case of a symmetric staff, but not an axe or mace
why not
Oh, I could shift it more upward the heavier the top, right?
That might result in the same thing, yes
have anyone ever had this issue? all i do is spawn the car and sometimes wheels dont function
I agree that center of mass is the way to go here. Having two RBs and a joint would likely not always be stable for something that needs to be firmly connected. Even a FixedJoint isn't always reliable
make sure you're using continuous collision detection
I set it on vehicle's rigidbody but it didnt work
wheels dont have a field for that
it's a Rigidbody property not part of the wheel collider
Wheel collider mass 1000 seems really high
Yeah docs recommend 20-80:
https://docs.unity3d.com/6000.3/Documentation/ScriptReference/WheelCollider-mass.html
And the unity car tutorial uses a Rigidbody mass of 1500
Oh the tutorial changed quite a bit for newer versions
https://docs.unity3d.com/6000.5/Documentation/Manual/WheelColliderTutorial.html
I built a rigidbody extrapolator and made a camera follower for my car, however Im observing an inconsistent jitter between plays. It seems to be consistently smooth on the first compile, but repeated plays seem to get weird jitter. Is there a common cause for this?
Left video is almost perfectly smooth. Right video is jittery. No changes made to code or scene between both.
without knowing any detials about your project, the rigidbody configuration, or your custom code, it's hard to say anything. My guess is it's framerate dependent.
Is there a good reason you don't use the built in Rigidbody interpolation/extrapolation?
the built in extrapolation drastically altered the simulation and caused massive issues
(my car started doing wheelies)
Its a car game so delay is kinda catastrophic
I think it has to do with the fact that the built in extrapolation/interpolation directly affects the rigidbody position, I would prefer to have these processes be cosmetic only
I can show ya what happens when I turn on extrapoliation
So maybe if you have code or logic depending on the Transform that could be the issue
I mean I do raycasts so I guess that qualifies
You can do the raycasts based on the Rigidbody instead of the transform
interesting proposition
ill try it
hm, I am doing these raycasts from a child object, do I need to do rb.transform.position+transform.localposition?
don't do .transform at all
that's the issue in the first place, remember?
right I meant rb.position, because I have a rigidbody on my vehicle object, but I need the offset of the wheel which is where im doing these casts from
If you want the world space position of a child object you would do this:
Vector3 worldPos = rb.position + rb.rotation * transform.localPosition;``` but this assumes you have 1,1,1 scaling too
ill give it a go and let you know whether unitys extrapolation works better or if my issue persists
I replaced everything accordingly, but now I cant get the original bug to occur with my own interpolation to compare them
however regular extrapolation works now
so you were right, thanks
Is there anyone who explains realistic Unity car physics? I have a few questions I’d like to ask.
it's best to just ask here so that everyone can see what you exactly need. someone with knowledge on the topic might help you
please don't crosspost
ok sorry
I’ve got a flick/plunge mechanic working, but it just doesn’t feel right. Weight feels off, launcher strength feels inconsistent, and endless tweaking isn’t fixing it. I even added some overlays to the game where I can tweak the values while playing.
Single dynamic shape, kinematic launchers, static rails. Using PhysicsMaterial2D on the dynamic shape with bounce and friction values.
At what point do you simplify / restart vs keep tuning? What would you check first? I feel like I am missing something important. Could the scale of my objects/scene be the issue? I didn't really consider that when building it out.
Is it true that Kinematic to dynamic energy transfer in Unity 2D is not a stable “power delivery system”? That's what my research has been telling me. Should I instead use a impulse-driven launch using AddForce?
I'm in Unity Alpha, seems like 3D physics has a bug: When using any IContactsJob and there's a dynamic body, if there's no AABB contacts, the system floods with errors:
ArgumentException: Actual value False does not equal expected value True.
Unity.Physics.SafetyChecks.CheckAreEqualAndThrow[T] (T expected, T actual) (at ./Library/PackageCache/com.unity.physics@b51efcbbfd90/Unity.Physics/Extensions/SafetyChecks.cs:143)
Unity.Physics.IContactsJobExtensions+ContactsJobIterator..ctor (Unity.Collections.NativeStream+Reader reader, System.Int32 forEachIndexBegin, System.Int32 forEachIndexEnd) (at ./Library/PackageCache/com.unity.physics@b51efcbbfd90/Unity.Physics/Dynamics/Simulation/IContactsJob.cs:406)
Unity.Physics.IContactsJobExtensions+ContactsJobProcess`1[T].Execute (Unity.Physics.IContactsJobExtensions+ContactsJobData`1[T]& jobData, System.IntPtr additionalData, System.IntPtr bufferRangePatchData, Unity.Jobs.LowLevel.Unsafe.JobRanges& ranges, System.Int32 jobIndex) (at ./Library/PackageCache/com.unity.physics@b51efcbbfd90/Unity.Physics/Dynamics/Simulation/IContactsJob.cs:336)
report it with the bug reporter!
IContactsJob has the following code:
int forEachIndexBegin = 0;
int forEachIndexEnd = jobData.ContactReader.ForEachCount;
if (jobData.IsParallel)
{
if (!JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out forEachIndexBegin, out forEachIndexEnd))
break;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobData), forEachIndexBegin, forEachIndexEnd - forEachIndexBegin);
#endif
}
var iterator = new ContactsJobIterator(jobData.ContactReader, forEachIndexBegin, forEachIndexEnd);
And the ContactsJobIterator has the following cctor:
public ContactsJobIterator(NativeStream.Reader reader, int forEachIndexBegin, int forEachIndexEnd)
{
SafetyChecks.CheckAreEqualAndThrow(true, forEachIndexBegin >= 0 && forEachIndexBegin < forEachIndexEnd && forEachIndexEnd <= reader.ForEachCount);
When there are no broadphase pairs (no AABB overlaps), the contacts NativeStream is allocated with ForEachCount = 0. In the non-parallel path, this means forEachIndexBegin = 0 and forEachIndexEnd = 0. The check 0 < 0 evaluates to false, failing the assertion.
This can easily be checked with the debug system, which uses the Interface (DisplayContactsSystem) and the Kinematic Character Controller, which is how I found the error, in DisableCharacterDynamicContactsSystem. Disabling both systems which schedules jobs makes the log stop happening
Dunno about others but I personally don't have a clear image of the mechanic you are creating or the issues it has. Maybe a video would help demonstrate it
To simplfy things.... When is a case you would want to use kinetic like a plunger hitting a ball driving the physics, vs using addforce to actually move the ball and just making it LOOK like the plunger is hitting it. Or does everyone just use addforce in these cases?
but yes I can make a video today to show you what I am talking about. I am going to try to implment addforce version now to see if that works the way i think it will.
also this is in regards to 2d physics.
you mean like pinball? I would 100% just do that with an AddForce call and have the plunger be visual only
pretty close to a pinball plunger! ok i have been trying to use AddForce for a few hours now and things are looking up.
One thing that is not related but still physics.... How in the world do i use a vector file as my collision map? I can't seem to find anything in the docs or any tutorials or anything. Saving my svg collision map as a png and then generating the collisions in unity produces the stair step effect on straight lines. In my vector its already exactly the way I want it
the 2D physics engine doesn't support colliders defined as vectors
but i can't generate a collider from SVG data?
you can generate a sprite from SVG using the vector graphics package and generate a collider based on the sprite, but no it does not support SVGs directly