#⚛️┃physics
1 messages · Page 16 of 1
but now the collision is gone
now i got the collision but i cant jump and i can walk throguh the hills
I don't understand what any of that has to do with the physics material 2D
MissingComponentException: There is no 'Rigidbody' attached to the "Player" game object, but a script is trying to access it.
You probably need to add a Rigidbody to the game object "Player". Or your script needs to check if the component is attached before using it.
UnityEngine.Rigidbody.AddForce (UnityEngine.Vector3 force, UnityEngine.ForceMode mode) (at <76b7ca2009dc47a6b89e7ffd655fd50b>:0)
PlayerMovement.jump () (at Assets/Scripts/PlayerMovement.cs:32)
PlayerMovement.Update () (at Assets/Scripts/PlayerMovement.cs:14)
i had to attach rigidbody2d it says
but now i cant connect my scrip
Your code is doing GetComponent<Rigidbody>
You are supposed to be dealing with Rigidbody2D
Just use the correct thing
Hello, i have a question regarding the 2D colliders used with rigidbodies.
With Physics2D.Raycast there are parameters you can use that indicate the Z axis of objects to include and exclude when casting the ray.
Is this option also available for rigidbodies to only hit other objects with rigidbodies with a Z between -1 and 1 for example?
So, with a jump, how would I go about calculating how much time it takes to get to a certain height (in this case 2m in 0.25s) before falling back down? I tried calculating a gravity factor by dividing the height by the square of the time (2 / 0.25^2 = 32 in this case) and calculating the force necessary to reach that height before falling back down again. For what ever reason, though, while the timing works great on paper, it's not panning out in game (the actual calculated time to the apex is 0.36s instead of the 0.25s I'm aiming for). Is there a reason this might be?
I am using 3D
What doesn't work with 2D?
You didn't actually assign the mesh to the Collider
What doesn't know it? What do you mean by that?
how can I glue 2 gameobject (squares) so they stick grid way?
What does "stick grid way" mean?
The blue is the player (core), the other are objects that stick to the core, they stick as if they are in a grid I suppose
the problem when I try this in unity the objects thats stick to the core just start drifting
if im trying rigidbody2d it sents a error code
They are drifting because you gave them dynamic Rigidbodies
What error code? Be specific.. share the full error
It's Rigidbody2D, and needs to be capitalized correctly
Assets\Scripts\PlayerMovement.cs(32,77): error CS1503: Argument 2: cannot convert from 'UnityEngine.ForceMode' to 'UnityEngine.ForceMode2D'
I have a rly silly problem. I'm making a game where the enemies dont have health, but instead your projectiles apply force to them and knocking them over kills them.
To make this system work, all the bullets also have to be rigidbodies with forces
I'm trying to make an enemy that can shoot back at me. It spawns in a bullet object, and then I apply force to the bullet to launch it. But for some reason when I do that, it applies an equal opposite force on the enemy that fired the shot.
Is there a way to add force to an object without affecting other nearby object in that way?
Yeah, because you need to use ForceMode2D. These are just basic compile errors
The bullet is probably colliding with the enemy as it spawns
AddForce only adds force to the Rigidbody you called it on.
Assets\Scripts\PlayerMovement.cs(32,41): error CS1061: 'ForceMode2D' does not contain a definition for 'AddForce' and no accessible extension method 'AddForce' accepting a first argument of type 'ForceMode2D' could be found (are you missing a using directive or an assembly reference?)
You're making simple compile errors, your code makes no sense if you're trying to call ForceMode2D.AddForce
It's also very hard to help if you just post error messages without the corresponding code.
But at this point you have a "writing valid C# code" problem, not a physics problem
public class PlayerMovement : MonoBehaviour
{
public float WalkSpeed = 2f;
public float jumpStrength = 4f;
public float JumpDelay = 0.75f; // Verzögerung in Sekunden
private bool canJump = true;
void Update()
{
movement();
jump();
}
void movement()
{
float horizontal = Input.GetAxis("Horizontal");
float vertikal = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(horizontal, 0f, vertikal);
movement = movement.normalized * WalkSpeed * Time.deltaTime;
transform.Translate(movement);
}
void jump()
{
if (Input.GetButtonDown("Jump") && canJump)
{
GetComponent<ForceMode2D>().AddForce(Vector3.up * jumpStrength, ForceMode.Impulse);
canJump = false;
Invoke("setJumpFree", JumpDelay);
}
}
void setJumpFree()
{
canJump = true;
}
}
@timid dove
It's not. The rigid body as well as the mesh collider for the bullet are set to ignore the enemy layer. And the enemy rigibody as well as its box collider are set to ignore the projectile layer.
At least it shouldn't be.
And yes I made sure all child objects have the same layer
how are you applying the force?
to the bullet-script directly?
or using some sweep-thing to apply force to everything within that area
To the bullet's rigidbody directly with Rigidbody.AddForce
The enemy script instantiates the bullet as a clone of a prefab and then immediately adds force to it in the same method
try disabling the colliders of the players or the bullets.
I'm pretty sure the only thing that would lead to this behaviour is them colliding.
Do you set the bullet-layer when you instantiate them, or on the prefab itself?
if you do it when you instantiate, it could skip a physics-update with the wrong layer.
I tried using a coroutine to temporarily disable the bullet collider when it's spawned and that didnt help
I think it might help to inform that the bullet does not actually spawn inside of the hitbox of the enemy. It's well outside.
And the layer is pre-set on the prefabv
actually even with the collider on both the cookies and the bullets disabled it still happens
but if I make the cookie's rigidbody kinematic it doesnt happen obviously
but I cant do that bevause then the player cant knock it over to kill it
Your code must be adding the force then. Show the code?
AddForce doesn't apply to other Rigidbodies magically
GetComponent<ForceMode2D>() what on earth is that
That doesn't make any sense, why are you doing that?
Rigidbody2D is the component you would add force to
You changed the wrong thing
The thing you needed to change was ForceMode.Impulse to ForceMode2D.Impulse. You are just kind of guessing.
I think you might want to step back and try to learn and understand C# a bit
If you comment out the force here, does the recoil force still happen?
actually yes o.O
alright wtf i gotta figure out why my rigidbodies are randomly committing sepuku with no force applied to them wtf
The force is being applied in other code I'd guess. Anyway we can safely rule out the bullet as the cause
Or perhaps you just missed something when looking at colliders etc
I guess I didn't understand how eulerAngles works;
transform.eulerAngles += new Vector3(30*Time.deltaTime, 0, 0) ;
When I wrote this codes, isn't this supposto rotate in x axis infinitely? But when the value is 90 degree, its stops there somehow. I realy didnt understnad
Use transform.Rotate(new Vector3(30 * Time.deltaTime, 0, 0)) instead of adding directly to Euler angles
(not a physics question btw)
okay okay its not my fault i copyed that from chat gpt and it worked
didnt know how to get the input and wanted to test first
can someone help me with this?
i'm trying to make a game with only up style movement, but i dont know how to make it so that the bean moves when the hand hits the ground
please ping me if you have a fix
tilemap collision is a bit wonky, it basically creates a cube collider on every tile. You'll need to use Composite Collider 2D. add it on the same gameobject as Tilemap Collider 2D and check the "Used by Composite" checkbox on Tilemap Collider. You can also change geometry type on Composite Collider to Polygons to prevent objects from clipping into the tilemap at high speeds.
Are you using a composite collider?
Do I add 2D Composite Collider without setting any parameters ?
also check "Used by Composite" checkbox on Tilemap Collider
is your tilemap's rigidbody dynamic? make sure it's static
You would need to use one to prevent this
it worked thank you very much
Cloning GameObjects that have RigidBodies ... what's the correct way to do this?
When I call:
var original = ...
var newClone = Instantiate( original );
DestroyImmediate( original );
Everything works except ... again the f!!!!ing Unity Joint class ... which generates a 'force' of "89,268" N 😦 😦 (:
(looking back on weeks of working around Unity Physics issus, they can all be summarized as "why won't Unity allow us to zero the forces on joints? We can zero them on RBs, we need to! And the forces here are knonw to be zero! It's just bugs in Unity's joint code that - for a single frame - incorretly guesses massive forces!")
But ... I'm sure something as simple as instantiating a set of RB's generally works 😄 so there must be something I'm missing that's necessary here - something obvious that RBs require?
when i run into a wall (that has a tilemap collider) my player spaz's out and it looks strange does anyone have a fix?
Huh. Well. After trying 6 different things suggested online ... the only thing that works is:
"When instantiating an object that has joints: destroy all joints and recreate them with their exact same settings"
(TL;DR: I am geniunely coming to loathe Unity's Joint class and whoever designed it. Bad enough that it was designed wrong in the first place - having each joint 'embedded' in an abitrary one of the two RBs, when it's obviously required by definition to be a 3rd GO - is bad enough and causes so many other problems ... but theimplementation is so so so so soooooo buggy and bad)
You're not moving your character properly. Likely you're moving it directly via the Transform instead of using physics properly
how would i do it correctly?
Move via the Rigidbody
I'm having an issue with the joint components, any of you familiar with those and willing to help a bit?
why did the cube go through the platform effector 2d smoothly the first time and then with a studder the second ?
Without seeing code who can know?
Suggest you ask the actual question 🙂
okay, cool
So, I'm working on this game where you can build vehicles and drive them. I'm using joints to connect the different parts. Right now, I have it so that all of the parts are just connected to a singular one. I was using FixedJoint2Ds, but no matter what I did, it would freak out if I had to many parts. It just wasn't really working super well
I switched to RelativeJoint2Ds because they seemed more stable, but it still has some issues. The main one is that the parts aren't always going back to the position that I want the joint to hold them at
I'll get a video real quick and then I'll send over the code I'm using to add the joint
childObject is the part I'm adding, parentObject is that 2x2 block you start with
the joints are getting added when the parts are being instantiated
All the parts start off static, and the butt button sets them to dynamic
{
public float speed;
void Update()
{
if (Input.GetKey(KeyCode.D))
{
transform.Translate(Vector2.right * speed);
}
else if (Input.GetKey(KeyCode.A))
{
transform.Translate(Vector2.left * speed);
}
else if (Input.GetKey(KeyCode.S))
{
transform.Translate(Vector2.down * speed);
}
else if (Input.GetKey(KeyCode.W))
{
transform.Translate(Vector2.up * speed);
}
}
}``` how would change this to make it use the right physics things instead of transform.translate (I would watch a tutorial on YouTube but there are no tutorials for 4 directional movement)
Set Rigidbody velocity instead of using Transform.Translate
i would use rb.velocity = (Vector2.up * speed); right?
in my 2d game my gameo0bjects are only colliding with SOME other gamobjects and others not
Without showing your setup, it's hard to say what the issue is
what should i show you ?
The objects you expect to collide that don't would be a good start
So are all bullets not hitting all enemies
Or just some?
Putting continuous collision detection on both objects would be a good start if it's just some
the bullets pass through the enemies but the enemies collide with each other
Did you make the layers ignore each other in physics 2d settings?
i actually did a few hours ago but when i check now it doesnt say so
Show screenshot of your physics 2d settings
Note that it's different from the 3d physics settings
can someone help me with this?
i'm trying to make a game with only up style movement, but i dont know how to make it so that the bean moves when the hand hits the ground
i've only ever made vr games before, so i'm really bad at rigidbodies and blah blah blah
maybe instead of a sphere collider i should try a square collider
void SetBarrierSize(float size)
{
// Assumi che 'size' sia un fattore che influisce sulla scala dell'oggetto in modo uniforme
transform.localScale = new Vector3(size * 2, transform.localScale.y, transform.localScale.z);
var spriteRenderer = GetComponent<SpriteRenderer>();
if (spriteRenderer && spriteRenderer.sprite)
{
var boxCollider = GetComponent<BoxCollider2D>();
if (boxCollider != null)
{
// Ottieni le dimensioni dello sprite in unità mondiali
Vector2 spriteSize = spriteRenderer.sprite.bounds.size;
// Calcola un fattore di scala basato sulla scala dell'oggetto e sulle dimensioni originali dello sprite
Vector2 scale = new Vector2(transform.localScale.x / spriteRenderer.sprite.pixelsPerUnit, transform.localScale.y / spriteRenderer.sprite.pixelsPerUnit);
// Imposta le dimensioni del collider basandoti sulle dimensioni calcolate e sulla scala
boxCollider.size = spriteSize * scale;
}
}
}
it enlarges the render sprite but the box collider does not or at any rate does not do damage inside the render but only up close
- Don't crosspost
- format your code properly so it can be read
ok sorry
changing scale should be enough
you shouldn't need to change the box collider size too
boxCollider.size = spriteSize * scale; ?
no if the collider is on the scaled object, it should get scaled automatically.
although
I see you're not uniformly scaling
so that might actually be an issue with it
not sure how box collider2d handles non-uniform scaling
so I have to change 2d collider box to something else ?
If a trigger collider is disabled, and I move it inside another trigger collider, and then I enable it. How can I detect the collision trigger?
you should get OnTriggerEnter when you enable it afaik... but what's the use case?
(assuming there's a Rigidbody)
Oh, I see
I have a system of Rooms that works by having triggers.
This system allows entities to know in which room they are.
If they are in a room far from the player, their renderers and lights are disabled.
All these worked fine.
Until I added pooled objects, which may reallocate them when their colliders are disabled. I think my problem is that triggers are not calling enter/exit and thus invalidating the room's system.
which things are being pooled?
Bullets
So the bullets are being activated and want to know which room they're in and they usually use OnTriggerEnter for that?
Yeah
I guess I can solve it with a bunch of Physics.ComputePenetration calls
But a better solution would be cool
Or just Physics.Overlap Capsule/Sphere/Box
Has anyone been able to get Kinematic Character Controller to work with additive scenes?
The motor seems to completely ignore subscenes even if I try running PhysicsScene.Simulate() in fixedupdate on those subscenes.
The package in question:
https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131
I've tried playing with execution order and manually simulating but no luck.
It does seem to inconsistently interact with normal rigidbodies on the scene, usually phasing through
It seems to be a result of using LocalPhysicsMode.Physics3D
Pretty concerning I dont see anything about physics scenes in the KinematicCharacterSystem.
The goal now is to make it work with local scene phsyics.
I tried forcing the system object to be in the same scene as the player but no luck.
Looks like it uses the default Physics.OverlapCapsuleNonAlloc implementation,
I could try using the PhysicsScene.OverlapCapsule for each mover
I want to get eulerAngles.x to return in 0 to 360. For some reason, Unity seems to normalize it? Can I avoid this when asking the value for eulerAngles.x in code? For instance, the inspector says 179.106 but eulerAngles.x returns 0.8943897.
The Euler angles value is entirely derived from the Quaternion. Anything set in the inspector is lost via that translation
I do not actually set it in the inspector. I just see that in the inspector it shows it correctly and in code it returns that other number
just make sure you're reading from localEulerAngles
I am pretty sure, but I'll check again tomorrow
Hi guys, I have PhysicsMaterial2d with a bounciness of 1, but when I put it on something, the object begins bouncing a bit higher each time, how can I solve this?
hi i'm encountering a problem with my ai prefab, they keep sliding on the surface and the running zombie wont keep his initial trajectory
https://cdn.discordapp.com/attachments/497874116246896640/1219612479408177202/20240319-1143-28.4696688.mp4?ex=660befa2&is=65f97aa2&hm=098faa670f6394a1c4def859774ef4ebae3df7518470eaf4a2c10f2646a262db&
this is the video before adding the multiplayer and the probuilder environnement
Amend your expectations of the physics engine. It does not make any guarantees about things like conservation of energy. It's optimized for performance.
oh ok
Hello, I was wondering if someone would like to help me with a physics problem involving my capsule getting stuck inbetween objects or on edges. I have a physics material with no friction. Im guessing the problem is related to how I AddForce. I can send code + images when I get home. Any ideas would be greatly appreciated tho
usually this comes from your collider hitting the seams between two colliders.
The most robust way to solve the problem is combining colliders of the ground. If it's a 2D game this is easyish to do with a CompositeCollider.
If it's 3D it's trickier
It is 3D, i have a really nice movement controller that can walk stairs and everything but this problem is really bugging me as Im out of ideas for the moment
Reducing Default Contact Offset sometimes helps
I just cant come up with a simple/good way to solve it, other than putting more colliders down of course but that seems a bit wack
Ill look into that after some sleep, ty for the suggestion. Any other ideas would help so that I can try them when I wake up.
I am reading transform.localRotation.eulerAngles
Hey guys, as you can see in the video, my problem is that player if he touches the wall he will just keep sliding on it and I cant walk anymore no matter what I press. My Player is Rigidbody based its not Character Controller. How can I fix this issue?
I have a wall that I don't want the player to walk through so I put a box collider 2d on both the player and the wall. However, when the rigidbody on the player is set kinematic, he is able to walk through it (works as intended when the rigidbody is dynamic).
How can I fix this or do colliders not work on kinematic rigidbodies
this is expected
kinematic rigidbodies are "unstoppable forces"
if you want your player to be a mere mortal who is stopped by walls rather than an unstoppable juggernaut, he will need to be Dynamic.
ah tyty
so does the use full kinematic contacts checkbox only apply to stuff like ontriggerenter?
but it doesn't actually block them from walking through the wall?
yes
tysm!
Hey guys, as you can see in the video, my problem is that player if he touches the wall he will just keep sliding on it and I cant walk anymore no matter what I press. My Player is Rigidbody based its not Character Controller. How can I fix this issue?
i have a friction less material on my colliders im not sure why my player get stuck between 2 objects and wont move, as soon as a disable the colliders they can move again, im not sure what i can do do make it stop getting stuck
Is it possible to just have things generate an "overlap" event for games like a bullet hell game where you just want a bullet to kill an enemy if it overlaps, and not have to incur the overhead of a physics system which is calculating velocity and impact etc?
I'd just like a trigger
But as soon as I added rigid bodies to my enemies and turned off gravity, they just started floating away...
I felt like I'm getting to the point where it's taking longer to work out how to make this system do a simple thing than it would be to just make my own system
Anybody can help me that i have a 3d model and 3 wheels that are connected with a belt in different shapes.
I want to do that when 3 are rotating along with the belt also rotate, wheels are rotating but when I apply script belt it is rotating different rotation
Hello guys,
I got a problem with Unitys HingeJoints.
I got these doors which are automaticlly imported, so they are childs of a hierarchy (see video).
On the DoorAssembly I put a Rigidbody and a HingeJoint (with limits).
When I start the game, the one door starts in a different position then in edit mode and the limits are off.
Now I think its, that one of the two parent objects of DoorAssembly is scaled -1 on X. But I dont understand why it happens and how to fix it,
because the HingeJoint defines everything in local coordinates, and these are represented in the editor fine.
Does anyone know why this happens and how to fix it?
I don't understand how this is #⚛️┃physics related neither do I understand what exactly you are asking
Why would the enemies need to have rigidbody? I would most likely use rigidbody on the bullets but if that's not an option, I would consider calling Physics.SphereCast every frame (or fixedUpdate) to trace the bullet forwards one step at a time
I need some guidance.
first time dealing with Unity Particle System.
I created a fire particle system and added it to a stick to make a torch.
I made a player object that can pick it up.
how can I make the fire to move based on the direction the player is moving?
Thanks - well I was just following the instruction manual. Trigger seemed to be what I want, but trigger won't work unless one of the colliding entities has a rigid body.
I just want a simple "these two objects are overlapping, so do something, like die" no collision, movement, etc.
I would generally not rely on Triggers because they don't take the collision detection mode into account meaning the bullets could go through other objects without notification if they move fast enough
I understand. I would be looking at light weight enough collision that I would make sure the speed of the objects would avoid such a scenario to ensure I just have to do overlap checks rather than raycasts.
I did find a thread on the forum, saying the most processor efficient way to do this is use the particle system for the bullets, it's lightweight collision and lightweight rendering
And they also mentioned DOTS of course
I'd image the particle system uses raycasts or similiar anyways (I would not even consider particle system, there's other efficient ways to draw lots of objects too). btw why are we caring so much about performance? how many bullets are there flying at the same time in the worst case? I don't remember the details anymore but I remember that sometimes Triggers can be even slower than Collisions due to the way it has to check each Trigger call once while Collisions can calculate all possible collision pairs at once so it's not necessarily any faster
Hey, I'm making a platformer, and I wanna make a custom script for collisions because I don't think the default one can do what I want.
Basically, I want the player to not collide with a platform if it is hidden behind the object, if the platform is partially hidden, I still want the player to collide with the part that is visible but not with the hidden part
Would there be a way to do this ?
how do you get a rigid with a mesh concave collider to collide with others like that?
seems like convex collider decomposition is required (and off course unity doesn't do that for you)
Hey guys, as you can see in the video, my problem is that player if he touches the wall he will just keep sliding on it and I cant walk anymore no matter what I press. My Player is Rigidbody based its not Character Controller. How can I fix this issue?
Emmathy Guidry
what?
Physics
I googled it and couldnt find anything
Thanks - well I just got turned off by not being able to even get the simplest setup working without the objects floating away without me moving them or the player "colliding" with the enemies and being stopped rather than just overlapping - it all just seemed unessecary, it's meant to be a lightweight game, they can overlap him and he can just take damage
just make the bullets have rigidbody and only colliders on the players. I don't see anything wrong with that approach
Oh ok I thought you needed both on one object for it to work. Trying it now
and use Collisions, not Triggers
I still can't get it to trigger 😦
Here's my setup;
Enemy script:
not Trigger, Collision
Oh there's different functions for that - yes that's from when I was using Triggers
Ok So OnTriggerEnter provides an "other" parameter, but the OnColliderEnter etc. functions doesn't, perhaps this is for performance and you use layers to determine the type of collision?
OnCollisionEnter sure does
OnCollisionEnter you mean?
I tried both - OnCollisionEnter doesn't want a parameter (gives a "wrong signature error") but OnColliderEnter does want an "other" parameter.
OnCollisionEnter does take parameter but note it's of type Collision, not Collider
Hang on, upon closer inspection the enemies seem to travel further upwards as they chase the player, I think they're flying over the bullet object.
Got a 3D game with 2D gameplay here
wouldn't you want to use the 2d physics engine then?
I've been wondering about that - on the surface of it, you think we should
and talking of things being lightweight, there's no reason to calculate things in 3 dimensions if 2 is enough
That's right
The artist / designer wants to use 3D objects though, so should be a matter of just positioning them in 2D space right?
right, you can mix 2d and 3d elements as you wish, there's not really a concept of 2d and 3d unity, it's all the same
I think technically your game could be called 2.5D game in that case
Better stick to 3D to keep the doors open right now, I think he wants a 3D world and wants to experiment with things bouncing round,
Biggest problem is I've seen the object pass through the other and nothing happens
how do you move the bullet?
Well the bullet is just sitting on the floor right now - the enemies chase the player and I run them through it - just trying to get the collision response!
Enemies are moved with manually setting their position
Funny part is, they trigger collisions on the player
actually, I think I know the reason, try to add rb.sleepThreshold = 0.0f; for the bullet (on Start, you can get the rb via GetComponent) and see if it helps
Enemy Update (Prototype code...):
// Update is called once per frame
void Update()
{
Vector3 difference = Player.GetPlayer().GetPosition() - transform.position;
Vector3 direction = difference.normalized;
Vector3 move_delta = direction * curSpeed * Time.deltaTime;
move_delta.y = 0;
transform.position += move_delta;
}
Is this because it's not moving?
yes. if it's not moving (moving via Transform might not help), it might start sleeping and therefore ignore any collisions with objects that are not moved via physics
Still nothing; Maybe it's better if I just get a tutorial project that has collisions set up in it
Clearly I need to find out how to do this in the most Unity way possible
oh wait nvm, the Rigidbody should be non-kinematic in order to simulate any collision
Ok so I should uncheck that
Is there a tutorial somewhere where you just have a player objects shooting bullet objects at enemy objects? There's gotta be
dozens for sure
yes
Ok this is so frustrating - now the enemies push the bullet around - and still no Console output!
I will go and find a tutorial, thanks for your help
then it's probably on the script this time but that sounds good idea to get it working and then modify to your needs
I have this all working now man, thanks for your direction. Got the enemy moving via the AI Navigation, and I'm getting collision notifications when bullet has the rigid body while enemy doesn't, but both have a collider (as you suggested a while back)
Only thing I'm curious about is now, you seemed to have some knowledge of the underlying system in relation to Trigger colliders. The Unity manual doesn't directly say whether or not Trigger is more performant, just that in most cases, a trigger is stationary and used for entities that cross through a zone. Google's Gemini AI insists that Triggers are more performant, but it also didn't mention that I needed a RigidBody for any collision to happen in the first place, and we all know how wrong the AI can be.
Naturally I'll profile in the end, but is it really true that leaving trigger unchecked would be better for performance?
In my enemy script, I have both of these, just as a catch-all
private void OnCollisionEnter(Collision collision)
{
Debug.Log("OnCollisionEnter Enemy");
}
private void OnTriggerEnter(Collider other)
{
Debug.Log("OnTriggerEnter Enemy");
}
Only when I check "Is Trigger" on the bullet, do I get a response at all. I guess because both of them need a rigid body for OnCollisionEnter to work?
it's not about performance
They are different things entirely
OnCollisionEnter is for physical collisions (non trigger) with a dynamic Rigidbody.
OnTriggerEnter is for entering a trigger collider
Yes I appreciate they have a different purpose, but their function may mean Trigger is inherently more performant because it doesn't require it to respond to the physics system the way something with a RigidBody does, it doesn't have to bounce away or anything, it just has to sit there and generate responses
The bouncing away has nothing to do with these callbacks
That will happen regardless of the code
Right well if it's no difference in performance either way then I will just choose whichever one works I suppose
I just don't see how performance is relevant. You need your game to work a certain way no? Pick the approach that corresponds to how you want the game to work.
It's going to be a bullet hell thing, and I'm wanting to learn about what will be most efficient in the Unity engine when you have a tonne of bullets
But from what I'm reading, if you need to scale up, you end up using a different approach anyway
outside the physics system
Yep I will be profiling in the end.
I have my answer then - just do whatever works and then the bullet hell scale performance thing will come later
Well, OnTriggerEnter will not calculate any collision resolving things neither do it support continuous collisions which to me is the biggest thing, if you use Triggers, you will be lacking the option to make the bullets register every collision regardless of their speed. Triggers just check whether the object in question overlaps with others once a physics frame but doesn't do any between frames predictions to prevent tunneling and there's nothing you can do about it. For sure choosing between Triggers and Collisions will have some performance considerations but as mentioned, getting the game working should be the first step and profile later to make sure it runs smoothly
HI! So I am working on a 3D top down game. I have a character (using the new input system and cinemachine, no character control, with a capsule collider on the empty game object, the graphics of the player do not have a collider or rigid body), that when he collides on a corner of an another gameobject, he is launches either upwards or downwards, I do not know where because it is out of the view frustum. I tried putting rigid bodies to the other G.O., applying a force either downwards or upwards, changing the camera clipping distance. None of these worked, so I am reaching out here. Hit me up if you have any idea on why it is happening and how I can solve it.
Wheels rotate but the belt is not any movement
How to rotate the belt along the wheels. Could you please help me?
Custom physics shape in the sprite editor
I am Using TileMap Render
i am aware.
This is how you customize the physics shape of a sprite in a tile:
#⚛️┃physics message
sorry i didn't understand
Thank you that's good to know. You're right about that, it's good that I can do it both ways, but also I'll control the speed of the bullets so that they will always overlap during a physics frame. The enemies are bring driven with NavAgent and the bullets are being fired by setting the velocity of their rigid body once, so it should be the physics frames taking care of that, not regular update, as I understand it.
I have a unity BallMesh controlled by a camera skinned mesh renderer, controlled by four rigidbody bones with springs, to simulate softbody physics for a large water droplet.
I want to make some sort of sysem to cause it to look like a certain part of the sphere breaks/cuts up into two halfs when i want, with the size of each half being controlled by how much breaks off.
One idea I have is the original sphere shrinks and a small copy is made at the position of the bone that
"broke apart" from the original sphere.
does anyone have any other ideas that could be easier to implement or control, or would look more convincing?
or another idea is instead of a small copy it just emits a particle sphere where it broke off (which wouldnt be softbody) but would get the point across
tried implementing this but the object jolts and teleports a bit every time it shrinks and spawns a copy.
Hello Pros, I've some question. I'm using configurable joint for the motion of my lever, But ATM I'm trying to find on how can I stop it bouncing up and down. I'm trying for my lever to drop down due to the small box weight without it bouncing.
Currently I'm using Angular drive to make the lever stay in place.
Found the solution : playing with drag property on the rigidBody components.
If you just expect the physcis system to predict that you are doing some sort of belt physics and deform the belt mesh accordingly, you are wrong. If you really wanted to simulate it, you'd have to construct the belt from individual joints that are linked together and moved by the physics system somehow but please don't, it won't be worth it in 99.9% of the cases. I would highly recommend rotating all the wheels via code and not mess with physics because it won't be easy (I don't think unity's physics engine is capable of doing that out of the box). When it comes to making the belt look like it's rotating, I'd probably use vertex or fragment shader to rotate it based on your code. Maybe other way could be to use skinned meshes to actually move the belt in parts but I'd assume it would be easier to use shaders. Regardless the visual part is quite hard problem and the mechanical part will be much harder than that if you actually want to simulate it but I would highly recommend not to. Feel free to ask on the coding channels if you need help coding the wheel rotation
Not sure if the right place to ask but I'm using PlatformEffector2D to get one-way platforms. But I find sometimes on the edges like if I had barely made it through, I fall through one-way platforms after a short delay. Are there any properties I can tweak to get this more consistent? Would increasing/decreasing the height of the collider (to be passed through) help?
anyone know how i can get my door to rotate like a normal door? when i open it, it stays open like this instead of opening like a door irl
I think if you make the door a child of an object where you would want the hinge to be the rotation would then be about the parent and work as you want
Anyone know how to fix inaccurate collisions of RigidBody objects when selecting any of the "active" collision detection methods in RigidBody property?
Those settings ruin airborne objects interactions, wherein they bounce away from each other without adding any rotational force. Using descrete detection has the correct physics interactions with the downside that fast moving objects can pass through each other depending on framerate.
Any advice? I've already turned physics steps up pretty high and set physics to framerate independent but it would be nice to make sure objects can't pass from one side to another.
hey I need to use non-convex mesh, it doesnt need any collision - only rays so im using layers but it says its not possible with non-kinematic rigid body (it's child of element with rigidbody) how can I fix that?
add rigidbody to child that is kinematic and has no gravity?
works like this
Could I get some help getting hinge joints to work? I tried watching a YT tutorial on them and I can't really understand why mine behaves differently, I have a hinge joint on this door (first screenshot), but when I run the game and try test it with the cube gameobject, it reacts really weirdly (like in the second screenshot)
looks like ur code might be wrong
Hinge joint component doesn't use code?
For me to swing my door open like a door would irl i had to code it that way, im aslo still new so maybe you know more but it works fine for me
Ahh well this is for a VR project so the component is to allow the door to revolve around a hinge that I place somewhere on the door and then it can also react to physics of other objects
- How's the cube moving?
- Most real doors have 3 hinges!
The way unitys hinge joint component works, one joint should work alone (they only allow pivoting around single axis)
So I have a dodge that is supposed to travel 2.5m in 0.5s. Currently how I'm handling it to make it lopsided (as in most of the distance is in the first half of travel time and little of it is in the second half of travel time) is to calculate a decay rate with (2 * distance / Mathf.Pow(time, 2)), the amount of force needed to cover the distance in time with (Mathf.Sqrt(2 * decay * distance)) then subtracting (decay * Time.deltaTime) from the velocity every physics cycle. While this works, it's not lopsided enough for my needs and I have no idea how to change any of these calculations so that it frontloads more distance at the start of the dodge and less at the end than it is currently doing without changing the overall distance traveled for the entire duration
So i am trying to spawn blood when enemies are shot(which is very straight forward yes) it was initially working but i had to change shooting from raycast to actual bullets collision and the blood does not spawn again. My code is right because all my logs show.
using System.Collections.Generic;
using UnityEngine;
using BlazeAISpace;
public class PoliceHealth : MonoBehaviour
{
public int healthPoints = 100;
public GameObject bloodEffectPrefab;
private BlazeAI blaze;
public bool debugHit;
bool isDead;
void Awake(){
blaze = GetComponent<BlazeAI>();
}
IEnumerator Start(){
while (true)
{
yield return new WaitForSeconds(5f);
if(debugHit)
TakeDamage(40);
}
}
//function gets called when the police is shot
public void TakeDamage(int damage)
{
Debug.Log("Took Damage");
if(isDead) return;
healthPoints -= damage;
if(healthPoints <= 0)
{
Debug.Log("Health is less than 0");
// Check if healthPoints is less than 0 to handle death logic
blaze.Death();
isDead = true;
PlayBloodEffect();
GetComponent<Rigidbody>().isKinematic = false;
GetComponent<Collider>().isTrigger = false;
Destroy(gameObject, 2.5f);
}else{
// Trigger damage animation
blaze.Hit(this.gameObject);
PlayBloodEffect();
}
}
void PlayBloodEffect()
{
if (bloodEffectPrefab)
{
Instantiate(bloodEffectPrefab, transform.position, Quaternion.identity);
}
}
}```
what could be the issue?
Hi, I have a unity car that has colliders, and when i set it to move based on simple waypoint system, it will tip and turn pretty severely
how do I make it just follow the simple waypoint system without it wobbling?
I have to have some collider because of triggers later in the level
Hi, I need help with colliders. I have a Quad with a mesh collider and for some reason (with a bit of force) the player can pass through the collider. I later, instead of the mesh collider, added a box collider that's twice as thick as the player's collider and the player can still pass through it. How do I fix this?
This basically
this should not happen obviously
- Use a BoxCollider not a mesh Collider.
- What do you mean exactly by " a bit of force"? Make sure you're actually moving your player in a physics way.
On the photo there is a box collider and it still does not work, as you can see the player is in the collider. By "a bit of force" I mean player has to crash into the wall for a couple of seconds to go through the collider
This is the part that controls the player
Ok yeah so you're not actually moving your player via the physics engine as I guessed
You're using transform.Translate, which is equivalent to just teleporting the object and ignoring physics entirely
Hi, I have a unity car that has colliders, and when i set it to move based on simple waypoint system, it will tip and turn pretty severely instead of following the path and not wobbling
how do I make it just follow the simple waypoint system without it wobbling?
I can't disable the colliders because of triggers later in the level
These are the waypoints
You'd have to explain how the movement works. Is it all physics based? WheelColliders? What's the deal
I'm new in unity and i would like to had a colision to this game object (the platform) in one time without doing it shape by shape . How can i do it please
PolygonCollider2D
Thanks it was what i was looking for
do limits work at all in physics2d hinge joints?
i get a lot of flipping and jitter
yeah when i switch to hinge 3d it's super stable
I know I'm effectively asking for a calculus crash course, but I only ever studied up to trig and I'm at a loss on how to do this.
Given these variables I'm trying to calculate the arc length of x assuming it's part of a perfect ellipse with the given information. How would I go about doing that?
What could be the reason that my player object is going inside of obstacles? My player has rigidbody and also obstacles has too. I checked freeze position for them but still i didnt understand why the reason
You aren't properly moving your player object with the Rigidbody physics
You're likely teleporting it around via the Transform
I guess so but I don't know the problem, normally it didnt do that. But I scaled my player to 3 from 1 and later i changed back to first value. Right after this changed, my player started to move like that
I just explained the problem. But it's an educated guess and not for sure without seeing your code
Wait I'll show you
If you are moving via the Transform that's absolutely the issue
No, I'm moving via rigidbody
I'll show you wait
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public static event System.Action OnPlayerInFinish;
Rigidbody rb;
public float speed = 8f;
public float turnSpeed = 8f;
float smoothInputMagnitude;
float smoothMoveTime = 0.1f;
float angle;
Vector3 velocity;
bool disable;
float smoothMoveVelocity;
private void Start()
{
Guard.OnPlayerSpotted += Disabled;
rb = GetComponent<Rigidbody>();
}
void Update()
{
Vector3 inputVector = Vector3.zero;
//Get Input from Player
if(!disable)
{
inputVector = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")).normalized;
}
//Get scale from input to control player movement
float magnitude = inputVector.magnitude;
//Position smooth value
smoothInputMagnitude = Mathf.SmoothDamp(smoothInputMagnitude,magnitude,ref smoothMoveVelocity,smoothMoveTime);
//Angle to face it
float rangeBetweenInputs = Mathf.Atan2(inputVector.x,inputVector.z) * Mathf.Rad2Deg;
//Angle smooth
angle = Mathf.LerpAngle(angle, rangeBetweenInputs, turnSpeed*Time.deltaTime * magnitude);
//Handle movement and rotation
velocity = transform.forward * smoothInputMagnitude * speed;
}
void Disabled()
{
disable = true;
}
private void FixedUpdate()
{
rb.MoveRotation(Quaternion.Euler(Vector3.up * angle));
rb.MovePosition(rb.position + velocity*Time.deltaTime);
}
private void OnDestroy()
{
Guard.OnPlayerSpotted -= Disabled;
}
private void OnTriggerEnter(Collider other)
{
if(other.tag == "Finish")
{
Disabled();
OnPlayerInFinish?.Invoke();
}
}
}
I'm handling the movement at FixedUpdate tho
MovePosition doesn't respect collisions
Ohhh
If you want collision you have to move via velocity or forces, and your Rigidbody needs to be Dynamic
Aka Not kinematic
Form?
As I said you need to move via setting the velocity or adding force
For adding forces yes
All right, I'll try it
For setting velocity you use the velocity property
Help pls i have this trash can shaped 3d object how do i add a collider that follows the edges of this object mesh collider creates a box collider around this object and then nothing cannot get inside
MeshCollider is the way
just make sure it's not marked convex
If you need the object to be dynamic then you need to build the collider up from primitives or smaller mesh colliders
3d are unstable too, just not quite as much!
so this video shows my movement. when I hold a direction to move, but also hold the direction into a wall, my character moves slower. I understand friction and all that but how do I get that to not happen. my character has a rigidbody2d on it btw
ive tried putting a physic material with no friction on both the player and the wall but it still happens
i switched to 3d and cranked up iteration count which looks stable
so the game uses 3d physx for dynamic movement and 2d for collision because it's a side scroller... i'll have to increase minimum specs 😅
like in Dune, only slow moving objects pass through shields
hi, when using physicsScene.Simulate(step), how do we retrieve this step value in FixedUpdates?
You don't retrieve it. It's up to you
If you want to use the "normal" timestep it's Time.fixedDeltaTime
which will match with the cadence that FixedUpdate runs at
But you can simulate however much time you wish.
Hi, yeah I realized that later 👍👍
I gave up on custom physics steps, since the execution orders mattered a lot in my code
Instead just used the normal fixedDeltaTime multiple times in a FixedUpdate, depending on the speed I want the simulation to be
Of course then using a custom function to replace FixedUpdate
anyone know how to get a physics situation such that the player rigidbody2d can't move a rigidbody2d it is standing on (which would be unrealistic), but can move it when it isnt standing on it?
^ vid shows the issue where the player shouldnt b e able to push the thing when standing on it. Cant have a solution where the player has a mass of 0 when it steps on it because then the player couldnt push other rigidbodies on the same platform.
If your game is single player and nothing else is capable of pushing the obj, lock the position of the object in an OnTriggerEnter func if the player is standing on the obj
sadly dont have that situation. the object would have to be able to move under gravity, forces, rotation due to mass imbalances etc
ultimately the issue here is that your player moves not by applying a counter force on the ground it's standing on, but by sheer magic
in the real world when you walk, you push one way against the ground and that pushes you in the opposite direction
but here you're likely doing AddForce deus-ex-machina style on your character
so there's no counter force on the thing it's standing on
it can also be a problem of friction and mass
Maybe the object needs to be more massive or have greater friction with the ground, and your player needs to exert a counter force on it when it moves while standing on it
thanks, the counter force idea was helpful
i think id have to scale the counter force amount based on if the player is colliding horizontally with the object and the angle it is doing so at, so that the object doesnt quickly move away from the player in the opposite direction i guess
Theoretically it should be a lot more massive than the player and have decently high friction with the ground such that it won't move unless the player really winds up and runs into the wall. Much like you'd expect in real life
yea that would be way easier, but i guess i like doing it the hard way such that the physics is exactly how i want it to be
While reading this i wanted to give a quick remark if you want your character to have constant speed you better use the velocity method (transform.translate) because if you use the add force method it will increase the speed overtime which makes the player movement delayed
Translate is not the velocity method.
Velocity is the velocity method.
Hello, I'm trying to add breast physics to my character but the google results do not really match my case. My issue is that the breasts of my character don't have their own bones, instead, it's the pectoral bone which handle them similar to my male characters. Slight rotations still gives an adequate effect so I'd like to add that if possible but I'm not sure how to make it work. I know I can get the velocity using the previous position and new position but from there, the math seems super complex to transform that into proper rotation with proper limitation and bounciness. Would anybody have some ideas?
Ops, my bad by constant speed I meant moving the object directly from the transform or using the velocity like this example :
using UnityEngine;
public class MoveObject : MonoBehaviour
{
// Speed of movement
public float speed = 5f;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
// Set velocity to move the object along its forward direction
rb.velocity = transform.forward * speed;
}
}
Yes I'm aware but those two things you listed are very different
moving via the Transform is problematic for many reasons.
Hi, Do you know how can I make this axe not go through the Terrain? should I do IK or Physics detection?
you would need to do both probably
physics to detect where the terrain is
IK to handle the animation to that point
Probably the simpler approach is the typical things FPS games do to just always render their hands/weapons on top of walls etc
Thanks, I have detected Terrain With a Raycast but about IK I'm not sure which Approuch Should I use, ChainIK?
I don't know. I would just do this approach tbh
do have resourcse I don't know how to do it
Thanksss!
i want to run some idea with you folks with more experience with physics.
the game is 2D, currently all gameplay colliders and rigs are 2D.
from recent test, hinge are far more stable in 3D.
currently i have both 2D and 3D running side by side: 3D for physics behavior and 2D for gameplay collision.
all 2D colliders are circles because objects are 3D and move along all axis, 2D colliders are the only one that don't sheer.
I'm considering converting everything to 3D and replace the circles with z-aligned capsules, to avoid bullets that are slightly off z=0 to pass through enemies
does it make sense and what's your experience with this sort of stuff
Anyone around with some knowledge on rigidbody wackiness? I'm using a Rigidbody.MovePosition for my "Ammo" and while it arcs nicely sometimes, other times it reverses its trajectory and flies upward.
Has anyone seen this behavior before?
In addition, the rigidbody is using global gravity, which has been set to -29.43.
Nevermind, found that the culprit was that my modified rocket script still had the projectile using a look at for the direction. 😅
how do i enable hdrp water physics?
hi I'm trying to do a raycast from a Transform of my object to another but the start position is not where I locate it
CODE:
RaycastHit objectHit;
public Transform ObjectDetectorIniPosition;
Vector3 direction = HeadTracker.transform.position - ObjectDetectorIniPosition.position;
if (Physics.Raycast(ObjectDetectorIniPosition.position, direction, out objectHit, Mathf.Infinity, ObjectsDetectingLayer))
{
if (objectHit.collider != null)
print(objectHit.collider);
Debug.DrawLine(ObjectDetectorIniPosition.position, objectHit.point, Color.cyan);
}
What do you mean by "is not where I locate it"?
the ObjectDetectorIniPosition Transform is near my axe
but look at the start position of cyan Ray
what ? 
it's World position so what's wrong with it
the red circle is HeadTracker which is my direction
First off make sure your tool handle position is set to Pivot, not Center
Ok now second - make sure you have actually referenced the correct Transforms
POerhaps you're referencing a prefab for example by accident
it's exactly the object I defined
let me unpack it
nah still the same
could be because of SkinnedMeshRenderer
click on that object. Where does it take you?
doesn't matter as long as you're referencing the correct Transform/bone
it won't take you to a place in the scene, it will highlight an object either in the scene or in the project window
the selected object is the X,Y,Z tool pointed

Scene view
Ok so I put the code in Late Update and now it fixed. do you know why this happen?
When using wheel colliders, is there a way to know how much motor torque will break traction? I am trying to develop traction control and abs for my car game but wondering if there is a way to calculate this instead of just adjusting motor/brake torque until the wheel stops slipping
Does anyone knows how to make objects' speed does not decrease tremendously when collided with other objects?
I am using rigidbody
and I set the collider as capsule collider
but it's speed seems to decrease tremendously
when collided with other object
well NONE of the collided objects can be pushed easily. They cannot be pushed.
Things slow down when they collide. Are you looking to make it so they don't interact?
what do you want to happen here
in the first scene when it collides with the ramp, it moves MORE faster
so WITH the ramp (swipe distance 150) and WITHOUT the ramp (same swipe distance)
has different power
and in the second scene, when it collides with the breaker block, and I clicked on the red button to make it disappear.
then I want to at least a 'few' momentum to remain
but all momentum disappears when collide with it
I’m making an iPhone game where one mechanic is launching balls in a direction. . I am using RigidBody.AddForce (force mode force) in fixed update that sets a cap on the velocity as well. When I build to my phone the ball moves fine but there seems to be something off. It seems almost blurry or laggy on my phone. It could just be me but I’m trying to figure out how to make this smooth. I’ve tried moving the ball in a variety of ways including force mode impulse as well as Lerping the transform. Nothing seems to fix it. Anyway here is a video of my phone playing the mechanic.
- Is interpolation enabled on the Rigidbody?
- Show the code
Yes Interpolation is on. Here are screenshots of some code
shouldLaunch is triggered to true upon player releasing touch after dragging.
Well you shouldn't be multiplying fixed deltaTime into the force
Though that wouldn't make it stutter
But it's making your force value have to be way too high
yea my force is like 4000
Yeah that's why
You can divide it by 50 and remove that
How does shouldLaunch work
And launchDirection
trajectory is calculated by subtracting current touch position (in TouchPhase.Moved) from initial touch position (set in TouchPhase.Began). Then the ball launcher class calls LaunchBall and passing in the direction.
Why the .1f on the y axis?
And what does LaunchBall do
For the line renderer so it’s above the ground
LaunchBall just sets the flag for that ball to tell it that it should apply force in the fixed update function
If you need it to slightly float above the ground why not just have move the collider for the ground slightly above the renderer
I don't see how the LineRenderer is related though
That magic number seems kinda sketchy
Yeah I was going to refactor it once I got another solution. The main issue right now is just that “lag”. It just doesn’t seem like it’s moving smoothly on my phone
TBH though I don't really see blur or lag. Are you having framerate issues perhaps?
Maybe it’s just me then. My last profile on it was fine but I haven’t tested the framerate on mobile
Test it
Going to now
Got it. The framerate was below 30. I set targetFramerate to 60 in my game controller
Much smoother
Thanks for the help @timid dove
i'm not sure if this is a physics thing or not, but my 2d character is slipping. i managed to make him stop as soon as i release one of the arrow keys, but for example if i switch from going right to going up, he slips a little bit.
no.. I want them to loose their speed slowly
You'd have to explain how it's moving
Give the player a larger mass or give the obstacles a smaller mass.
sooo, before, the character kept sliding a bit after i released a key. i fixed by adding a transform.Translate(0,0) when i release one of the keys. but still if i keep going right then press the up arrow key, then release the right arrow key, the character keeps sliding a bit to the right. which is understandable cus what i did to fix the sliding when only one key is pressed is with a variable for when the player is moving (in any direction). so i was wondering if there was a way to add friction to the ground. tho this is in a top-down view 2d game
I meant, show the code
transform.Translate is not what you want if you're using physics btw
Yeah i dont have a rigidbody or collider or anything
Soooo no physics at all
And i'm sorry id have my computer rn so it would be much appreciated if it is possible for you to help me by me just trying my best to explain what i did
That's why j started my msg like that xD
There wouldn't be any sliding then unless your code is making it slide
so it's not really possible to answer this question without seeing the code
One guess would be that you're using Input.GetAxis which has smoothing, instead of Input.GetAxisRaw
I am indeed using getAxis
I'll change it when i get the chance, remove the translate(0,0) and see the results. Ty
Im trying to make a game where 2 players are connected by rope. i have the rope kinda set up but i cant figure out how to connect the rope anchors to the players.
they are restricted but the rope looks all funky and the rope is connected to just the space and not characters
Using joints
Joints have a connectedBody property
Yeah i have it where the characters are connected to the respected ends of the ropes and one works perfectly find and the other one doesnt now
one of them is just stuck in place
oh i fixed it
ok now they are constrained correctly but my players wont jump? you can see them trying to jump but they dont get lifted off the ground
that doesnt seems to work NONE of the object can be pushed like that
plus the other object doesnt have rigidbody
it only does the collision with the box collider
Physical collisions don't work without Rigidbodies
As in - it won't be able to move
It will just be an unmoving obstacle
You can't push an object unless it has a Rigidbody
i dont want them to push
I just want them to decrease their speed slowly
You want to use a trigger collider and change the velocity in code then.
If your player hits an unmovable obstacle naturally it's going to stop
Or bounce off
oh
Yes that makes a trigger collider
I push some casts inside **FixedUpdate() **that depends on position. But Rigidbody.position/Transform.position is not correct in FixedUpdate(). It seems it is delayed but how will i fix that? Even i re-order the Script Execution Order, it does not fix it. Physics.SyncTransforms() does not seem to fix it either.
It seems it calculates by velocity but i need answers.
I remember i face this issue before. But could not remember the fix.
Just always use Rigidbody position
All right. Why is it happening tho?
That's what matters for physics queries
Interpolation or extrapolation
My rigidbody is not using any of those. Do you mean the physics system using those internally even it is not set in rigidbody?
Shouldn't...
Show the code?
Okey
private Vector3 lastPosition;
private Vector3 lastNextPredictedPosition;
// future: Custom system for updates.
public void FixedUpdate()
{
// Did not work.
// Physics.SyncTransforms();
var position = WorldRootSingleton.Instance.transform.InverseTransformPoint(selfRigidbody.position);
var nextPredictedPosition = position + (position - lastPosition);
Debug.LogFormat("Transform Position: {2}, Rigidbody Position: {0}, LastPosition: {1}", position, lastPosition, WorldRootSingleton.Instance.transform.InverseTransformPoint(selfRigidbody.transform.position));
// Register De-Activation for collider chunks in old position
// It uses Physics.BoxCastNonAlloc and takes Position, Dir, distance
RegisterColliderChunkDeActivations(WorldRootSingleton.Instance.transform.TransformPoint(lastPosition), (lastNextPredictedPosition - lastPosition).normalized, Vector3.Distance(lastPosition, lastNextPredictedPosition));
// Register Activate for collider chunks in new position
// It uses Physics.BoxCastNonAlloc and takes Position, Dir, distance
RegisterColliderChunkActivations(WorldRootSingleton.Instance.transform.TransformPoint(position), (nextPredictedPosition - position).normalized, Vector3.Distance(position, nextPredictedPosition));
lastPosition = position;
lastNextPredictedPosition = nextPredictedPosition;
Debug.LogFormat("Updated LastPosition to {0}", lastPosition);
}
Not refactored yet... I'll delete logs in order to read easily
I don't know it is just regular casting there is no magic behind the scenes
I will try including the velocity movement. I think this problem occurs due to one of my custom systems. Thank you for helping...
and then what should I do in the script?
Listen for the trigger (OnTriggerEnter) and slow the velocity
oh
hi people, someone knows how to make an object with cloth component but its mesh collider can follow to cloth movement? because I got some problems with my floor cube collider and my mesh of my cloth
hello, how can i fix my 2d player's sliding and make him have consistent speed at all times? ty
you'd have to show your code
- Well you're using forces so your object is going to have momentum. If you don't want that, you should switch to setting the velocity directly
- You should never multiply Time.deltaTime into your AddForce call (nor into setting velocity)
why not? (2)
Time.deltaTime is used to convert a "per frame" quantity into a "per second" quantity.
AddForce with the default mode is already a per-second thing
in fact Time.fixedDeltaTime is already factored in
soo addforce....well adds force every second instead of every frame?
no it adds it every time you call it
but it's expressed in Newtons
it's intended to be called every physics frame without adjustment
(at least in the default mode)
As for velocity well it's already meters per second
you don't need to adjust it
your speed is your speed
but velocity won't stop the sliding is it?
it will if you set the velocity to what you want (0)
you basically just want:
void FixedUpdate() {
rb.velocity = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")) * speed;
}```
exactly what i did except i multiplied by speed
yeah right there
ok the more i think abt the more it makes sense
tysm
After maybe 10 hours, i finally figured out my problem and it wasn't about sync in transforms or physics.
Why is that happens? I am updating the "LastPosition" variable inside FixedUpdate. Why FixedUpdate updates my variable in async?
I remember someone said "Do not update your variables inside FixedUpdate" before i'll look for it in channel: I couldn't find it. It would be correct for frame by frame input variables but i didn't understand for custom variables.
So, as far as i am aware, there is a 255 triangle limit for convex mesh colliders. Is there any way to bypass that limit, and add more triangles to a convex mesh collider? I am trying to make an accurate collider for a complex object
Use multiple colliders
I've been debating a kinematic model for car movement vs dynamic.
While a dynamic model would be the most physics-realistic, kinematic is still realistic but just leaves out the need for forces, and allows for position and heading to correlate.
Thoughts? Also, for a kinematic model, I have ackermann steering completed I just need to find which equations to use for the car steering and movement which are dependent on velocity. I've been searching around but no such luck as of yet
What have I done wrong with my ragdoll character joints ?
what is the best way of handling ragdolls? I have a navmesh agent that just basically controls the movement, and attached to it is the gameobject that has the ragdoll, ive also researched about navmesh and physics not really being good with each other, and since I am new to this thing, Im not quite sure how to handle this scenario, basically i just want the ragdoll to only activate when entity dies, because when i start the game, the navmesh will start going crazy, since i have the ragdoll RBs attached to its child, any tips on how could i approach this?
why the wheel collider isnt colliding? it's in correct rotation but it isnt colliding
I’m not really sure if this is the best way to do it, but you might be better off having a non-ragdoll zombie and spawning in the ragdoll when the zombie dies
sometimes turning off the physics and colliders and stuff on all the child components can backfire in weird ways with the animator, but you might be able to get away with it? it depends
do configurable joints still have effects even if all the constraints are set to “free” and the springs are turned off?
I’m making a ragdoll grabbing system and I turn off the mouse to hand movement joint when it grabs a wall, but it seems like the joint still affects the ragdoll
what’s weird is that only happens around 50% of the time, and it seems like it’s completely random
I set up a linear limit like this,
var b = dictionaryRight.ElementAt(i).Value.linearLimit;
b.limit = 5f;
dictionaryRight.ElementAt(i).Value.linearLimit = b;
var c = dictionaryRight.ElementAt(i).Value.linearLimitSpring;
c.spring = dictionaryRight.ElementAt(i).Key.physicBody.mass / 4;
c.damper = c.spring + 2.5f * c.spring;
dictionaryRight.ElementAt(i).Value.linearLimitSpring = c;
dictionaryRight.ElementAt(i).Value.enableCollision = true;```
But Im wondering if there's a way to make it so that the connected rigidbodies cannot be within a distance of each other. How do I make a minimum distance for them to be at ?
Does anyone here have experience with these errors?
Here is the project for anyone willing to check it out
https://github.com/ICOnce/Destroy
my physics based fingees look happy
thanks for the reply! i noticed that while the animator is enabled, the rigidbodies or the ragdoll is not doing anything, so what i did was just set all the rigidbodies to isKinematic and only activating it when the entity dies
the reason why my problem arose was because the navmesh component is not attached to the parent transform of the ragdoll (in the first picture), it worked when i removed the 'Variant 1' and moved all its components into the 'Zombie 1' gameobject, in that way it directly controls the transform rather than the parent
i wasted a whole day trying to fix it when it was just a bad placement of components 0___0
story of my life
I found the issue, i am dividing by zero, but I am not sure how to fix that while still keeping the formula correct
When the non-existence of the universe is helping you with a formula
For real
I thought I entered some weird reality when Unity told me I had an invalid world
so does rigidbody collision actually allow colliders to overlap slightly ?
why does this happen? the car parent have rigidbody it have the wheel meshes in different empty GameObjects than the colliders, but its still not colliding
What kind of collision behavior are you expecting
Being the wheel on the ground instead of being half under it
well that depends how you're moving this thing
I am not moving it yet I just need to collide it with the ground so it wont fall through ground
moving it with physics is the only context in which the collider is going to do anything.
lets try something before playmode raise the vehicle above the floor so the wheels arent touching the ground then enter playmode, also make sure gravity on the rigidbody is checked while doing this
want to be sure the problem isnt from your placement
Yea the vehicle before playmode is above the ground also gravity is checked I followed multiple tutorials but none of them worked
When I slightly move the collider in the playmode the vehicle is little shaking but like isnt colliding with the ground
you have also checked the layers in physics settings to see both your ground and wheel layers collide
if you would not mind please re-send a picture of the wheels with the isometric view, i want to see the collider gizmo perfectly
thats what I thought but I checked that several times if both can collide
hey stupid question can you show the collider for the ground?
Collider for ground is terrain collider box colliders collide with it with no problem only the wheel colliders does not
after you have sent it I would also like to know if you designed the car yourself, I had an issue like this before and I resolved it by changing the rotations of my mesh, as you can see the tiny circle on the wheel collider is meant to pointing to the ground but in your image it is pointing towards the right.
just googled the small circle is the raycast and it should be pointing down towards the ground
I'm using wheel colliders on a vehicle model and if I don't rotate the wheels the car lands on the ground and it works fine. However, as soon as I start rotating the wheels around the axel, the car goes through the ground. I heard wheel colliders are infinitely thin and can have this issue, but why only when I rotate them? What are some solut...
so basically you could either rotate the mesh entirely on your 3d app or remove the tire mesh and rotate it, lets see if we have a different result
Yea its my model I'll try that
Please provide feedback
worked 👍 thanks so much for your time and help
Lovely
Hey guys, we just upgraded from unity 2021.1.16 to 2022.3.23. There aren't any errors but our general movement, bullet physics and such behave very differently. I have been checking around and found that they added "simulation mode" to the physics settings in 2022, which was set to fixed update. I changed it to update and it's better but it's still not the same as our 2021 build. I don't know what else might be causing this. Any ideas?
A setting called Auto Simulation is missing in 2022, but i don't know if that has anything to do with this
Settings on 2021
Settings on 2022
You almost definitely don't want simulation mode to be set to Update. The old setting would have been FixedUpdate.
That same Dropdown is what replaced auto simulation btw
It's possible you have framerate dependent code in your project
Thank you, would framerate dependent code change how everything works just because of unity version?
In 2022, our movement and bullets are much slower and jittery in fixed update mode.
Could it be the new Fast Motion Threshold setting in 2022? 2021 doesn’t have that.
In 2021 version our movement & bullets still behaved the same in low or high fps.
Oh wow I just fixed the bullets. Disabling interpolate on their rigidbody instantly fixed it.
Any idea what might be the cause?
Yeah disabling interpolation the player fixed the movement too, I just don't get why.
I think interpolation might have a bug in new Unity versions because this is the 3rd or 4th time someone has mentioned it causing issues lately
Dang, I see. Thanks a bunch for the help though!
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
Question. Ive been working on a PJ. When my sprite flips direction via script He get stuck in wall. I have a tile map collider, rb and composite collider setup. Ive changed detection to continuous and geometry to polygons and still no luck. any suggestions?
hi guys! How zeroing actually works? i write a function with that code ```cs
public Vector3 AimPoint(float distance)
{
return transform.position + (transform.forward * distance);
}
```cs
//Here the point where the bullet will be instantiated
pointShoot.LookAt(cameraController.AimPoint(100f)); /* theoretically, according to what I understand, here zeroing should be set to 100 meters */
Rigidbody tempBullet = Instantiate(bullet, pointShoot.transform.position, pointShoot.transform.rotation);
transform.position is the camera position
The bullet spawn on the barrel of the gun, the red line is the direction of the camera and the green is bullet trajectory, i made based on second image from a forum thread about zeroing: https://forum.unity.com/threads/fps-shooting-accuracy.227427/
i have problems because the shoot is not hitting the target properly
I have no clue where the given code is attatched to so I don't know what transform here refers to but it seems like you are pointing the guns barrel exactly towards the target but if the bullet drops at all during its flight due to gravity, it will undershoot the target and as far as I understand, zeroing is tackling exactly that. In order to take the bullet drop into account, you must apply some kinematic equations to calculate how much the bullet will drop and add that to the target positions height
You might find this short series interesting if you are having hard time understanding how and which equations to use: https://www.youtube.com/watch?v=IvT8hjy6q4o&list=PLFt_AvWsXl0eMryeweK7gc9T04lJCIg_W&index=3
transform is camera position(it´s a point X meters away in camera direction), the bullet is not dropping because of high velocity (the drop happen in a so far distance), i tested yet
the first code is attached to camera, the second on weapon, the weapons is accessing camera here cs pointShoot.LookAt(cameraController.AimPoint(100f));
how are you moving the bullet then (btw I really think you should take the bullet drop into account regardless but you do you)
tempBullet.velocity = tempBullet.transform.forward * weaponStats.bulletVelocity; ````
look the difference between the lines, the white line is camera direction, the green is the bullet trajectory, the bullet is so fast that in the close distances the drop not happens, the bullet starts with 900 meters per second of velocity
but what is wrong then? what are you expecting to happen and what happens?
in the games when you use zeroing, the bullet go to the point you are aiming, when you see far target the bullets drop, FPS games have an option to adjust zeroing to hit the target, in my case the bullet is not hitting the point i aiming in close distance.
the white circle is the bullet hit, look that the point is a little below from where I aiming
my question is, how properly calculate zeroing?
is your zeroing value set to the precise distance between the gun and the wall?
in this case zeroing is set to 25 meters, but i don´t know if i implemented the zeroing in the right way, i don´t find anything on google about this to help
i made based on this explanation, but i don´t know if is correct, imagine like the first stick adjust zeroing to 25 meters and second to 50 meters
so the distance between the wall and the gun is 25 meters right?
Actually, wait a second. From the horizon it seems your rifle sight is little bit above the center of the screen. I think you should calculate the zeroing from the perspective of the sight, not the camera (so you should use the sights position and forward vectors instead, if there's no transform at the center of the sight you could make one empty child object to work as one)
@ashen tapir But then you still need to make the sight centered correctly to the camera I assume, otherwise it won't look like it's hitting the right position (that's why often rifles have sight at front as well to precisely align your eye to be parallel with the barrel). Those hologram sights (or whatever they are called) usually works in a way that if you don't look at them straight through, the dot will still show where the bullet is going but it will look like the dot is now on the side of the sight (the image below shows how the dot stays at the target when the shooter changes his heads/eyes position relative to the sight). Don't ask me how that works but that's how it works. In order to implement that in unity you'd maybe need some sort of special shader for the sight glass that moves the dot according to the view angle. The lazy solution would be just to center the sight with the camera and most likely no one would notice the dot not moving during transitions as most don't even know it works like that
if my character already has all colliders assigned how do i turn it into a rigidbody
yes i know, i made a shader that works like real life holographic sights, in the image i showed you the red dot is exact on the center of the screen, i tested that so many times, i opened Escape from Tarkov to make a test, and the same thing happens, it´s because the bullet is starting from the barrel and not the center of screen (or center of aim) like other games, i finally found a website talking about that, zeroing is a point where the bullet and sight intersect, so if a zeroing is adjusted to 25 meters the bullets and sight will intersect 25 meters away like in the first video, but the intersect need to be in the top of the curve, you can see examples in the images and videos I sent.
Oh god this is so complicated, but i finally found the solution.
Thanks @unique cave for your help bro!
I hope this information can help others like me
I understand what you are trying to do but I still don't understand why the solution you provided us wouldn't work (to me it looked like it should work. the barrel being lower than the sight shouldn't matter in this case). Btw why does the red dot seem to be above the horizon line? is the gun (and camera) angled downwards or is the horizon so close it's actually that much lower than the screen center? In a perfect world, the vanishing point should go through the center line of the screen if the camera is not tilted
it´s because the camera is not static, they can rotate up and down
wait, in this image the zeroing is clearly way too far while the wall is just few meters away. have yet tried to shoot somewhere having the zeroing exactly the same distance as the distance to the wall?
yes, like in this image, look that in second example of this image the player is aiming in the head but the bullet hit chest, if you read this website i think you will undestand better: https://defendersanddisciples.com/zeroing/#:~:text=A firearm zero is the,Impact at a given distance.
I do understand, that's exactly what happens and is supposed to happen. When you are 2 meters away from a wall and your gun is zeroed for 25 meters, you will undershoot, isn't that what happens in the game? Are you now trying to do the zeroing so that your bullet goes over the sight line and falls back at the zeroing point ("Far Intersect" point) as in the image you sent (like it goes in real life)?
yes exact, i need to calculate the point where the intersection will happen, the idea is that the bullet will drop after that, the lines will touch each other but the bullet cannot be above the sight line, like in the video, after that point the bullet will start drop
my mind exploded after that🤣
for example, if zeroing is 25 meters away the intersection need to be 25 meters after shoot
but you are not considering the bullet drop still right? in that case you don't need to worry about the parabolic fly path, and in fact, I don't think the bullet goes over the sight line even in real life when you zero your gun to 25 meters, the bullet will have so much upwards momentum and it gets to drop so little in that time it most certainly would look like this ⬇️
I thought transform position always one frame delayed no matter what unless there is a interpolation going on but there is no interpolation, just setting rigidbody positions. I am querying Physics Casts at rigidbody position as Predator suggested. However, Transform is somehow equals to next predicted position which is unexpected. So will this thing be problem?
It does creates problems in cast system. I need to test in order to understand this more.
transform positions and Rigidbody positions won't get synced until the physics simulation step
it's not as simple as "one frame delay"
interpolation and extrapolation will also move the Transform between physics updates to make mostion visually smooth
How do you fix this physics lag? I just want a raycastable trigger collider on a moving rigidbody.
In this example it is example it is attached via a fixed joint to the main vehicle (I tried with and without interpolation) rigidbody.
Behaves exactly as having no rigidbody sadly.
Whats the best way to handle this?
https://i.gyazo.com/8aabc0577775d9d6ba77295fa7e3dbbc.mp4
Is Physics Queries(or Casts you say) depends on Rigidbody Position or Transform Position? When i do cast at Rigidbody Position, cast getting wrong results. It seems Physics Queries using Transform Position in order to keep compatibility of old Sync(Physics.SyncTransforms()) system if i understand this behaviour correctly
Raycast to collider. Really simple, Collider is parented to moving rigid body, but it gets out of sync with fast movement. I don't want them getting out of sync without having to update the physics every frame if possible.
Uh those ripples mostly happens when you go far away from origin (in my tests start point around +3 or 5k) which is called Floating Point Precision but in your case it seems okey because the car is looking pretty awesome.
Are the colliders have rigidbody too? Parenting and syncing **dynamic **rigidbodies is not impossible but really hard. Oh fixed joint i should have been read carefully...
No, its the physics lagging behind rendering, as its done in a fixed time step, I'm trying to figure out how to selectively update a rigidbody or collider to be up-to-date every frame the proper way.
As an example, if I force update the rigid body by setting its position and rotation ONLY the position gets applied for some reason. I've tried .Move, .position and .rotation AND tried it with all freezing flags on & off.
And its still broken. I don't get it, why is it so inconsistent with its implementation?
https://i.gyazo.com/2376a820d55c603f4feecdf1c1cddd4b.mp4
Can anyone help me a my friend cant figure out why We can get out Project into Add?
like I have the Unity Project but when i click Add its not on my Computer
Im loosing Sleep over this... PLZ help!
I've finally done it
Updating every frame isn't the "proper way". As you surmised the physics scene is only updated during the physics simulation.
Move the Rigidbody itself or use Physics.SyncTransforms() to force a sync.
MovePosition is absolutely wrong as that doesn't get applied until the physics simulation step
So right now I move the rb via .position and .rotation, but the rotation does not seem to apply. if I use the parent's transform.rotation it stays consistent, but flips around an axis by 90 degress on some colliders for some reason.
What's the end-goal of this?
If you really want to go down this rabbit hole why not just set physics simulation mode to Update?
Make it a trigger collider
Because I do not have the performance budget for that. I'd preferable just update the interior interactables every frame, it would really help if I can figure out how to lock the rotation, because Unity is not helping with that at all. Very odd behavior, and duplicate methods of locking orientation all not working so far.
What is the goal here
What's the point of all this
I would try setting both of the transform and rigidbody position at the same time. This trick is preventing Auto Sync Transform call while keeping in sync.
As i read from some of the articles from Unity, in old system of physics , when a transform has changed, transform was broadcasting through every component in GameObject which was causing performance bottleneck. Now the newer system never do that but instead, none knows the transform has changed until some of them try to read. And some of their developers had said "You are not supposed to use transform while you had rigidbody but developers always did the opposite.". Ofc they said "This behaviour changes on every system since 2D and 3D uses different physics engine because they implemented differently." I hope you find a solution because i don't know how could you do, just helping.
Interacting with trigger colliders if they jitter like that is impossible at fast speeds as the raycast will just miss the collider.
I could use a dot product to check if you're looking near it, but that is just not nearly as intuitive with the different shapes of a car interior buttons.
I'll just have to figure out how to lock a rotation of a parented rigid body because all the options in the docs just don't work, only position lock works. :/
https://i.gyazo.com/8aabc0577775d9d6ba77295fa7e3dbbc.mp4
Ok so some kind of Raycast interactions
Honestly if you need that it might make more sense to use a separate physics scene for "inside" the car
Then nothing moves relative to the player and this isn't a problem at all
Hm, never heard of a sperate physics scene, could you elaborate? Is it just a separate scene loaded additively?
Does anyone know a way to move a rigidbody let's call this "A", according to another gameobject "B"? With or without a rigidbody, whichever works best. I've seen people mention joints but I can't seem to produce the effect I'm looking for - A moves by changing it's velocity according to input, and B moves by slerping it's initial position with it's destination.
I want A to still be able to control it's velocity and act as it would at any other time, but at a certain point I want it to add B's position/velocity to itself so that it moves with it.
did implementing exactly what you just said not work? Adding A.rbody.velocity to B?
if you then want that added/final velocity capped or interpolated over time you interpolate it in the Update function with the starting value as current velocity and target as sum of those A and B velocities. Then, in the 3rd parameter you mutliply by some custom InterSpeed value to get the desired effect. That's what I would do right off the top of my head
shouldn't it be the other way around, adding B velocity to A?
B is the "parent" in this case
right, whichever is supposed to follow receives the velocity sum and has it applied. This might be tricky to get reliaby working, but you can start somewhere with a very few lines of code!
yeah every variation I could think of has its issues
however I'm reconsidering the entire idea as I might not include this
sorry to waste your time but thank you for your responses <3
if all you'd like, is for the "child" object to mirror the "parents'" position with a delay you can actually do interpolation on Vectors directly, not worrying about where they end up after moving too quickly. You can then very easily set a fixed offset so they stay away from each other and so on. People solved issues similar to what you experience 100's if not 1000's of times and many post their solutions online. Worth looking at them, can always get inspired too!
I have looked online and only things I could find that are good for my specific implementations don't work / I haven't been able to get them to work
My implementation and execution are extremely specific, I wouldn't come here if I hadn't done everything I believed I could've tried
re-reading your initial question made me realize that what I just wrote above is most likely exactly what you want implemented, 2 objects keeping their relative postions the same but a "child" copies the movements of the "parent" with a configurable speed?
not really
I wanted the "child" to copy the "parent's" velocity yes, but I wanted the child to be able to apply it's own forces on top of that, not to mention that moving the "parent" could apply forces onto the "child" depending on how you set it up
but either way, I don't think I need this anymore, not because I can't get it to work right now, but because it doesn't fit my vision for my product
I see, seems a bit less straight-forward than I initially thought then, but still very much feasible. Perhaps some custom implementation of a Joint component. Whatever you decide, if you manage to get it running I'd love to see the end product!
Oh don't get me wrong, I'm sure if I worked it long enough, I could get it running. Thanks for the advice anyway ^^
ok so i hope that im putting this in the right chat but I wanna make a minigame where u balance a plate and the plate has rigidbody but i have no idea if i can do this without using the old input system and not letting it fall myself
That shouldn't depend on which input system you're using
I guess ur right
hey folks! i have a really newbie question i need some help on: im currently doing the "junior dev" learning track and i cannot for the life of me figure out why the player car is passing thru the obstacles and only barely just nudging them as it does
ive made sure to add a rigid body to all the objects and have played around with turning on and off interpolation, cycling thru the various collision detection methods, making the timestep smaller, varying mass and drag, and nothing seems to get the obstacles to behave as expected (ie: flying away like startled chickens)
in fact, at lower speeds the boxes just kinda slide gently over the player car model, so the issue isnt just at higher (but not wildly high) speeds
ive spent a lot of time trying to find people who have solved this, i assume, exceedingly common issue and i feel like im probably missing something obvious that everyone else has already figured out and just arent saying because its so obvious lol
I have rigidbody movement setup (I use addforce for movement and then add a counter force to make sure it doesn't speed up super fast or slide about) and for whatever reason stopping is super.. snappy? It's like when an object is near stopping it'll instantly stop moving
Like it'll be super smooth at stopping until the very last bit
I can record a video at some point just not now
I think I've figured it out. There's still friction between a frictionless object and an object with friction (player still had friction)
Yeah that was the issue. Player and all objects are now frictionless (the counter force makes up for no friction)
No matter what I do, I cant freeze the rotation of a rigidbody that is a child of another. this is so frustrating.
Well a Rigidbody either:
- Is dynamic in which case parent-child relationships won't do anything for it
- Is kinematic, in which case freezing rotation won't do anything because that only affects rotation caused by physics
What are you trying to accomplish?
I have a trigger collider (used for raycasting) that is a child of a rigid body, but when that rigid body moves to fast the trigger gets out sync.
The only solution I found is adding another rigid body to the child, and updating its position and rotation every frame.
But then other issues arise like rotation not being frozen (with both Constraints and rb.freezeRotation).
Kinematic doesn't work either, setting rotation manually to the parent.
Or the object is being locked to 180, -180 or 0 rotation with rotation frozen in constraints.
I've also tried setting the Center of Mass and Inertia Tensor Rotation to zero.
when that rigid body moves to fast the trigger gets out sync.
Elaborate on this? What do you mean by out of sync? Never heard of such a thing. How are you detecting it being "out of sync"?
Visualized via built in physics debugger.
I asked you to explain, but you never did. What is it?
Okay, so the interior of the car would be a seperate scene. Never seen this before, I'll take a look.
It still would be simpler if either of the rotation constraints would actually work.
yes the interior of the scene would be a separate scene exactly. Then there's no movement essentially and you don't have anything to worry about with raycasting
And about stopping rigidbody rotation if parented to another? Is there really no way in this entire game engine to do this?
For these reasons that concept doesn't make a lot of sense
Well you need to have a rigidbody on the collider otherwise it wont be up to date with the visuals. If I just have the collider with no rigidbody it behaves just fine obviously, appart from not updating as you'd expect.
Makes it even weird that setting the position works flawlessly.
Could anybody help me troubleshoot why this is happening?
the gameobjects have relative joints on them that are attached to that main 2x2 block
and sometimes they just get super weird like this
Without seeing the code? Who knows.
So i want to make theese hands flop around when moving, but the problem is that they just move with the parent, is there a way to do this?
The behavior in the video is way after this though, no?
You'd need to use a different physics implementation; that isn't a unity limitation but a physx library one.
Nothing else is going on though
I just set the rigidbody to dynamic
You'd have to show how things are set up. But basically you'd need a ragdoll setup and you'd need to actually move the parent with physics. Movign with the Move tool is not physical
i mean clearly something else is going on. How is the whole thing moving?
don't you have some script moving it?
Not here, no
it's just rolling around on its own?
Yeah
There's a script that applies torque to the wheels if you press a button, but I'm not pressing that button
Besides that it's just basic Unity physics
I can post the code in a minute when I'm back by my laptop
alr that makes sense
thanks
this is a script on the wheels
move is only set to true when you press a button on the screen
maybe you have move set to true in the inspector.
also you should not be using Time.fixedDeltaTime in your AddTorque
AddTorque(-speed) is all you should have
also that's going to speed up indefinitely
I wasn't the one who wrote it, but yeah
I'll check to make sure it's not set to true, but I'm pretty sure it's not
even if it was, though, it by itself hasn't caused problems
other vehicle configurations don't get all weird
well it will cause the thing to rotate/move on its own
the wheel is attached by a wheel joint
I should've said that, my bad
here's one that doesn't get super weird
it's not set to true in the inspector
hi, beginner here
anyone know how I can add upward force to a 2d ball if I were to click on it?
just a suddenly burst of momentum that's all
damn...
Clicking can be done using raycasts, the momentum with rigidbody.AddForce
Cool how would this look like in a script?
damn...
im gonna ask more but ik yall just gonna say just google it
which i did
and im not exactly clear on what to do after going through several results
oh well sucks to be a late adopter i guess
Look through the 2D physics examples GitHub that's pinned to this channel
I guess all i need is a simple jump mechanic so to speak
Hey so i have a couple of character joints, and is there a way to make a character joint try to stay up right no matter what?
like if the joint falls over i want it to go back up by itself
You could ask ChatGPT to write some simple code for you
Then verify what the output is with the Unity docs
Its fine to do this to get started with the engine
But best not to rely on ChatGPT all the way to the finish :)
hey it worked thanks!
wow the wonders of the future is finally here
incase anyone needs my code:
public float upwardForce = 5f;
private Rigidbody2D rb;
void Start()
{
// Get the Rigidbody2D component attached to the ball object
rb = GetComponent<Rigidbody2D>();
}
void OnMouseDown()
{
rb.AddForce(Vector2.up * upwardForce, ForceMode2D.Impulse);
}

@slow bolt If you don't know the answer to a question do not send people to chatGPT, etc. see #📖┃code-of-conduct
This applies physics methods outside of fixedUpdate . You should lookup tutorials, courses on Unity !Learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
@hazy furnace Yea, just noticed you were pinged instead of community conduct, link. Sorry about that. Warning will be removed.
haha
It happens when not updating position through physics methods or when doing this in Update instead of FixedUpdate
It's because you are not normalizing the vector
take all the inputs first, merge into a single vector, run Normalize() method on it, then apply to movement
make sure you are moving rigidbody and not transform as well
or using forces if you want reactive physics
no, this will ignore physics
if you want proper collisions you need to use Rigidbody.MovePosition() or AddForce etc. you can lookup code examples in the manual
Anyone have any thoughts on why my ECS physics looks like it is running in slow motion? Default gravity, reasonable / realistic mass and size, no drag.
Seems like I have to crank gravity up to -50m/s^2 for it to feel a bit more real. unexpected. I think this is caused by my cards not being appropriately scaled. But when I make them playing card size (2.5" x 3.5"), they start jittering all over the place. Do you need to change the settings to get Unity Physics for DOTS stable with small objects? Project Settings -> Physics -> * doesn't seem to have any impact.
Ah yeah if your objects are huge you're just seeing the "godzilla effect" in action
not sure about the jittering thing.
Hi, my player is a potato (an imported potato mesh is there) to which I've attached a character controller. My goal is to make it so that the upper portion of the potato would be free, if the player moves forward it leans back whilst the camera stays in position and the feet too. Is there a way to achieve this?
I think what I want here is an inertia kind of effect(?)
It's almost as if Unity Physics for DOTS can't handle small objects (e.g. playing card scale). Maybe there is a way to configure it, but so far I can only find the PhysicsStepAuthoring component. The Project Settings -> Physics doesn't seem to have any impact.
Seems like they aren't settling, instead rocking back and forth. And only starts happening once there is enough rigid bodies in play.
Is there a known way to deal with this effect? Saw some references to increasing gravity and messing with the time scale.
Those would be the ways. It's just a consequence of looking at large objects from a distance. The acceleration of gravity is the same but the distances are much larger, leading to things seeming "slow"
Ideally you'd use the correct scale but I understand you're having issues with that
There might be other settings to tweak in the physics settings
#1062393052863414313 might have some better answers too
Unity Physics for ECS seems to have very few exposed settings. It isn't clear where you might try to correct this behavior.
But ya. Since being able to publish the game to VR or AR headsets is required, getting correct scale to work is important.
If I use two directional friction type and character moves on static ground object then combining is on static and dynamic or other way?
Im testing it and static friction on moving character still makes it slower
hey, making a game in 2d but i have a issue where when my character moves while jumping the character falls much slower, how do i make the character fall at normal speed while jumping?
if (Input.GetKey(KeyCode.RightArrow) == true)
{
myrigidbody.velocity = Vector3.right * givenvalue;
}
if (Input.GetKey(KeyCode.LeftArrow) == true)
{
myrigidbody.velocity = Vector3.left * givenvalue;
}
if (Input.GetKeyDown(KeyCode.UpArrow) == true)
{
myrigidbody.velocity = Vector3.up * Upval;
}
myrigidbody.freezeRotation = true;
that is the code im using
i dont think you should be altering velocity directly, as it would replace the velocity from gravity
honestly idk how it doesnt cancel it completely
try using https://docs.unity3d.com/ScriptReference/Rigidbody.MovePosition.html
and also take a look at https://docs.unity3d.com/ScriptReference/Input.GetAxis.html to replace those IFs
Hi I know this may be a bit simple but I'm starting. I have a grappling hook on my char. It gets pulled towards the points. That's fine but I want to make some fake points that are loose and when the char grappling hook touch them the points gets attracted to the character. But honestly I still don't know how to do it without losing the main functionality. Any ideas? Thanks
How do i point a configure joint towards a position?
@arctic iron it depends. You want it with some input o any trigger?
just an input, so just point it towards a position, isnt that hat the target position is for?
Yes it says connector anchor. There you put it and should work it must have a collider or a rigidbody
@arctic iron
how do you show the center of gravity of a rigidbody? with a script 😉
transform.TransformPoint(RB.centerOfMass)
Then use Gizmos.DrawWireSphere or whatever to visualize it
i meant without a script
I watched a tutorial how to make a character not stick to walls and the dude sets the friction of the player to 0, which makes sense i guess, here i set the players AND the grounds (at least the vertical edge colliders) physics material to 0 friction yet i still stick to the walls, any suggestions?
use rigidbody.AddMovement() instead of transform.position
Isn’t it called MovePosition
You can't
Hi there, maybe stupid question, but I can't figure out what's happening 😄
I have an empty game object with lots of sprites as children that is my player character. I attached a rigidbody2d to the empty object that is the parent of all these sprites. now my player won't fall down and any velocity changes in the rigidbody have no effect on the player. i see the velocity change in the inspector, however it does nothing. do i have to put the rigidbody somewhere else or am i missing something?
- no advertisements in the help channels
- posting on multiple channels is not allowed
Hi it's foot ik and mocap animations not related to Physics and animations?
How are not related?
These channels are not intended for promoting games/dev logs.
Ok I got it now thanks for your response.
How would you prison a sphere rigidbody inside moving kinematic colliders?
- Why it goes off from the prison even there is no space?
- Setting the rigidbody position from the script achieves the same result.
Moving by transform effectively teleports the rigidbody. Move rigidbodies through rigidbody methods for better physics behaviour.
are there any other ways? my movement is currently based on giving the player a velocity, and jumping uses impluse
how to make sprite shadows in build in pipeline?
it's not the right channel. but use urp.
is there a way to do this in core
there is no built in way. you probably need to write your own system
yes i am stupid
I guess you can try this:
Vector3 mynewvelocity = myrigidbody.velocity;
if (Input.GetKey(KeyCode.RightArrow) == true)
{
mynewvelocity.x = givenvalue;
}
if (Input.GetKey(KeyCode.LeftArrow) == true)
{
mynewvelocity.x = -givenvalue;
}
if (Input.GetKeyDown(KeyCode.UpArrow) == true)
{
mynewvelocity.y = Upval;
}
myrigidbody.velocity = mynewvelocity;
myrigidbody.freezeRotation = true;```
This allows you to keep the velocity from gravity even while moving left or right
guys my mesh colliders are not working properly
box colliders do but mesh colliders dont
i use convex mesh colliders
what can cause the issue?
they do not collide
is this building on to the solution where i would use MovePosition or with my velocity & impulse based system
What are you expecting them to collide with?
anyone have a few to dis/confirm a 2D physics question?
Just ask your question. if someone knows, they'll answer
It seems that I cant connect multiple game objects, each with polygon collider 2Ds, Rigid Body 2Ds, and Fixed Joint 2Ds, and they hold together and move as on combined entity. they fly/push apart as forces act on them. Googling seems to suggest that you can only have one RigidBody 2D for the overall, combined entity. Is this correct? :/
What are you trying to accomplish
have 2 or more objects be able to combine into one.
Hello. Got a problem with my colliders or rigidbodys. You see that if the beak collides the bounce pad doesn't add the right force to the player. But the other parts of the body are working. What should I change?
Sure but how do you want that object to behave
imagine it's a raft and is floating. the raft is made of three sections. so it floats as one entity. but, if a (particularly hefty) bird were to land on the right-most section, that end of the raft should feel more weight and dip lower into the water causing the whole raft to lean. (dumb example but should help convey what im trying to do. balance based on weight across the overall entity made up of multiple objects.)
Sure but you don't need the objects to move independently
It should all be one Rigidbody then
I guess you can do that with hinge joints. That connects rigidbodys
What you described with the leaning would just be a natural consequence of the physics
You don't need any joints
hm. okay. ty
try setting the ground friction not the player
Basically once you attach an object to the main piece, delete its Rigidbody
but then i wont be able to have a system where i can still different frictions to the ground like ice could be 0.5 and grass 4 or wtv, now all have to be 0 so the player doesnt stick to walls...
also id have to then have the friction on the player, no? wouldnt that just cause the same problem
why dont u set certain fricition for each type of objects?
wdym?
thats is what i am doing, each type of floor will have a friction
make a pyhsics material for each object you want
but i have a problem where i stock to said floor if i collide on the side
maybe add a collider at the edge of it and set a custom friction to that
like 0 so u dont stick to it
i already tried that 🫠
thats how its currently set up
4 edge colliders, top 1 has friction, side ones have 0 friction, player has 0 friction
still stick to walls
not really sure
yea i dont understand either
my movement script that moves the character side ways set velocity of the object, thats how the player moves, but it doeant touch the y-axis speed
so like
totally no clue how to approach this
try using raycast to detect if ur player is on the surface and if it is then add more slidy force
so basically set the ice object friction to 0 and whenever the player is on top of it
use force
with yours
I see, could u please explain how the code works? It seems to save the y_axis velocity and just apply it after the x.axis velocoty is changed, but i already dont change the y-axis velocity when moving left or right
when you use something like myrigidbody.velocity = Vector3.right * givenvalue; you are effectively setting y to zero
since Vector3.right is the same as new Vector3(1, 0, 0)
here is how i do it
You don't need to check !right arrow in second if
it's "else if" so it will be checked if the first "if" didn't happen already
yea makes sense
I got some balls with an rigidbody and a collider2d, but when I got an fast spinning object and try to drop them on it, instead of them getting launched they just stay in the same place
can you show the rigidbody and collider of the balls in the inspector
And idea why my motion vectors seem to just be screen or world space positions? The closer to the origin, the smaller the motion vector. This is happen when the physics solver has pretty much stopped the cards from peceptively moving.
how can i have many objcects in scene like 2k balls, that have rigidbodies and movement script without lagging like hell? now on 500 balls it lags
Using DOTS would give you way more perf.
DOTS would definitely help but the question still remains whether it's enough though. I'd assume 2k is quite lot even for DOTS to handle at least on lower end devices. @gilded burrow more information about the game you are doing and what those 2k balls would represent/do in the game would help figure out whether there's even better solutions available than DOTS
In this video we push Unity Physics to its limit again with the new DOTS physics engine. Will it crash this time ?
Link to the Brackeys video : https://youtu.be/8zo5a_QvJtk
We will create a script that generate a tower of cubes, first with regular GameObjects and Rigidbodies then with ECS Entities and DOTS physics
This is the very first video...
Somewhat old video.
Some type of native GPU simulation would be faster. But you might be hard pressed to find better performance than DOTS without going to the GPU.
fair enough
caveat: afaik.
I have a question about when a rigidbody updates, If you have 2 scripts adding a force both in the normal fixed update does the rigidbody get updated after all scripts have been completed or after every script?
The physics simulation is a separate phase of the frame, after all FixedUpdates.
Ok so when using addforce? it wouldn’t update the velocity until all the other objects have used addforce
It doesn't update the velocity specifically until the actual physics simulation step
You can see the accumulated forces in GetAccumulatedForce()
Ok thanks
Hey, im encountering phantom drag when adding force to a configurable joint door and hingeJoint door when all drag of their rigidbodies is 0. The force is only applied once and no backward force is applied in code. anyone know where this comes from? I am currently offsetting it by repeatedly setting the velocity back every update. I am also encountering backward movement when my doors are hitting their limits while no collision options are enabled. i want the doors to stop when they hit their limit without encountering any drag on the way as a baseline.
friction?
Yes, phantom friction/drag
when i change time scale from project settings to low value like 0.3~ when i have many objects in scene, its not lagging anymore, do you think there would be a way if i look around it to make it work like this? otherwise im gonna learn what you said, DOTS
I meanit may be actual friction
the door touching the ground for example
or - does the joint itself have resistance?
It happend even when the door was floating and the joint has no spring/ dampening
is there any other property that could cause friction/drag?
I've got an object here that's a single plane, but is just set to render as translucent so it can pull off that fence look. As long as it's set to the right layer, are raycasts still blocked despite that render setting?
actually it looks like it's just passing through it which isn't ideal
raycasts have nothing to do with rendering
raycasts only interact with the collider
assuming you mean a Physics raycast
yeye, just wondered since it was passing through
but I see now that I put a collider on the base but not the fence :/
Sorry for late response
How are you spinning the "fast spinning" objects?
you should be using angularVelocity
If I want an object to approach another while respecting minimumTimeTaken to approach and otherwise attempting to reach a maxIdeal force, how would I modify the rigid2D to account for them?
Scenarios I can think of is when it's going too fast and I need to slow it down some to allow minimum time, when I'm good on time but not yet at max desired force and when i want to slow down smoothly to avoid a sudden stop.
Sounds like you want a PID controller tbh.
Thanks will look into that
Does the spinning objects also have rigidbody?
No only collider
Add them rigidbody too
Tryed adding a rb now, but frozen the x and y
Still just having them there
How do you rotate them?
public bool rotation = false;
void Update()
{
if (rotation)
transform.Rotate(Vector3.forward * rotationSpeed * Time.deltaTime);
else
transform.Rotate(Vector3.back * rotationSpeed * Time.deltaTime);
}
Pretty simple
You can try angular velocity as PraetorBlur said