#⚛️┃physics

1 messages · Page 22 of 1

silver moss
#

So what if your capsule is like this?

#

The character up (yellow arrow) is more than 80 degrees from the right side normal (white arrow)

#

And the right ramp will get ignored because of the dot check

indigo echo
#

then this would'n be possible

#

the ramps aren't exactly 45 degrees, it's more like 30-ish

silver moss
#

Why are you using transform.up instead of world up direction though

#

Are you supposed to be able to run on ceilings and stuff?

silver moss
indigo echo
#

something like this

silver moss
#

Alright

#

I think you just need to tweak the dot check, make it more forgiving

indigo echo
#

nah, doesn't explain what i showed earlier

#

also, i changed it to use RB.trasform.up on the check and it's still happening

silver moss
#

In this scenario (angled ramps on both sides), imagine this:
-Frame 1: You hit the Right ramp. You adjust your transform.up to align to the Right ramp
-Frame 2: You hit the Left ramp, while still colliding with the Right ramp. Your transform up is already aligned to Right ramp's normal (pretty much perpendicular to Left ramp) from the previous frame. Your dot product check for the Left ramp fails

#

Maybe use a combination of dot check with player up direction, and dot check of current ground normal?

#

Max of those maybe?

indigo echo
#

i get what you mean, but what i don't understand is why what's happening in the next screenshot is possible

silver moss
#

This one? What's wrong here exaclty

#

It looks to be aligned correctly - probably because it hit both surfaces at the same frame

silver moss
#

Make your minGroundDotProduct more forgiving but check the dot to the current ground normal (if already on ground)

indigo echo
#

i lowered the ramps, i don't know why queries say there's two hits and SC says there's one except when the character is on the exact middle

silver moss
#

Only reason I can think of is that your if statement evaluates to false and groundContactCount doesn't get incremented for one of the ramps

#

Have you normalized the vector that you put into Vector3.Dot?

indigo echo
#

i mean, it's only one vector at a time so it's already magnitude 1

#

and groundContactCount it's only to know if the character is on ground

indigo echo
silver moss
indigo echo
#

it's just hitCount

#
static readonly RaycastHit[] hits = new RaycastHit[10];

void DetectSurfaces(){
  Vector3 sphereOrigin = RB.transform.position + RB.transform.up * 0.5f;

  int hitCount = Physics.SphereCastNonAlloc(sphereOrigin, 0.505f, -RB.transform.up, hits, 0.5f, layerMask, QueryTriggerInteraction.Ignore);

  for (int i = 0; i < hitCount; i++){
    if (Vector3.Dot(hits[i].normal, RB.transform.up) >= minGroundDotProduct){
      groundContactCount += 1;
      avgNormal += hits[i].normal;
    }
  }
  print(hitCount);
}
silver moss
#

And those magenta arrows are the hit normals shown by physics debugger (I haven't actually used it)?

indigo echo
#

yes, they are the queries you told me about

silver moss
#

Are you using any other physics queries apart from this? 👀

#

Specifically sphere checks

indigo echo
#

nope, just physics debuger

#

ah that, no

silver moss
#

Physics queries mean methods like Raycast, SphereCast etc. Those are queries

indigo echo
#

just SC

silver moss
#

Weird then, not sure why it would show two contacts(?) when it prints 1 🤔

#

Unless it registers the two contacts as one hit

#

Still weird

indigo echo
#

this is what runs after DetectSurfaces ```cs
bool isGrounded => groundContactCount > 0;

void StateUpdate(){
stepsSinceGrounded += stepsSinceGrounded < 2 ? 1 : 0;

if (isGrounded){
stepsSinceGrounded = 0;

RBNormal = avgNormal.normalized;
Debug.DrawRay(RB.transform.position, RBNormal, Color.blue);

}
else {
RBNormal = Vector3.RotateTowards(RBNormal, -gravity.normalized, RBNormalResetMaxRadDelta, 1);
}

RB.transform.up = RBNormal;

hVel = Vector3.ProjectOnPlane(RB.linearVelocity, RB.transform.up);
vVel = Vector3.Project(RB.linearVelocity, RB.transform.up);

groundInfo = new() //Update groundInfo
{
isGrounded = isGrounded,
RBNormal = RBNormal
};
}

#

this is what actually changes RB.transform.up

young gate
#

Is there a good method for ignoring collisions certain faces of a convex mesh collider?

#

I looked into using modifiable contacts for it but it seems to actually get the face of a contact isn't exactly simple as it's not part of the contact data

#

I could raycast to find it, but it seems like overkill especially for every contact every frame

unique cave
#

So what is the context behind the question? What is it in your game that you want to fix?

young gate
unique cave
#

For the latter I believe contact modification would be the only way but I'm not familiar with the actual process of how it's done

hidden snow
#

Hi there, what is the best way to implement an enemy attack with firing arrows for example in the way that the object faces?

unique cave
young gate
#

Not just for accuracy but for performance

unique cave
young gate
#

It was awful for the interior faces of composite mesh colliders though

unique cave
shadow plinth
#

Is it normal that OnCollisionEnter() sometimes just not being called when object collides with something? It just ignores collisions from time to time and I don't really know, how to counteract this :\

silver moss
#

For example moving the rb with transform, while you should move it with rb.AddForce/velocity/linearVelocity

shadow plinth
#

maybe my physics settings are incorrect or something

silver moss
#

What inspector is that 👀 Oh physics settings in unity 6(?)

shadow plinth
shadow plinth
silver moss
#

What are your objects composed of and how have you confirmed that OnCollisionEnter is not getting called?

silver moss
shadow plinth
silver moss
#

So you have no if-statements before the Debug.Log or anything?

shadow plinth
#

nah, debug is not in any if statements or something. In fact, it doesn't matter if I put it in the start or in the end of the function

#

here collisions with zero relative velocity are collisions from cube contacting with ceiling, but when it hits the floor, OnCollisionEnter() sometimes just ignores the collision entirely

silver moss
#

Is the whole room one mesh collider?

#

Like are the walls and the floor the same mesh

#

I noticed from the video that it doesn't play a sound when it slides down the wall

#

Which would hint that it is already colliding with the room (wall) when it hits the ground

shadow plinth
silver moss
# shadow plinth yes

It counts as a single collision, i think unity produces only one collisionenter per collider

shadow plinth
#

Yeah, I see. OnCollisionEnter() is being called when entering collision with object, not creating new contact point

silver moss
#

Yeah so I suggest separating the room into smaller objects

#

Probably helps with rendering and physics performance too

shadow plinth
shadow plinth
#

I have investigated further and discovered, that bounciness of physics material applied to the object can trigger this issue. Basicly, objects with bounciness will not trigger "OnCollisionEnter()" or make "OnCollisionStay()" not provide new contacts for this collision sometimes

shadow plinth
silver moss
shadow plinth
#

so, setting higher bounciness helps it to correctly display velocity, but now impulse is zero

#

correct velocity and impulse calculation appears only when object is nearing the end of bouncing

urban forge
#

How can i build a wall run mechanic with a fp player

unique cave
shadow plinth
#

Good idea! I will try it and write here about the results later

shadow plinth
unique cave
shadow plinth
unique cave
#

That sounds very weird though, I don't think the bounce can be too fast to detect because the collision is obviously resolved. The impact shouldn't be too hard to calculate from the momentum change either so I can't really think of any reasons as to why that might happen

shadow plinth
#

yeah, that makes sense, but somehow this strange issue exists

unique cave
#

Kinda wild guess but I would check that too for good measure

shadow plinth
unique cave
#

Since OnCollisionExit takes in Collision too it would make sense it would show the last step values or something like that because otherwise it would only return no contacts since it obviously wouldn't hit anymore

shadow plinth
#

yeah, it's wrong too

unique cave
#

Might also be there to get .gameObject, .artuculationBody etc. only though

#

Unfortunate

shadow plinth
#

I also tried slowing down the entire game, but it doesn't change anything

unique cave
#

If that's really the highest impulse of all contacts and not just of GetContact(0), I'm pretty much out of ideas

shadow plinth
#

it's the same for collision.impulse.magnitude and the highest impulse of all contacts... 💀

unique cave
# shadow plinth it's the same for `collision.impulse.magnitude` and the highest impulse of all c...

Seems to have been issue for years from what I can see from the forums so it might as well be a problem with PhysX and not unity specifically. Couldn't find anything from UE thought which uses PhysX too so no idea what's the deal with that. Unfortunate no unity dev have confirmed the cause of the issue either on the forums at least that I can find. You could always file a bug report though there's a chance many have done so already on the same problem and they haven't fixed it to this day

tight compass
#

does anyone know why the size of the red colliders arent changing along with the radius etc of the collider components ? i'm using the physics debugger. my ragdoll seems to be influenced by the red ones and is giving wild results. ive set this one up manually after the ragdoll wizard was doing the same thing

#

also the colliders are not selectable with mouse select on

silver moss
tight compass
#

no animations and ive applied scale in blender

#

also i have realised they are selectable but I have to actually click where the green colliders are located and not the red part

#

not sure if a screenshot of the rig helps but here it is. @silver moss

tight compass
low magnet
#

Do you know why terrain made of tiles acts differently depending on the direction of movement when the player jumps while the terrain is above the player's head?
This problem does not occur in editor but only in webgl builds.

gray coral
#

Does anyone knows a better way to grabbing a physic object smoothly? I have tried using Lerp position and rotation, Fixed Joint and Spring Joint. The Lerp seems the more smoothly but still has glitches. My game is like Moving Out or Human Fall Flat but just the arms are controlled by sticks

dull jungle
#

If you want a physic-y feel you shouldnt lerp manually

gray coral
#

Is there a way to improve the physics engine to avoid glitches like when you grab the object against a wall? I twiked the rigidbody 'drag' and 'angular drag' but not sure if I am doing the right way

gray coral
#

Seems is working better now with a fixed-joint and adjusting some parameters, but now the Rig of the right hand is moving weird, Any ideas, this is my right hand constraint, any ideas?

spark grail
#

How do I do water physics?

soft prawn
#

Hey all, so I'm working on a motocross style game and the physics of the bike are killing me. Right now I am trying to implement a raycast system that keeps the bike above my terrain but all that happens is it attempts to and the falls through the world (the box collider on the bike is keeping it from free falling). Any tips on how to keep this bike from constantly falling?

royal willow
idle estuary
#

Hey guys

    {
        Vector3 forceX = orientationX * moveDir.x * currentAccelRate;
        Vector3 forceZ = orientationZ * moveDir.y * currentAccelRate;

        rb.AddForce(forceX + forceZ, ForceMode.VelocityChange);



        //Clamp
        Vector3 flatVelocity = new Vector3(rb.velocity.x,0,rb.velocity.z);
        if (flatVelocity.magnitude > currentMaxSpeed)
        {
            float fallspeed = rb.velocity.y;
            Vector3 n = flatVelocity.normalized * currentMaxSpeed;
            rb.velocity = new Vector3(n.x, fallspeed, n.z);
            if (Input.GetKeyDown(KeyCode.Space)) Debug.Log("Velocity " + rb.velocity);

        }
    }```

I have the code above called in FixedUpdate. While the included Debuglog does tell me the change of velocity was operated (maxSpeed set to 7), the player object still moves with a magnitude of approx 20 in game. Did I miss something ? In Midair (so without dampening) and when nothing is inputed, the intended effect is observed and the velocity is reduced to a magnitude of 7.  I don't understand why it does go beyond as clamp is done right after adding forces due to player input...
royal willow
#

does the rigidbody itself show a magnitude of 20 or does it show a magnitude of 7?

idle estuary
#

It shows a magnitude of 20 (and is moving at said speed) while the log display 7 at the end of the function BUT a log placed before the function shows a magnitude of 20...

#

There is no other place in the project that add speed to the rigidbody

royal willow
fresh palm
#

Hiya :3 I am am having some issues adding collision to my spider thing rig:

torpid hollow
#

does anyone know how to make the object with spring joint more dominant then the connected body, right now I want to make a balloon rope system like GMod and i want the connected body to fly with the balloon but I do not know how to do it, anytips would be appreciated (got it working by changing the mass)

red oriole
#

I have two wheels with Hinge joints that are motorized, and both are attached to the same boggie
but, when i start the simulation, the boggie starts spinning around the first wheel very quickly?

unique cave
loud ridge
hexed laurel
loud ridge
hexed laurel
frigid pier
# loud ridge I dont think anyone will.whenever I post in this server everyone ignores me.

To get an answer you need to post an answerable question.
Answer to

how can I make walking better I dont want this to happen
Is quite obvious one - set up animation and script it to work in a natural way and respond to movement.

No-one here will guide through hours of proper procedure of how to do that even if they know.
Your best bet is to find a tutorial that tackles this aspect and follow it. Or get an asset that already does that.

frigid pier
silver moss
#

I assume you are using joints for the legs. Make the animation animate the leg joint target angles?

frigid pier
#

Just adding legs shuffling around would work here.

#

That part should be scripted probably, you don't want rigid animation on that.

#

Simplest solution would probably be adding impulse force to joints one after another in the direction of movement.

hexed laurel
# loud ridge I dont think anyone will.whenever I post in this server everyone ignores me.

✅ Get the FULL course here at 80% OFF!! 🌍 https://unitycodemonkey.com/courseultimateoverview.php
👍 Learn how to make BETTER games FASTER by using all the Unity Tools and Features at your disposal!
👇
🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/courses
👍 Learn to make awesome games step-by-step from start to finish.
🎮 Get my Steam Gam...

▶ Play video
fresh palm
inner thistle
#

because nobody knows what "some issues" is supposed to mean

royal willow
#

you have to actually provide details so we can help, we are not mind readers

loud ridge
loud ridge
#

I though I wrote it but didnt know I forgot

#

I posted this question on another channel before maybe thats why I forgot

frigid pier
# loud ridge <:notlikethis:1068134558123442236> sorry https://hatebin.com/rivpipcygk

Seems to have a lot of problems, it looks like you are triggering leg movement every frame when you need to pulse them from time to time when body shifts enough from them. No idea what animations there suppose to do.
You are pushing legs there with a force multiplied by an incredibly small deltaTime number which makes no sense there.

Like I mentioned previously

Simplest solution would probably be adding impulse force to joints one after another in the direction of movement.
Designate leg space where each of them will be at rest. When body shifts far enough from any of them push one with an impulse force diagonally top-right or top-left to make a step. (or just animate knee movement to that direction and release)

fresh palm
loud ridge
frigid pier
static spruce
#

Hello.
I move both my player and the enemy using a Rigidbody and the AddForce function. If the player sticks to the wall and the enemy (who follows you) pushes, the player goes through the wall and ends up outside the room.

#

Is that enough information?

timid dove
static spruce
#

I don't want it to happen, of course

#

The player has collision detection already

timid dove
#

If course it has collision detection

#

I'm saying switch the mode to continuous

static spruce
#

Sorry, I meant the player has continuous collision detection already

timid dove
#

If it's going through the wall then you probably have some code that is not moving it via physics

#

or rather moving it via some other means than physics

#

What does "sticking to the wall" mean in your game exactly?

static spruce
#

Press up key and move upwards facing the wall

timid dove
#

Sharing videos, scripts, and screenshots might be useful

timid dove
static spruce
#

Give me a sec

#

Selecting the code that I was going to show made me realize what was the problem

#

Thanks @timid dove

frigid pier
#

probe trigger stay event to track it

frigid pier
#

Up to you to remember what was hit already

#

use a dictionary with coordinates as keys

#

you can optimize by remembering last hit not to access dictionary constantly

#

you can optimize by checking coordinates yourself

distant crater
#

So I try to use a Platform Effector for one way platform and it turns out I can just walk between the top and bottom just fine. I just want to walk on top. How do I make the game ignore the bottom

frigid pier
#

When particle coordinate moves by a tile size

#

Tilemap is uniformly square, you can easily calculate tile coordinate yourself, but GetTile method probably light enough and does the same.

#

YourWorldCoordinate divided by tile size will get you a tile coordinate.

frigid pier
#

You check only when you need to, when it stays collision

#

You check events only against collider you need

#

If it's a tilemap with a composite collider you are checking against, why would something overlap

#

what is overlap? If it's inside collider it triggers stay event, if it's not it's not

#

If your contact collider too large, use a small one then? Just for the point.

#

Collision coordinate is the coordinate of your bullet during collision event.

#

It's up to you to decide what point is a collision point on the object. If it's a fixed object you can just decide where it is manually, if it's a round object you can get point on outer radius opposite the direction it was travelling.

distant crater
frigid pier
#

You need to ask more descriptive questions. First one can be an empty game object on the bullet prefab placed on the point of the projectile, to easily get coordinates to check against. Second one is self explanatory.

distant crater
frigid pier
flint portalBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

wind meadow
#

question, do triggers count as part of the non-trigger collider's shape

#

so like i have a capsule collider not set to trigger and then i have a sphere collider that is larger than the capsule collider but is set to trigger, does that sphere collider count as part of the capsule collider's shape for stuff like ontriggerenter?

frigid pier
#

Why would they be, they are different colliders with different properties. Something you can easily check as well.

wind meadow
#

eye sea, cause...that seemed to be the case at least (triggers count as part of collider shape)

wind meadow
#

is there some kind of collision matrix i'm missing or?

#

slowly providing screenshots

#

both capsule colliders (as pictured are NOT set to triggers)

#

but the sphere colliders are set to triggers

#

yet they trigger the OnTriggerStay response

#

so unsure what's going on

timid dove
wind meadow
#

so rigidbody will call even if both triggers intersect?

timid dove
#

If you want OnTriggerXXX to work for only one collider, put that collider on a child object and put the script with the callback on that child only

#

You can also set such children to different layers and use the layer matrix

wind meadow
#

eye sea

#

guess i was surprised rigidbody allows trigger to interact with other triggers

#

given i thought the main feature/drawback was triggers cannot respond to each other

timid dove
#

Not sure where you got that idea

#

The main feature of a trigger is that it is not physical/solid

wind meadow
#

right

#

A trigger doesn't register a collision with an incoming Rigidbody. Instead, it sends OnTriggerEnter, OnTriggerExit and OnTriggerStay message when a rigidbody enters or exits the trigger volume.
I guess i misread this then

#

i guess the triggers are an extension of the rigidbody's bounds

timid dove
#

When they say register a collision they mean a physical collision/interaction

#

Where the motion of the Rigidbody is affecting

#

I.e. bouncing off

wind meadow
#

or blocking

#

i guess what i'm confused is

#

so the triggers if they're on the same gameobject as the rigidbody

#

count as an extension of the rigid body?

#

so if that trigger interacts with another trigger even if a non-trigger enters it, it will call the respective OnTrigger?

timid dove
#

All colliders on the Rigidbody or it's children are part of that body

timid dove
#

Yes

wind meadow
#

ok

#

now that makes sense

#

so if i move the trigger to a child of the gameobject

#

and that child has no rigidbody

#

then that trigger will only call its ontrigger functions when it collides with the capsule (defined as non-trigger)

#

assuming that other object with capsule ALSO has a trigger on child object and not the object with rigid?

timid dove
#

It will still be part of the Rigidbody but you will be able to put a script on that child object that will only get OnTrigger callbacks for that single collider

wind meadow
#

but basically

#

that trigger can still call ontrigger when up against another trigger then?

timid dove
#

Yes

wind meadow
#

if that trigger has a rigidbody either on itself or on teh parent

#

eye sea

#

well that's annoying but at least i understand why

#

question, how performant or non-performant would it be to call sphere overlap every fixed update?

unique cave
stray charm
#

i've never used unity physics before, does anyone have a good tutorial they can point me towards for getting a lantern in the player's hand to swing depending on the cameras movement?

#

reacting to wind too

#

assuming this is how i do it

stray charm
stray charm
wind meadow
#

cause it won't be just one gameobject

#

or really hundred

#

cause i plan on making an RTS and want to do a check if enemies are in range of the unit

unique cave
wind meadow
#

fair, what would you say is the better approach?

unique cave
#

With couple dozen calls it might not make a performance difference but the physics system is just not designed for that

wind meadow
#

so should i move it to update then?

#

no that's worse

unique cave
# wind meadow fair, what would you say is the better approach?

Would be worse yes. Usually you would just keep list of the objects to check and iterate over it to check the distance. If you only need to know whether something is in range, you can use the squared distance too instead of the actual distance (Vector3.Distance is somewhat slow due to square root)

wind meadow
#

Usually you would just keep list of the objects to check and iterate over it to check the distance.
I guess for every player troop, iterate through them to see the distance between each player troop to all the enemy troops on the field?

unique cave
# wind meadow > Usually you would just keep list of the objects to check and iterate over it t...

Basically you would replace each CheckSphere with the list iterated once. Depending there might be some better ways too and especially if there's a lot of enemies to check for, you may want to consider switching to quadtree/octree or similar data structure instead of list to speed up the search. The physics system uses similar data structures to accelerate the search but I wouldn't generally use the physics methods for checking something as simple as that

#

Profiling/benchmarking really is the only way to figure out any performance issue but I assume there are better ways than using a system that is not supposed to be used for that

half elk
#

Hey all, I'm working on a basic 3D mini golf game and I have all the typical things working, the course, the hole etc...

#

However, when applying force to the ball, it doesn't "feel" right

#

So between the ball, and the two physics materials

#

I'm wondering if there is anything obvious I'm missing

#

I know this is a little vague, but I'm happy to go into more detail

timid dove
half elk
#

@timid dove ( Ignoring the last hit where it goes off the world ) - I think maybe the friction is causing the ball to jump? Before I had no bounciness on the ball, but then I set it to 0.5. Maybe if I remove the bounciness on the ball and try to apply them to the wall colliders specifically?

#

Also, please pardon the design, I'm newer with asset creation :X

coral mango
unique cave
royal willow
#

Also for the bouncing, if you are using a mesh collider, check if it is actually flat as that might cause that issue

woeful egret
#

collider gets stuck inside ledges? Not sure whats happening here, i have a slippery material on both as well.

Note - if i make RB discrete detection this issue doesnt occur, however i cant have that due to fast moving preojectiles

timid dove
woeful egret
#

I’m physically passing through the mesh collider on impact and getting stuck

stray charm
#

i do have an issue now where if i move my camera quickly, the lantern fails to catch up and lags behind as seen here (where i'm spinning to the right)

#

there's only one hinge joint in use, not sure how to keep it so that lantern doesn't become seperated from its hand

#

how do i put a component into fixedupdate?

unique cave
stray charm
unique cave
#

You cannot set whether hinge joint uses fixedUpdate or regular update, it uses the former regardless

unique cave
stray charm
#

gotcha, that makes sense, just a communication then

#

doesn't solve how to prevent my issue though hmmm

unique cave
# stray charm

If the player is rotated in regular update as it likely is, you could really simulate the lantern movements yourself and not rely on the physics system if you don't specifically need physics for it

coral mango
#

Unless it needs collision, I'd agree that using a springbone script is likely easier.

soft prawn
#

Has anyone here every really messed with motorcycle physics before? I've been working on some for a while now and there are some aspects I would like to discuss and see whats going wrong

surreal oasis
#

Anyone here having problems with Physx in Unity 6000.0.25f1 LTS that the moving object disappears from scene when colliding with other objects in 3D space?

surreal oasis
#

upgraded to 6000.0.27f1 LTS but still having the same disappering problem of the ball, even I don't have any script that destroys it 😦

timid dove
#

It can only move things

surreal oasis
# timid dove Physx wouldn't destroy a GameObject

but is there any case where object destroys itself for no reason? Because I checked the scripts, there is nothing in there that Destroys it, downgraded it to 2022 LTS and still having the same problem. What should I do in physics settings?

#

the object that destroys itself, is a ball for a Pinball game

#

OMG, now i see that it was autodestruct enabled on trail renderer, omfg xD

#

yep, that fixed the problem, omfg xD xD

timid dove
white hound
#

anyone have settings for a humanoid ragdoll character joint?

muted brook
#

Anyone have ragdoll physics

royal willow
uncut anvil
#

Hey guys - Do you know why when I try to get my IK hands to grab onto this Rigidbody object and connect them with a Fixed Joint why it keeps floating in front of me?

#

For more context: My left and right hands have the fixed joint on them. When I hold left click, essentially the arms move up and the IK target moves to the object and makes the "Connected Body" of the fixed joint for each hand the object that I want to grab

runic warren
#

Is there a way to set up spring joints such that a certain axis of the rigidbody always lines up with the joint anchor?

#

for example, in my scene using the VR AutoHand package, I'm trying to make a slingshot that'll launch objects, with the spring attached to the handle of the slingshot's "cradle"

#

right now, I can hold it like this

#

but I can also hold it like this

#

I don't wanna be able to do that lol

#

for context, objects launched with the slingshot would be placed in the white sphere collider next the handle

#

and the anchor of the slingshot is the orange dot on the right

finite crescent
#

What is the best way to handle rigid bodies getting stuck on walls. A code example would be great 🙂

royal willow
finite crescent
#

Is using physics materials frowned upon? Or is this a good practice to do?

royal willow
# finite crescent Is using physics materials frowned upon? Or is this a good practice to do?

it is okay to use, but requires more effort or more setup to do than the latter in my previous message, Also an important thing I left out is you would want to do the AngleOfWall >= Threshold check whilst also checking if you are in the air as well, as it will ignore input's all the time even if you are on the ground. I'm also going off the notion that if you walk into a wall and keep on holding input whilst in the air, your rigidbody will get stuck as it is a common issue with movement

timid dove
finite crescent
#

Thanks for the tips everyone, much appreciated

serene ridge
#

Is there something like a spring joint, but for compressive forces? Or am I missing something about how its set up?

#

🙂 Or maybe I've over-complicating my code... I'm doing something physics based where I have a flat surface that I want to be able to press down a bit on one side, and have it bounce back to the regular position as if there were springs at the corners (really, it's more long the lines of those little rubber legs on a boardgame that give a little but go back in position).

#

I feel like this ought to be something that min/max distance on the spring joint ought to handle, but the fact that both of them say that it will apply the force to bring them together if the distance exceeds that amount...

finite crescent
#

Hi everyone, me again. I have this speed control and my move speed is set to 5. however in my debug logs velocity is coming out at 5.5? Any suggestions?

#

I am also aware that my bools do nothing rn

#

nvm Im thick af

royal willow
finite crescent
#

I want the player to shoot a shotgun and be propelled backwards. When I used the ForceMode.VelocityChange method the player just seems to jump backward not having any type of real smoothness. Obviously a shotgun shot is meant to be abrupt but not that abrupt. Any suggestions. Here is the current code:

#
{
    float angle = Vector3.Angle(GetPlayerMovementDirection(), GetPlayerLookDirection());
    float multiplier = (float)System.Math.Round(angle / 180, 2);

    if(GetPlayerMovementDirection().magnitude == 0)
    {
        multiplier = 1;
    }  

    if (OnSlope())
    {
        if (multiplier > 0.05)
        {
            maxSpeed = e.force;
            rb.AddForce(Vector3.ProjectOnPlane(-1f * GetPlayerLookDirection(), slopeHit.normal).normalized * e.force * multiplier * 5f, ForceMode.VelocityChange);
        }
    }
    else
    {
        if(multiplier > 0.05)
        {
            maxSpeed = e.force;
            rb.AddForce(-1f * GetPlayerLookDirection().normalized * e.force * multiplier * 5f, ForceMode.VelocityChange);
        }
    }
}
royal willow
#

you could try changing forcemode.velocitychange to forcemode.impulse

finite crescent
#

I tried that and it went ballistic

royal willow
#

what do you mean by ballistic

finite crescent
#

It just goes so fast that the player wont know whats happening

royal willow
#

try lowering the force you add to it

finite crescent
#

I have then it doesnt move at all it is very odd

royal willow
#

what did you lower it too

#

and what was it before

finite crescent
#

it was 20 lowered to about 5

#

it might be to do with my player mass as its currently 1

#

that did the trick

royal willow
#

yeah I was gonna ask about the mass of your rigidbody, glad you fixed it

finite crescent
#

what should the mass be realistically?

royal willow
#

the default mass should be fine 🤔 (you can play around with the mass if you want) Were you absolutely sure the force being applied on the rigidbody was 20 or 5 (using debug logs), or were you basing that off of the multiplier variable you have?

idle estuary
#

Hi there,

I have the following code called once each FixedUpdate.

        RaycastHit rayHit;
        if (Physics.Raycast(transform.position, Vector3.up, out rayHit, yVel * Time.fixedDeltaTime + buffer, wallNGroundLayers))
        {
            Debug.DrawRay(transform.position, Vector3.up * (yVel * Time.fixedDeltaTime + buffer), Color.yellow, 5);

        }
        else
        {
            Debug.DrawRay(transform.position, Vector3.up * (yVel * Time.fixedDeltaTime + buffer), Color.green, 5);

        }```
The resulting behavior is presented in the image below.
As you can see, the ray doesn't register the collision with the ground. he layerMask has been correctly selected and the layer correctly applied to ground. No red errors. Any idea on what to check next ?
timid dove
#

Also - is this a regular Unity Plane? It will only have one-sided collision afaik.

#

You're shooting the ray from below

idle estuary
# timid dove Also - is this a regular Unity Plane? It will only have one-sided collision afai...

It is a cube actually. I'm shooting the ray from the bottom of a "Player", in a upwards direction but with a vertical velocity that is negative. So in the situation on the screenshot, the transform position of said player if above the ground (outside any given cube). The layermask is set up as Serialized Field in code. The LayerMask is then assigned in editor (Image below) and all the cubes composing the "ground" per se have their layer set to "Ground" (image below).

timid dove
timid dove
idle estuary
timid dove
#

Since it's shooting up

#

And rereading this is looks like you're trying to use a negative maxDistance? Raycast doesn't work that way

idle estuary
#

It was my understanding that draw ray and raycast behave the same

#

my bad

#

Yep this was the issue 🙂 thx @timid dove

uncut anvil
#

Hey everyone, do you know why I'm unable to connect my hand's rigidbody to this Fire Extinguisher's configurable joint?

#

It clearly adds it (through script) to the connected body, but when I pull my player away, it doesn't stick to the hand

#

Trying it with a fixed joint works better, but not ideally, so I'm trying a configurable joint. Maybe a setting is wrong?

coral mango
uncut anvil
# coral mango How are you moving the player?

Sorry I didn't see this, man. I use this:

float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");

movement = new Vector3(moveHorizontal, 0f, moveVertical);

// Clamps movement so it doesn't go too high when going diagonal
movement = Vector3.ClampMagnitude(movement, 1);
kind mauve
#

I gave up having a one rigidbody on a player, now each subcollider have a kinematic one
The problem is
The main parent have a dynamic rigidbody with no colliders, it's the player basically, it's layer is arbitrary as I hope it doesn't matter
The child with a collider and a kinematic rigidbody
which meant to be colliding with the floor
(the layers of the floor and a child collider GameObject are meant to collide in the matrix)
Is not doing it's job of detecting the collision
any advices?

#

I guess kinematic colliders don't mean to collide?

#

this is.... infuriating

#

I was going to use that with a combination with Platform Effector 2D to only get collisions I want

#

So, everything is 2D
Long story short I want a player to have different colliders for colliding with different things
How do I meant to achieve that?

coral mango
kind mauve
#

also can someone explain to me how does layer overrides work on child objects having only a collider but not a rigidbody (parent have one)

#

do they work but assuming the rigidbody layer?

#

do they even ever work?

coral mango
kind mauve
#

so I guess the work but assuming the rigidbody layer

#

I ve spent to many time going back and forth trying to figure out how to make such usual thing

#

Should I make a parent body having a no collisions layer and give it the collision managing script and include layers I need on childs with no rbs?

uncut anvil
tight dock
#

Hello

#

I've been dealing with a problem with ragdolls, that is, I can't seem to get them to be the least bit good looking

#

New project, ubiquitous avatar, default ragdoll wizard settings, and it freaks out horribly

#

I'm using unity 6 but I doubt that would mess up physics

#

So many videos online use this same avatar and ragdoll wizard look great, or at least playable

#

here and here

In this video we're going to look at how we can implement Ragdoll physics in Unity.

First of all, we’ll look at how to configure a ragdoll for a character and then we’ll look at how to activate the ragdoll when the character's killed.

We’ll also look at how we can target specific body parts and have that affect the Ragdoll

The project files a...

▶ Play video

Learn the creation workflow for Ragdolls in Unity, how to toggle between an Animator and Ragdoll, and think through some optimization ideas when you have a large number of potential ragdolls in your game!

Ragdolls are a hugely popular mechanic in games that add, usually a funny mechanic into your game. What they always do though, is allow you t...

▶ Play video
#

They pretty much just do this and it looks infinitely better

#

That's my lesson to never use a fucking pre-release ever again

timid dove
#

Looks like it's been fixed no?

tight dock
#

Yeah I updated to .28f1 and it seems to be okay now

#

Still gonna avoid pre-releases from now on, I just thought that they were problematic for large studios, not the everyday user

timid dove
mossy swan
#

Hi, figured this might be the best place for this. For those that have implemented raycast bullets that move over time (not instant), did you ever encounter the issue where you could "miss" thin or fast moving objects, due to the fact that the raycasts aren't part of the main physics update? So on Frame N, your bullet would move forwards and end just in front of a thin object moving in the other direction. Internal physics update then runs and moves that object forward, putting it "behind" your bullet... and then on Frame N+1, your raycast now starts ahead of the object and therefore "misses" it. Are there any clever solutions for this? I'm currently thinking of just starting the raycast from the previous starting position and basically make the raycast twice as long. It's still not a perfect solution mind.

inner thistle
#

do the raycasts on FixedUpdate

mossy swan
#

I am. That's not the issue. It's the fact that they aren't part of the main internal physics update, so one still happens after the other.

inner thistle
#

It won't cause the issue the way you're describing it then

mossy swan
#

It really does. Note this is not an "infinite" one frame raycast... this bullet is moving over time.

inner thistle
#

I don't doubt there's an issue, but the internal physics update runs in the same step as FixedUpdate so your code can't be out of sync if it's also in FixedUpdate

mossy swan
#

I'll get a diagram together, it's probably easier to show that way.

mossy swan
inner thistle
#

Is there a reason it's using raycasting instead of physics collision detection? Setting collision detection mode to continuous would solve the problem. With raycasting you'd basically have to re-implement continuous collision detection manually

mossy swan
#

Yeah, these bullets are not rigid bodies. They are just positions and velocities basically. Don't want the overhead of making them full rigid bodies. It's pretty common for bullets to be implemented as raycasts, so hoping others have encountered this issue.

silver moss
# mossy swan

Maybe in the second frame you could raycast the first frame's path again?

#

Thats something i have thought but gotta experiment with a bit. It should also make hits more forgiving so sniping moving targets should get easier

#

Another scenario you have to consider is when the bullet ends up inside the enemy between updates. Raycast wont detect colliders that it starts inside of, so an OverlapSphere before raycasting can be used to fix that

lost current
#

random question fellas

#

so I'm trying to remake a couple player movement controllers I made for a sidescrolling 2D platformer & I want them to like, not constantly set the rb's velocity to a specific value (as most player controllers do from what I've seen online)

#

is there a way to do that without having it feeling weird?

mossy swan
# silver moss Maybe in the second frame you could raycast the first frame's path again?

Yeah that's where I'm currently at. Thinking about just making the raycast start from the bullets previous starting position. It's not perfect because the other object could be moving even faster and "jump" that entire raycast too... But at the same time it should be possible to roughly know what the fastest speed an object in your game can travel.

mossy swan
idle estuary
#
    {
        if (depth == 0)
        {
            return (startingPostion, initialVelocity); 
        }
        RaycastHit wallHit;
        Vector3 targetPosition = startingPostion + initialVelocity * Time.deltaTime;

        if (Physics.CapsuleCast(startingPostion + new Vector3(0, GameData.playerThickness, 0),
                        startingPostion + new Vector3(0, GameData.playerHeight - GameData.playerThickness, 0),
                        GameData.playerThickness - GameData.collisionBuffer,
                        initialVelocity.normalized,
                        out wallHit,
                        initialVelocity.magnitude * Time.deltaTime + GameData.collisionBuffer,
                        wallNGroundLayers
                        ))
        {
            Vector3 newTargetPosition = startingPostion;
            float distanceToNormal = Mathf.Sin(90 - Vector3.Angle(-initialVelocity, wallHit.normal)) * wallHit.distance;
            if (distanceToNormal > GameData.collisionBuffer) //the player is not presently against the wall so we snap them to it.
            {
                newTargetPosition = startingPostion + initialVelocity.normalized * wallHit.distance /*+ wallHit.normal * GameData.collisionBuffer*/;
            }

            Vector3 vectorToProject = targetPosition - newTargetPosition; //the remaining velocity vector that we have to project
            Vector3 newVelocity = Vector3.ProjectOnPlane(vectorToProject, wallHit.normal) / Time.deltaTime * GameData.wallSlidingDeccel;


            return CollideAndSlide(newTargetPosition, newVelocity, depth - 1);
        }

        //we hit nothing
        return (startingPostion + initialVelocity * Time.deltaTime , initialVelocity);
    }```
I'm looking for critics/ review for my code for Collide and Slide algorithm. Things works only in very specific conditions and I don't know where I went wrong here.
#

ScreenShot is clearer

stuck bay
#

Actually, is it okay to constantly manipulate this? Physics2D.queriesStartInColliders = false;

tender vapor
#

there's no wavedash code in here at all, just a dash, and the ground collision handles the sliding

#

you can tune it with drag, friction, bounce, etc

cunning wigeon
#

idk

#

it doesn't look like wavedashing to me but i might be wrong ig

tender vapor
#

im basing it off what i see from ssb

#

the basic logic is the same, vertical speed is transferred into horizontal speed, celeste's technique seems to incorporate a jump into that to get airtime

abstract lily
#

Okay so does anyone have a tutorial to understand how character joint work... Cause one thing that made me fear making physics game is the character joint, The arrow that should explain don't match up the limit i set. And it just confuses me so badly

#

I don't know why it like this

#

it just horrible

elder peak
#

HI, i need help with a small probleme i have, my player collider right now use a capsule collider, the issue with this is when i walk on narrow edge the player will slide of the edge. what type of collider can i use to be able to walk on a pixel wide edge? im trying to mimic the movement of csgo kz game mode. thank you

#

i tried to use raycast to detect the edge of the ground but it does weird thing like making the player jump 3 time as high as normal and other stuff

timid dove
timid dove
elder peak
timid dove
#

Depends how good you are

elder peak
#

right, that kind of was a dumb question of me XD

#

but its possible to make it smooth right

brittle crown
#

So i have a ragdoll where the Bones are parented to each other, and this causes bugs when making a child bone Kinematic, if i unparent all of them: Would the Rig still be the same?

timid dove
brittle crown
#

So if i make a child Kinematic and move a parent, it bugs like ALOT and starts spinning and going crazy, ill make a screenshot

#

Yeah the ragdoll just goes crazy

brittle crown
#

I just checked and it also happens when just not moving the parent

#

but all i really wanna know is if the Rig Stays the same if i unparent the Bones?

timid dove
#

No - the skinned mesh renderer depends on the hierarchy

brittle crown
#

Alright, Thanks

uncut anvil
#

Hey guys - Do you know how to close the gap between a Fixed Joint and its connected body? When I attach mine to the hand of my guy (left hand in screenshot), it always has a gap between the object and the hand.

I just add the fixed joint when it hits a small trigger (sphere) around the hand, which has a radius of .25

uncut anvil
#

Code for attaching Fixed Joint

// Check if the collider is interactable
if (collider.CompareTag("Interactable"))
{
    grabbedObj = collider.GetComponent<Rigidbody>();

    grabbedObj.AddComponent<FixedJoint>().connectedBody = lHand.GetComponentInParent<Rigidbody>();
}
uncut anvil
#

If the arm swings by anything interactable, it grabs it

uncut anvil
#

Idk how I would do that with physics though. Raising the arms, that is

#

Right now I have a rigidbody ragdoll that I use to move my player. Everything else is moving via physics

#

I'll try messing around with the anchors though. Thanks again Praetor

stuck bay
#

I assume theres no way to simulate physics at different rates for different objects?

  • this can be done with physicsScenes but then they cant interact with each other iirc. And i need that functionality
exotic coyote
#

Anyone here done car collisions before with rigidbodies i am having sticky and rotation issues

unique cave
timid dove
vast rose
#

Hey guys, a question, I made a script to throw objects in a certain direction calculated by a raycast from the camera, everything works perfectly except when the character looks down, the rigidbody can't get enough force horizontally to reach the point, why ?

#
        Vector3 forceDirection = (itemHolder.transform.position - targetPosition).normalized;
        Vector3 horizontalForce = forceDirection * throwForce;

        // Add a fixed vertical force to create the arc
        Vector3 verticalForce = Vector3.up * throwUpwardForce;

        // Final force to be applied
        Vector3 forceToAdd = horizontalForce + verticalForce;

        // Apply force to Rigidbody
        itemRigidbody.AddForce(forceToAdd, ForceMode.Impulse);
#

(the target position in this case is the camera raycast)

#

the item holder is positioned to the right in the player's view

timid dove
#

A - B gives you the direction from B to A

#

Second - you're basically just fudging things here

#

I don't know exactly what the end goal is here

#

but if your goal is a perfect parabolic arc that lands at the target, you need to actually do the math to calculate the ballistic/parabolic trajectory to give the correct initial velocity.

vast rose
timid dove
#

the only effect of AddForce is to change the velocity.

#

So you should do whatever is simpler for you

#

which is likely assigning the velocity.

vast rose
#

Perfect, thank you very much for your help!

glass bramble
#

hi
i am begginer and i was creating my first level using probuilder.
but when i hit walls the charcter randomly goes up and stop usally and the top of the level
i tried and when i put a norrmal 3d cube it does not do that
also my walls and ground are all the same object
what should i do?

woeful egret
#

when i slide, i set collider size to be smaller, for some reason the collider goes through the floor for 1 to 2 frames.

(This also causes me to be not grounded which ends slide.)

Anyways just wondering is this a bug with capsule colliders? Or a known issue? The collider im standing on is just a box collider.

vast rose
vast rose
#
        Vector3 displacement = targetPosition - itemHolder.transform.position;
        float distanceHorizontal = new Vector3(displacement.x, 0, displacement.z).magnitude;
        float flightTime = Mathf.Sqrt(2 * distanceHorizontal / gravity);

        Vector3 horizontalVelocity = new Vector3(displacement.x, 0, displacement.z).normalized * (distanceHorizontal / flightTime);
        float verticalVelocity = (displacement.y + 0.5f * gravity * flightTime * flightTime) / flightTime;

        Vector3 finalVelocity = horizontalVelocity + Vector3.up * verticalVelocity;

        itemRigidbody.linearVelocity = finalVelocity;```
timid dove
vast rose
#

I researched and this is the formula I found

#

I'm using the same formula to draw the trajectory, and it seems correct, but the rigibody doesn't seem to obey

timid dove
#

that's the formula for calculating how long something will be in the air for a given starting vertical velocity

#

the horizontal velocity doesn't make sense there

#

or actually it might even be the formula for calculating the maximum height achieved?

#

Either way it doesn't really make sense there

vast rose
#

Man, I hate game dev sometimes

#

As I said, my formula is not wrong because I am using the same formula to draw the path, and the path is normal, it had to be something to do with the rigidbody

hoary kelp
#

Not sure in which channel to ask this but I'll ask here since It's about physics. So I run into a "problem" that when a characeter jumps near a wall, then it would have friction, I added a 0 friction material to my character (which is only a capsule for now). Will I run into problems later? I'm still learning unity

timid dove
#

if you don't, you won't.

hoary kelp
#

well, I'm not seeing where I would need that, but for example, let's say I make a terrain where the players needs friction. I could just add an if that adds friction to it when on that terrain no?
But I'm thinking super ahead right now

timid dove
hoary kelp
#

yeah, I understand! thanks

gray sentinel
#

As far as physics are concerned, submarines would effectively use the same rough model as aircraft with the additional effects of buoyancy right?

royal willow
#

If you mean are the physics of an aircraft and submarine the same, no they are not. If you are talking about would they look the same, no they would not. I'm not entirely sure what you mean by "same rough model" as they would be made to fit the physics of each vehicle

gray sentinel
#

Dang ok.

#

I haven't played with physics much, but I was looking at putting together some physics assets from the store so I could have ground vehicles, boats, submarines, planes, blimps ect and everything in-between. Not looking for flight sim levels of detail here but just trying to get an idea of how that would work and how to think about it.

#

Have to identify the discrete systems and they have to interact with each other in a functional way.

royal willow
#

Each system is its own thing, they may be "similar" but they will be entirely different on how it actually works (e.g how the foils on a sub are "similar" to airfoils)

gray sentinel
#

I'm not going for super realistic either, so in the approximation, the fluid dynamics of a subs dive plane wouldn't be much different than that of an aircrafts elevator right?

#

You end up just applying a directional/rotational force based on the deflection of the control surface which is then multiplied by some coefficient of it's velocity?

royal willow
#

well air acts like a fluid so yes they act the same

#

they try and produce the same effect, I'm an aviation guy so I don't know a deep dive into submarines

gray sentinel
#

" deep dive into submarines" har har

royal willow
#

I was not even planning that lmao

gray sentinel
#

excluding them as a control surface, I woudl think that a submarines dive plane or any of it's static planes would be a symmetrical airfoil with no angle of attack

royal willow
#

if any of its foils are level, then sure I guess you could say it has no AOA (AKA 0)

gray sentinel
#

no AOA relative to the shape of the vessel I guess

royal willow
#

well AOA is the chord line to the relative to the oncoming wind, but I guess you could change that to oncoming water? I have no clue

#

They probably have some new terminology for it

gray sentinel
#

I think there is a bit less to worry about when it comes to water, as flow seperation isn't much of a thing?

#

and I don't want to deal with cavitation

#

So what I need is an asset for some good driving physics with tires/tracks. a decent asset for aerodynamics that I can use a simplified version for water, and an asset to address bouyancy

#

ohhh.. a blimp would also use bouyancy

#

in order to make blimps work you need air density at different altitudes

royal willow
#

I used this before and it was quite good, there are also other github assets out there but I have not tested them

#

as for buoyancy there are some unity tutorials that have wave buoyancy (if you want waves that is, recommended for semi realism/arcady to actual realism)

gray sentinel
#

I'm not 100% sure I want waves

royal willow
#

you want like a flat plane?

#

maybe with a shader on it to look like water

gray sentinel
#

Yeah a shader, I'm just wondering if the gameplay impact would be beneficial or detremental

#

Turrets on a ship would have a harder time in rough sees, but something on land shooting at a ship wouldn't

#

it would be a heavy environmental impact on balance that is assymetric between land/sea and air

#

I guess if I have the sea's be always consistent it would be easier to balance against it

#

That SimpleWings looks good

#

The other asset on the store I was looking at went a bit too in depth on airfoils so this might be better

royal willow
#

oooh you are making a battle scenario using land vehicles/aircraft/watercraft? If you make waves happen in the open sea and not near the shores it would be harder to shoot other enemies, if you just make it a flat plane but a lot of terrain it would heavily depend on how big the terrain is and the placement of it

#

you would have to test though as it would depend also on the ships speed, fire range and among other things

gray sentinel
#

Yeah, something similar I guess to From The Depths, but without it's nightmarish building system.

royal willow
# royal willow you want like a flat plane?

if you do go the flat plane route, the buoyancy is much easier to implement as you do not have to do any calculations for the current wave height to move the object up and down

gray sentinel
#

That's true

#

I'm thinking of going with something in the asset store for bouyancy and see if it can fit my needs

royal willow
#

yeah the asset store or github

#

github has some gems you can find

gray sentinel
#

hmm I'll take a look there

#

I haven't done too much 3d, so this project is probably out of scope for me, but I'll see how far I get I guess

royal willow
#

just don't burn yourself out, Also try not to get stuck on a certain thing for to long

gray sentinel
#

I mean, that's what's kililed the last 3-4 projects I've done

#

There is always something complicated I try to setup and I get burned out on it

#

I haven't scoped this project much, I'll probably make a prototype and realize that it's too much and go back to making something in 2d lol

#

Anyways, thanks for the info

royal willow
wraith berry
#

Hi guys im trying to make a fishing line with joints and collision to realistically simulate it, spring joints are just giving me grief is there any other joints people might reccomend

bleak umbra
wraith berry
wind charm
#

i'm building an ar drone game where user need to fly drone passing though some obstacles. here's my collission setup, the problem is that. when the drone touch the sphere in the middle of the obstacle, it just don't move maybe because of the rigid body, but still it should trigger ontriggerenter since i use isTrigger for the sphere collission but it didn't do anything, i add log but there's no log

#

it only trigger when the edge/line of drone box collider touch obstacle's edge/line of the sphere collider. why is that?

silver moss
pale mist
#

the one on the left is for PC while the one on the right is for mobile

silver moss
#

My understanding is that PhysX is not deterministic across devices

#

Anyway, the difference in your video is pretty massive so I don't think it's just a determinism issue

timid dove
silver moss
#

Perhaps your code is framerate dependent

timid dove
#

But yeah most likely it's that ^^

#

I.e. adding forces in Update

pale mist
#

dphysics

silver moss
#

I know that there's DOTS physics, Havok, and Bullet available

#

Those are either deterministic or have the possibility to be

#

In any case could you show the code you use for jumping before we talk different physics engines 😄

pale mist
#

Ooh I heard of bullet sdk, I thought it was only for python or self-built for c projects

#

Ill look into it

#

I'll look at my other code again though

#

i might have to git blame someone today

#

thanks for helping me

silver moss
#

Like can you hold down the button and it applies it every frame?

pale mist
#

and since it's called in update it did become framerate dependent

silver moss
#

Right, that's the issue

#

You should add the continious force in FixedUpdate

pale mist
#

yep ill do that 🙏

silver moss
#

How is the stick following the cursor?

#

What components are you using and what does the code look like?

tranquil bridge
#

Is there a way to make a 2D physics material not multiplicative, but a maximum instead like the 3D ones? I'm trying to let a player collider with 0 friction to interact with a slope collider that should be stopping it completely

#

nevermind ig 2D doesn't have that option, guess I'll have to implement that myself

coral mango
#

Or just add an invisible wall

loud ridge
timid dove
#

so to cancel it out, you could calculate exactly what the force would be that you're exerting on the player and apply an opposite force manually.

zealous violet
#

Hiiii, I am a unity beginner, i am confused how to make two object collide with each other

lone frost
#

hey so i got a project file which converts 3d model/animtion into pixel art sprite sheet
here is the link:-https://www.youtube.com/watch?v=kALXAWSDYEo&t=5s

but i need to use legacy rig for this to work and when i convert my fbx into legacy rig it becomes invisble like shown in the images but is visible in any other rig mode
how can i fix this please?

zealous violet
frigid jetty
timid dove
zealous violet
#

okay thanks i will check that

rain citrus
#

Hi. I'm using Unity Physics 1.3.8 and when I disable Automatic Tensor on the rigidbody, I get fields to enter a custom tensor. But whatever I enter there, nothing changes in the simulation. I can set it to zeroes and it requires a lot of force to start rotating and I can set it to 10000s and it still behaves the same. With Automatic Tensor enabled, the spheres can be rotated with much less force already. Is it expected that these fields have no effect?

frigid jetty
rain citrus
frigid jetty
#

if it's still rotating then it's not implemented

wind quail
#

i have assigned the children of the prefab to that layer too

rain citrus
timid dove
wind quail
#

wait

timid dove
#

since it says cloth, I assume it's 3d

wind quail
#

yes

#

thanks haha

stuck pollen
#

Yo im trying to make a dash and since nothing I do seems to be working lol i decided to ask chat and it came up with this that also doesnt work(its supposed to dash on z):

#

Any helpers in chat?

timid dove
runic warren
#

What's the most proper method of applying counter-rotational forces? For example, if I have a object meant to act as a motor spinning some blades around in a circle, I want the motor itself to also be trying to rotate the opposite direction

runic warren
# timid dove AddTorque

Follow up question, is there a way to lock the rotation axis of those blades to the object they're parented under without using joints? freeze rotation is locking the rotations relative to the world instead of locally

timid dove
runic warren
#

at least for what I'm trying to do with it

latent oar
#

Hello, I've been messing around with unity for around a month now and I was wondering if there's a generalized best practice when it comes to gravity.

#

Should I use the inbuilt gravity system attached to rigidbody component, or would it be better to simulate gravity using my own system?

#

For context, this is regarding a 2D platformer

royal willow
#

you can use the built in gravity system unless you need a custom one (i.e. custom gravity directions)

timid dove
#

General best practice is to use the built in gravity unless and until it fails to meet the needs of your game.

narrow quiver
#

every time i joint many objects together they start flying

silver moss
narrow quiver
#

ok so firstly i have set of objects with rigidbodies that in runtime generate themself shape to pick

#

then i scan for everything that touches and assign connector between them, which is 2 configurable joints with all motion types locked

#

the more pieces i connect the more destructive it gets

silver moss
#

Having 30+ interconnected joints is probably never a good idea

#

Is this for the destructable car you mentioned? Why not just have them as children (without rigidbodies) and add the rigidbody to the part when it detaches?

#

Like I suggested before

#

Also note that rigidbodies should not be children of other rigidbodies unless the child is kinematic

narrow quiver
#

how i would make wheel without children?

#

also i probably can make on parent but then joint break force wont trigger

silver moss
#

Are you using actual physical, rotating wheels or what?

#

In any case a non-kinematic rigidbody should not be a child of another rigidbody.

narrow quiver
#

ones that start spinning and move car along when adding force

#

wheel colliders bad since they only work on raycast down

silver moss
#

So how is that related to what i said

#

Why do you expect that the wheel has to be a child

narrow quiver
#

since i cant really make wheel prefab otherwise

#

i should keep all parts loose somewhere?

silver moss
#

They can have an empty parent

#

Like actually empty, no rigidbodies or anything

#

And do not move that empty parent

narrow quiver
#

i assume so since constraint does all work moving them already

#

didnt know parenting changes that much

silver moss
#

Parent-child relation moves the child's transform and this will conflict with the rigidbody trying to also move it

silver moss
# narrow quiver yes

I would just use non-rotating wheels and add the forces manually, depending on if the wheel is on ground or not

#

But if you can get physically rotating wheels to work reliably then great

narrow quiver
#

they worked at the point where i was jointing everything to single rigidbody

#

now instead im connecting between 2 different ones each time so i need redo wheel mechanic once again

#

ok but now

#

that gives me networking issue

#

how would i allow rigidbody physics to be networked then

#

if im syncing x gameobject position

#

another constraint for every object to hold onto these objects?

grizzled tundra
frosty ore
grizzled tundra
#

ah okay thanks

frosty ore
#

the fact that ur colliders are nested inside hte graphics may be the issue

#

havent ever done a bike.. but im guessing its pretty similar to the =same issue

frosty ore
#

always makes wheels YEET

silver moss
#

The wheel collider modifiers the world pose -> you assign the world pose to the graphics -> wheel collider is child of graphics

#

So it is a feedback loop

frosty ore
#

thats the technical jargon i lack ^

grizzled tundra
#

ah i see, wheel go yeet cos of recursive

frosty ore
#

bet!

#

makes a good clip tho 🤣

grizzled tundra
#

🤣

#

i suppose i have another issue now....the wheel dont spin right

#

this is all for the rear wheel, the front is the same issue

frosty ore
grizzled tundra
#

yeah i cant win here

frosty ore
#

heres what u may have to do.. (wheel colliders work best with objects that are scaled 1:1:1 with the pivot in the center)

#

you may need to make a gameobject as the wheel (an empty) and adjust the graphics soo that the wheel is centered..

then that empty gameobject acting as the wheels main object now has as scale of 1:1:1 u can use it instead of the actual mesh

grizzled tundra
#

ah okay

frosty ore
#

alot of models have shitty wheels..

#

artist dont take the time to make sure the pivots are correct

grizzled tundra
#

i am said artist rn 😅

frosty ore
#

thats even better tbh..

#

u can pull it back into ur modelling software and edit the pivots a bit better

#

also apply the scale to zero it out.. (1:1:1)

grizzled tundra
#

oh boy a new thing i gotta learn rq 😅

frosty ore
#

its easy do u use blender?

grizzled tundra
#

yeah

frosty ore
#

i can show u real quick..

grizzled tundra
#

please

frosty ore
#

for the pivot u can just select the wheel and set origin to geometry.. If its a true circle.. it should get pretty close to center

#

for the applying the scale.. u just select the object in object mode..
Ctrl + A then Apply -> Scale

#

then when u re-export the wheel should have a scale of 1:1:1

#

if its not.. it may be because its nested inside the whole object (bike) and it may need its scale applied so it becomes 1:1:1

#

funfact: (always make backups)

#

u can check visually w/ the Info tab on the right...

#

should show u both the Scale u currently have... and the actual dimensions below it

grizzled tundra
#

i think ive done it

#

done it to both

frosty ore
#

yup.. says 1:1:1 now..

#

and u should be able to rotate it in the scene perfectly if its origin matches the center

grizzled tundra
#

u are a life saver honestly

#

so glad i asked for help now

frosty ore
#

remember to utilize these too

#

u can change what origin ur using to rotate and whatnot.. and next to it <--u can change from global to local.. to make sure stuff looks as it should

grizzled tundra
#

gotcha

#

i use those quite a bit

frosty ore
#

good, good.. welp good luck 🍀

#

gotta get to work myself

grizzled tundra
#

thanks a bunch

grizzled tundra
#

hey guys what do i need to adjust to stop the bounciness of the suspension?

#

also bounces when my character isnt mounted

spare valve
#

is there a way to make a 2d collider from a mesh?

edgy hamlet
#

does two object collide without rigidbody? i just want them to stop when they hit

spare valve
#

i thinnk collider without rigidbody is ment to be static

edgy hamlet
#

i see, so same apllies for multiplayer i guess

#

i need to setup with physics enabled

silver moss
spare valve
#

thats what i was doing but i was wondering if there was a nother way

grizzled tundra
twin nebula
#

I'm assuming that unity just adds the velocity onto the position in the next physics step right? Assuming there's no drag and stuff

#

I'm trying to predict where my rigidbody controller will end up because it keeps hopping up and down on slopes

grizzled tundra
timid dove
twin nebula
#

Thank you 🙏

orchid sinew
#

Hey guys, I'm trying to set the player on fire when they touch the red object but it throws itself out of the sphere when it touches the first time. Anybody know why?

timid dove
loud ridge
#

I cant make weapons trigger because I want them to collide with shields I have and othr weapons.

narrow quiver
#

if car is heavy and im pushing it with 1 force will i be able reach same force (for example 10) and car will be slower while force remain the same?

timid dove
narrow quiver
#

im using addforce()

#

perhaps i should be using something for velocity instead

timid dove
#

they are related concepts but your question makes no sense

#

so I have no idea what you're asking

narrow quiver
#

im not sure to which one im refering

#

but what i was asking for is if car is heavier does it have to go with slower speed to reach it

royal willow
#

yes that is how physics works, F = M * A (newtons second law) so the heavier the car is the longer it will take to reach top speed

#

if you set the velocity directly, it will immediately reach the desired speed which is unrealistic (unless of course you ease the value to the desired speed but this is more of an arcady approach)

narrow quiver
#

no i wanted to do something like

#

im applying constant 1 force from behind

#

but i noticed it doesnt do it consistently

#

instead it accelerates

#

so i wanted limit it to for example 10 force max

#

but also wanted to limit it based on how heavy car is

#

so if its heavier then max speed is lowewr

royal willow
#

so all you want is a constant force but incrementally increase that force until it reaches a force of 10 (or based off of the weight of the vehicle)?

#

or do you want add a force to the car and clamp the max speed of the vehicle to 10?

timid dove
timid dove
#

increase that force until it reaches a force of 10
This is a completely meaningless statement. Force does not "reach" anything, nor does it build up over time

#

it is something you apply immediately with the AddForce call.

royal willow
#

yes I know, I was asking if they wanted to increase the force that is currently being applied to the vehicle over time, the question they are asking does not make sense

narrow quiver
#

so if rest of car is heavier the limit is lower

royal willow
#

so all you want is to do is to make the max speed of the vehicle based off of the weight of the vehicle?

narrow quiver
#

i simply want acceleration curve to fit in 1 second

#

it takes me like 10 secs to reach max speed

timid dove
royal willow
#

you could have just said that

timid dove
#

and mass will be factored out of the equation entirely

narrow quiver
#

i thought that isnt what i want because it ignores mass

timid dove
#

that's exactly waht you want

#

it doesn't ignore mass

#

it handles the mass part for you

#

so that you can ignore mass

#

internally it is multiplying the mass into the force it applies to cancel the mass out.

narrow quiver
#

well i think it works better now

compact rampart
#

Hey, does anybody know how to make a physics material for ice in 3D? (I'm using Unity 2023.1 LTS btw, not Unity 6)

silver moss
sonic jetty
#

I can't seem to figure out what Unity changed the "Used by Composite" option to in Unity 6 on the Tilemap Collider Object. Has anyone been able to figure out what the same functionality was moved to? Would it just be the "merge" operation?

compact rampart
silver moss
#

@compact rampart And probably Friction combine: Min

compact rampart
silver moss
#

Set dynamic and static friction to 0

#

On the physic material

twin nebula
#

I have a configurable joint setup and I was wondering how I could let a rigidbody move freely but have the joint keep it a minimum distance away from the connected body

#

So for example if I wanted a max distance of 5 units the rigidbody could move as close as it wanted but no further than 5 units

#

I tried linear limit but the limit seems to do literally nothing

#

Either it does nothing or it's extremely inaccurate

#

I also want it to be a hard limit not some sort of springy stuff (although it can be a tad springy)

distant crater
#

So I'm having issues with slopes and I'm going nuts about it.

silver moss
#

And how are you moving the rigidbodies?

twin nebula
twin nebula
#

If you want I'm happy to share the movement code as a base

silver moss
#

Yeah show the code

twin nebula
#

Alr give me a mo

#

Actual movement of the collider is between line 57 and 66

silver moss
twin nebula
#

Player is just the container main collider is the rigidbody

#

Linear drive does.. something? It's like the hand becomes limp on the floor and will randomly decide to go to where it should be

silver moss
#

I can't see anything wrong from a quick glance:
-Joint limits seem ok (although I didn't work with joints in a while)
-Code seems ok - you are moving the rb with with forces

#

It's worth to try adjusting Mass scale/Connected mass scale

silver moss
twin nebula
#

Dang mass scale was a good call

#

I've changed the limit to 0.1 and changed the mass scale to 10 (so the player isn't dragged around by the hand as much) and it looks a lot more stable

silver moss
#

Oh nice

twin nebula
#

But unfortunately it just crumbles the minute use gravity is enabled

#

I probably should've tried that before sending that message

silver moss
#

Let's step back a bit, what are you trying to accomplish here?

#

Like what game mechanic

twin nebula
#

I'm trying to have the left hand (the ball) attach to the main collider and act as a floating physical hand that I can attach to objects

#

Instead of it being hard locked at a certain distance from the main collider I want it to retract but have linear limit sort of cap how far it can extend out

silver moss
#

I see.
The "Player" object is not moving at all, correct?

twin nebula
#

Yep

#

If worse comes to worst it wouldn't be a bad idea to write my own sort of cap instead of using a joint I guess. That way I could keep the hand completely separate from the main collider and decide whenever the hand can influence the body

silver moss
#

Yeah, controlling the hand rigidbody manually is a good option too

#

It's definitely doable with joints but maybe a bit overkill

#

And can be tricky as you noticed...

twin nebula
#

Yeah lol I hate joints sometimes but they can be awesome

#

Well thank you for the insight and I appreciate the help

distant crater
twin nebula
#

It snaps up and down steps / stairs and wont shoot off slopes

#

I didn't give everything so that movement isn't just drag and drop (and you'll probably have to get rid of a few network related things in it)

distant crater
#

ok, i'll check. thanks

twin nebula
#

Was just to kind of give an idea but if you need help setting it up lmk

#

No worries#

honest river
#

Trigger collides and calls OnTriggerEnter2D with another trigger of a layer that I disabled in project settings.

#

Character GameObject: Rigidbody2D, BoxCollider2D(Trigger enabled), Layer: Character
Gate Goal GameObject: Rigidbody2D, BoxCollider2D(Trigger enabled), Layer: Gate Goal.

In the physics Character and Gate Goal are disabled. Yet, it collides and generates events.

timid dove
#

Also make sure there are no other colliders on the objects

honest river
#

Ah I see yeah I was changing 3D settings

#

Thanks

#

So there is no way to have the same collider to intersect with some layers and block other? I'll have to setup different colliders to block and intersect and make them the child game objects of the main game object?

uncut anvil
#

Hey guys question from a failed attempt by me -

How would you guys go about attaching a rigidbody to the hand of a player character?

I've tried using a trigger on the hand and "on enter" creating a fixed joint on the item that attaches the hand as the connected body. However, whenever I do that, the object is always flying around unpredictably.

I'm open to any ideas you guys may have.

serene flower
#

making it kinematic, forces, collisions or joints will not affect the rigidbody anymore. So it wont be flying around

uncut anvil
serene flower
#

Depends on ur game and how do you want it to feel

uncut anvil
#

Rather than a person effortlessly carrying around something without weight, regardless of the RB mass

honest river
#

Is it not possible to have parent game object have a trigger collider and a child game object have a blocking collider?

#

Right now whatever is on he parent game object works and the child game object is just ignored.

maiden belfry
#

You can absolutely have a non-trigger collider on a child object

#

and it will be an obstacle for objects with a rigidbody and a collider

short bolt
#

No option in unity to make a joint connected to an object not controlled by physics?
I am trying to have something attached to a weapon the player hold, and have it move as the player walks and moves the weapon. The issue when the player walks, the Character Joint seem to stretch. There doesn't seem to have an option for a joinb where the joint cannot stretch outside of the socket?
There is no way to make a joint rotate only?

maiden belfry
#

This seems like two unrelated questions

#

Lock the position if you don't want the position to change

#

I'm not sure how this relates to "an object not controlled by physics"

short bolt
#

I mean... locking the position lock it's position globally. So it's not useful if it suppose to lock onto another object

#

From what I understand... all joints in Unity physics have springiness, you can somehow force it not to spring. But making it work is kind if weird

#

I might try to implement my own small physics like code

#

Just for this specific thing

#

And use the collision by unity

maiden belfry
#

Note that you can use a kinematic rigidbody if you want the joint to stick to something that isn't affected by physics

honest river
# maiden belfry Define "works" here

Well, this is the behavior I get:
If I have a trigger on parent and blocking colllider on child, only the trigger works.
If I have a blocking on parent and trigger on child, only the blocking works.

honest river
#

I tried all combinations with rigid body 2D: none, on either and both of them.

frail fossil
#

@shadow heath let me give more context

shadow heath
#

alright

frail fossil
#

so I the top part that read chest roation info

shadow heath
#

you said your hand wasn't a separate rigidbody..?

frail fossil
#

and position info

frail fossil
#

here are the hands

shadow heath
#

so what do you want exactly? the hands to grab the gun?

frail fossil
#

All this mess started with multi-aim control not working if the target was on the camera

frail fossil
#

I have a parent object that hold the guns position but that gun lags

shadow heath
#

then you would need to create animation states and toggle them via scripts

#

you can't make dynamic changes to your gameobjects during runtime without scripting

frail fossil
#

I have animation states for basic animations

#

the object is visually lagging behind when I turn but the cords are not

#

the whole point of the aim and ik constraints from what I know is that they do not need states

shadow heath
frail fossil
#

nessacrily

shadow heath
#

it's not that hard lol

frail fossil
#

but wont help this issue

shadow heath
#

then rework your set up because that's exactly what you need for that set up.

frail fossil
#

I dont have any states that would interfere with the hand holding the gun?

#

wait I just had an idea

#

what if I parent the hand bone to the gun

#

that might do what I want and eliminate the scripts causing the lag

shadow heath
#

try it out

frail fossil
#

that worked

#

The issue with implementing scripts the way you are saying is that since I just learned unity I would have to completely tear apart this project which I sadly lack the time for

#

you are Otherwise completely correct that I need to completely rework my project

#

but I rn just needed a quick solution

#

still doesnt make sense why the cordinate rely scripts cause it to lag when parented to the bone constaint pointers but not to the bones themselves, even thought the bones rquire information from the same scripts

shadow heath
#

completely understandable. glad you got it to work. it's a pain to negotiate between these small details when I don't entirely know what you've set up behind the scenes. by the way, how much scripting was involved?

frail fossil
#

So i have an animation handler

#

a fake parent

#

a fake parent rotator

#

input manager

#

mouse look

#

Player position changer

shadow heath
#

I was under the impression you had none of that which is why I suggested to manipulate the physics a little, lol

frail fossil
#

its fine

#

its late for me rn

#

And I have been debuggin random issues constantly

frail fossil
#

I would need a specified gun script if I were to read player input and then if they are turning at a rotation have the gun purposefully lag behind a bit as if it had mass

shadow heath
#

the reason it lags behind is I believe there is some physics acting on it as constraints don't fully block physics interactions. this could be coming from a script or if it isn't a physics issue it could be overlapping of different rotational movements from the orientation. it's happening when your character moves/turns right? or when standing still as well?

frail fossil
#

it would more jitter

shadow heath
frail fossil
#

well my gun doesnt have a rigid body

#

if I add a rigidy body the jitterness disappears but then physics come

shadow heath
#

you just set it up? did you remove it

frail fossil
#

I removed it due to it causing more problems

#

I should very much use a rigidbody

#

but that would again require a project rework

shadow heath
#

well you might need to rework it to get it to work.

frail fossil
#

I mean it just works now so

#

Im happy

#

at the very least I didnt spawn any topology monsters during the creation of this

short bolt
heady latch
#

The upper leg is using a motor and the lower legs are using Rigidbody2D.MoveRotation. the lower legs have started to distance themselves from the joints and snap back. Any ideas on ways to avoid this would be apreesh

grizzled tundra
#

i have mesh colliders on both wheels with convex enabled on them also if that helps

dapper lichen
#

doh! a whole day late- oops

grizzled tundra
#

np xd

#

im nowhere near i want

silver moss
# grizzled tundra Hey guys, im making my own wheel collider as per recommended but i am getting th...

From a quick look at the code, I noticed that you are modifying the object with transform:cs transform.position = targetPosition;
Andcs transform.Rotate(0f, steering * turnSpeed * Time.deltaTime, 0f);
You should never modify a rigidbody's transform directly, it will lead to incorrect physics, bad collision detection, just overall glitching.
Use the rigidbody methods/properties to move and rotate it instead.

#

Also looks like your character has a CharacterController..? Did you make it a child of the bike? Show more info about your setup

#

No idea if character controller works should be a child of a rigidbody. You should at least disable its collisions with the bike

hidden trout
#

Hey all, how can i prevent my player from rotating when they collide with a surface? I know i can constrain rotation, but the thing is i still want to be able to rotate in all directions (in 0G), and still not bounce all over the place when they hit a wall.

        if (isColliding) rb.constraints = RigidbodyConstraints.FreezeRotation;
        else rb.constraints = RigidbodyConstraints.None;

I've tried doing this at the start of fixed update, however it still doesn't seem to work. isColliding is set by the onCollisionEnter and OnCollisionExit functions:

    private void OnCollisionEnter(Collision collision) => isColliding = true;
    private void OnCollisionExit(Collision collision) => isColliding = false;
timid dove
hidden trout
timid dove
timid dove
hidden trout
#

I'll check it out, thanks

winter rose
#

im using configurable joints for my rope but when and object collides with it above snail speed it freaks out and starts clipping and flying any idea on how to fix this?
either that or it ignores collsion

winter rose
#

unreleated to my first question. but what 2d joint would you use for a pulley system

bleak umbra
#

joints probably wont help you implementing actual (non-goofy) mechanisms. it’s usually best to make a custom simulation for those.

quick rock
#

Hi
If i check for input through the new input system and need to do some physics calculations as reaction to the input it doesnt work. Is there a correct way to do this instead? I tried setting a flag that input for jump has been pressed and in fixed update i wait for the flag to be true and then run the calculation, when i try to print the current velocity in there it prints (0,0,0) even tho in rigidbody component i can see it isnt that.

#

any idea what to do ?

#
void FixedUpdate() {
    if (_physicsJumpFlag) {
        // Jump logic, cant have its own function or doesnt work
        _physicsJumpFlag = false;

        // Log velocity before and after applying force
        print("Velocity before jump: " + m_rb.velocity);

        Vector3 jumpDir = m_rb.velocity + Vector3.up * m_Stats.jumpForce.currentValue;
        m_rb.AddForce(jumpDir, ForceMode.Impulse);

        // Log velocity after adding force
        print("Velocity after jump: " + m_rb.velocity);
    }
}


// Receive jump input
public void Jump() {
    // Register jump input
    StartCoroutine(JumpBufferCoroutine());
    // Attempt to execute jump immediately if conditions allow
    TryJump();
}

void TryJump() {
    if (!_canJump || !(m_Stats.isGrounded || _coyoteTimeActive) || !_bufferedJump) return;
    ExecuteJump();
}

void ExecuteJump() {
    _canJump = false;
    _bufferedJump = false;

    m_Crouching?.StopCrouching();
    _physicsJumpFlag = true;
}
#

when i print the velocity in fixed update outseide of the flag it has correct values

#

I feel like there is something weird with the physics ticks and the input being offset off of them

timid dove
#

JumpBufferCoroutine()
What's this?

#

Also what are these and what else interacts with them?

    _canJump = false;
    _bufferedJump = false;```
timid dove
#

Also missing from here is how the rest of your movement code works.

quick rock
# timid dove Miossing a lot of info here
using System.Collections;
using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(FPMPlayerStats))]
public class FPMJump : MonoBehaviour {

    [Header("Jump Settings")]
    public float coyoteTime = 0.2f;
    public float jumpBufferTime = 0.2f;

    FPMPlayerStats m_Stats;
    FPMCrouch m_Crouching;
    Rigidbody m_rb;

    bool _canJump = true;
    bool _bufferedJump = false;
    bool _coyoteTimeActive = false;
    bool _physicsJumpFlag = false; // Physics calculations must be in fixed update or it doesnt work so i have to do this workaround

    void Awake() {
        m_rb = GetComponent<Rigidbody>();
        m_Stats = GetComponent<FPMPlayerStats>();
        m_Crouching = GetComponent<FPMCrouch>();
    }

    void FixedUpdate() {
        print(m_rb.velocity); // This prints correctly
        if (_physicsJumpFlag) {
            // Jump logic, cant have its own function or doesnt work
            _physicsJumpFlag = false;

            print("Velocity before jump: " + m_rb.velocity); // This prints (0,0,0)

            Vector3 jumpDir = m_rb.velocity + Vector3.up * m_Stats.jumpForce.currentValue;
            m_rb.AddForce(jumpDir, ForceMode.Impulse);
        }
    }

#

    // Receive jump input
    public void Jump() {
        // Register jump input
        StartCoroutine(JumpBufferCoroutine());
        // Attempt to execute jump immediately if conditions allow
        TryJump();
    }

    void TryJump() {
        if (!_canJump || !(m_Stats.isGrounded || _coyoteTimeActive) || !_bufferedJump) return;
        ExecuteJump();
    }

    void ExecuteJump() {
        _canJump = false;
        _bufferedJump = false;

        m_Crouching?.StopCrouching();
        _physicsJumpFlag = true;
    }

    void OnGroundedChanged(bool isGrounded) {
        if (isGrounded) {
            _canJump = true;
            // Execute the buffered jump if it exists
            if (_bufferedJump) {
                ExecuteJump();
            }
        } else {
            // Start coyote time if leaving the ground without jumping
            if (_canJump) {
                StartCoroutine(CoyoteTimeRoutine());
            }
        }
    }

    #region Coyote and buffer coroutines

    private IEnumerator CoyoteTimeRoutine() {
        _coyoteTimeActive = true;
        yield return new WaitForSeconds(coyoteTime);
        _coyoteTimeActive = false;
    }

    private IEnumerator JumpBufferCoroutine() {
        _bufferedJump = true;
        yield return new WaitForSeconds(jumpBufferTime);
        _bufferedJump = false;
    }

    #endregion

    #region AddGroundedListener

    void OnEnable() {
        m_Stats.OnGroundedStatusChanged.AddListener(OnGroundedChanged);
    }

    void OnDisable() {
        m_Stats.OnGroundedStatusChanged.RemoveListener(OnGroundedChanged);
    }

    #endregion
}

#

Here is the entire class for context.

#

the rest of the movement isnt really important. what bugs me is how can the velocity be printed correctly in the fixed update if it is outside of the physics jump flag

#

The Jump() is what the input class calls. The input works via the new input system so it just reacts to the event caused by new input

timid dove
#

Adding forces to jump like this only works if the movement code doesn't interfere with that

quick rock
#

oh yea but what im askin and kinda need to know how is it possible that


void FixedUpdate() {
        print(m_rb.velocity); // This prints correct values 
        if (_physicsJumpFlag) {
            print("Velocity before jump: " + m_rb.velocity); // This prints (0,0,0)
        }
    }

#

because it does not make any sense to me

#

its both in the same update function

timid dove
#
void FixedUpdate() {
        print($"Velocity is {m_rb.velocity} at {Time.fixedTime} on {GetInstanceID()}");
        if (_physicsJumpFlag) {
            print($"Velocity before jump: {m_rb.velocity} at {Time.fixedTime} on {GetInstanceID()}");
        }
    }```
Try this more informative logging
quick rock
#

the fixed time is different..