#⚛️┃physics
1 messages · Page 13 of 1
do they not get destroyed as soon as they collide?
so what interaction are they supposed to have with players?
none
oh then yeah just use layer based collisions for that
k
i think eventually, i might want some other interactions, but i doubt it honestly
hopefully it should be an easy change later if i need to
You can even use https://docs.unity3d.com/ScriptReference/Rigidbody-excludeLayers.html to explicitly just exclude certain layers (the player layers) from the bullet prefab itself
do you know where im supposed to set that? it doesnt seem to be in the inspector
it's in the inspector for the Rigidbody if you're on Unity 2022+
oh im 2021
i think there were some other things that i need from 2022 anyway so i might just upgrade actually
ill make a backup tho
If I have an object that's the child of another object, when I set the velocity of the parent, the child moves the same way just by virtue of being its child, right? (just confirming before my actual question)
If, at runtime, I set the parent of an object, then change the velocity of that parent, it doesn't seem to apply to the child if the child isn't kinematic.
What concept is eluding me?
Oh, it's because it's a different rigidbody...
I need to use Fixed Joints
@timid dove the exclude layer and everything else is working flawlessly! thanks for all the help!
If they each have their own rigidbody, no
rigidbodies don't respect the Transform hierarchy when they are dynamic
Yeah, that's what I read. Works perfectly with the FixedJoint2D 😄
(and makes it stupidly simple)
I'm having a Hinge Joint 2D issue. The attached object keeps rotating. Here is my setup:
Tractor: Empty object.
- Body: Sprite Renderer, RigidBody 2D, Polygon Collider 2D, Hinge Joint 2D
- FrontLoader: Sprite Renderer, RigidBody 2D (target of the Hinge Joint 2D)
-- Main: Polygon Collider 2D
-- Lower: Polygon Collider 2D
I've read stuff about issues when the joint items have a parent/child relationship, but in this case they're siblings.
(as of now, the FrontLoader is rotating non-stop at maybe... 0.2hz, and there seems to be something wrong with the colliders of Main & Lower since they don't quite rotate)
I think my issue has to do with the not quite rotating colliders actually. I'll investigate that direction...
I tried merging FrontLoader and Main together, move Lower at the same level (so Body, FrontLoader and Lower are at the same level) and adding a rigid body to Lower too, but nothing seems to work. The colliders of FrontLoader and Lower still don't rotate at runtime even when their GameObject does.
images/video would be worth about a million words here
That kind of video, or one where I show all my inspector values?
are those colliders being created by a script or something?
Oh, and the only code I have that is supposed to affect anything relevant here is:
void FixedUpdate()
{
this.rigidBody.velocity = new Vector2((this.movementSpeedMultiplier * this.inputMovement).x, 0);
if (!Mathf.Approximately(this.inputMovement.y, 0))
{
this.hingeJoint.useMotor = true;
this.hingeJoint.motor = new JointMotor2D { motorSpeed = this.inputMovement.y * this.frontLoaderAngularSpeed, maxMotorTorque = 10000 };
}
else if (this.hingeJoint.useMotor)
{
this.hingeJoint.useMotor = false;
}
}
public override void HandleMove(InputAction.CallbackContext context)
{
var inputValue = context.ReadValue<Vector2>();
this.inputMovement = new Vector2(inputValue.x, inputValue.y);
}```
(I know I can optimise that not to set the motor each FixedUpdate, but I'm trying to get it to work before optimizing it.)
also can you show the inspector for the polygoncollider2d
The Body, FrontLoaderMain and FrontLoaderLower all look the same:
(but different points, and the FrontLoaderLower is on the "Ignore Crate Outer" layer while the others are on "Default")
(Btw, I updated to 2023.1.17f1 and it wasn't something that was addressed.)
From what I've read online, RigidBody2D objects don't handle being rotated well, but I don't understand how that could be since HingeJoint2Ds kind of need their RBs.
Found the issue. It had to do with the transform being rotated on the Y axis. (by 180, being the poor-man's flip)
But I found some other weird behavior with hinges, limits and motors: When a motor tries to rotate past the limit, or into another object but can't because of external constraint, it "saves" part of that "overshoot" as buffer and lags behind when trying to turn the other way.
Notice how when I go to the floor, in the inspector, the motor speed will stay at 45 for 5secs. That's me making it go down. It then goes to 0. When I try to make it go up, the Motor Speed goes to -45 for a few seconds (not the full 5secs) before the front loader is actually raised.
The same thing happens on the other side when the limit is hit. (the down part wasn't the limit being hit, it's the floor being in the way)
Can someone explains the difference between Include Layers and Exclude Layers in colliders? If I exclude nothing, of what use is Include?
Layers can also be excluded via the physics settings layer matrix
I understood thanks to the C# documentation of these fields
includeLayers and excludeLayers are additional layers to take into account
so the settings layer matrix is authoritative, and then comes the overrides from includeLayers/excludeLayers
I wish they would have named that additional include layers or something like that
alright so I have this tank, in which the wheels are a different mesh than the body, and I have an armature and I’d like to be able to use wheel colliders, how would I manage to have the wheel mesh’s like bind to the colliders
WheelCollider has this: https://docs.unity3d.com/ScriptReference/WheelCollider.GetWorldPose.html which you use to pose the visuals
Does tank steering work with wheels? Or is it a pain?
What are some good tutorials for active ragdoll?
I've been moving a dynamic RigidBody2D using velocity, and as it squeezes some other dynamic RBs, it squishes them against some static RB and they start behaving weirdly. I would prefer if my main RB would stop to prevent that at some point.
What design problem do I have leading to that?
Should I be checking properties like totalForce and restrict the velocity based on that?
Is there a known way of approaching that problematic?
Should I flip it all on its head and use forces rather than velocities?
You will always have some odd physical interactions if you overwrite rigidbody velocity
Applied forces give you correct physics, but not the kind of nonrealistic movement that we often expect from game characters
You could potentially find a middle ground between them by applying forces based on what the velocity is, to limit maximum speed but to also decrease inertia at times it feels appropriate to do so
That's what I was thinking if looking into. Check the delta v based on current speed vs target, then multiplying that's by the weight. Possibly a maximum speed increment per delta time if I want acceleration, but I'm not sure I'd need it.
(Thanks for confirming this!)
||| RaycastHit hit; if (Physics.Raycast(unitPivot.transform.position, unitPivot.transform.TransformDirection(Vector3.back), out hit, Mathf.Infinity, groundLevel)) { Debug.DrawRay(unitPivot.transform.position, unitPivot.transform.TransformDirection(Vector3.back)); Debug.DrawRay(unitPivot.transform.position, hit.point, Color.blue); Debug.Log(hit.transform.name); ||| I have a very detailed earth moderl(32k vert) and im trying to make a infintry unit which will find out if its on land or sea using physics.raycasthit to get position etc, I have an issue tho, the raycast(white line) is directed to the earth correctly, but somehow im hitting a point somewhere away from it(blue one, from pivot to hit point) and the console is also saying that im hitting the earth, i tried with and without rigidbody. 2nd try, looks like i get the same resoult for a regular unity sphere??
I made the change, and the problem is still there, but maybe slightly less?
(so now I never change the velocity or the positions of anything directly)
Respected,
i have applied force on a gameObject with rigidbody.
But when I applied force in z-axis then automatically force applied on x-axis even there are no force can seen on x-axis in rigidbody component and even still force applied when I freeze the position x..
can someone please guide me how can i resolve the issue.
Thanks
you'd have to show the code
but forces will be applied in whatever direction you apply them in
Vector.forward + Vector.down
with add torque for rotation
what makes you think a force is being applied on the x axis? Show your code and show the result
Hi, I have minor problem.
I have ragdoll, I don't want it to move till I press "Play". But it has like 50 different child objects, so I didn't think it'd be smart to disable its gravity and programmatically go through it and enable Gravity in the rigidbodies once Play is hit... please suggest what else I can do
I also cannot set Time.Timescale to 0, because I rely on the OnCollisionEnter()
Gravity isn't the thing you need to disable. The rigidbodies should be kinematic and changed to non kinematic
And just do it in the code, see if it's a problem first before you discount it
Looping over 50 elements is probably not a problem
it wouldn't be a problem, it would work
i just didn't think it'd be of best practice
Why not?
because i thought there'd be some other better practice solution
Not really
guys,is there any form for fix this so that they are not so that when the objects collide with the player they go far away as if they hit at high speed? (which shouldn't happen because the player moves slowly)
more gmod style
here are the settings of the player
Does the character controller have anything to do with it?
this case is a minority but it has happened to me that they were shot further away
Lmao
Looks like you're probably doing something wrong with your CC like calling Move twice in a frame
My rigidbody player keeps moving upwards when its pushing into another physics sphere, how do i stop this?
converted to mp4 for easy viewing
the movement looks pretty janky in general. Hard to say without seeing your code.
would you like me to post a portion of the code?
Ideally the full movement script
[SerializeField] private Rigidbody PlayerPhysics;
[Space]
[SerializeField] private float WalkSpeed;
private void Update()
{
PlayerMovementInput = Vector3.Normalize(new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")));
UpdatePlayerMovement();
}
private void UpdatePlayerMovement()
{
Vector3 MoveVector = transform.TransformDirection(PlayerMovementInput) * WalkSpeed;
PlayerPhysics.velocity = new Vector3(MoveVector.x, PlayerPhysics.velocity.y, MoveVector.z);
}
You should turn interpolation on too to make it smoother
What happens when you just use a Capsule collider instead of your custom mesh collider?
no difference
the ball is rolling
then friction with that rolling ball is pushing your character upwards
this is a just a natural interaction with the ball
it won't happen with a cube for example
or any other object that doesn't roll
hmm, is there a way to customize friction specifically for the ball and the player? I'd like it to still have friction but not push the player upwards
Thanks, ill look into it
After creating a physics material with 0 friction applied for both objects the player isn't pulled up the ball anymore! 😁
how does unity/PhysX solve the problem of order of execution not being garanteed?
cuz i am writing and studying to make something similar from scratch, but the only way that I would know how to solve in in OOP ( instead of having all data in an array that makes it easier ) is to have each object have an array of " contacts " and iterate through them to see if changes were made.
Unity doesn't solve that problem, it gives the tools to work around it if needed
Physx solves that problem by processing everything in phases such that order doesn't matter
yeah, I see both objects merging into eachother and a simple cube taking 1 millisecond kf processing, so I DO belive you that they do NOT solve it 😂
Got an issue with hinge joint
I got a robot simulated in this game and its gimbal was under the control of a PID controller. The problem is that the gimbal seems hard to stabilize when the chassis follows it. It looks well when the chassis is spinning in a specific direction. I guess the problem is that the chassis was moving the gimbal when rotated itself but I don't know how to confirm this and fix it.
Anyone got some idea about this kind of issue?
Respected, I want to achieve this type of movement.
1- The rotate around rotation you see in the attached video is achieved by animation or code, and how?
2- I want the turning effect which you can at the end of the video, where force applied in the direction of face and then rotate until the gameobject will not straight.
Please guide.
thank you
ok so this has probably been asked a unitrillion times
but how would i get the player to stick to a slope and not jump over when going to the top alongside not sliding down unless crouched
i also cant jump when on one (i forgot to apply the ground layer, whoops!)
im currently using a rigidbody.velocity setup for movement, i could send the code if needed
If you use physics, then it is obvious that your player is going to slide unless there is infinite amount of friction. You can player with it by using physics material (https://docs.unity3d.com/Manual/class-PhysicMaterial.html)
That being said, having infinite friction is probably going to prevent you to move with velocity. In your situation, you would probably be better off by deactivating the gravity and applying it yourself whenever you want it in the FixedUpdate.
how could i detect im on a slope
(i dont want to use a specific layer or tag for any slope
Im making a car game and im using the wheel collider component i have the script and when i test it the wheels and the wheel colliders go through the floor but when i press wasd they move and turn and the brakes work i just don't know why the car isn't moving and why the wheels are in the floor
If I have the following 4 RigidBody2D, all with colliders, I have some weird interaction.
Crane: Dynamic. Forces are always applies to this one.
BoxA & BoxB: Dynamic. When held by the crane, they are held using a FixedJoint2D created at that moment.
Floor: Static.
The scenarios:
Crane -> BoxA -> Floor: Everything looks good.
Crane (Holding) BoxA -> Floor: Crane can goes slightly through BoxA, but bounces out.
Crane (Holding) BoxA -> BoxB -> Floor: Crane can goes a lot through BoxA, and never bounces out.
Crane -> BoxA -> BoxB -> Floor: Weird physics happen.
Anyone has ideas on how to resolve this?
Are there any performance or precision impacts when using Position Constraint vs programmatically setting the position such as transform.localPosition = new Vector3()? I want this gameobject to transform predictable and accurately, while not sacrificing performance or collision precision
You are not going to get proper collision behavior with a PositionConstraint
Not with setting Transform position
That can only be done via the Rigidbody
I kind of cheat by using Transform on a kinematic rigidbody, Im guessing PositionConstraint is for animation purposes. Thanks tho
You use raycast/spherecast (down) and check the normal of the surface.
currently working on the controller and physics for my "hover car f-zero type controller", my main problem is moving on things like this ramp, instead of smooth movement like moving on the normal floor it kinda goes up like on stairs. Anyone got an idea how i could fix that or maybe a better way of doing it than im doing it right now? thanks
btw im not using gravity on my rigidbody right now
Are you using a box collider or sphere/capsule collider?
my "car" is currently a cube with a box collider
currently having some trouble with slope sliding, i start the slide on the slope, it takes a sec and boosts me forward and not down+forward, i understand the issue just not sure how to fix it
https://pastebin.com/TxnNCKL1
lmk if u need the whole slide script
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
theres also a thing where when you slide backwards up a slope it curves it upward and forward lol
Hmm, you should try swapping out the box collider with a capsule/sphere collider there. When I started my project I used a box collider and it kept getting caught on slopes, has something to do with the curved surface of the other collider shapes that helps me move up and down slopes
my car is actaully hovering over the ground so the ground doesnt interact with the collider
I'm trying to use Physics.IgnoreCollision on the same frame that my RigidBody is hitting an object so that it can pierce through it. However, this seems to still make the Rigidbody slide off of the hit collider for one frame, causing the attack pattern to look janky, as seen in the video (see how it leaves the enemies while they're still alive).
Is there any way to prevent the Rigidbody from sliding before calling IgnoreCollision? Note that I can't use triggers and I still need to have the first frame collision detection.
ok ive gotten to this, but how would i change the gravity for the player and only the player
rigidbody3ds only have a use gravity variable, which creates more problems than solves
This is from my personal experience, but for stuff that travels on a surface, you should use a collider instead of a raycast. You should make a capsule/sphere collider that can only collide with the surface its on, and offset it so its below your car, which should give it the illusion that the car is floating whilst hopefulling fixing your issue
You create a script that apply the gravity.
public void FixedUpdate()
{
if(NotCrouch() || ...)
{
rigidbody.velocity += Physics.gravity.y * Time.deltaTime;
}
}
ok its definitely starting to get somewhere
Im making a car game and im using the wheel collider component i have the script and when i test it the wheels and the wheel colliders go through the floor but when i press wasd they move and turn and the brakes work i just don't know why the car isn't moving and why the wheels are in the floor
can someone help please
Following up my previous post, the same sort of problem seems to be happening to my bullet bouncing script, where Physics.ComputePenetration isn't always able to run properly due to the Rigidbody pushing it out before it can be calculated.
Both of these worked before when I used a trigger system, but now both of them don't work.
If anyone has any ideas on how to deal with this, I'd be glad to hear them!
OnCollisionEnter is too late to call IgnoreCollision
the collision already happened
yh thats my problem but idk what else to do
if you want the bullets to go through why not just ignore collisions between the bullet layer and the wall layer in the first place
it's unclear what you're trying to do
the first one is piercing, the second is bouncing
well which one do you need help with
both bc theyre the same issue
I don't really understand
Can you explain what behavior you're trying to accomplish exactly?
im trying to make the first vid pierce and the second one bounce, but im calling a collision function after the fact
and obv thats nopt working but idk how else to do it since i need the collision to happen but it cant be trigger for piercing
im trying to make the first vid pierce and the second one bounce
I have no idea what this means
i posted two videos
Can you jsut explain in english how you want the game to work?
Yes I saw the videos
they don't tell me what you're trying to achieve
for the first part, i want the bullets to go through the entity without being affected by collision but still send callback for the hit so they can take damage
the enemy in red
So you want the bullets to go through enemies and bounce off of walls?
but it will work the other way around for when they hit each other
the first part is piercing
so thats all im saying in that explanation
bouncing can wait for a sec
Is this what you want?
all i want for rn
is to ignore bouncing
just looking at the attack going through entities
You can try to use OnTriggerEnter for that but SphereCast will be more reliable (each physics frame, looking forward at where the projectile will go this frame)
that wont be very reliable for fast projectiles tho is my problem
and trigger wasnt working when you last helped me out with that wall collision problem
ig maybe something like script orders might do something
but that would break a lot
actually it seems like you cant even change that for rbs
SphereCast is reliable
oh wait do you mean like set it at the exact spot it'll be at?
set what at the exact spot that what will be at?
the sphere cast at the spot the bullet will be at
spherecast from the bullet's current position to the position it will be at the end of this upcoming physics simulation step
i.e.
Vector3 start = rb.position;
Vector3 projectedMotion = rb.velocity * Time.fixedDeltaTime;
if (Physics.SphereCast(start, radius, projectedMotion, out RaycastHit hit, projectedMotion.magnitude, someLayerMask)) {
// handle hit
}```
oh i think i misunderstood what spherecast was
i thought it was like a boxcast, but this is just moving one along a ray
ill try this out then
it's exactly like boxcast
just sphere shaped instead of box shaped
maybe you misunderstand what boxcast is
sorry i mean physics2d.boxcast
i guess they are different things then
im not used to 3d
they all take a shape and move it along a straight line in the scene
and then report any hits
This is true of any of the XXXCast functions
in 2d and 3d
idk lol im just gonna try to figure out how to implement this
in 2D you can get away with using 0 as the distance and use it as a janky OverlapBox
but you should really just use OverlapBox for that
I think I just got the piercing to work
it doesn't seem to get stuck anymore
I'll see if I can't do the same sort of thing for bouncing
If anyone has any ideas on how to fix this I'd be glad to hear them because I just can't figure it out
How can I find the joints connected TO a rigidbody? (As opposed to ones that are on the gameobject)
Alternatively, how do I detect when the connected body is destroyed?
Afaik, there isn't something built in for that. You can create an interface for any bodies that you want to allow being jointed and an extension method to do the magic. The same pattern could also be in charge of communicating the destructions.
Thanks!
I actually have the same situation. I haven't done the implementation yet though, but it's on my backburner 🙂
im making a game where two players send enemies down a lane and eventually cross paths, trying to figure out the aggro system and i was thinking of using OnTriggerEnter with colliders, how do i properly set up the units to work like that, do they need two colliders, one which is trigger and one that isnt, and then a rigidbody? or is one collider enough?
so generally speaking, don't be afraid of using multiple colliders. the player character in my current project has 7 different colliders and still uses raycasts, overlaps boxes etc.
Got a strange issue, I have a wheel controller constantly checking if it is colliding with the ground. I got a ground counter got reset in OnCollisionStay() and count down in the FixedUpdate()
But in the game, when the wheels stabilized, the OnCollisionStay() seems not conducting anymore without trigger the OnCollisionExit()
This is pretty strange
The right part in Inspector you can see that the counter fall to 0 when the wheels stay.
But the Exit Log didn't showed up which means the OnCollisionExit() hasn't been performed
I have to push the wheels to the ground to reactive my wheels
Can anyone tells me why this will happen?
your Rigidbody is probably falling asleep
Check the "never sleep" checkbox on your car's rigidbody
Hello how can i calculate the stopping point of a rigid body when an impulse force is applied to it
assuming no drag and no friction, there will be no stopping point
it will continue forever until some other force stops it
Yeah true but i have angular and linear drag and mass and the force will be applied do you have any idea calculate it
I think you'd be better off implementing your own drag and then you will be able to calculate it perfectly
Unity's drag formula is not known (though some people have reversed engineered it)
i used a tool last year that broke meshes apart like an explosion and would bake them into an animation. anyone know what tool that could have been?
When you are using ontriggerenter do you have to attach the script to the gameObject that will cause the trigger or can attach the ontriggerenter script to empty and then reference the gameObject the will be set as the collision object?
nvm it was rayfire
The event only propagates on the same GO that the collider or rigidbody is attached to.
Thanks
Respected, I am using line rendering of two points between two gameobjects. The staring point is stationary and ending point is continuing moving in any direction.
But the problem is if object is near to the camera then line renderer seen thick, if goes away it looks like ------
I try with different values but didn't achieved the right result.
My line rendering is the thin wire...
and the material i using on it standard->opaque. I have also tried unlit material.
Please guide.
Thank you
Just sounds like standard perspective effects. Further away objects look small
not sure what this has to do with physics or what you're trying to achieve
problem came here when i set the larger width then it see much thicker, and if i go away then it looks like -----
is there any way set the width according to the distance
When I build my project(2022.3.11f1) some cloth renderers seem to be vanishing while others are working. Not really sure what the best way to debug would be, whether it is the simulation or the rendering going wrong.
aha, apparently cloth needs the mesh to be read/write enabled in build but not in editor... weird.
to expaind on my previous critique of unity's physics as I build my own
one of the issues I encountered is "where" to insert cast queries we call from script while a simulation is run, or even pre-processed to get the result of several deconds in a single frame.
if you call the raycast during update clearly there is no time to check multiple fixedupdates.
But even if you call it within fixed update, YOU ARE NOT GUARANTEED that the raycast will be shot after the target object has moved 🥺
you'd need to call it in a Afterfixedupdate, but that doesn't exist.
It exists
after yield return new WaitForFixedUpdate (); in a coroutine runs after the simulation step
Not ideal but it's there if you really need it
thanks 👍 i'll double check, cuz last time I tried using it I remember it not working or not solving the problem i encountered
Hey everyone. Say I have a pair of scissors that are partly open. Where the blades connect is the parent joint, and each blade has a bone and a box collider. If I move the scissors to the edge of a desk for example, I'd like the scissors to open based on the box collider of the tables edge, then close to the default scissor opening when I pull it back. I know I need to use a hinge joint, but I don't understand how to set that up. Do I apply a two hinge joints to the parent joint and the connected body is each blade, or a hinge joint to each blade back to the parent? Any thoughts would be greatly appreciated!
Need some help here. My character here interacts with slopes in a suboptimal way. When coming off of an up-slope, the momentum carries them off the ground briefly, which forces them into their falling animation. The same thing happens when they come onto a down-slope. How can I make the character hug the terrain so that this doesn't happen?
I'm sure there's a simple solution here that I'm just not seeing. I've never seen or played a platformer that has this issue.
cast a ray to the ground (or overlap_sphere)
if distance of said ray is smaller than the amount (meaning the character is allegedly walking down a slope, instead of falling)
- add a downward force
or - directly change position
I always went with option 1 with rigidbody characters moved with addforce, and opton 2 with kinematic ones, that goes without saying, you ARE ALREADY moving after several ray queries anyway
Does anyone know of a way to make different objects get update at different physic frequencies?
You can " almost " mange to do that by forcing interpolation and change static colliders by script, but it doesn't feel intented and more of a hack
Here's my problem and the thing i do not understand.
I got an elevator with the following parts ( see screenshot )
Platform - Empty object, with a Scale of 1.0, which is moved by the elevator script
Platform.Physical - the visible mesh and the ground collider
Platform.Attach - trigger-collider that makes the player a child of itself.
The player is a Unity.CharacterController moved in Update
The elevator script moves the Platform in Update
I got debug lines showing, that the player character while being a child of Platform.Attached is moved by the exact amount that the whole platform is moved.
This works flawlessly while moving upwards, but moving downwards, the player OnTriggerExits the attach-collider.
The player is a CHILD of the collider and has ZERO movement in local space relative to the collider, they are both moved by the parent of the collider. Yet the OnTriggerExit happens.
Update:
The coordinates after moving both objects in Update logged and then in the next physics tick logged:
a) same coordinates -> TriggerStay
b) same coordinates -> Trigger Exit
what the magic?^^
kinda outta the blue, but if you were to have a tank with the road wheels as wheel bodies can you have a piece of code auto draw track lengths between them so you have dynamic tracks and suspension?
Is there a way to make a projectile be shot directly at a certain position, as in it despawns once it reaches tge position
With your imagination and some code, anything is possible!
Well can u teach me how to get to my goal
lmao
Hey everyone. I come here after a few day of research and a lot of trial and error, but I just can't figure out a solution to my problem.
I'm working on a script that launches a projectile to any given target position with a parabolic trajectory.
And I used this article https://en.wikipedia.org/wiki/Projectile_motion to figure out the formulas for calculating things like velocity, the time it takes to reach the target, angle, etc.
The problem I'm having is the fact that my projectile always gets launched from the (0,0) position. What I would like is to be able to launch it from any given position.
I was looking at the formula for the angle which I believe is the cause to my problem. It even says on the wikipedia page that the formula they show is for "when fired from (0,0)". I just can't find a way to make it so that it works no matter the position my projectile is fired from. I'm really new to this so I would really appreciate some help. 🥲
All you need to is target - origin to get the relative position of the target from the start point
Then proceed with the math as normal using the relative target
I tried that but it doesn't work.
you must have done something wrong then
Would you be interested in taking a look at the code?
Have you read this page yet? https://docs.unity3d.com/Manual/class-Cloth.html
no i dont like looking for stuff to read honestly
Id rather just someone tell me what i was confused about
Any ideas why this is happening? The player has two circlecollider2d for the wheels. The ground is a tilemap with a compositecollider2d. I used custom physics shapes to make the grass flat. i don't see any imperfections, but i am consistently getting this behavior where i get stuck or i am launched into the air for no reason. i cannot visibly see any imperfections. collision is set to continuous on the player and the tilemap/ground.
movement is pretty simple; i use addforce for forward movement and braking. for the wheelie i use addtorque.
I would suggest using two box colliders, one for the ground and one for the ramp itself.
Just remove the tilemap colliders altogether? I can try that. so create a composite using boxes instead of a tilemapcollider2d?
Yes, you can try that.
this didn't seem to make much of a difference. i got stuck on the ground less, but still experience wacky physics. here is a few clips to demonstrate. launching into the air when hitting a collider that isn't totally flat. sudden acceleration (not from my input) when landing if i do manage to go over the ramp smoothly.
and the collders for reference
is it possible to cause this by my adding force and torque to the rigidbody2d of the player? i am starting to think this must be the reason. i also alter the center of mass using my script as well.
It shouldn't be, I guess, unless it's done in the update loop.
i use these vectors to change the center of mass based on the state. the intent was to get the player to behave a certain way that looks good, but it could be messing things up
it is done during update
oh jeez i forgot about fixedupdate
i guess i am rusty 🤦♂️
ok, so i just moved all the physics to fixedupdate AND stopped changing the center of mass. i will find another way to get the movement i want. the issues seem to be gone entirely.
Here's the result. Thanks for the help!
Looks great, good luck in development.
Why does the child rigidbody shifts a little? Imagine player plays too many hours, it obviously wont be here after he came back to this cube.
Fraction, mass, drag does not matter, i also tried those. The same behaviour still happens. I need to make that respond correctly. The only thing works is by setting the Rigidbody to Kinematic which is same as not having a physics object lmao. I have no idea what is the cause and how will it get fixed.
dynamic Rigidbodies are not expected to follow along with their parent Transforms
they follow the physics simulation
I know. I am trying to implement Floating Origin system and this is needed due to collisions, movement and so more. Unreal does that thing very well and i see its achievable somehow. But i need to know why is it happening here? What is the main cause? Yes it is physics simulation but what is the root cause of that small shift even i move harder it just shifts verrrry little not dependent on the velocity or something.
We could say its because FixedUpdate things. But its not. Changing TimeStep would not help in this case.
well first off you should be testing with moving things via code not the move tool in the editor
Already did that sir just didnt sent because it was in another project
second you should move all dynamic Rigidbodies manually by setting rb.position on them
Rigidbody.position will break the Floating Origin system sir. First thing, the Rigidbodies wont work. They will act like they are not a child of Floating Origin world. I know the physics dont have a Child-Parent behaviour but i believe it should follow the transform of parent correctly if i dont set the rb.position which is wrong in my case by small shifts.
how will it break the floating origin system?
Are you trying to do this by making everything a child of one mega parent object and moving that?
As i said, rigidbodies wont work
That's not the right approach
It is the right approach.
it's the right approach for the static elements in your level
not for dynamic/movable bodies
Most of the people just assuming that moving one parent is wrong. If i dont do this, the code will break the performance and the game wont be a game
foreach (Transform t in worldRoots) {
t.position += worldShift;
}
foreach (Rigidbody rb in dynamicBodies) {
rb.position += worldShift;
}```
Yes that is the inefficient approach
how so
how many dynamic Rigidbodies do you actually have?
this is the same as your approach, just separating the dynamic bodies out
If i using floating origin technique, means that the world will be really big. Which means there will be so many rigidbodies if the game subject supports that
Imagine you do a foreach over thousand rigidbodies.
I dont even tell the particles, other systems.
Open world games only work by dynamically loading and unloading objects that are close/far from the player
You won't be able to do a thousand Rigidbodies open world or not
my box colliders edit wont show unless zoomed out, so any help?
also you can use the job system to do this much faster anyway
https://docs.unity3d.com/ScriptReference/Jobs.IJobParallelForTransform.html to move a lot of objects fast
Believe it or not, moving a parent is the best way for this approach. Whatever, why are we arguing FO methods, i need to know the cause to fix it.
The cause is that dynamic bodies don't follow the Transform hierarchy
I don't know that there's a fix for that. Maybe make them kinematic, then move, then unkinematic
either way you're going to have to do special handling for all the dynamic bodies
I fixed it guys just press F to focus on it and then itll show 😄
i have a rigidbody and it is fence model, now i want to make this fence bend abit as car crashes into it, how can i implement this feature?
Hi, I'm creating something similar like this, where the object rotates based on the tilt of the users device. I was wondering if your game also happens to work like this and if you could give me some insight on how to make this work smoothly, as from the video your rotation is pretty smooth while mine just goes crazy 😅
Depends on how your fence looks like.
If it's made of metal planes, like one in the real life.
You can create a mesh and offset it's vertices positions on impact.
Probably, using a compute shader.
Can't tell more, as I'm not a graphics programmer.
I know this sounds counter-intuitive but is there a way to decrease collision accuracy for specific objects?
If its relevant in 2D
I've setup a system that allows for purely cosmetic rigidbodies to be attached to an object but they tend to get hooked on objects
I want to decrease their collision accuracy so they can still collide with terrain but wont get hooked on it
I tried things like disabling collision depending on if it can see the thing its attached to but it just didn't feel natural enough
As you can see its not exactly the best looking thing
Just use a simpler collider
Maybe even a box collider or circle collider
I am right now using a circle collider
Its just a bunch of chained rigidbodies connected by a LineRenderer
I guess I don't really understand what I'm looking at in that image
Flexic Engine: Softbody Physics for Unity Engine
Step behind the scenes with SIDGIN as we reveal the heart of our innovation – Flexic Engine.
🕹️💡 Watch as we showcase our optimized SoftBody physics engine, meticulously crafted to perfection. Flexic Engine isn't just an engine; it's the result of our commitment to pushing the boundaries of what's possible in Unity development. This sneak peek ...
This isn't for sale, just a demonstration of what's possible on Unity.
Sorry it isn't very clear as the line renderer is a layer above. The line renderer's positions are adjusted to 4 connected rigidbodies
Those connected rigidbodies are using circle colliders
However sometimes it's possible to hook them on stuff
Sounds like there's gaps between the circles. The answer is the same. Change the colliders
Maybe use capsules without gaps between
Why does the gizmos appear in here, but the rotation is centered somewhere else?
When I rotate using the gizmos it is centered around the gizmos but when I rotate using the values in the inspector it's centered somewhere else
Change pivoting
Switch from Center to Pivot for tool handle position (hotkey is Z)
does anyone know what margin of error I should expect in terms of non-determinism in the engine. Like will it be around 1% or 10% etc? Specifically for velocity updates, not collisions
Physx is deterministic on the same hardware given the same inputs
Not sure what you mean exactly by velocity updates
like if you have two diferent hardwares both running rb.velocity = 5 * Vector3.forward
what would you expect their differences to be in delta position
I just posted this on reddit maybe you could give me an opinion: Hey, I'm trying to come up with some ways to do my server authoritative stuff for my multiplayer game (I'm using Unity PhysX). I've thought of this approach I was wondering what you all thought:
I'll have each player be using a client network transform, so they will have full control over their positions and their input will feel responsive.
In the background, they send their input to the server. Thankfully my movement is pretty simple, so I can just have the server check if the player's movement falls within an acceptable range of error (that could be caused from non deterministic physics calculations), and as long as it does they are good to go. The check is done on a per tick basis so compounds in differences over time are irrelevant.
Zero in this particular case
really? Im pretty sure that there is still some difference becasue the last time I implemented this there was still error
There will only be a difference in cases where a difference in precision of the operation will make a difference
5 * 1 is going to be exactly 5 everywhere
Right, that was my thought too, but then I posted my issue to here and a bunch of people said that even setting rb.velocity is not deterministic
apparantely the calculation is not just multiplication
That being said the amount it actually moves each FixedUpdate might be different if your DeltaTime is the default which is 0.02 which isn't actually representable in binary
It'll end up being done at different precision on different hardware and you'll move slightly more or less
But this difference will be very tiny
Hmm, would that be the same if I was running it on a custom tick rate ?
oh is that why people use tick rates of 64 and 128 cause it is perfectly representable in binary?
Yes
But that still doesn't guarantee determinism because those numbers will interact with other calculations in the game
ok for some reason, last time I tried to implement client prediction there was an error of like 1% in position
Why not just a traditional setup of server physics with client Side prediction?
cause last time I tried I got that result
but I guess I can try again
the issue is that the non determinism causes me the need to reconcile, correct? Now if what you say is true and if I do everything properly I will only have percent errors in the 0.0001%, reconciling is no big deal obv, but if percent error is larger than reconcilliation becomes much more noticeable and is unacceptable
I'm going to go test this! Thanks for your help and ill lyk the reuslt
Much bigger issues will come from when that difference is the difference between a collision or a miss, or when something happens on the server that the client doesn't know about, like a new object spawning or a player changing directions etc
This will always cause a jarring reconciliation
even at 0.0001% levels of error?
in that case isn't my solution better?
maintaing client authority means no reconcilliation, whilst having the background process ensures no cheating
Every client can't have authority on every object
There will be reconciliation for non local objects still
yeah I just meant for their own players, non local objects i'm not too worried about
I'm trying to make a simple minigolf game using Kenny.nl assets. I've created a few test courses to test out the physics of a rolling/bouncing golf ball, but I'm having issues with the ball not rolling smoothly over the joints in the mesh collider. I've found a similar issue here: https://forum.unity.com/threads/ball-rolling-on-mesh-hits-edges.772760/ but one of the linked solutions on github is a dead link. I've tried modifying the mesh in Blender to join the objects together, I have weld vertices checked on the import of the models. I've tried seemingly every combination of interpolate and collision detection on the rigidbody, but nothing seems to have any effect. if the rigidbody ball is rolling sufficiently fast over an edge in the mesh, it will seemingly just bump up over it. if there is something built in to unity to fix this that'd be great, otherwise a link to the code in the dead link to Github about how to modify narrow phase contacts. this is just a frustrating thing that seems like it should be simple to figure out, but I'm struggling.
Hey, When I join to rigid bodies with configurable joint, they stop colliding and even fall into each other. How is that?
Ouh there is a checkbox 😄
Mine is for PC only, so keyboard controls. I'm using AddTorque on the rigidbody2d component. I'm just adding positive and negative torque values to stabilize/control the rotation.
Ah okay, thanks. Yeah I tried that as well, but it’s hard to get a smooth feeling for now.
Yeah mine is not primarily for control. It just helps the motorcycle stay in a wheelie without too much fussy player input.
Oh and I'm using conditional checks to add the positive or negative torque based on the current player rotation angle. If he rotates too far forward or back it adds some stabilizing torque to keep him in a wheelie but it can be overcome with throttle/brakes
Hello. I have a physics based movement, and it connects to a static object, with a spring joint. When trying to move the object with a simple forward direction, the joint applies force to it and slows it down. However, i also want it to rotate it like how the momentum would do in real life. I found the AddTorque and Joint.currentForce options, but got stuck on how to use them properly. [This is a top-down view, where a force would spin the arrow shaped object until we stop adding more forward directed force]
I believe the default behavior is actually the one on the right. I would guess you set up your spring joint such that the object is actually attached to a point directly above itself rather than the screw
Gravity would only move it at the lowest point, I want to keep an input (direction downwards) that makes the object spin around the screw after getting caught by the spring, but now, it only moves to the lowest point and comes to a halt.
this is incorrect
the spring if configured properly will pull the object towards the attachment point of the spring
that will involve some horizontal motion in the diagram you gave
I simply believe you configured the spring incorrectly
Or perhaps you hve constrained the x axis motion of the Rigidbody
Also if continuous downward force is applied to the object it dampens the swinging motion (as it would in real life)
Hello, I am trying to create a non humanoid rag doll for my character
I have created rigid bodys for each part along with joints connecting them
It's made up of 2 arms, a head, and a tail
normal Rig body tools don't work given there's no legs to connect to it
is there a way to constraint the bottom ends in one place so they do not rotate as well? Thank you
does anyone know why rigidbody.MoveRotation() doesnt work when the object is parented to another rotating gameobject
Is it kinematic?
i tried both kinematic and non kinematic for both the parent and the child and neither worked
the rotation worked fine when the parent stopped turning too so idk
i updated to a more recent version of unity and it seems to be fixed so ig it was just an old bug
How do I stop my ball from slowing down when it is colliding with the walls on the left & right?
frictionless physics material I guess
So I'm making a game where the player just falls down a huge tunnel and needs to evade obstacles
Can anyone give me some tips or resources about how to find optimal fall speed & movespeed?
Try some values, test it, tweak the values, test again, repeat until it feels right
So i got a problem,,
I want to make a car model that i downloaded move in unity, as a beginner, i followed a tutorial from youtube.
After following the tutorial, i was able to move the car using a car controller script, however i can't make the front wheels turn when i turn the car, because in the tutorial its asks me to add the mesh of the wheels, however I only have the object called FL_Wheel_GRP or FR_Wheel_GRP, no meshes
What do I do here?
We'd have to see which components are on all the various objects to be able to comment
My Wheels and Car Components look like this
I hope this is what you were asking for
In the Wheel Controller Script i have only selected the front two wheels, as i only want them to turn, but i have the same object selected for both the wheel collider and the Transform, which might be causing the problem
why is that mesh renderer disabled?
Where's the actual active renderer for the wheel?
Where's the renderer for the car itself?
I disabled that to try and work around the issue by duplicating the wheels and throwing those into the Transform section, it didn't work, I have 8 wheels with 4 on the outside, however the outside wheels turn
what I'm getting at is - where are all the renderers
you're just trying to rotate the renderers right?
So locate them, and use those
the other issue would be if your code is correct
Renderers are what one needs to see an object in the environment right?
Ok i think i know why it still shows, is it because all the child objects of FR_Wheel_GRP have the mesh renderers turned on?
Okay so after checking this more closely it seems like each part of the tyre comes under the FR_Wheel_GRP object, and they all have a seperate mesh for each part, so how do i just use one mesh? should i change the code to include all the meshes?
i don't see how the meshes themselves are relevant
presumably there's some parent object that encompasses the whole "wheel", yes?
simply set the pose on that object, all of its children will follow
Ah, i see, let me look into that then, and ill update, thank you for helping @timid dove
So what i did was I took all the objects under FL_Wheel_GRP and made them the children on the object FL_Tyre_GRP, now the wheels definitely turn but we have a new problem
so i have this staircase on wheels and i need it to pivot on the wheels instead of the center, how would i do that?
it needs to be able to pivot around the wheels so it can round corners
I personaly dont fibd the cloth component very good for making cables.
I suggest you find other solutions for this.
Here are two good cable packages for unity:
https://github.com/Hrober0/Cable-physics
https://github.com/NoxWings/Cable-Component
The first one collides with other cables and the world whilst the second one dosnt
And the second one uses line renderers to render the cable but the first one renders a 3d cable
Cable physics made with unity. Contribute to Hrober0/Cable-physics development by creating an account on GitHub.
Both of them have physics however. I think since the cables you need are so small and dont need to collide with aything the second one is a better choice since it also gives more performance
When i shoot a gun, the bullet spawns in front of the gun but, to far away from it. The range from the gun depends on the shooting speed. Someone that helped me said its because of updated function. This is the code:
hi! i have 500 rigidbodies in my scene and it seems this is too much for unity. i would think that if all of them are rectangles it shouldnt be a problem, is there something i could do?
Unity is very efficient at handling a large number of physics objects, but performance will likely vary based on how many objects are awake at once as well as things like system power/memory. A beefy pc could likely brute force a huge amount of objects while a weaker one will struggle. Proper testing with a range of systems is a good idea if you plan to release this game.
I don't know if there's a set limit on how many objects is too many, that likely comes down to your preference as the designer of the project.
Box colliders are more efficient than mesh colliders, so having 500 boxes would likely show some performance improvement over 500 complex mesh colliders.
500 rigidbodies colliding with a static floor will also process much faster than 500 rigidbodies colliding with each other in a big pile.
If you run into performance problems, you might first check that objects that stop moving are going to sleep properly.
So my minigun shooting 100 bullets per sec should be fine?
If you don't specifically need physics objects for bullets (small high speed objects tend to go through other objects easily) I'd consider Raycasting.
If you do need physics objects, I'd use a pooling system so the game can reuse bullets that are done being fired or that get cleaned up. If you're spawning 100 objects a second you're going to run into issues anyway, I'd consider lowering it to 60 per second or less. (Framerate, etc)
Unity can handle maybe 500 objects but if you spawn 100 rigid bodies PER SECOND and dont clean them up, you're going to eat up your entire system ram in a very short amount of time and likely freeze up unity before that point.
Nah they desapawn in like 6secs
Btw you seem smart, do you have any idea about this ^
That would be about 600 objects which probably isn't too bad if you optimize your game well. I'd definitely use a pooling system instead of Destroying all those bullets because every time I ity has to run trash collection, it will cause a performance hit
600 is assuming the player is the only one firing rigidbodies.
he is yeah
I would still consider lowering this because if your framerate is less than the bullets fired per second, bullet spawning will either be skipped or bullets will spawn inside each other
I need a little help with my Rigidbody, whenever I start the game isKinematic gets set to true I have no idea why, none of my scripts set isKinematic to anything. Here are the components of the object
Due to the network rigidbody
Yes, thanks :D
First of all how ot make this ragdoll behave normally, second of all, how do i make it self balance? https://gyazo.com/ab222cec24cd57be02da8bc592b6cce4
- Move it with physics not by dragging stuff in scene view
- Find a research paper? 😬
it starts moving for reasons, and falls super slowly as if it was paper https://gyazo.com/1db1107db0767347748839887e3590ac
https://gyazo.com/054c474db1fdb3c1068a8163f7614818
how do i make it normal
super slow falling is likely due to your code
And when i reduce the drag it falls at normal speed but does this https://gyazo.com/42388e11c4bf371af85dc3ac6c32d8fb
wait wrong vid
no, when drag was 0 it falls at normal speed, the only code in there is for those target points and they aren't attached to my thing so it shouldnt interfere.
so leave drag at 0
if you have very high drag it will make it fall/move slowly
but then it starts doing this, what can i do abt it? https://gyazo.com/42388e11c4bf371af85dc3ac6c32d8fb
no idea - what are all those moving points? What code is causing it to move, etc
"the only code in there is for those target points" < what does this mean?
don't mind those moving points, they don't interfere
You sure? Are those not IK targets?
its for the Ik rig for the feet, they are supposed to make the procedural animation thing, but rn they don't interfere, so idk what is causing my weird ragdoll
IK will definitely interfere - in that it will make the ragdoll move
yes, but i removed the target from the rig thing
but i made it None for now, so they shouldn't, right?
disable the IK constraints entirely
ok
I did, and he's still behaving weirdly
how are ragdolls usually made? Maybe i messed up somewhere?
ragdolls are made by attaaching colliders and rigidbodies to all the bones in the model and connecting them with joints
thats for all my joints with a rigidbody
i didnt do it for all bones cuz theres too many but for the important ones, am i supposed to do it for all?
do it for whichever ones you want to be simulated
already did, which type of joint should i use?
Ugh, anyone have quick ideas of why there's this magically barrier between my colliders that prevents a collision, even though gravity is working correctly?
Default Contact Offset in Physics 2D Settings
It's not preventing a collision - the collision is happening
Hm, ok. I'll have to investigate why my script isn't firing then. Thanks 👍
How can we get overlap collider inside Non convex mesh collider.
I am using Physics.OverlapCapsule to check for non contact spawn point for player. But problem is the overlap capsule don't detect collision inside Non Convex mesh collider. How can I fix this?
OverlapCapsule should have no problem with such colliders.
Where did you get the mesh from? Maybe the collider geometry is degenerate?
On the internet I found out this is a limitation of Unity. I had an L shaped box of mesh collider which is non convex and bigger than player size. Non convex mesh colliders will not overlap if the player is completely inside it
You may be confusing CapsuleCast with OverlapCapsule
I am using Overlap Capsule
This chain was working perfectly two days ago. Yesterday I was messing with baking lighting and during that time somehow I must have messed something else up. I have no idea why this is happening or how to fix. Any ideas?
It's a series of chain links with hinge joints (was working great, I just tried using configurable joints instead, same exact issue). I checked tutorials for chains like this online, and they give me the same steps.
without any details it's hard to say
"working two days ago" doesn't help us now
What details do you want?
you'd have to show how it's all set up
Also how any involved objects are moving (aside from natural physics movement)
MeshCollider i would immediately be simplifying to CapsuleCollider here
done, hasn't changed anything yet though
each link in the chain's hinge joint has the link immediately higher than it set as its Connected Body
the top "anchor" link is set like this:
the top link doesn't move (ofc, it's Kinematic)
but the rest freak out
are they colliding with each other?
maybe disable collision on the joints (not shown in your screenshot)
Are they colliding with anything else? A script with OnCollisionEnter could help diagnose
the behavior does look like a collision issue, but I don't see why that would be happening as it wasn't an issue yesterday, and when i space them apart to make sure the colliders aren't hitting each other they behave the same
good idea, i'll try that
maybe the whole chain is inside some other big collider
right
they are colliding with each other, no other objects
double check all the colliders are in sane positions/sizes/etc and that collision on the joints are all disabled
if the chain is just hanging at rest none of them should be colliding with anything
make sure there aren't any extra stray colliders either
Checked, and all colliders are in the same positions and enable collision is disabled on all of the hinge joints
no other colliders in the scene, this is a fresh scene I made to test this
Update: Started to make progress...I changed the scale of the objects and it's jittering less
...just kidding, it's still the same issue.
I've seen most people online recommend doing anything involving rigidbodies in FixedUpdate, so I move my characters programatically there, like so:
public virtual void FixedUpdate()
{
Vector2 frameVelocity = this.velocity * Time.fixedDeltaTime;
objectRigidbody.MovePosition(objectRigidbody.position + frameVelocity);
}
However, won't this mean that my game will look the same regardless of framerate, since most movement is tied to the fixed update rate?
Yes this code will work the same regardless of the framerate. Is that a problem? That's a good thing
My issue is that the game will appear the same whether it's running at 60fps or 144fps, right?
You're confusing the visuals with the behavior.
It will behave the same at any framerate.
Turn on interpolation on your Rigidbodies and you will get apparently smooth motion at all framerates
But under the hood, Unity's physics operates at a fixed 50hz (by default, configurable)
So, even if I'm only instructing the physics engine to MovePosition my rigidbody at 50Hz, it will interpolate for different framerates?
If interpolation is enabled, yes. That's what interpolation does. It visually interpolates the Rigidbodies on rendering frames between physics updates so the motion appears smooth
I see. Thanks for the clear up!
While I'm at it, is there any advantage to doing it like this, and not with objectRigidbody.velocity = this.velocity?
not really
only if you plan on doing a lot of unphysical things
if you just want to move in a straight line at constant speed, setting and forgetting velocity is better
Thanks
Hello everyone, I need some help with Phisics2D.
basically I'm developing a 2D platformer, where I have an Enemy IA that uses Pathfinding to find the fastest way to get to the player, when my enemy needs to jump it runs a code that uses the target position that he wants to land, and his current position to calculate how many (Vector2)Velocity I should add to my RigidBody2D.
Now lets talk about the problem:
I've created this enemy behaviour a few months ago and it was working, then I spend some time updating other parts of my game and tried to add the enemy again today, and turns out that he is not landing on the target position when he jumps, he lands to early.
What I already tried?
- First I wanted to check if it was really working before or if I was just crazy, to test that I cloned my project from an old commit and tested using the same scene and it worked.
- After that I assumed that since it is using the same code it must be something related to the RigidBody2D component, then I checked field by field from this component, and it was exactly the same.
- Then I tried to log every step of my logic to see if there was something different, it was "equivalent", It wasn't exactly the same because the target and the initial position was a little bit different but just for the sake of comparison, the version that works has the Velocity was -6.30, 17.55 and the one that is not working was -6.25, 16.9, so its almost the same, dont justify the difference.
- Then I tried to check the Physics and the Phisics2D into the project preferences, and they are almost the same, the only difference was into the layers, because the newer version has more layers.
now I dont know what to do, feels like if in the newer version my enemy is heavier, but it has the same mass inside the RigidBody2D, and also the same gravity scale, do you guys know what could be causing that?
I could make a call and share my screen if some of you want to see my project environment :).
Thanks a lot for your attention
LOL, forget about it, I spent a day looking into it, but it was other part of the code changing the RigidBody2d.Velocity
One quick way to find out.
It depends
public static List<Gravity> Attractors;
public Rigidbody Rb;
public Vector3 force;
[SerializeField] private Vector3 InitialVelocity;
private void Awake()
{
force = InitialVelocity;
}
void FixedUpdate()
{
foreach (Gravity attractor in Attractors)
{
if (attractor != this)
Attract(attractor);
}
}
void OnEnable()
{
if (Attractors == null)
Attractors = new List<Gravity>();
Attractors.Add(this);
}
void OnDisable()
{
Attractors.Remove(this);
}
void Attract(Gravity objToAttract)
{
Rigidbody RbToAttract = objToAttract.Rb;
Vector3 direction = Rb.position - RbToAttract.position;
float distance = direction.sqrMagnitude;
if (distance == 0f)
{
return;
}
float forceMagnitude = G * (Rb.mass * RbToAttract.mass) / distance;
force = direction * forceMagnitude;
RbToAttract.AddForce(force);
}```
how can i add the force vector with the InitialVelocity vector so that the body that is to be attracted has a initial velocity on the z axis resulting in an orbit
when i add them on awake nothing happens the z value of the force vector sets to 0
Why not just set the velocity to InitialVelocity in Start?
No idea why the force variable would or should be involved in that
Or why it isn't a local variable in the first place
BTW for gravity you generally will want to use ForceMode.Acceleration to be realistic
Since that makes it proportional to the mass
Which type of joint would I need to use for a drum crash cymbal? If that even is the best way of doing it
I have a player with a RB that I rotate using Rigidbody.AddTorque.
Everything works fine, except:
The player has a trigger collider as a child, that I use for some raycasts.
I need to periodically adjust this collider's scale.
When I do, the rotation from AddTorque just instantly stops.
Is this expected?
Hi everyone, do someone know how to use BioIK on 3d object but do not use animator . Although I only need to adjust xyz value, I do not know how to calculate 🥶. I wish can let this model movement smoothly like a human action.
It's expected but the fix is simple, just store the angular velocity in a variable before scaling and restore it after scaling
Hello, quick question about colliders. I've got a tube which has a rigidbody, and I need relatively accurate collisions (the player walks around the inside of the tube walls). Even when I split it into segments, the convex colliders are just filling in the inner side. Is there a way to force the convex collider to map both sides of the mesh, or am I going to just have to use loads of box colliders (or a magic third solution I hope someone can suggest?)
The inside collisions matter much more than the outside ones if thats any help!
Do you understand what convex means?
An outer curve, yes - opposite of concave. But its also the only option for a mesh collider to work with a rigidbody, so its my starting point for my question. I guess I could write better by saying "how would I make a concave mesh collider", but I feel like there might be solutions that don't require the mesh collider to begin with, or can more accurately bind it.
Do you have an actual solution, or are you just taking problem with terminology?
You can't make a concave mesh collider if you want the Rigidbody to be dynamic
Your only option is to build it up from smaller component colliders such as box collider or other convex mesh colliders
I was only asking because you seemed unclear about why the concave mesh collider was filling in the arc
Alright, thanks. I was hoping for something easier but not the end of the world 🙂
Not a problem, apologies if I came back as defensive/hostile
https://github.com/SebLague/Fluid-Sim
Hey, I found this fluid simulator source code from Sebastian Lague on YT. Could I get help on how I'd connect and run this script on Unity? (I have never worked with unity before)
Ok thanks - will try that tomorrow.
Edit: Did not work in my case.
i want 2 box colliders a collider just collisions but also a box collider that has no collider but is use full for other stuff how would i do that
nvm
I have a ship which is sinking, red dot is center of mass, blue dot is offset center of mass(accounting for the compartments now containing water). How can i get a rotation angle(angle at which the ship is sinking) from those two CoMs? Or alternatively how can i get said rotation from all compartment's weights and ship's own weight? The images aren't accurate, just a representation of the problem. Not exactly looking for a strict solution, a nudge in the right direction would be enough
Why not just AddForceAtPosition
And let the physics engine figure out the torque
"rotation angle" doesn't make much sense
it's an rts, i'm really concerned about performance. And about torque, won't the ship sinking increase the surface area which increases buoyancy, so if the amount of water isn't extreme enough to submerge the entire compartment won't it balance out at some point giving me said angle?
What makes you think the physics engine is not performant?
plus i want the movement to be rather predictable, so the ship won't bob up and down in the water, that would mess with the aiming scripts a lot
Anyway torque is determined by distance * force. Basically take the center of mass of all the water as the point of force and the boat com as the fulcrum
Torque is distance from fulcrum * the force
If it's an RTS and you don't want physical accuracy it's simple enough to fudge a lot of numbers here
Basically distance from center of the boat determines the angle and just tweak the multipliers till it feels good
I never thought about using water's CoM as the point of force, that clears things quite a bit, will try!
Hello, do someone how to write inverse kinematic on unity 🙏
This is probably one of the easier things to figure out, but I just cannot wrap my head around it. This ball seems to reach its top speed very quickly, especially on slopes when no input is given from me. I want it to be able to roll down inclines and gain speed while doing so, y'know, like a real ball.
You can see here that after I stop pushing the ball up the steepest incline, it reaches a fairly slow top speed and then just stays at that speed until the terrain flattens out.
I apply force while going down the long incline at the end, but I mean...that doesn't count. I apply the force with an input.
I would guess it's code related. You might also have a high drag or angular drag configured
Angular drag is at 0.05.
Linear drag is 0.
I even tried turning off the controller script and it still caps out very quickly at a very low 3.75 units of velocity on the long downward incline.
how are rolling spheroids in unity supposed to function because I must have made some mistake
there's also a global max RPS (rotations per second) in the physics settings but that's 7 rps by default I believe
which is quite fast
do you have a very high friction or something? What's the mass of the ball? Usually there's a lot more slipping with default settings
Unity perfect spheres have an infinitely small point contact patch which complicates friction and rolling resistance
The ball's mass is 0.5
what if you set it to 0
and if you set frictions to 0 and Minimum?
Just trying to rule things out
that might make it slide rather than rolling ofc
unless it's your controller that is causing the rolling
It was, I believe, the max angular speed.
I set it to 100 and the cap came right off.
nice
weird that it's set to 7 by default when that's so...small
and it causes such a blatant issue with what's arguably the most basic physics process
High rotation speeds cause issues with collision detection for non spherical shapes
Imagine calculating whether a rapidly rotating 2x4 will collide with something
It's a tradeoff
they called me the rapidly rotating 2x4 in high school
I wonder if it would actually be better to forgo the natural rotation entirely. Just have a rotation-restricted rigidbody with much lighter friction that can just slip around, and just rotate the model in a child object according to velocity.
Because I need to keep a reference to the point of contact between the ball and whatever surface it's touching
and I imagine that will be messy if the ball is constantly rotating crazy fast
This is how Unity's roll-a-ball example works
you're shitting me
Good Morning, I'm wondering if anyone is able to help me using Joints. I've been struggling with this problem for some time and I'm at my witts end. Basically I have two objects (A and B). I want them to remain parallel to attempt to remain parallel to one another. The objects should push apart from one another if they get too close, and pull back together if they get too far away. I've been using the Joints in Unity. My problems are as follows:
Spring Joint allows me to maintain a distance between the two objects, this works great. However the objects can 'slide' forwards and backwards and end up hitting one another as seen in the picture on the right
Configurable Joint i thought would get me where I need to be. However again using the image attached, the objects don't actually rotate...so the angular/rotation constraints for this joint don't help me.
Does anyone know of a way I can get these two to remain parallel. I guess the closest thing I can think of is a Fixed Joint. But with some spring added.
I'm trying to avoid writing my own physics simulation for this.
Hello
I got also a problem with configurable joints on a simple seesaw. The boxcollider and the mesh making different rotations
what mesh
you mean a meshCollider of the same shape? Or what?
It's a simple scaled cube with a box collider, an rigid body and an configureable joint.
Should I try a mesh collider?
I'm saying I don't understand what I'm looking at in this screenshot
you're saying what that the box collider is not in sync with the renderer?
That would seem to imply they are separate objects. Show all the components on this object, basically the full inspector, and what it looks like in the hierarchy
the screenshot you showed is a little ambiguous - not showing the rest of the inspector and not showing the hierarchy
I imported it from an other project.
Currently I'm out with the dog.
Maybe you are right that I mixed two objects.
I duplicated and tried different settings
create a spring between two rigidbodies that are (1,0,0) apart. then, in fixed update, try setting the velocity of the rigidbodies' to
void FixedUpdate() {
var originalVelocity = rigidbody.velocity;
originalVelocity.x = 0f;
originalVelocity.y = 0f;
rigidbody.velocity = originalVelocity;
}
that's it.
if you only want the rigidbodies to move along a certain vector, you can do
void FixedUpdate() {
var originalVelocity = rigidbody.velocity;
originalVelocity = Vector3.Project(originalVelocity, axisOfTravel);
rigidbody.velocity = originalVelocity;
}
that's it
does this make sense?
That's an interesting approach. But unfortunately force is being applied to each of these objects to cause movement, so I can't affect their velocity without breaking that. I was thinking another approach might be to check the angle to the connectedAnchor against transform.forward then prevent movement if it exceeds a given angle.
I appreciate the reply btwe
@timid dove The problem was the scale. Thanks for helping
Hi guys! One quick and tricky question: how will you apply physics to the clothes of a slime without being texture?
Wdym by "without being texture"?
I have a problem with 2d physics, i have an enemy with a circle collider 2d and a rigidbody2d, it has a physics material applied that has its bounciness set to 1 and friction to 0. I want it to just bounce around like a screensaver and it works perfectly on the floor and walls of my tile map but when it hits the ceiling it just slides across and doesnt bounce off and i can't figure out why
It's better to just do this manually in code with CircleCast and Vector2.Reflect
The physics engine isn't going to give that perfect elastic bounce etc
you can try the projection
But unfortunately force is being applied to each of these objects to cause movement, so I can't affect their velocity without breaking that.
how do you figure? what do you think applying forces does?
the physics problem of what you're doing is, there's a tube around the two objects sitting on tracks, and the wall's tubes applying an equal and opposite force reacting to the spring's forces on the walls of the tube. it is basically a static collider. if you want, you can model it as placing the objects inside a bunch of static colliders.
in real train tracks, there are grooves on the wheels going around the rails preventing the wheels from slipping left and right, and the weight of the train prevents it from flying off. on pneumatic tires, which are way more complicated, it's the weight of the car interacting with the tire's friction and shape
Of course. You're right. I think I've got something that works, I'm checking the angle of the joint and applying some force if the angle exceeds what I want it to. This seems to get the behaviour I'm after but there's some more kinks to iron out.
// Update is called once per frame
void FixedUpdate()
{
worldStart = transform.TransformPoint(springJoint.anchor);
worldEnd = springJoint.connectedBody.transform.TransformPoint(springJoint.connectedAnchor);
Angle = CalculateAngle(worldStart, worldEnd, transform.right);
if (Mathf.Abs(Angle) > Tolerance)
ApplySpringForce(worldEnd - worldStart);
}
hmm... you should try what i showed you
i'm not sure why you are messing around with something so complicated
if there is no velocity in the directions you do not want the rigidbody to travel in, it will not travel in those directions.
Vector3.Project is exactly replicating the behavior of perfectly fitting static mesh colliders around the object and setting its coefficient of restitution (whatever they call it in unity, "bounciness") to zero
Okay just trying to wrap my head around how it will help in my situation. Thanks again
Perhaps it was in my explanation. I said that I wanted them to remain parallel, that's not strictly true. I want the objects to be able to move parallel to one another within constraints if that makes sense? Like object A should be able to move on the X axis a certain amount before springing back towards object B
yes, that's exactly what will happen
at least in my example
the two example snippets are basically saying
"remove all the momentum (velocity) that isn't going along a certain vector"
Alright I think I just need to try what you've provided and see what the result is :)
you can certainly do it as "take all the momentum and put it in this direction" but it will not be stable*
yes. as long as you configure your springs correctly. usually damping and coefficient need to be way higher than you think
Can someone help? Player can move inside colliders when is trying to move at the angle of 2 objects holding W and A or D
And even climb walls when only moving forward
Okay going through walls is fixed but still the force is making player able to climb walls
Calling MovePosition inside Update is incorrect
it should only be used in FixedUpdate, and only once per FixedUpdate
MovePosition also doesn't respect collisions
why not move with velocity?
or adding forces
MovePosition is intended for moving kinematic bodies
Adding force is not working correctly with jumping
When I add force being on ground it need more force to move then when player is in the air
For example when I am on the ground I need 500 force to move player but then when I am in the aire I am just being pushes so far with this force
all of this:
if (Input.GetKey(KeyCode.W))
{
rb.MovePosition(rb.position + transform.forward * Time.deltaTime * 5);
}
if (Input.GetKey(KeyCode.S))
{
rb.MovePosition(rb.position + transform.forward * -1 * Time.deltaTime * 5);
}
if (Input.GetKey(KeyCode.D))
{
rb.MovePosition(rb.position + transform.right * Time.deltaTime * 5);
}
if (Input.GetKey(KeyCode.A))
{
rb.MovePosition(rb.position + transform.right * -1 * Time.deltaTime * 5);
}```
Could all just be replaced with:
```cs
Vector3 input = new(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")));
input *= moveSpeed; // I guess 5 in your case
Vector3 rotated = transform.rotation * input;
rotated.y = rb.velocity.y;
rb.velocity = rotated;```
And it will work correctly with jumping and not cause you to climb walls either
Also your Jump function should be used ForceMode.Impulse or ForceMode.VelocityChange
Yeah but I like to write a code that I fully understand
Vector3 rotated = transform.rotation * input;
rotated.y = rb.velocity.y;
rb.velocity = rotated;
All of 3 lines
for what do I need rotation?
Vector3 rotated = transform.rotation * input; < this takes the input vector and rotates it according to how your player is facing, so W makes your character move where they're facing for example
Yeah but it does anyway
rotated.y = rb.velocity.y; < this takes the existing y velocity and puts it into the vector so that:
rb.velocity = rotated; < doesn't change the y/vertical velocity but will use the input velocity for horizontal
what does anyway?
Sure, you're doing it a different way
So shouldnt it be just transform.forward?
I'm jsut showing you a simpler way to do everything
no, because forward only is for forward
notice have you have 4 separate lines of code
to do each direction
My code is doing all of it at once, just by rotating the input direction according to the player's current rotation
transform.rotation
that is the rotation of the player
Why is there transform.rotation?
Why wouldn't there be?
that's very useful information
it tells us what the current rotation of the object is
we then can apply that rotation to the input direction, as my example is doing
that makes it so the input is relative to the character's orientation
which is what you want
but not just the forward, the forward, the right, the left, the back, the up, the down
yeah
all of that is basically captured by the "rotation"
but like "Horizontal" and "Vertical" input is a world's vector
Not the local
Right?
which is why we have to convert it
which is why we do Vector3 rotated = transform.rotation * input;
But this lines? rotated.y = rb.velocity.y;
rb.velocity = rotated;
this gets the converted version
So after we rotate we have some vector like (1, 0, 1) for example (to move forward and right)
We want to now add in the player's vertical velocity
yeah
in case they were jujmping or falling
so let's say they just jumped and are moving upwards at 5 m/s
so now we get (1, 5, 1) with rotated.y = rb.velocity.y;
and we assign that to the Rigidbody velocity rb.velocity = rotated;
now the object will move in such a way when the physics engine runs
So isnt it the same as adding force when I press space?
I mean shouldnt it be in the jump function instead of moving function?
rotated.y = rb.velocity.y; because this makes player jump right?
adding the force is where the y velocity comes from in the first place
no
we do this here so that our normal horizontal movement doesn't overwrite the y velocity to 0
it's just saying "preserve the y velocity as whatever it already was"
otherwise when we do rb.velocity = (1, 0, 1) we lose our y velocity
Oh so its to prevent overwrite by the input?
yes
That's the best physically correct way to move the player.
Not by changing the position but by adding velocity
Yes
the physics engine itself handles changing the position
you want this so that collisions are respected properly
So in my expirience when I do this its sometimes makes player pushed in some direction
For example when I hold W for so long it makes player go forward even after I end holding W
Because velocity is stacked up
that's when you add forces
adding forces changes velocity
and hwen you stop adding forces, the velocity remains
in this case we are setting the velocity outright
so when we release input, it will set velocity to 0
meaning it will stop immediately
try it out
yes, sort of 😉
I'll let you in on a little secret
rb.AddForce(Vector3.forward);
^ this is pretty much the same as:
rb.velocity += (Vector3.forward * Time.fixedDeltaTime ) / rb.mass)
AddForce just additively sets the velocity
Ooohhh
you can actually achieve either movement style using either technique, but it is simplest to overwrite velocity using rb.velocity and simplest to add velocity using AddForce
Yeah but now it sticking me to the wall
I can just stay on the wall by just holding the button in the direction I am moving
Two ways to solve this:
- Use a custom frictionless physics material on the wall
- Use a raycast to determine if you're next to a wall and disallow moving into the wall if it hits
Why should I be using this instead of AddForce?
it's not instead
it's part of AddForce
Okay
rb.AddForce(Vector3.up * jumpVelocity, ForceMode.VelocityChange); for example
So why use this kind of mode instead of default?
because default is intended to be used for a continuous force in FixedUpdate, for example a rocket engine. Where you add force every frame
These are for "one-off" forces such as a jump or an explosion
If you use the default for this, it's like arbitrarily dividing your force number by 50
because it does * Time.fixedDeltaTime inside
So thats why I have to use like 350 force
and whats the diff behind impulse and velocityChange?
Impulse divides by the object's mass
velocitychange does not
so with impulse a 50 kg object will go 50x less than a 1kg object
with VelocityChange both will go the same amount
So you use VelocityChange when you want any object's velocity to change by the same amount no matter how heavy it is. Use Impulse when you want heavier objects to be affected less by it, and lighter objects to be affected more.
Use a raycast to determine if you're next to a wall and disallow moving into the wall if it hits
Is there a tutorial video or something?
idk
I was trying to make it but I cant imagine how that would work
I dont even know what that is
https://docs.unity3d.com/Manual/class-PhysicMaterial.html
You can add physics mateirals to the wall colliders
make one with 0 friction and minimum friction combine
But that shouldnt make my wall like ice?
I mean very smooth?
And from one side yes the player couldnt stick to the wall but at the other side it cant walk on the wall properly either
yes
Do you need to walk on walls?
Yes
Most people only walk on floors!
Yes
But its like a cube
So I would have to make child of this cube as a floor
Right?
Or is there other option?
No
Its working perfectly
@timid dove Thank you very much for teaching me so much. I really appreciate that since u are the first person who tryied to explaing things to me instead of telling me that u will not "spoon feed" like others always was answearing my questions.
how can i keep a rigidbody's position constrained within the confines of a sphere?
I assume having a spherical collider without inverted normals so that it keeps the object inside wouldn't work for some reason?
hey everyone, got a quick question about physics-based projectiles being synced over the network. Working on a game and need projectiles similar to this video, but after further research it turns out this is fairly unrealistic. Tried a combination of Raycasting and physical bullets, but the guns stats (projectile count, bullet speed & size, etc.) are constantly changing making it difficult to find a balance. Any ideas??
➤SHOOTING with BULLETS + CUSTOM PROJECTILES || Unity 3D Tutorial:
I've already made a tutorial about shooting with ray casts, but a lot of people wanted to know how to shoot with bullets. So in this series, I'll show you everything you need to know to start shooting bullets/custom projectiles in Unity 3d! :D
I forgot to mention the DOWNLOADS in...
nope
Well, I'm an idiot, but maybe you could just check to see if the object's distance from the point of the sphere is too large, and if so move it to the point on (or just within) the sphere in question?
Or apply a force towards the inside that gets stronger the further away from the center of the sphere is or something. Only have it applyt he force if it's in contact with the edge? I dunno. Just a thought
Make a collider of that shape
I'll see if that works
Hi, I have noticed that physx joints become very loose when the rigidbody has small mass or small inertia tensors, and one way to make the joints stiffer is to artifically scale the inertia tensors for the connected bodies, physx joints have this option
Is this the only way?
I am confused by the ConfigurableJoint's "linear limit" setting.
If I set it to 0, the joint doesn't move at all, even when the "Spring" field in the "Linear Limit Spring" section is non-zero
Shouldn't setting it to 0 make this behave like a SpringJoint?
The SpringJoint pulls itself back towards a distance of zero
A slightly non-zero value makes it behave as expected
Hi, i'm not sure if this is the right channel to ask but I can't find a better one. Currently I have 2 gameObjects with the same parent, and with 0,0,0 as their transform position, yet they are at different positions in the scene, can anyone help me figure out what could cause that? (I'm trying to make both gameObjects spawn at the same position)
Mornin' all. I'm having a weird issue that's beginning to become rather irksome. lol.
I'm procedurally generating rooms out of 'segments' (walls/corners/doors), each segment has their own box collider to prevent the player from walking through them, which is working great, however, if I 'push' the player against anywhere where the box colliders meet or overlap, the player can glitch through. Is there a way to prevent this?
Is there a way to prevent the "jumping" when colliders move over the point where two colliders meet?
There's some issues that are simply down to how the solver works where, if you go fast enough through a collider, or you manually move a transform to overlap with a collider, it'll come out the other side. The quickest thing would probably be to turn up the solver iterations or make the colliders a bit thicker, or try using a different collision detection mode for your player
Ah thanks for that. I'm using "RigidBody.MovePosition" to move the player, will try the things you mentioned 🙂
as long as you're not trying to move the player too fast, you should be alright
It does move pretty quick tbh and it's only where colliders meet or overlap.
yeah, fast moving colliders have a habit (again, due to how the solver works) of flying through colliders sometimes
Okay. I'll give a few things a go and see how it goes. lol.
I have an object made up of lots of objects that I want to 'explode' on enabling, I've got it working sort of, but how can I increase the amount of force all of the parts exert on each other so they explode out more?
Hello! I have a question about delta time. Lets say I'm doing what people say to do which is have your movement code be pos.y += vel.y * deltaTime, what happens if there is like a second-long frame lag? Won't deltaTime be in the thousands and all of a sudden my guy will be in the stratosphere? I get the general idea of why we multiply by deltaTime, but I worry that if there is a big lag spike people will just be teleported into the sky way higher than they would normally be able to jump to
deltaTime makes that the value wont change with frames but with time. Lets say that u change your x position without a deltaTime and you have 60 fps and your friend have 120 fps. He will be 2x times futher than you
I forgoted once to add deltaTime on flying script and when I was flying correctly my friend was skyrocketing with just holding space for 1 secound
@dense copper
Anyone?
I'm trying to make a ragdoll for this spider like character. Ive created the capsul colliders and joints for the legs and body. How do I finalize them into an official ragdoll prefab?
I'm creating a VR game, and I want only the legs of the character you are playing as to be ragdolled, while the upper body still follows your VR character. How would you do this?
As if the legs are paralyzed, and the rest isn't.
Give your body a kinematic Rigidbody and attach the legs with joints
@timid dove like this?
I was responding to the other person
What do you mean with "finalize"? Isnt it already a prefab?
Is it reasonable to put multiple ConfigurableJoints on the same object that connect to the same thing? I want a joint that uses a spring to resist angular movement and that has hard angular limits
I have a sphere with a rigidbody and a sphere collider attached. I've written some logic that uses AddForce to apply an impulse force towards Vector3.Forward when the Spacebar key is pressed. The sphere is a child of another transform. I wish to be able to scale the parent transform from 0.5 to 2. The outcome I expect is that when I run the game, the AddForce should push the sphere the same distance and speed relative to its parents current scale. However, this is not the case. I've been scratching my head on this for the last 4 days. Can anyone help?
Unity physics doesn't know or care about scale
the effect the force has on the object's velocity depends entirely on the force amount, the Rigidbody's mass and the ForceMode used in the AddForce call.
Scale doesn't factor into that calculation at all
If you want the object to be pushed 4x as far you need to either:
- increase the force by 4x
- decrease the object's mass to a quarter of what it was
Thank you for the reply! I will give this a try. Does the drag or angular drag value also need to be changed?
maybe
depends on what you want ¯_(ツ)_/¯
note that forces only affect velocity
the "distance" something goes when it gains velocity is essentially infinite
unless some other force stops it
such as drag or friction
or a force in the opposite direction
Drag would change how the object slows down over time.
If you just want the object to move 50% as fast when its parent is half as large, halve the force
Generally if you are looking to achieve some very specific physics goals it's best not to use Unity's built in drag feature, which is not well documented, and implement your own if you want drag.
Can someone explain line renderer to me? I dont get it at all
Sure, it's a renderer that renders lines in the world
Are you using the correct mode (world space vs local space)?
You're also only setting one point. What about the other point?
What point?
Thats what I dont get it
The ray is send
And raycast is getting hitpoint
Shouldnt it go from gameobject to the hitpoint?
You need the origin of the ray and the hit point
The line has at least two points
by origin of the ray u mean like the interactor source?
Well that's bad too then
Because then you need to convert the hit point into local space
Which you're not doing
I mean I was using worlds position before
Pick world or local and be consistent
But I unchecked it
Why?
Because I dont want worlds position since it is laser gun
I want laser to be local rotation and position of a players
This is not relevant
That's already handled in your Raycast
Anyway all you need to do is feed the appropriate positions to your line renderer based on world or local space
Right now you're giving it a world space position (the hit point) but it's set to local mode
And if you set it to world space mode you need to make sure both points are set
!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.
Did you set it to world space?
Yes I'm on a phone
As u can see use world space is checked
And the debug log is giving me a message that ray is hitting but the line renderer is still fucked up
@timid dove nevermind it works
I just changed the gameobjects rotation
As always thank you for help
Using 2D physics, rb w/ hinge joint & collider is ignoring collisions with other objects that have colliders but no rbs. Why ?
The second a rigidbody is added, collisions work as intended. If the hinge joint is removed, collisions work as intended with objects that do not have a rigidbody.
It's unclear from your question which objects have joints and which have colliders and which are moving. Could you clarify?
Sure thing! Object A has a dynamic rb2D, a hinge joint2D with no connected RB and a boxcollider2D. Object B has a boxcollider2D and nothing else.
I ended up adding kinematic rbs to all the geometry that isn’t moving but I’d much rather have a different way
None of the colliders are marked as triggers
and which object(s) need to move? Only Object A?
static RB probably works too but... Yeah i don't think it should be needd
hi, could someone please help me figure out why my grounded check is returning false? The collider used for the check is set as a trigger, it's the one extending down from the player. the layer mask includes the Ground layer which is applied to the tilemap. the CheckIfGrounded function is called in Update()
the collider:
I double checked that i am using the correct collider and the layers are applied to the correct objects
before I made this function I had m_IsGrounded set from OnTriggerEnter and OnTriggerExit, that worked but I needed it to confirm the grounded status every frame instead of just when it's expected to change
Show where your LayerMask is configured etc
this may be a reallyyyy dumb question. But I cant seem to get through my doors that I have made with these preset items for a class project. all the oter doors that were previously in the "Level" pack she gave worked but whenever I make my own I can never walk through it
show the wall colliders
(you will need to turn on Gizmos if they're not on already)
and also show your player
showing as checking the box? or actually send screenshot for player?
as in selecting the wall and showing what its collider(s) look like in the scene
for example is the wall collider covering that whole doorway?
that would prevent the player from going through
yea it seems to be covering the whole door way. How should I set up the colliders so the player can walk through?
oh snap I got it figured out!
Thank you!
are charactercontrollers meant to be only for the main character or for all characters in game?
They can be used for whatever you want.
I've actually used it for a top down camera controller script once or twice out of convenience.
yeah I just always coded whatever it is myself
like adding colliders and physics to the different entities I have etc
so I do not really understand what a character controller is ought to be
just a very general controler for physics driven things that implements much of the common functionality?
Here's nVidia's explanation of why they created it https://docs.nvidia.com/gameworks/content/gameworkslibrary/physx/guide/Manual/CharacterControllers.html#kinematic-character-controller
Thanks! Really nice read
what's the best way to prevent the player from bumping slightly when entering a slope?
this is what i mean
you can see the little jolt
can someone help me configure a configurable joint to allow the connected bodies to move closer, but not allow them to move further away? Like a rope, with no stretch but easy compression
to link these
This code is written in a roundabout way to set your velocity exactly to a certain velocity
That will naturally override whatever other velocity the object has picked up
I'm spawning in a bunch of door prefabs (all set up exactly the same), but I'm having a weird issue where it seems very hit and miss as to whether my 'bullet' prefab hits the door. Some of the time the bullet just passes straight through. I have a Trigger to control the opening/closing and a collider on the actual doors. The bullet detects the doors via tag. Is it possible that the trigger and collider are interfering with each other even though they're on seperate objects and have different tags?
Okay so after some experimentation, it looks like if I shoot the doors at an angle the bullet passes straight through, but if I shoot pretty much dead on it works as it should. Anyone have any ideas on how to fix the issue please? 😕
How are you handling the collision?
Sounds like probably some run of the mill tunneling happening
Sorry man, had an early night. Literally just with colliders, and coding it with oncollisionenter, checking for the tag and then doing things. But sometimes it just doesn't recognise the collision at all (bullet passes straight through)
Anyone that has a clue about this one: I have a mesh. Once I add a mesh collider on it, Unity just crashes and doesn't give a crash report. I made it a package for those wanting to try?
Happens in Unity 2022 and 2023
This is a potato video of it happening
Just tunnelling then.
You need some combination of
- continuous collision detection
- slower projectiles
- thicker colliders
- smaller fixed time step
- manual raycasting
mesh collider for a mesh with 49k vertices?. You'll want a simpler mesh
Probably shouldn't crash but that's probably why it's crashing.
Okay thanks. Will take a look at various things 🙂
I need a meshcollider for the project purposes. But that’s not why it’s crashing. I have done meshcollider with 8mil vertices before
Pretty sure Unity has a 64K vertex limit per mesh 🤔
what happens when you try it with a much simpler mesh? Try giving it a cube or something
only for uint16 meshes
That’s not an issue, I have a whole scene coming from navisworks with much heavier objects and much simpler objects. Out of the 40000 objects there are 3 corrupt meshes that crash Unity. The others Don’t have that issue
I filed a bug report
Hi! i'm trying to do active ragdolls for the first time, but i'm struggling a little bit, any tips on how to make it?
what i got finished is the ragdoll
and an animator body
i tried doing this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class Zombie : MonoBehaviour
{
[SerializeField] private List<Transform> animationJoints = new List<Transform>();
[SerializeField] private List<ConfigurableJoint> phisicalJoints = new List<ConfigurableJoint>();
private void Update() {
for (int i = 0; i< animationJoints.Count; i++){
phisicalJoints[i].targetRotation = animationJoints[i].rotation;
}
}
}
but didn't work as expected
just updating in case anyone want to do something similar, i just used localRotation instead of rotation 👍
There is a much easier built in system for rag dolling… in the 3D objects -> Rag dolling tab… if you haven’t looked into that, you probably should as well… Though perhaps your script suits you better
Can anybody explain to me why this happens sometimes?
Sometimes I get launched in the air like this as if some forces are pushing me. Notably, it happens when I try to jump into an object that is right in front of me
My char doesn't use a rigidbody in any way, he is moved via character controller but sometimes he gets pushed around or launched like this. I can't figure out why
You'd have to show your code.
Since you're not using physics, all movement is due to your code
