#⚛️┃physics

1 messages · Page 79 of 1

timid dove
#

Make your script rotate the player instead of the camera

nocturne coral
#

I fixed it, the script I was using it wasn't working properly

wispy quarry
#

anybody got a spider-man webswing thing?

#

I found some resources on grappling hooks, I guess thats a good start.

sonic snow
#

so i'm making a weather and climate model

#

it's for mecha_moonboy's game if he's mentioned it much here

#

it's not too far along yet, still working on getting solar heating right

dry tundra
#

what'd be the best way to make a character controller interact with rigidbodies? I was using this approach but by doing it this way there's no influence from the rigidbody's size at all. How would I be able to achieve that effect?


    void OnControllerColliderHit(ControllerColliderHit hit)
    {
        Rigidbody body = hit.collider.attachedRigidbody;

        if (body == null || body.isKinematic)
            return;

        if (hit.moveDirection.y < -0.3f)
            return;

        Vector3 pushDir = new Vector3(hit.moveDirection.x, 0, hit.moveDirection.z);
        body.AddForce(pushDir * pushPower * (speed / 2), ForceMode.Impulse);
    }```
royal epoch
#

so I have this code that makes a bullet bounce off walls using ray casting. It works 90% of the time but sometimes a ball or too will just teleport through the wall. The first line makes the bullet move and the rest is the ray casting. Does anyone know why this is happening and how I can fix it?

supple sparrow
dry tundra
#

for example, when two rigidbodies interact, what exactly happens?

supple sparrow
#

What you did looks okay at a quick glance. What doesn't work ? You don't like the result you got ?

#

If you wanted a result relative to size, you would add it into the equation, like you did for speed

dry tundra
#

Hmmm

#

I see

#

But just to clarify

#

I had an impression that rigid bodies would be harder to be moved by other rigid bodies depending on their size

#

Isn't that how it works?

supple sparrow
#

Oh good question

#

Never used rigidbodies with much of a difference in size so can't really tell 😛

#

But now I want to know too 🙂

#

But I just discovered it now so can't tell if useful

dry tundra
#

I didn't quite understand what that would do

#

OH okay I get it

#

But wait, does that happen by default or...

manic harbor
#

Okay so I have no idea what Im doing atm, but how do i rotate my rigidbody?

#

rn im rotating the object using transform.Rotate() but my rigidbody.AddForce (or rigidbody.velocity that I used previously) is still moving in the same direction

#

AddRelativeForce doesn't work as it reaches hyperspeed and becomes extremly glitch

#

nvm found a solution. copied a piece of code from another project and modified it a bit

Vector3 direction = transform.TransformDirection((currentVel + currentNitroVel)-rb.velocity);
rb.AddForce(direction - rb.velocity, ForceMode.VelocityChange);
manic harbor
#

actually, it glitches out a lot if i rotate it a lot

stuck bay
#

why do the physics joint give me a null reference exception if i just add one to an object?

#

When i used them last time this didn't happen

#

But it's been a while

neat coral
#

I would reboot my editor

stuck bay
#

ill try it

harsh nest
#

so I finally gave up on using traditional wheelcolliders and switched instead to this raycast implementation: https://github.com/unity-car-tutorials/SimpleRaycastVehicle-Unity/blob/master/Assets/Scripts/RaycastWheel.cs

the problem i'm facing now is it seems to just slowly slip backwards and no amount of adding equal rigidbody force, messing with slip values, etc seems to solve it. notice the Z value in the top right: https://i.gyazo.com/fbd493642a6ea2b54b0cd8cf32263a55.mp4

GitHub

Experimenting with Simple, Alternative Raycast Vehicle Physics for Unity 3D - SimpleRaycastVehicle-Unity/RaycastWheel.cs at master · unity-car-tutorials/SimpleRaycastVehicle-Unity

limber carbon
#

I am working on making a wire using Config Joints. And one of my big issues is that the joints seem to drift apart even though movement is locked. Anyone have any ideas?

gloomy field
#

any ideas why is my rigidbody not colliding with other objects? they all have box collider and they are not triggers

timid dove
#

And how are you moving said objects

slender crescent
#

How can i prevent my hinge joint to effect connected body? I just want it to follow like parent-child and turn around it when i press some key

fringe heron
#

Hi. how to do edge collider alternative in 3D?

I want to have 2 points and between them a cube with collider. please

slate lily
#

What is .maak

unique cave
fringe heron
#

I want to drag positions with mouse

#

and Down position will be A point
Release Position will be B point

#

in 3D

#

and want between box collider

#

._> idk how to do

pale gate
#

fixed

wispy tinsel
#

I have a quaternion rotation of object X
How to get quaternion rotation that is supposed to be rotation of bullet, assuming they come from center of object X?

#

without transforming into euler (if possible)

#

transforming from euler is fine tho

gloomy field
#

but its just falling and going through them

#

and im using a rigidbodu

#

rigidbody*

timid dove
gloomy field
#

im not home yet ill do it as fast as i can

midnight basalt
#

Is there a way to addForce to a rigidbody across two axis simultaneously (i.e. diagonally)?

#

Currently I’m using addForce.forward, addForce.right, addForce.back and addForce.left. This works sufficiently for moving along one axis, but doesn’t apply force along two axis

timid dove
#

Including one that is pointing diagonally

midnight basalt
#

I’ve tried using addForce(1,0,1) for example, but then there’s the issue of velocity

#

I’ve also tried Input.GetAxis and can’t seem to get that working properly either

#

For whatever reason the gameObject either refuses to move diagonally or has inconsistent velocity

timid dove
#

If you have other code that's explicitly setting the velocity, AddForce isn't going to work right

#

the only effect of AddForce is to change the velocity

midnight basalt
#

It seems to be multiplying the values, so moving diagonally increases the speed at which the object is moving

timid dove
#

so it's more force overall

#

The magnitude of (1, 1, 0) is sqrt(2) (aka like 1.44 something), while the magnitude of (1, 0, 0) is 1

midnight basalt
#

So in that example, would a solution be to use (0.5f, 0, 0.5f)?

timid dove
#

no

#

(1 / sqrt(2), 0, 1 / sqrt(2))

#

or just

(1, 0, 1).normalized```
#

or cs Vector3.ClampMagnitude(new Vector3(1, 0, 1), 1)

midnight basalt
#

rb.AddForce(1,0,0).normalized; throws up an error

timid dove
#

course it does

#

AddForce doesn't return anything

#

there's nothing there to normalize

#

you make your vector and pass the normalized version of it into AddForce

#
Vector3 force = <whatver>;
rb.AddForce(force.normalized);```
midnight basalt
#

Okay, so for instance

Vector3 right = new Vector3(1f,0,0);
rb.AddForce(right.normalized);

#

Now this works better

#

Still seems to be moving faster diagonally though

timid dove
#

Show code

midnight basalt
#

Now I'm sure that it's user error on my part, and I'm also sure there's a way to optimise this code, possibly using GetAxis

timid dove
#

Using GetAxis can certainly simplify this a lot but the idea is you should build up a single Vector2 and then finally normalize that and call AddForce with it one time at the end

#

Also AddForce should not use deltaTime

#

Your use of deltaTime is why you need such a high value for "speed"

midnight basalt
#

Okay that makes sense

midnight basalt
#

Yeah that's working a lot better

#

Thanks (once again) for the help @timid dove

#

I guess I can also lose the Time.fixedDeltaTime

mental lion
#

I got a question guys but I don't really know where to post it, I think this is the closest it would relate to

#

I'm trying to make a flip counter for this snowboarding game, I figured I'd have a hit box on top of the player (flipbox) and if the board's hitbox touches the flipbox it will count as a flip however my flipbox does not follow the character perfectly, it sorta lags behind, does anyone know how to fix this?

#

I remember having a similar problem before with my character I just can't remember how I fixed it

desert timber
#

Hi all,

I'm trying to make sense of mesh colliders being used on very large mesh objects. Everything I read online says to avoid them, but very few specifics or benchmarks are provided.

In the case of a static mesh object where each mesh face is fairly large compared to a character's size (let's say 2x the width at least), do we get away with using them?

I'm imaging low poly terrain ideas, except with very high poly models being used for terrain. (It's not always easy to segment large mesh models, and the renderer seems happy with veery large models.)

A mesh collider with 50-150k triangles would be extremely useful to me, and it seems to work?

Is anyone familiar with this concept?

Thanks!

desert wave
mental lion
#

No I didn't fix it yet, started working on some other coding stuff. I had the idea to move the hitbox by placing it as a child of the Cinemachine Follow Camera on the Player

#

I remember doing some setting that smoothed out the camera on the player, not sure if there's a similar setting or something I could do to mimic that with the hit box

desert wave
#

?

mental lion
#

I'm super new

#

In the middle of taking the 2D course online on Udemy lol

#

I have no clue how I'd do that

#

You're saying have the hitbox itself follow the player?

mental lion
#

I'm not sure how I would do that in code

#

I have an idea, but I'm really new

desert wave
#

offset being a vector3 that you set in the editor

mental lion
#

So offset would be a serializedfield?

desert wave
#

yes

mental lion
#

That is basically the idea I had lol

#

gg

#

Thank you

#

That single line of code would have taken me ages to figure out

desert wave
#

np

#

gl

devout token
#

@nocturne fern I'll ask over here as it's a tangent, what in your view is the problem of using RigidBodies for FPS movement and what do you view as the correct alternative?

#

There is a bit of a clarity issue because there is no official best type of movement for each kind of character, so every tutorial tells beginners to use something different

strange lark
#

Anyone know any good reading on how to prevent a character controller from clipping through walls at high speeds?

strange lark
#

Thanks! I guess I wrote a really shitty version of a sweep test, but the above will help me (hopefully) make it a bit better 🙂

meager coyote
strange lark
#

Something I'm not sure on, is if I catch high speed collisions with a raycast, how far should I move the character into the wall to enable sliding?

#

My game is grid based, so I'm stopping at the hit, then moving velocity into the wall, with a maximum of 0.5 (half a grid)

#

That seems to work pretty well, but If I hit an edge at very high speed it's a bit weird, but probably fine

meager coyote
strange lark
#

Hmm what would happen if you ended up inside a wall with the above approach?

meager coyote
#

you need to check the slide vector as well, so you dont slide inside something

#

pretty sure you can find lots of info about how its done in various older games (like quake3 etc)

#

code is also available. doom 3 has some very advanced physics etc

#

full CCD for everything IIRC

nocturne fern
# devout token <@!481596074340122626> I'll ask over here as it's a tangent, what in your view i...

Rigidbodies are designed for things that are driven by Unity's physics system. When there are behaviors from the physics engine that you do NOT want your character to experience (such as bouncing) you essentially have to work AGAINST the physics engine to override that behavior. You do not have the same precision with a rigidbody's movement that you do with a character controller. This adds up to a lot of work.

Character Controllers on the other hand are designed specifically to drive characters with movement typical to what you would expect in most AAA titles where they glide across the floor naturally. You do have to code in special cases like jumping/gravity but I did both of these things in 150 lines of code which is nothing.

Another side effect of using rigidbodies for FPS is that your rigidbody is moving on FixedUpdate which is every 0.02s (technically, it runs 0.02s worth of physics simulations for every block of 0.02s that has passed, it doesn't actually run exactly every 0.02s). The issue with this is the camera will be really jittery if you put it in fixedupdate as well but if you put it in update and you have your rigidbody moving in fixedupdate they will move at different points and you will get a camera jitter. This is not extremely noticible with a third person if you do some hackery. But in an FPS game...this is really bad.

The only games where rigidbodies are technically proper is games like Human: Fall Flat where you actually want this bizzare behavior. Maybe some other 3D adventure games where you care more about how the character moves visually than you do about giving the player precise controls. Many 2D Unity developers use rigidbodies beccause its easy to set up in 2D but its technically not proper. No other game engine defaults to using rigidbodies for player characters. Basically every other engine uses character controllers.

#

I guess one newer phenomena is some people are starting to use root motion exclusively to drive character movements. I wouldn't say its common but I know its out there.

Basically, character controllers don't even use the physics engine aside from collision detection and correction. Sidenote, the lack of a proper character controller in DOTS is one of the main reasons I haven't moved over to DOTS. They do technically have a character controller...but it's not done well...

slender crescent
devout token
# nocturne fern Rigidbodies are designed for things that are driven by Unity's physics system. ...

Any system is "proper" as long as it does what you need. If you want physical forces to act on your player, be it an FPS or not, Rigibodies are the most convenient option. Sure you do have to put some work in to stop unwanted behaviour but if physics are the goal it's still better than coding physical forces from scratch as you would have to do with a Character Controller.

I don't have any particular beef with Character Controllers but it's baffling that they don't have gravity and jumping from the get-go. 150 lines for something that should be a given is a lot asked from someone who just wants something that works, especially a beginner.

The FixedUpdate thing is a non-issue. You're expected to enable Interpolation on Rigidbodies and the stuttering is gone.

If I see beginners using Rigidbodies incorrectly it's usually because they've learned from tutorials to move using Transform.Translate and in Update loop no less.

devout token
#

What kind of colliders are they with what kind of physic materials

slender crescent
jaunty viper
#

how is the unity wheel collideres friction simulated?

#

im trying to make my own physics car system and i wanna make friction so just curious

nocturne fern
# devout token Any system is "proper" as long as it does what you need. If you want physical fo...

They don't have gravity and jumping because not all character controllers can jump or are affected by gravity. Jumping and Gravity are not actually 150 lines of code, they're like 3 lines of code. It's acceleration/deceleration/turning boost that takes 150 lines of code. If you just have doom controls where input directly sets velocity to some value than you can do all of this in like 30 lines of code. I actually take major issue with Unreal Engine's character controller because it does way too much (UE's actually has full network replication support out of the box and such which is why their character controller and movement code is tens of thousands of lines of code)

You will never get amazing character controls with a rigidbody in an FPS game. Either you have the camera only updating its position every 0.02s or you have the camera moving at different times than the player.

Of course you can hack any code to 'make it work' but I'm just saying there is a reason that literally no other game engine is even set up for the possibility of driving your character through the physics simulation. It's one of those things where the Unity community says "do it this way" but Unity devs are like "Uh, that's not what its for". Unity is pretty varied in what kind of games it can make. If your player is a ball in a pinball game than yea, you would technically have the player driven by a rigidbody. But if you're making something like an FPS or an Open World RPG or Open World Survival style game...character controllers should be your default. The amount of AAA titles that use rigidbodies (or other methods driven by the physics simulation) in these genres is approximately zero.

Yea it sucks you have to add code but...you can't go very far in Unity if you don't get used to coding things manually.

dense wagon
#

How can I stop my car from slipping on the terrain every time it turns?

#

I can't seem to get a hold of the friction modifiers

#

Any help will be appreciated

devout token
# nocturne fern They don't have gravity and jumping because not all character controllers can ju...

Why's it an issue if the camera is using the body's interpolated location?

Most open world style games have basically entirely static worlds and don't need accurate physics on the player. Triple-A games have the resources to code in all interactions and edge cases that the physics engine normally would take care of, and they're basically all using root motion with their mocap'd animations anyway.

It seems to me you're making a lot of assumptions what player movement should be like. The only relevant question is: does the tech work towards the project's goals?

#

By coding interactions I mean stuff like how the player reacts being pushed, sliding down slopes or being hit by falling rubble. Not every project has those, but it's really nice that Rigidbodies react to all of that without any sort of extra work.

#

That kind of flexibility goes a long way when you're prototyping or just starting out and don't necessarily have the time or motivation to implement all of it manually

#

From my experience unity devs don't really give any official advice how to use techs like this, but if they didn't want Rigidbodies to be used for characters they should've made physical forces be an option for Character Controllers

jaunty viper
#

if you're using wheel colliders you can't use friction material

#

*physics material

#

if you're using like a raycast system you can't do that either i think

nocturne fern
#

In a third person game I don't think the camera issue really manifests but in first person games it's fairly blatant. I AM making assumptions about what player movement should be like because we have a very long list of games that have handled character movement a certain way and while deviating from this can be innovative how many developers actually even want to be innovative when it comes to how player movements are handled? If you're not trying to do something unique when it comes to the character's movements, use a character controller so it feels natural to your average player.

I'm not saying you should never ever use a rigidbody as a character controller...but again specifically in 3D humanoid style games, there's very few genres where a character controller is not the best option. Overwatch doesn't want players moving around like ragdolls (except when they're dead).

devout token
#

Common or conventional doesn't equal good either
How many triple-A open world games in recent years have been notorious for their glitchy character movement? In first person games being able to glitch your character out of play area with a physics object is so routine that players are not only not surprised when that happens, but expect it

nocturne fern
#

If you do both of those things you will still have an immediate problem where when the character hits a small object on the floor they will bounce upwards like a ball and flop back on the ground. There is a way to get rid of this behavior but this is what I'm saying...you're working against the physics simulation and essentially undoing everything the rigidbody does to take advantage of like 5% of what the rigidbody does instead of just recoding that 5% into a character controller. In this particular example you end up having to undo the rigidbody behavior and then end up programming step up controls which...the character controller already does for you. So you're putting in extra code to get rid of rigidbody behavior and then putting in more code to do what the character controller already does...

And rigidbodies introduce a lot more glitches than character controllers. Just look at Skyrim's character controller vs the objects that you can move around that are controlled by their physics engine....

devout token
#

Interaction with various physical forces is a lot more than 5% as you'd have to code every type of interaction separately, but again that depends on the project. It hardly makes a difference in the end whether you're coding against the physics engine or coding up all the features Character Controller doesn't have.

#

The Controller handles horizontal movement and slopes and that's about it? The real tragedy is the coding you'll have to do either way just for something so basic

#

Everything about Skyrim and its engine is glitchy so I don't think that proves much 😄

#

That one can't even reliably flip quest flags without losing them to cosmic background radiation, apparently

nocturne fern
#

My 150 line movement code does basically everything Skyrim's character does.

The character controller Unity provides does all the collision stuff. It resolves collisions, handles sliding against a wall, provides step up control. Yea, making a character controller from scratch would be a lot of work but using Unity's and just coding the behavior is not that complex.

Skyrim's engine is fine, it just gets a bad rap because they put a bunch of crappy assets and scripts into it. People associate bad animations with the physics engine and they associate crashes with the engine crashing when its usually their scripts causing the crashes. The modern Gamebryo engine is actually pretty great, but they deviated from it years ago and have been patching it as they go. It provides high graphical quality and works quite well, but garbage in garbage out.

devout token
#

I've always thought of its character physics as one of the floatiest and glitchiest on the market, but that's off topic

nocturne fern
#

That's just their settings on the character controller - I think they have a really low gravity value and such which makes it feel weird but its not the engine its their implementation. Now the physics simulation is bad by modern standards yes which is why objects that collide go flying.

devout token
#

That and how the edges of the character seem to strangely stick to things when you try climbing anything

#

Guessing you're programmer by background if coding missing features in bothers you less than reining in pre-existing ones
Might even give a sense of control as you can decide how to build it
Or maybe your projects don't need complex interactions

#

Either way, I've tried making various types of characters with Rigidbody movement, Character Controller movement and some without either
My only takeaway is that all of them are just a miserable amount of work to get working nicely, but also that depending on the project none of them are better than the others

#

Which is kind of a weird contrast compared to how much unity's navmesh agents offer with out of the box functionality

#

They even got jumping while Character Controllers did not

nocturne fern
quartz wyvern
#

if you have a kinematic rigidbody - can you move it via transform position without issues ?

timid dove
quartz wyvern
#

i dont want any collisions on it

#

but it seems to still collide even when i have kinematic on

#

and im using transform.position

timid dove
quartz wyvern
#

well i had this:

    public void PickUp()
    {
        _rigidbody.isKinematic = true;
        _rigidbody.angularVelocity = _rigidbody.velocity = Vector3.zero;
        _rigidbody.detectCollisions = false;
    }
    
    public void Drop()
    {
        transform.SetParent(null);
        _rigidbody.isKinematic = false;
        _rigidbody.detectCollisions = true;
    }
#

so when i pick it up its still colliding with things

timid dove
#

Is it Rigidbody or Rigidbody2D

quartz wyvern
#

3D

timid dove
#

Colliding how

#

Like its own movement is affected?

quartz wyvern
#

let me make a gif

timid dove
#

Or other objects are affected

quartz wyvern
#

it seems to collide when i pick it up from the table but pickup is the function shown above

#

so i don't know why it glitches out like that, some times it frees itself however

timid dove
#

Show the rest of the code

quartz wyvern
#

this is the RB of sphere when its glitching

#

and okay let me get rest of the code

#
    private void TryPickUp()
    {
        var pickable = _pickables.Nearest(); // get nearest pickable object

        if (pickable != null) // we found something
        {
            _holding = pickable; // set nearest
            pickable.PickUp(); // calls object to update rigidbody 

            //set the pickable object as a child so it follows player
            _holding.transform.position = _holdPoint.position;
            _holding.transform.SetParent(_holdPoint);
        }
    }

    // pickable.PickUp();
    public void PickUp()
    {
        _rigidbody.isKinematic = true;
        _rigidbody.angularVelocity = _rigidbody.velocity = Vector3.zero;
        _rigidbody.detectCollisions = false;
        _collider.isTrigger = true;
    }
#

@timid dove here u go

timid dove
#

That's not the rest of it

quartz wyvern
#

what else do you need to see?

#

thats all of the pickup code

timid dove
#

The whole script ideally

quartz wyvern
#

do you need the drop code aswell?

#

theres only 4 functions, pick up and drop

#

2 on the player 2 on the objects in question

timid dove
#

So you move by parenting

quartz wyvern
#

yes since its no suppose to be subject to physics anymore

timid dove
#

That should work fine 🤔

quartz wyvern
#

thats why i dont understand why its glitching on my table

timid dove
#

Show drop code please yeah

quartz wyvern
#

okies

#
// player drop:
    private void DropObject()
    {
        if (_holding==null) return;

        var dropOffPoint = _dropPoints.Nearest();
        if (dropOffPoint != null && dropOffPoint.PlaceItem(_holding))
            _holding = null;
        else
        {
            _holding.Drop();
            _holding = null;
        }
    }
// object drop:
    public void Drop()
    {
        _collider.isTrigger = false;
        transform.SetParent(null);
        _rigidbody.isKinematic = false;
        _rigidbody.detectCollisions = true;
    }
#

and the place item for drop off point:

    public bool PlaceItem(Pickable item)
    {
        if (CanPlaceItem(item))
        {
            item.transform.position = Position;
            item.Drop();
            OnItemRecieved?.Invoke();
            _item = item;
            return true;
        }
        return false;
    }
timid dove
#

Seems relatively straightforward

quartz wyvern
#

yeh - its why i am confused why its colliding with my table

#

kinematics shouldn't do that

#

it correctly set the parent aswell so its trying to move with the player

#

unless its some physics bug ive discovered

timid dove
quartz wyvern
#

it has no children. it only has a parent when its a child of the player when im holding it

#

if i drop it the parent is null and so its free to be physics based

timid dove
#

Also do you get any warnings about collision detection modes when it becomes kinematic?

quartz wyvern
#

no i get no warnings unless i need to enable some more advanced warning logging some where to see that

timid dove
#

Nah

#

How does the player move?

quartz wyvern
#
            _rigidbody.MovePosition(heading.normalized * _moveSpeed * Time.deltaTime + transform.position);
            Vector3 orientation = Vector3.RotateTowards(transform.forward, heading, _turnSpeed, 0.0f);
            _rigidbody.MoveRotation(Quaternion.LookRotation(orientation));
#

thats in fixed update

timid dove
#

Hmm

quartz wyvern
#

heres the inspector when its glitching

timid dove
#

Do you have any listeners for OnItemReceived

quartz wyvern
#

no i've not implemented that yet

timid dove
quartz wyvern
timid dove
#

Also can you show the inspector for the hold point

#

Is it just an empty Transform

quartz wyvern
#

hold point is just a empty GO

#

player has RB and stuff though

timid dove
#

I'm pretty stumped TBH

quartz wyvern
#

same lol

#

you're welcome to try use those functions to see if you reproduce the problem

timid dove
#

Maybe tomorrow. It's pretty late here.

quartz wyvern
#

@timid dove i thought i had a solution but guess not. i assumed that its collider was being considered for the player's RB even though the RB of the item was kinematic, but disabling the collider still causes issues so i guess thats not it either 😦

#

fixed it

#

had to stop making it a child of player

#

no idea why but oh well

fringe heron
#

Hello. should we use deltatime in FixedUpdate, when trying to move (or addforce to rb)? and should we use it when we are setting rb.velocity =?

fringe heron
#

I want to set velocity of rb and then ball will start bouncing on the edges of screen. When I'm doing it, velocity is deccreasing afterr every collision. I want to remain constant speed. (or just speed up after time)

fringe heron
fringe heron
timid dove
#

It tells you the time interval between FixedUpdate calls and physics simulation steps

fringe heron
#

Time.deltaTime does the same too but not in fixed intervals and I use it when I try to move obj via transform.position

#

and I wonder whether Time.fixedDeltaTime is used in same way but when trying to move rb

unique cave
#

deltaTime in FixedUpdate is exactly same as fixedDeltaTime (0.02 by default)

fringe heron
#

Yes. But where can I use fixedDelta. where should I multiply it

timid dove
unique cave
#

MovePosition ig

timid dove
#

Use velocity or add forces

fringe heron
timid dove
#

Doesn't matter

unique cave
#

it's still 0.02

timid dove
#

FixedUpdate will be called multiple times to catch up

unique cave
#

it may not

timid dove
#

It will be

unique cave
#

it is trying but not always it is able to

fringe heron
#

Interesting. thank you. so I will never use deltaTime stuff when dealing with rigidbodies? (setting velocity.... adding forces or torques)

timid dove
#

Unless you reach the max per frame in which case the physics sim is slowed on purpose

#

In any case it still represents the same fixed time interval

fringe heron
timid dove
#

Just set the velocity manually

fringe heron
#

I do

#

but it slows down after each collision

timid dove
#

You can't rely on perfectly elastic collisions

#

The engine isn't built for that

fringe heron
#
  • I use 3D physics and rb pos Y is frozen
timid dove
#

Set the magnitude of velocity yourself

fringe heron
#

and all rotatioons of ball too

timid dove
#

Don't rely on the existing magnitude

fringe heron
#

I checked it

timid dove
#

So what's the issue

fringe heron
#

but rb.velocity is going frrom 40 to 20

#

and rb starts sslowing down

timid dove
#

Ehy

fringe heron
#

wait I can record a video

timid dove
#

You're setting it to 40 no?

#

Unless part of your vector is in the Y direction

fringe heron
#

yes

timid dove
#

Then it will be cut

fringe heron
#

Oh... interesting

#

maybe that's the point.

#

I have something like that

#

and want to bounce through walls. and since it 3D .. you might be right

#

that reflected vector should be only xz

timid dove
#

Project the vector on xz plane

#

Before normalizing and multiplying

fringe heron
#

Thank you. I will try

#

?

#

It still slows down.. hm

timid dove
fringe heron
#

Yessyes. 1min

#

wow. it worked 😄

#

Thank you very much

#

Just one question

#

sometimes it stucks like this

#

what might be the problem?

#

it did the same thing.

#

maybe it is richocheting between that 2 collider

#

no.
It sleeps

#

Nvm. I think it wouldnt be problem. Thank you.

wispy tinsel
#

What are ways to prevent horizontal collisions in character controller?
rn I adjust velocity of character by doing collider cast in direction of it's velocity:

                    foreach (DistanceHit distanceHit in horizontalDistances)
                    {
                        horizontalVelocity += (distanceHit.SurfaceNormal * -distanceHit.Distance);
                    }

But, every time character goes into wall, it starts to stutter (like, 1 frame closer to wall, the other further)

#

skipping all hits with fraction <= 0 helps with walls, but
it doesn't help with corners:

#

same stuttering, characters clips through both walls (kinda goes left and right)

#

I assume it can be fixed by doing new cast after every adjustment, but I have a strong feeling that it can be avoided

jaunty viper
#

how is the unity wheel collideres friction simulated?
im trying to make my own physics car system and i wanna make friction so just curious

wispy tinsel
#

hey?

nocturne fern
#

Sorry hit enter instead of shift enter

You don't want to prevent horizontal collisions. Your character controller capsule is too small which is causing the mesh to clip inside the wall. Make the capsule larger and it will keep away from the wall.

#

The character controller capsule is the object from a collision point of view, the mesh is just a mesh that can collide through anything.

wispy tinsel
#

I want to prevent collision of collider with walls/corners, not mesh's

#

because as of now, character teleports back on collisions

#

which is extremely noticable

nocturne fern
#

You're using the default character controller component right? Then you just use this component's .Move() function and it will automatically prevent collisions using the capsule defined in the component. You shouldn't have an actual capsule collider child.

wispy tinsel
#

no I make my own

#

since there's no built one in dots

nocturne fern
#

Oh...

Yes dots...

This is why I don't use full dots...

They DO actually have a character controller in the sample pack. However, it's terrible because it integrates a bunch of features that you don't need, the input system never worked for me, and it's actually not even implemented with DOTS.

Quite frankly a DOTS character controller is someting that not even the devs have bothered to do yet so it's pandora's box. I made some progress and was able to resolve simple collisions but then I couldn't get the step-up and slide-against-wall code to work and went back to non-DOTS.

#

I would first look at the sample they included and see if you can make sense of it (it's bad though).

wispy tinsel
#

I found source of one that almost works

#

so far, gravity is great

#

steps are too

nocturne fern
#

In the sample pack?

wispy tinsel
#

but wall sliding

#

no

#

but it's kind of based on sample one

nocturne fern
#

Ah yes - I remember looking at this. I think the code was an outdated implementation of DOTS which is another reason I quit DOTS, it changes massively every once and a while - you could try contacting the blog author https://www.vertexfragment.com/about/

No gaurantee he'll get back to you, but the amount of people that know enough about modern DOTS and know the inner workings of character controllers in Unity (not just how to use them) is very small. A few months ago when I was attempting this I could not find a better source.

#

Let me see if I can remember a research paper I stumbled on that was regarding custom character controllers...

wispy tinsel
#

I just need to figure out how to do collision correction correctly

#

for object sliding

#

it's same thing for both, dots and object based

wispy tinsel
#

Hmm

#

when I do collider cast into only 1 direction

#

for example 0,-10,0

#

my fraction*normalSurface would be vector that is parallel to my direction?

wispy tinsel
#

Anyone has any idea how to use dot product of quaternions?

stuck bay
#

Anybody know an asset that allows for floating balloons? Like air density / helium type of thing

neat coral
stuck bay
#

Sure if I knew how to code haha

#

Thanks though

neat coral
#

Well you don't really need to code much

#

I think that property is even available in yhe inspector for rigidbodies

wispy tinsel
stuck bay
#

Hey guys, I have encountered one weird thing. I have Player object and I've set AreaEffector2D as child of a player to follow it
but, areaeffector2d doesnt seem to work when it's a child
any ideas how to fix this?

unique cave
unique cave
wispy tinsel
mellow haven
#

can someone please help in creating googly eyes?

neat coral
#

yes for sure

mellow haven
#

is it easy to add to an existing character?

#

i dont even know how to start haha

neat coral
mellow haven
#

i would need the version without script and with rigid body i think

nocturne fern
timid dove
#

I'm guessing for VRChat

#

probably best to ask in the VRChat forums or discord

ionic dome
#

So question about input and movement, do I have to manually check that a collision hasn't occurred before moving the transform of the character? or does the colliders handle that for me, I know they handle that with regards to gravity, but what about walls?

wide nebula
#

If you move your object with forces, then the physics will handle collisions for you.

ionic dome
#

Ok. So then I don't move the transform, I let the forces handle that

#

That answers my question

#

Thanks

wide nebula
#

You don't want to move with transformation, no, it'll teleport it through colliders.

ionic dome
#

got it

viral ginkgo
#

@ionic dome You could boxcast, capsulecast

#

From startpos to end pos

#

And see where it hits a wall or see if it hits

random arch
#

Hi, i was watching a tutorial about car controller, and then the guy car flipped over and he changed the spring and damper values without explaining why. Now my car keep flipping and i cant find good values and his values did not work

#

Still stuck here

random arch
#

x.x

tough geyser
#

Hello.
Any idea on why physics break if the Camera stops looking at the physic objects? I have 2 RigidBodies interacting with a Joint and it works great, but as soon as the Camera looks away from it, when it looks back the physics changed in a way that the objects dont look right anymore

neat coral
#

wdym don't look right anymore?

snow coral
#

Hi, I'm very new to unity and I'm in the middle of making flappy bird on my own. I currently have upper and lower walls to stop the bird from falling out of the cameras view, now the problem I'm facing is that the pipes collide with those upper and lower walls when I only want them to collide with the left wall (so I can spawn them back to the right of the screen). so can anyone help me with getting the pipes and the upper and lower walls to ignore collisions?

neat coral
#

or set them to kinematic

#

and*

snow coral
neat coral
#

you look it up :)

snow coral
#

👍

neat coral
#

@snow coral feel free to ping me if you can't get it working

snow coral
snow coral
#

with the collision layers

#

how do I make an action happen only if a specific object is colliding with another specific object?

untold dust
#

I've got a character with animations for locomotion, a controller, everything is working great. I add a Rigidbody and now he floats upwards slowly. The only changes I make from the default are to freeze rotation. It appears to use the capsule collider to update its center of mass, but why does it float away?

timid dove
timid dove
untold dust
#

I'm kind hoping to fall when I jump from platform to platform and miss. I was also after a ragdoll effect when I get shot at.

wispy tinsel
#

What is result of multiplication of quaternion and single float?

bleak umbra
wispy tinsel
#

I still struggle to understand how to correctly rotate quaternion without transforming into euler

bleak umbra
#

my multiplying them

wispy tinsel
#

Basically, i have simple rotation to perform

#

let's say 90 degrees on Y axis

#

I create quaternion of Euler(0,90,0) and then multiply them?

#

and in what order then?

bleak umbra
#

fooRotatedBy90 = fooRotation * Quaternion.Euler(0,90,0)

wispy tinsel
#

what is order of Quaternion.Euler btw?
ZXY?

#

oh yeah

bleak umbra
#

XYZ

wispy tinsel
#

xyz?

#

wha

#

is that missleading description or?

bleak umbra
#

in what way?

wispy tinsel
#

it says it rotates z x y

bleak umbra
#

i think its perfectly clear

wispy tinsel
#

in that order

bleak umbra
#

ZYX is the rotation order that is represented by the quaternion

wispy tinsel
#

oh

#

it's for quaternion -> euler?

bleak umbra
#

you dont have to worry about that

#

it only matters if you do advanced quaternion manipulation or need to make them compatible with manual euler based rotations

wispy tinsel
#

I hope I don't kek

bleak umbra
#

btw. if you use Quaternion.AngleAxis() instead of .Euler() its more explicit what your rotation actually is if you are doing stuff outside worldspace

wispy tinsel
#

I mean, I work with 2 different math systems which uses Unity.Mathematics

#

it's quaternion special

bleak umbra
#

in what way?

wispy tinsel
#

no idea, but it's different

bleak umbra
#

its just implemented differently for speed purposes

#

so you might have to deal with radians vs degrees or inputs need to be normalized to give you more control over when those operations happen

wispy tinsel
#

Nah, it is different.
Normal Quaternion clamping would be -90 to 90, while this quaternion forces me to do this pepega mode
x = (x > 200) ? math.clamp(x, 269.9f, 370f) : math.clamp(x, -10f, 90.1f);

#

at least, when I extract it to euler angles with Quaternion of UnityEngine

bleak umbra
#

thats what i just said, it wants you to do stuff manually that the regular math does automatically because it may not be necessary in your particular calculations and thus provides optimization opportunities

velvet rivet
#

i have dynamic friction of the floor set to .3 and the static to .5 but when i have a cube with a constant force in one direction, the cube will eventually start careening to the right

#

anyone know why

timid dove
#

Is it hitting the edges of any Colliders? What's the floor made up of?

#

And how are you applying the force?

velvet rivet
#
rb.AddForce(transform.forward * forwardForce * Time.deltaTime);
#

so this is for the cube movement

#

this is the physic material applited only to the cube

#

not sure if this helps

#

i seem to get a fix if i disable gravity

ruby cobalt
#

I want my character to walk over like this steps how can I make it

untold dust
sacred osprey
#

I have an Object that travels at a certain speed, lets say 400 m/s. I want this Object to decelerate and come to halt at an exact distance, lets say, 800m. Now I want to figure out the deacceleration (-acceleration). I have searched for formulas, but I only found this one: a = 2 * (Δd - v_i * Δt) / Δt². and I dont think it is the right one.

jovial wraith
sacred osprey
#

I have it from a website, and the description of the formula is this: "Use the Distance Traveled calculator. Enter the initial speed, the traveled distance, and the time that passed. You will not need to know the final speed."

#

Because I know the final speed, 0 m/s

#

And I dont know the time

jovial wraith
#

your gut about how to choose an equation is good

#

look at the 4 options under BIG 4 on that site

#

and find one that matches the variables you know with acceleration as the only unknown variable

sacred osprey
#

thank you

twin pike
#

Not sure if this is the right place to ask but I'm making a game where the player is running and fails if it hits an obstacle, like a fence, and I want the fence to fall when the player hits it. I set the player mass to 1 and the fence's mass to 0.0000001 and it still doesn't fall, just moves slightly.

stuck bay
#

I want to join (fixed join) 2 dynamic bodies, but able to rotate

stuck bay
#

such as a wheel joint but without any suspension. when the rigidbody is shifted, it shouldnt get pulled back to the connected, instead the other body should get pulled

lethal wyvern
#

Hello How can i find the velocity of a rigidy body relative to its transform and not like the world origin

timid dove
lethal wyvern
#

is that a vector 3

timid dove
#

Yes

lethal wyvern
#

Thanks

#

you are a hero

real pebble
#

Guys, is there way to find out true velocity of the rigid body on collision moment?
I'm trying to get "relativeVelocity" from collision, but it's seems to be kinda random when I'm using it with VR. I'm punching with the same force in real life, but getting drastically different values. Please help if anyone knows.

gloomy field
#

i still have no clue my chair isnt colliding with the floor, here is the floor components:

#

and here are the chair components:

#

can someone help me please?

languid hull
#

either one should be marked convex

gloomy field
#

tysm!

ionic dome
#

So, my character model is set up with the input system, but for some reason it won't move left or right, just jump. But it's not the input system because the correct vector value is generated by the inputs, the character just doesn't respond to them. But if I perform a jump, the character jumps like it should.

#

So.... It's not enough force.....

#

hmmm

#

and it doesn't repeat as the button is held

timid dove
ionic dome
#

So now the question is how to make the input continuous for direction

steady thunder
#

Hey Guys
Is it possible that when the ball rolls through the hole that the shape deforms so that the ball fits through?

timid dove
#

If you use some kind of softbody physics simulation, sure

#

Unity doesn't have that built in though

lyric canopy
#

anyone using the Havok Physics package ? the latest "Quick Start" guide mentions to get the package in the Package Manager with "All Packages" turned on. except, that dropdown option does not exist any more it seems ( using 2021.2 ), and clicking on the Asset Store Havok Page's Personal-Plan links to .. the Quick Start guide again 😐 wat

#

does that mean it's not possible to install the free personal version just for testing ? or am i missing something obvious

#

"Enable Pre-Release Packages" is on btw

spare solstice
#

what's the difference between continous and discrete collision?

timid dove
# spare solstice what's the difference between continous and discrete collision?
spare solstice
#

@timid dove Thanks That cleared my doubts

candid pasture
#

hy! beginner here
for some reason my colliders dont seem to work correctly, and stuff can just go through each other for some reason
ive made two projects based on unity's official tutorials and both projects' colliders work fine on their tutorial video but not for me
i attached some footage of the 'go through' thing im experiencing. any help would be much appreciated

https://streamable.com/gfka5n
https://streamable.com/36yh1c

#

sorry for the poopish quality

neat coral
#

Are they on trigger?

#

Can you try to set the collision detection mode to continuous?

candid pasture
candid pasture
candid pasture
neat coral
#

what collider do you have on the car?

candid pasture
#

box, rigid body

neat coral
#

how big is it?

candid pasture
#

its shaped like the mesh

#

i did not modified it

#

made a cube, scaled it, the collider is the same size

#

and i thought maybe its a 'my model' thing since i decided to make my own stupid car instead of using the asset store like the tutorial, but after the plane i realized its not about the models probably

frosty ore
#

should forces be applied where the wheel connects to the car

#

or where the wheel contacts the ground?

#

in the gif its applying them to the anchor point thats selected.. (the top of the suspension)

candid pasture
#
Unity Learn

Overview: In this lesson you will make your driving simulator come alive. First you will write your very first lines of code in C#, changing the vehicle’s position and allowing it to move forward. Next you will add physics components to your objects, allowing them to collide with one another. Lastly, you will learn how to duplicate objects in t...

#

im following this tutorial

frosty ore
#

well... transform.Translate isnt good for physics

#

whats happening is ur car is moving into the blocks before the physics get a chance to react an tell ya u hit them

#

for a rigidbody u should most likely use Rigidbody.AddForce()

#

to move it directly

#

now there is a work around..

u can move ur car using translate and then after u move the car set the carCollider (which would be on a seperate layer) to the cars new position..

in the start u could unattach it if its a a child of the car..

boxCollider.parent = null;

and then

after ur move function

boxCollider.transform.position = car.transform.position;

candid pasture
frosty ore
#

and then use interpolation on the rigidbody to smooth out the jerkiness ull most likely git

frosty ore
candid pasture
#

i just started out. so even figuring out AddForce syntax took a bit

frosty ore
#

seems ur collision detection is different

candid pasture
#

i even tried to change transform.Translate to RigidBody.MovePosition
still goes through

frosty ore
#

can u paste ur full code?

candid pasture
frosty ore
# candid pasture

thx.. im dragging it in my project to see if i cant help ya get it working 🙂

candid pasture
#

thank you so much! i really appreciate it

frosty ore
#

i have a couple of car controllers on my YT channel w/ collision and a github project with the complete project if u wanna check those out

#

its a 3d set up tho

#

rather than a endless runner setup like u have

#

we'll try to get this to work with physics tho first 👍

candid pasture
#

im just hoping it wont get too complicated cuz at the time being im too dumb to understand anything. as i said i just started today

frosty ore
#

gotcha working 👍

#

ignore the orange car doing acrobatics in the background

candid pasture
#

currently watching ur car controller vid

frosty ore
#
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    // Variables
    public float speed = 40;
    public float speedTurn = 15;
    private float leftRightInput;
    private float forwardBackwardInput;

    private Rigidbody rb;

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    private void Update()
    {
        //Input should be called in Update so u get a new input every frame
        leftRightInput = Input.GetAxis("Horizontal");
        forwardBackwardInput = Input.GetAxis("Vertical");
        
        //rotating or translating the gameObject itself should also be done in update
        transform.Rotate(Vector3.up, forwardBackwardInput * speedTurn * leftRightInput * Time.fixedDeltaTime);
    }

    void FixedUpdate()
    {

        //anything physics related should be here in the fixedupdate

        rb.AddForce(forwardBackwardInput * transform.forward * speed * Time.deltaTime);
        
    }
}```
#

heres the code i used

#

just make sure to freeze ur rotation on the x and z

#

and that'll keep ur car from flipping over

#

i think that was ur problem originally when u tried to use addforce 👍

candid pasture
#

exactly! it worked fine with going forward. but backwards it just did a backflip

#

thank you so much dude!

frosty ore
#

no problem mate...

#

u evidently tried before hand to get addforces and stuff to work.. so ur on the right path.. code.. test.. try to fix.. rinse and repeat..

#

ull be coding up games before u know it 😄

candid pasture
#

@frosty ore
so i got to another problem. was working on it for a while but couldn't figure it out
so thanks to your help and advice about freezing the rotation on x and z axis, it now moves forward and backward nicely. the thing is with the rotation, is not effecting the path of the car and if you rotate it still goes the global forward and kinda just drifts

https://streamable.com/z19cqp

#

im going back to your youtube video for possible clues

frosty ore
#

whats the cars heirarchy look like?

candid pasture
#

the red part is the parent (which has the script, collider, and rigid body components) wheels and the top part are attached to the parent

#

i noticed you made a sphere for the overall function and mesh itself is separated. im trying translate my heirarchy the same way

frosty ore
#

well ur AddForce function uses transform.forward

#

the blue arrow is the transforms forward..

#

i think in ur example ur rotating the car model.. but the rigidbody.. (the main parent) is still facing forward

#

after u turn the car click the Car parent and see if hte blue arrow is lined up with the car or if its still facing foward down the road

#

what i do in my script is I rotate the car.. model..

#

and then when i apply forces to my sphere im not using the spheres forward direction

#

im using the cars forward direction instead

#

so is ur rotation function rotating the rb or the car model?

#

if its rotating the car model where u add forces u can

rb.AddForce(carGameObject.transform.forward * input * moveSpeed);

#

so it always pushes the force towards the facing direction of the car

#

im going back to your youtube video for possible clues

i would take this with a grain of salt.. considering my setup is very different..

i unparent the car model from the root car object in my start function.. so in my code i have to set the cars position to match the rigidbody after every time i move it..

and then i move the rigidbody relative to where the car is facing..

i have to unparent it because if it remains a parent i move the sphere and then the car moves too because its a parent.. and then sphere has to move to catch up.. so u get weird rubberbanding and stuff

candid pasture
#

and also carGameObject.transform.forward dosent seem to be the right syntax. i assume you just said it as an example but im not sure how the syntax can be corrected

frosty ore
#

yea its just an example

#

ud need to assign it

public GameObject car;

#

and then car.transform.forward; would be w/e gameobject u put there

#

's forward direction

#

something doesnt seem right tho

#

working fine in my scene

#

the car object

#

just a rigidbody and a box collider

#

car model is just an empty gameobject w/ a cube as a child

#

^ a prefab of the car.. u could just add ur graphics to the car model and line it up

#

if that package doesnt work in ur scene.. make sure ur car isnt a child of something else..

#

like Environment or something.. it might be messing up the transform.forward..

candid pasture
#

im not sure why transform.forward havent been working at all. i just have used new Vector3(0, 0, 600) all the time im not sure how to apply it with the GameObject variable

candid pasture
candid pasture
# frosty ore

wtf... i just opened the package in a completely new project and its not working like this at all

#

it doesn't move. just rotates

#

same with my project when i use transform.forward

frosty ore
#

turn the speed up

candid pasture
#

bruh right right sorry

frosty ore
#

😉

#

its a balancing act between the forces u use

#

and how much mass and gravity u have on the rigidbody

candid pasture
#

FINALLY!

#

@frosty ore thanks for everything

#

got it working

#

sigh of relief

frosty ore
#

Great news! 🙂

candid pasture
#

i lost a few braincells but boi does it feel good to finally see it working. thanks so much

frosty ore
#

not a problem..

mortal granite
#

Is there a way to push an object with a kinematic object? I have my character set to kinematic and want to push a block.

#

NVM, I'm just dumb. I do have a follow up question though. Should I add the script to do the pushing within my player controller or add it to the actual movable object? Does it matter?

timid dove
#

The object being pushed needs no script, it just needs to have a dynamic Rigidbody and a collider

mortal granite
#

Got ya. That seems better for sure. I think I’ll make a state for it, that way I can control the speed when pushing

pallid mango
#

anybody have a good method for limiting angular rotation on more than the X axis in Unity? configurable joint allows for doing it with X but that's it afaik 😦 I'm thinking of using colliders and layers 🤮

neat coral
#

limiting rotation or freezing rotation?

pallid mango
#

limiting x and z, freezing y.

pallid mango
#

nvmd, I didn't click the little thing on z limit. My brain thought the thing below showed it was already clicked. Arg.

gloomy hornet
#

How can I calculate the impact force of an object with a trigger collider and a rigidbody?

bleak umbra
gloomy hornet
#

(0.5 * mass * velocity^2)/collision distance
cool, so what if that distance is 0?
say, the two objects don't deform at all,
or should it just be a very small number?

timid dove
gloomy hornet
bleak umbra
#

nothing in newtonian physics stops instantly

gloomy hornet
#

👍

#

alright, I suppose I should find a chart of the amount by which different materials deform

#

because I somehow feel that infinite force wont fit the bill for my purposes

bleak umbra
#

making it physically accurate is probably not necessary. a simple impact model is probably giving good results too.

gloomy hornet
#

what do you mean by impact model?

bleak umbra
#

a realistic model would require simulating deformation, which is expensive

gloomy hornet
#

agreed, and definitely not something I intend to do

bleak umbra
#

it would make sense to simplify that

gloomy hornet
#

alright, I'll try testing it with some generic small values

hollow thistle
#

I have been trying to make universal physics simulation like in KSP and it works fine.
Then I tried to add an orbit like system and I can't understand it and figure out how. Any help?

neat coral
#

The orbit system is easier than the air physics imo

#

Which part do you have trouble with?

hollow thistle
#

the orbit one

#

i need to use something called initial velocity but i dont understand it

neat coral
#

have you looked into orbital maths?

#

It's essentially just gravity tho

pliant fern
#

I’m currently using a sphere collider with a torus to make an inner tube going down the slide, but i have to lock the torus’ rotation otherwise it moves unrealistically, but when the rotation is locked it also doesnt move realistically because its supposed to look like a water slide with the inner tube going down instead of just staying in an upright position

#

I’ve tried making it so that just the torus (inner tube) has proper collision but then its collision causes it to stop sliding prematurely

#

I’ve tried also using a mesh collider but it doesnt seem to work properly on it

#

Im thinking i could make it follow a path based on the slide and have it increase in velocity depending on the downwards direction it’s going and decrease in velocity depending on the upwards direction it’s going but im not sure how difficult that’ll be to code

wet bear
#

Not sure if this is an actual physics question, but:
I just added a script to increase gravity at the crest of a jump, but when the character falls from over a certain height, it clips through the ground box collider. Any tips on where to start looking into what's going wrong?

wet bear
#

thank you 🙂

#

Huh. That seems too simple. I set Rigidbody collision detection to continuous and it works ^^

stuck bay
#

I have a mesh, but I want to prevent it from falling into the ground..

#

Here's my mesh with gravity off.

#

But I want for my mesh to run without falling off the plane.

timid dove
stuck bay
#

All I needed was a capsule colllider.

wispy tinsel
#

Is there any known intros into ballistics? I am trying to simulate player as cannon ball shot, while keeping X axis fully static in 2D. Or maybe I need smth else for that?

wispy tinsel
#

welp, it appears it's ez af

#

horizontal velocity is constant

#

vertical is gravity

buoyant raven
#

why collision2d.relativeVelocity returns zero while one of the collided objects doesn't move and how to fix it?

wispy tinsel
#

what is Vector3.Up for 2D space?

#

I'm trying to make use of LookDirection

#

rotate my object based on direction vector

#

it's 0,0,-1f

#

if anyone curious

light hound
#

i have a rig similar to a ragdoll. But, i'm using 'Configurable Joints'. I'm applying torque force to a joint, how do I make it not effect its connected body as well?

steady peak
#

Is there a way to have a collider automatically fit to an object?

#

not with scripting or during runtime, just in the Unity Editor

wide nebula
timid dove
#

Which is the same as Vector3.up without a z coordinate

wispy tinsel
#

oh

#

I didn't know that was a thing xD

#

welp
0 0 -1 also works perfectly

#

and is compatible with math package

timid dove
wispy tinsel
#

true, I think my character is backwards

#

but that is intended

#
        float2 direction = new float2(horizontal.value, vertical.Linear.y).Normalized();

        quaternion newRot = quaternion.LookRotation(new float3(direction.x, direction.y, 0f), new float3(0, 0, -1f));

        var rotData = GetComponentDataFromEntity<Rotation>();
        rotData[player] = new Rotation { Value = newRot };
steady peak
empty echo
#

Lets say I have a "powerup" that I want to float up and down. I want gravity to apply to it, so that it doesn't float high in the air, only just above the ground.

How can I give it gravity via rigidbody, with a collider so that it stops at the ground, without the player colliding with the rigidbody?

timid dove
mossy swan
empty echo
#

@timid dove Forgot to respond earlier, but that was exactly what I needed. Thanks so much! 😄

coarse hamlet
#

is there any easy way to make a RigidyBody2D with dynamic simulated physics NOT slide down a slope?
currently my enemies are using RB2D, and they cannot climb even slight inclines, they just slide down

#

oh actually a physics material with a friction of 1 kinda does the trick

silk stone
#

i wasnt sure where to ask this because its about colliders but ill try here:
i have my map that has a mesh collider for the player to walk and etc, and i want to make it so when the bullet hits anywhere on the mesh colilder it will destroy the bullet, but it doesnt work in some places:
on this corner it works:

#

but on that wall it doesnt:

slate lily
#

Make box collider ignore steps mesh collider anyone can help?

timid dove
slate lily
#

I dont care how big the solution is I just need it

slate lily
#

Basiclly my question is can I disable collision at specefic point on a collider

#

Not the whole collider

#

Or ignore it at that point

timid dove
#

Not easily

#

Maybe with the contact modifications API

ripe coral
#

Guys, need your help!
How do you fix glitching on character movement thru non-flat textures?
Please take a look on short video below. Character experience "blinking" glitch..

timid dove
ripe coral
timid dove
#

You verify by reading your code

ripe coral
#

Doing now, but I dont think I ever call it more than in one FixedUpdate

timid dove
#

Are you using CharacterController or Rigidbody?

ripe coral
#

CharContr

timid dove
#

Alright so count the times you're calling Move

ripe coral
#

I have really big "solution" for movement that i did a year ago 🙂 checking that my function to move charcontroller not called more than once. Thanks! will update

ripe coral
slate lily
ripe coral
#

That is better video of the issue...
Guys please advise how to fix that?
I'm using CharacterController.Move()

stuck bay
#

can i get some help on my ap physics hw

#

it's kinda hard

hollow echo
stuck bay
#

it's for my unity class

hollow echo
#

It isn't

stuck bay
#

it is

#

it's for ap physics u mech

#

mechanics for unity

#

colloquially ap physics c mech

wide nebula
#

Sure, if you can show your work in Unity, you can get help. Otherwise:

hollow echo
#

If it's not got Unity in it, it's not directly Unity-related. Seeing as you phrase it as "physics homework", I am inclined to believe you are lying

stuck bay
#

i never lie

#

the juggling image is a unity sprite

hollow echo
#

!mute 722482434154823750 24hr no

flint portalBOT
#

dynoSuccess the one true god#7771 was muted

tawdry dawn
#

hey, why does Unity sometimes ignore collisions with small triggers, if they happen at a fast speed? Any way on how to prevent this from happening? I had an issue like this and fixed it by making my trigger bigger, but still, this is probably not a perfect solution.

timid dove
# tawdry dawn hey, why does Unity sometimes ignore collisions with small triggers, if they hap...
tawdry dawn
#

This explains everything, thanks a lot

nocturne fern
# ripe coral CharContr

Wait wait wait,

Please tell me you're not using a character controller's .move function in fixedupdate?

ripe coral
nocturne fern
ripe coral
#

Give me 30 min. Brb home soon

nocturne fern
#

Also double check your variables on the character controller component.

The skin width should be about 10% of the radius and min move distance should be set to 0. This is not default, but the official docs say it should be 0 in most cases. Why they have the default set to the exact opposite of what they would recommend? I have no idea.

#

These values work well for me but your character may be bigger/smaller

ripe coral
#

@nocturne fern My movement code is huge but in fact, I have a function StartMotor() listed in "update"
And start Motor itself contains
_characterController.Move(_playerDirectionWorld * Time.deltaTime);

#

I also tried values in your examples (i have super similar and tried both). No changes

nocturne fern
#

Well first of all displacement is equal to velocity x time not direction x time. But I'm guessing that's just a misnamed variable.

One line of any code will never really reveal the issue. Like I said check your character controller settings, bad skin width values can cause problems and if minimum move distance is not set to zero it can cause stuttering.

ripe coral
nocturne fern
#

Is it just the rock mesh that you have trouble with or is this happening often?

ripe coral
#

all meshes where my slope limit close to the angle I need to move on it

ripe coral
#

It was a code issue indeed...
My function to apply sliding was glitching 😉
thanks for help anyway!

stuck bay
#

for my ai instance, the raycast2d does not originate inside the collider that is attached to the child gameobject. it originates insides the parent's collider, how can i make it ignore the parent collider. at the same time, i dont want it to ignore it self, because there are other instances that are clones of this gameobject

nocturne fern
unique cave
#

<@&502884371011731486> nitro scam

supple pawn
#

Hi guys, I have a PID controller to balance a bike but I have problems when its going uphill or downhill, anyone can give me some insight regarding this?

frozen adder
#

Hmm, Hello everyone, I have this problem that when my object collides with a certain collider instead of inverting its velocity, it decreases the velocity value very little value over time, it works well when colliding for the first time, but when it collides for a second time it encounters the problem I mentioned earlier, any advice for this?
P.S : Sorry for bad english

manic harbor
#

So in my game, i created a forcefield shader that i applied on a sphere mesh. now i want to use that forcefield as a barrier for my map, like a battle royale damage circle altho with/without collision. how do colliders work with meshes with inverted normals?

#

like if i have a sphere thats inside out, will it act weird or? i remember having some extremly weird glitches before where my player would shake a lot but it could be unrelated, but i'm still unsure if this is even the right approach

#

Oh and it's in 3D btw

neat coral
#

you can always enable backface

manic harbor
neat coral
#

then you don't have to invert it

manic harbor
#

im not too familiar with backface stuff's tbh

#

ah

neat coral
#

I presume then it should just work

#

but do you actually want to use it as a collider anyways?

#

probably just a trigger?

manic harbor
#

well idk im thinking about that tbh, i think it would be cooler if you slowly died from going out of bounds instead of just getting bounced off by a wall

neat coral
#

if it's a sphere it can just be a distance check as well

manic harbor
#

like from the center?

neat coral
#

yeah

manic harbor
#

hmm that could work too

#

I think i’ll do a distance check tbh, sounds like the easiest solution. Altho i’m still a bit unsure on how backface culling works so i’ll dig deeper into that though

#

But thanks for the help!

neat coral
#

hope I didn't give too many wrong infos

prime matrix
#

Hi,
i am having the problem that objects fall through the terrain, once physics applied.

Setup:

  • Terrain with Terrain collider
  • Stone Object with Mesh Collider and RigidBody
#

If i click start, the expected behaviour would be that the stone rolls down the mountain on either one side, but what happens is that stone falls through/into the mountain terrain

prime matrix
#

(see around mid of video, the white box is setup collider whise like the stone)

fleet silo
#

I'm putting together a first-person character controller. And I must be mixing up local vs global in some way. But I just can't work out what I'm doing wrong. I have head tilt (pitch) and player turn (yaw) all working and camera is hooked up. But when I move forward, the player only moves forward when I'm facing the +'ve z direction. If I turn 90 cw, moving forward moves the player rightward. Here's the code to move the player forward...

// forward
Player.transform.Translate(Player.transform.forward * forwardDelta);

It's like it's applying the transform locally rather than globally - as in, it's applying the vector twice.

fleet silo
#

So yeah, this works ...

Player.transform.position += Player.transform.forward * forwardDelta;

But isn't that the same as the previous version?

remote lance
#

Hello, i'm having a problem with 2d colliders. feel free to inform me if this is not the right channel to post about this problem. i'm doing an endless runner minigame right now. i've done everything i know to make the coin pass through-able while destroying it. 80% of the time theres no problems, but sometimes when i jump at it from below it bonks my player character on the head anyway. any advice?

#

the code on the coin prefab that interacts with the player's player tag

#

the coin prefab's components

wide nebula
#

If you want to pass through a collider while also detecting it, you need to turn on IsTrigger on the coin's collider.

remote lance
#

thank you, i will try that.

wide nebula
remote lance
#

double thank you 😄

#

@wide nebula triple thank you, it worked

obsidian warren
#

Why when I rotate my boat it goes up like a helicopter

#

The more I rotate the faster it spins up

crude finch
#

in the first video the physics of the swords break and go allot slower when it is published but in the second video in the editor it is working as intended.

Has anyone gotten this problem before, i can't wrap my head around it

shadow seal
#

maybe you forgot to make some part of it framerate independent

compact talon
#

hi im using a basic rigidbody2d and the issue im running into is that occasionaly, the player will land and he'll do a small bounce with no jump input

#

im not sure how to fix that, if i even can but would be appreciated

prime matrix
# neat coral check your layers

Thank you for looking at my problem, can you be a bit more specific maybe, i tried to figure what you mean but wasn't successfull

woeful pulsar
#

I have a ball with 1 collider + rb and a cylinder with 1 collider.

Cylinder monitors for OnCollisionEnter and performs the following logic if the colliding object is the ball :
set ball's velocity to zero, add force to ball in direction ball.position - cylinder.position(so away from cylinder)

Somehow, OnCollisionEnter gets called twice occasionally

#

any gotchas I don't know about?

woeful pulsar
#

ok, well apparently setting the velocity to 0 directly was the culprit.

ball.Rigidbody.AddForce(ball.Rigidbody.velocity * -1f, ForceMode.VelocityChange);

works fine

round bronze
#

Anyone know how to make chracter controller ignore raycasts

clear belfry
#

Can anyone help me on the difference of center of mass and center of gravity in Unity? I understand that there's ways to set both in code, but how are either calculated in the first place? Do they relate at all to the objects origin, or the origin of the mesh being used for the collider?

#

Many tutorials treat them as being the same, but from my understanding they are not, right??

unique cave
digital stump
#

hello, I have a question. is it make any sense? and if yes how much performance I'll get?

wide nebula
#

Don't crosspost @digital stump

unique cave
wide nebula
#

The car should be checking the collision to avoid having potentially hundreds doing it themselves.

digital stump
# wide nebula Don't crosspost <@437632464555474944>

I got it. sorry, just didn't know what topic will suit better. I won't do so in the future
about the answer- I forgot to mention that I will be sending Do_Something(Vector3, GameObject, and Float) is it still better to Put a Collision-check on the Car?

wide nebula
#

Yeah, even just because as mentioned above it makes logical sense the car is responsible for this.

#

The car crashed into the tree, not the other way around.

digital stump
#

Cool, i see. THX again

toxic field
#

Hi all! I'm having a little strange behavior from Physics.CheckBox where it can detect an object outside its collision scale, and its offset is quite large 😦

#

idk, what is happening?

#

all scales are 1

#

maybe it's debug with wrong scale?

#

ahm...

#

now works correctly

#

I just subtract the scale from it by (1,1,1)
so... does that mean physics.CheckBox by default comes +(1, 1, 1)?

#

this is kinda confusing...

rare bluff
#

anyone know how yo use animation rigging for gorilla tag movement?

idle estuary
#

Hey guys, I added a Physic Material 2D to my tilemap but it doesn't seem to affect my player (who has a dynamic body type). Changing the values of the material at runtime or inbetween doesn't change a thing :/

#

Okay so PS: Not exaclty. The friction value doesn't seem to change a thing

willow dirge
#

can anyone share a resource for "swiping touch control for hypercasual games"?

shrewd umbra
#

anyone know why my cube wont touch the ground?

#

its a 2d cube sprite

wheat shuttle
shrewd umbra
#

ints not the collider

unique cave
shrewd umbra
#

can i set it compelatly to 0?

unique cave
# shrewd umbra can i set it compelatly to 0?

it can't be 0 but it can be close (0.0001 seems to be the smallest value). small values can cause some jittering so it would be better to decrease it only the amount you really need

median rampart
#

how do i get my fixed joint to not break?

#

the break force and torque are both infinity

#

but it still breaks

crystal tundra
#

anyone have any idea as to why I am getting these irregular physics.processing spikes?

#

Many thanks

swift pagoda
#

Hi guys, I have the following problem, when my player jumps on a slope, it jumps more than in the normal ground.

The code for jumping is

        {
            isGrounded = false;
            rb2D.AddForce(new Vector2(0f, jumpForce));
        }```

Is there any way to fix that?
timid dove
#

I'd guess you're applying the force more than once on the slope

#

But hard to say without seeing more code

obsidian warren
#

my boat wont tilt normal again?

crystal tundra
obsidian warren
#

well it literally wont tilt to 0 degrees on the z-axis

#

When it tilts to the left or right, it wont tilt back anymore

crystal tundra
#

its impossible to debug your problem with that information

#

I would need to see code etc...

#

there is no way of telling where the problem lies if all I have is a picture of a boat

obsidian warren
#

my code is not preventing it from tilting back

regal summit
#

I have a Rigidbody2D that I call MovePosition on in FixedUpdate. This works.
If I parent that RB to a gameObject who's transform.LocalPosition is being set to on Update or FixedUpdate, MovePosition no longer moves the RB.

How can I move the RB respective to its parent, but also still be able to move the RB itself?

turbid cipher
#

Hello everyone.
I am facing this issue in my game:
Whenever the player touches an object that has an animation in the environment, it clips out of the map and falls down..
What did I do wrong? And what should I do to fix it?

cold rivet
#

im trying to get this "spoon" to be attached to a spinning joing, but when i do it glitches out when the player bumps into it

coral mango
#

Is there a preferred method for getting the average of collision contacts? For instance, to spawn a prefab at the averaged position and normal of multiple contacts. Or is there a better approach altogether?

keen river
#

Ok, odd question: let's pretend we have a character with hair at the back of its head, hair that can take the form of strange wings (darker part on sketch, connected to the bottom back of the head).
The hair does not require any energy in this case, and it can be more or less dense.
Can the character possibly fly with this size of wings? If yes, how fast should the wings flap for the character to fly?
Otherwise, how big should the wings be so the wings don't have to flap at a ludicrous speed?

#

(also check previous, more help-requiring questions)

keen river
#

(so, the back/front flight motion)

#

It actually doesn't seem specific to bumblebees, even less if you include fictional characters yet the flight may get mixed with bird flight and/or the the characters can also glide.

wispy tinsel
#

any tip what I could possibly miss when setting up collision detection?

#

my OnCollisionEnter2D is not getting called

timid dove
#

only works with dynamic bodies

wispy tinsel
#

any way to at least call check myself?

timid dove
#

You can use a trigger instead

#

that will work with a kinematic body

wispy tinsel
#

I really want it to be kinematic

#

oh

fierce mulch
#

Hey,
so i played SpaceFlight Simulator an my Mobile and im trying to recreate the Planet Orbits (Gravity). I tried with Newtons Law but it doesn´t seem to Work quire right. I gave every Physic Object a Script so they attract each other based on the Mass. Does anyone have a better Solution? I would Love to be able to launch e.g a Rocket from the Planet 😄

wispy tinsel
#

what would be a method for trigger collision?

#

found it

timid dove
fierce mulch
#

Oh sorry i forgot to link the Game or any Footage and i already watched Sebastian Leagues Video 😄

#

My Problem is that the Planets are moving to Objects with very little Mass too but they should stay in there Orbit around for example a Star and that when a Object is to Close to the Ground its getting Stuck inside the Planet

timid dove
#

I mean it just sounds like you're complaining that your physics are too realistic?

elder mango
#

Hi people, anyone knows about Cloth in Unity? I have a character with a cloth hanging from his belt, is it strictly necessary that the mesh of that cloth be separated from the mesh of the character?

wispy tinsel
#

Is there a way to run collision check myself? Basically I simply want to have collider only, without any rigid bodies

#

and on demand I want to see whether that collider collides

timid dove
#

Feel free to browse the scripting reference to see all of them

wispy tinsel
#

you mean do collider casts?

#

not really what I want

#

but I guess physics don't work that way

timid dove
#

I mean any of those various direct physics queries, including but limited to xxxCasts

idle estuary
#

Good evening guys.

I have tried to find the solution online but couldn't find an answer. I'm trying to create an icy ground but can't seem to make it work. My character is simply ignoring the friction (bouciness works). I gather it is because my player movement is dependant on the renewal of the velocity each frame but I'm lost on how I could fix that. Simulate fricition with the gorund ?

#
    {
        dirX = Input.GetAxisRaw("Horizontal");

        if (dirX < 0 && (speed > -maxSpeed))
        {
            if (rb.velocity.x <= 0)
            {
                speed -= acceleration * Time.deltaTime;
            }
            else if (rb.velocity.x > 0)
            {
                speed -= 2 * deceleration * Time.deltaTime;
            }
        }
        else if (dirX > 0 && (speed < maxSpeed))
        {
            if (rb.velocity.x >= 0)
            {
                speed += acceleration * Time.deltaTime;
            }
            else if (rb.velocity.x < 0)
            {
                speed += 2 * deceleration * Time.deltaTime;
            }
        }
        
        if (rb.velocity.x > deceleration * Time.deltaTime)
            {
                speed -= deceleration * Time.deltaTime;
            }
            else if (rb.velocity.x < -deceleration * Time.deltaTime)
            {
                speed += deceleration * Time.deltaTime;
            }
            else
            {
                speed = 0;
            }
        
        rb.velocity = new Vector2(speed, rb.velocity.y);
    }```
#

The part of my script controlling horizontal movement

timid dove
idle estuary
#

It is perhaps I'm fairly new to Unity 🙂

#

I will look into that

#

thx

elder ore
#

I can't seem to get the DOTS physics package to work, I'm getting errors at Broadphase.cs:873, Is there a specific Unity version I should be using? I'm using the latest LTS

thorny pike
#

please help, I don't know why why transform is not locking to its child objects

#

the child object positions is 0,0,0 to its parent, but when I move the parent position, the child gets separated to its parent origin

timid dove
thorny pike
#

ohhhh ok, how did that get switch

#

thank you, @timid dove

fallow harness
#

both of these objects have a collider but they wont collide. can someone help?

fallow harness
wispy tinsel
#

Irrelevant question:
Is there a way to get collision info in Trigger collision in 2D?
Basically I need to get at what angle collision happened and on what distance.

#

OnTriggerEnter2D(Collider2D collision)
Only provides collider

fallow harness
#

maybe get the rotation of the collision

#

idk for sure im not used to 2d games

wispy tinsel
#

yep

#
            RaycastHit2D[] results = new RaycastHit2D[1];
            collision.Cast(playerController.PlayerVelocity, results, 0.1f);
#

I guess I need to make my own new cast

#

sad life

wispy tinsel
#

Sooo, my 2D sprite is constantly rotating in update to look at where character is going.
I want to add flip annimation (360 angle flip) on Z axis, but with respect to that look rotation.
Basically character does flip, but at the end of animation he will naturally slowly get to his look current look rotation.

    private async UniTaskVoid FlipAsync(float duration, CancellationToken cancellationToken)
    {
        shouldRotate = false;
        var endTime = Time.time + duration;
        var angleDelta = 360f / duration;
        float angle = transform.rotation.eulerAngles.z;
        float time = 1f / duration;
        float counter = 0f;
        while (Time.time < endTime)
        {
            counter += Time.deltaTime;
            Quaternion targetAngle = (counter * time < 0.75f) ? Quaternion.Euler(0f, 0f, angle) : VelocityRotation;
            transform.rotation = Quaternion.Lerp(transform.rotation, targetAngle, Time.deltaTime * 5f);
            angle -= angleDelta * Time.deltaTime;
            await UniTask.Yield(cancellationToken);
        }
        shouldRotate = true;
    }

I came up with this little part, but it doesn't respect current rotation (VelocityRotation) enough. So after animation is over by 75% it starts lerping towards that look rotation, but since that swap is instant - animation feels unnatural.
Any tips how I can smooth it along whole animation cycle?

#

And that "constant" rotation I mentioned earlied is disabled by shouldRotate

viral ginkgo
#

or make your lerp interval (Time.time-startTime) / (endTime-startTime)

#

instead of Time.deltaTime*5f

wispy tinsel
#

and creating them is just next level complexicty

viral ginkgo
#

@wispy tinsel So you have a character
In a top down game

#

Probably looks at the mouse position

wispy tinsel
#

platformer

#

looks at his velocity vector

#

and I want to him to do flip

viral ginkgo
#

So its not top down?

wispy tinsel
#

no

viral ginkgo
#

Okay

wispy tinsel
#

damn, should have mentioned it

viral ginkgo
#

If your characters forward is the look direction, I'd have easy time explaining a solution with quaternion.lookdirection and quaternioun multiolication

wispy tinsel
#

I do use LookDirection

#

to determine quaternion of velocity direction

viral ginkgo
#

Quaternioun.Euler(0,0,interval * 360) * Quaternioun.LookRotation(velocity)
?

#

wanna do something like this?

wispy tinsel
#

not really

#

I want my character to flip

#

sooo

#

for example he is falling

viral ginkgo
#

thats flipping

wispy tinsel
#

and hits some bubbly object

#

he jumps back into air

viral ginkgo
#

flipping with respect to look

wispy tinsel
#

while also doing 360 flip

viral ginkgo
#

ah but velocity also changes alot

wispy tinsel
#

yeah

viral ginkgo
#

and thats the problem

wispy tinsel
#

so initial rotation won't be equal to end rotation

#

and that my first code shows it in it's glory

#

rotation gets big spike at the end

#

so I think I need either figure out

#

how to change deltaAngle over time

#

which is target angle basically

viral ginkgo
#

why does flipping needs to depend on velocity?

wispy tinsel
#

it doesn't need to

#

but that I meant

#

when flip is over

viral ginkgo
#

then the problem is just recovery from flip okay

wispy tinsel
#

that original 0 angle when flip started

#

yeah

#

exactly

#

recovery

viral ginkgo
#

rotation = quaternioun.slerp(rotation, quaternioun.lookrotation(vec), deltaTime * 5)

and whats the matter with this?

wispy tinsel
#

so the only good fix to this would be making flip smooth so it's end position would be that look direction

#

well matter with this is that after 75% when instead of my 360 rotation I start to lerp to velocity rotation

#

which is supposed to be recovery

#

it's just bad

#

because velocity rotation can be very different

#

and thus if it's too big -> lerping through it is way faster than initial flip lerping

viral ginkgo
#

so you wanna continue the flip rotation until it meets the velocity rotation and then you wanna stop the rotation?
@wispy tinsel

wispy tinsel
#

kinda, but it needs to be in fixed time as well

#

so whole flip takes 2 second, neither less nor more

#
        var endTime = Time.time + duration;
        var angleDelta = 360f / duration;
        float angle = transform.rotation.eulerAngles.z;
        float time = 1f / duration;
        float counter = 0f;
        while (Time.time < endTime)
        {
            counter += Time.deltaTime;
            transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(0f, 0f, angle), Time.deltaTime * 5f);
            float curAngle = transform.rotation.eulerAngles.z;
            if (-10f <= curAngle && curAngle <= 10f)
            {
                break;
            }
            angle -= angleDelta * Time.deltaTime;
            await UniTask.Yield(cancellationToken);
        }

here's my best take on it

viral ginkgo
#

could check the difference between rotations and its below some value, you can do the lerping

wispy tinsel
#

once I reach Identity rotation I just break lerping, but it's not doing fixed time

#

so it just recovers itself, which makes it somewhat smooth

#

but still can be glitched if current velocity looks almost at floor (0,-1,0)

viral ginkgo
#

your flip needs to ends in 2 seconds huh

wispy tinsel
#

it's just example, obviously I'll play with values

viral ginkgo
#

i mean a fixed duration