#⚛️┃physics

1 messages · Page 30 of 1

elder lintel
elder lintel
#

fixed it on my own

elfin latch
timid dove
#

I would guess a script setting the vertical velocity to 0 each frame, that's the usual cause

elder lintel
#

Basically what Praetor said

signal wyvern
#

Anyone able to help me debug my Client Prediction setup for my game, Im currently predicting the entire scene, this includes water, bouyancy and the boats, Meaning that almost everything you see as a client is ahead of the server, the clients then receive updates from my server, client then resets to this update and re-simulates back up to its current frame, continuously realligning the client with the server. im specifically stuggling with the boat destruction and im getting some jitter when splitting boats which indicates a difference in state, Im reappling joints and resimulating the destruction for clients which i believe is potentially causing this jitter, wondering if theres any experts out there which know everything there is to know about adding/destroying joints specifically fixed joints.

wicked phoenix
#

Hi, does anyone know of a clean way to move a non-kinematic rigidbody character on a moving kinematic-rigidbody platform? I currently have the platform using a spline so that it loops around smoothly in FixedUpdate.

Here is the script for the moving platform currently:

public class MovingObjectParenter : MonoBehaviour
{
     [SerializeField] private Rigidbody rb;
    [SerializeField] private List<Rigidbody> collected;
    private Vector3 prevPos;
    private Vector3 _velocity;


    void Start()
    {
        prevPos = rb.position;
    }

    void FixedUpdate()
    {
        Vector3 _distance = rb.position - prevPos;
        _velocity = _distance;


        for (int i = 0; i < collected.Count; i++)
        {
            collected[i].MovePosition(collected[i].position + _velocity);
        }

        for (int i = 0; i < agents.Count; i++)
        {
            agents[i].Move(_velocity);
        }

        prevPos = rb.position;
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.TryGetComponent(out Rigidbody _rb))
        {
            if (!collected.Contains(_rb)) collected.Add(_rb);
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.TryGetComponent(out Rigidbody _rb))
        {
            if (collected.Contains(_rb)) collected.Remove(_rb);
        }

    }
}

It "somewhat" works on the player, but the player slides around too much during the movement. Any help is appreciated. Note: I move the player rigidbody using AddForce.

signal wyvern
wicked phoenix
#

Unless I can figure out an alternative way to "fake" that movement I guess

signal wyvern
#

my game is above we move entirely on moving boats

wicked phoenix
# signal wyvern What are you struggling with?

It's mainly keeping the rigidbody player on the moving platform. Either the player just doesn't move fast enough with the platform or he slides too much in the direction of the platform's movement

signal wyvern
wicked phoenix
signal wyvern
unique cave
signal wyvern
#

If i were you i would make a child object of the platform, with no physics & i would set the players rb.MovePosition(ChildObject) each frame

#

you can then apply player movement to the child object which will automatically consider the movement of the platform

pulsar canopy
#

Is it possible to add IK to joints in any meaningful way? Or, joints to ik.

ideally, they would behave the same like normal IK but be reactive with the environment?

Or do I have to forego the animator and write some kind of movement system for the joint that would emulate ik movement?

bleak umbra
pulsar canopy
bleak umbra
# pulsar canopy I have already used anim rigging extensively. I'm trying to figure out if and ho...

Well, they are fundamentally opposed concepts. To make them cooperate you need some sort of negotiation mechanism like Ubisoft‘s IK Rig discussed here https://youtu.be/KLjTU0yKS00?si=ORFMo95zwygaAhmh

In this 2016 GDC talk, Ubisoft's Alexander Bereznyak breaks down the basics of IK Rig technology for animators, and explains how it can be used for everything from video games to feature films.

Register for GDC: http://ubm.io/2gk5KTU

Join the GDC mailing list: http://www.gdconf.com/subscribe

Follow GDC on Twitter: https://twitter.com/Officia...

▶ Play video
pulsar canopy
#

the closest thing to what I'm trying to do is puppet master but I've also tested that in a number of ways and it didn't work in my case

#

maybe I should remake puppet master with my own rules and joint types and logic etc.

valid cave
#

hey i'm making a 2d platformer game and just started making the prototype and almost finshed the movement script done but i have a bug where my rig or player is sticking to the edge of a box collider 2d here my code using UnityEngine;
using UnityEngine.InputSystem;
you will not get credit when i realse the game
because i will forget your name or username https://paste.mod.gg/cuvicopulcbs/0

silver moss
#

If your character was moved by recalculating the velocity each frame, it'd be easy to just add the current platform's velocity to the final velocity before applying

wicked phoenix
wicked phoenix
#

I'm using rigidbody.MovePosition to apply the platform's movement change to the player

signal wyvern
#

My physics is in simulation mode: script for networking purposes, and ive realised that interpolation does not work when in this mode for some reason, does anyone have any fixes for this or know of any workarounds to get some interpolation, otherwise my objects just move at the fixedUpdate rate which is only 50fps

pulsar canopy
#

I have an ik chain for my player's arm which grabs the environment and pulls the player forward when moving (or at least that's what it should look like).

It works well but it doesn't have reactivity with the environment that I would want.

I turned off the animator and rig weight and tried building a chain of configurable joints. It gets me the reactivity that I want (i.e. player extends hand forward but is blocked by a terrain piece jutting out, so he bends the arms inward) but I find this hard to control.

It also only works if it gets stuck there for a bit, otherwise it just moves forward through parenting.

I have problems transitioning the animation to the next iteration of it because my hand just gets stuck behind the player.

Bare in mind, I'm talking about crawling through tight tunnels and pulling myself forward with the hands. Even if I manage go get the hand stuck on terrain (purpose being to make it appear like he's grabbed the terrain, it gets left behind the player when he moves forward and there is no space to bring it back.

I've been thinking of some kind of system that combines joints and ik but it's tough to make that combo work I think. Does anyone have any ideas on what I could do here?

Making a dual rig is another options without joints, just rigidbody colliders but I'll have the same problem pulling it back

late hound
#

Working with an fps movement system i created based on dani's old movement tutorial but heavily adapted to my needs. Everything works great the only problem is the fundamental issue of applying external impulses (such as an explosion force) or a knockback.

The system doesn't use unity's friction (friction on all objects is zero) and instead uses a custom countermovment logic, the problem is that when a player recieves a horizontal knockback while grounded they barely move, compared to while airborne they go flying.

This seems to me like a fundamental flaw in the movement system I created, but pivoting to a whole new system is kind of impossble right now unless absolutely neccessary.

Any other advice and feedback regarding the code is also very welcome!

*Main movement lines are 700-800
This is for an fps parkour game
For additional reference, the player should not be able to surpass their maxspeed with their own input (walking, sprinting, etc), but things like external impulses (explosions, and such) should allow the player to go far beyond their max speed

timid dove
late hound
# timid dove I haven't read your code (on mobile) but it sounds like you're probably doing so...

im almost sure the problem is coming from the countermovement block which is used to keep the movement snappy and also stop the player when no inputs are pressed and they are grounded, the problem is how the countermovement is programmed is contradictory to letting external forces be applied and i don't really know how to still keep the movemeent snappy but also allow things like explosions and impulses to affect the player

#

perhaps i could have an external script handle the forces applied to the player applied by explosions, but i don't even know where i would get started

twin bramble
#

You can modify the counter force in air to make it a bit better

noble prawn
#

hey so I'm turning gravity on in a rigidbody via a script like so:

public void Interact() {
    if (Player.Instance.HasBeerCup()) {
        //Player is carrying a beer cup
        BeerCup playerBeerCup = Player.Instance.GetBeerCup();
        playerBeerCup.SetBeerCupParent(this);

        int beerCupTableLayer = 7;
        beerCup.SetBeerCupLayer(beerCupTableLayer);

        beerCup.transform.GetComponent<Rigidbody>().useGravity = true;

        float beerCupPushForce = beerCup.transform.GetComponent<Rigidbody>().mass * 2 * (tableLength / Mathf.Pow(timeForBeerToGoToTheEnd, 2));
        beerCup.Push(transform.right, beerCupPushForce);
    }
}

but for some reason, despite me turning gravity on, the rigidbody still won't fall

#

I already checked if it is kinematic, which it wasn't

#

has anyone encountered this before?

#

this interact function is also only called once; when the player clicks the interact button

#

but for one, it seems like the rb moves forever

#

and two, the y value never changes--so the gravity isn't working

#

I've also tried adding a friction physics material to the surface but that doesn't seem to stop it either

twin bramble
#

After u cause the script to change them ofc

#

And change it manually to see if it's a problem with the script or with the rigidbody

worldly burrow
#

Hey, I am trying to make a pong clone but I am a bit unsure on how to handle the physics. I made the two player paddles by locking the X and Z axis, and moving them up and down with rb.MovePosition(). Still, when the ball hits one of the paddles from up or down, that paddle it's pushed because of the applied force.
I tried using Kinematic body type but now learned that it doesn't interact with other objects. Is there a way to create a body that cannot be pushed by other objects but still be stopped by static ones or push other objects?

pulsar canopy
#

But really, the best way would be to use kinematic rigidbodies and manually code the ball movement as it would only require using reflection vectors and no other calculations.

worldly burrow
#

My first guess would be to establish a max and min y in a variable and not allowing the paddles to move further if they are already there, but I wonder if there is a different aproach

worldly burrow
kind mauve
#

@tender gulch #💻┃unity-talk message
that does not seem to work
I double checked all colliders, main one have a layer not included in mask, all other colliders have layers included in a mask, and everything have rigidbodies
code samples in case

Physics.Raycast(shooting_barrel.position, mob_ai.target.coords - shooting_barrel.position, out RaycastHit hit, test_mask_of_shooting);
RaycastHit[] hits = Physics.RaycastAll(shooting_barrel.position, mob_ai.target.coords - shooting_barrel.position, test_mask_of_shooting);
foreach (var ht in hits)
    {
         Debug.Log("RaycastAll hit " + ht.transform);
    }
Debug.Log("Raycast hit " + hit.transform);

Maybe Unity don't allow parent collider exclusion?

#

Raycasting all hits everything, Raycasting one hits only first biggest collider (parent)

tender gulch
#

As well as hit.collider.gameobject

kind mauve
#

all that looks right

#

I mean I can just use RaycastAll and pick what I want but I don't understand why Raycasts hitting everything

tender gulch
#

As well as the layer of the hit object.

#

Also....

#

Can you put the normal raycast log right after the raycast and not after raycast all?

kind mauve
#

seems like logging out LayerMask doesn't work

tender vapor
kind mauve
#

640... whatever that means

#

I ve heard of bitwise operators or something but it looked like LayerMask type allowed me to bypass that

#

that might be it!

#

I mean issues with a mask

tender gulch
#

or rather index 7 and 9

tender gulch
#

Yeah, it's probably used as the max distance:

public static RaycastHit[] RaycastAll(Vector3 origin, Vector3 direction, float maxDistance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal);
#

And probably same in the single cast as well:

public static bool Raycast(Vector3 origin, Vector3 direction, float maxDistance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal);
#

So you're just not using the layermask as a layermask

zenith parcel
#

guys im trying to use character controller for my player but its not applying collisions so it just phases through the floor and falls, but when I try to put a BoxCollider it says it conflicts with the character controller

silver moss
#

So the issue is in your code or object setup

#

Does the floor have a proper collider?

zenith parcel
silver moss
#

Have you confirmed that it is the correct size

#

If yes, then it's probably a code issue

#

Your character movement code

zenith parcel
#

the movement code is literally just this

#

btw after messing up some properties, now the player just get stuck in the same y position instead of falling

kind mauve
timid dove
tender vapor
#

praetor's question wasn't a suggestion

#

with a CC, you need to apply gravity yourself

zenith parcel
tender vapor
#

well, normally, you'd store the vertical velocity yourself, apply acceleration, and then combine that with the horizontal velocity in the move (1 move per frame)
(with extra logic - if grounded, apply a fixed grounded vertical velocity)

#

i don't know how much, if any, of that changes with the context of network

tender vapor
zenith parcel
tender vapor
#

i believe that's handled by CC, assuming your Move calls are set up correctly

barren gorge
#

PhysX docs says that you should call Move only once per frame

pulsar canopy
#

Can anybody explain articulation bodies to me?

Loke, I tried chaining joints to one another for something, but it was unstable and jittery when constantly colliding with stuff.

All I understand is that art. bodies are supposed to help with that. Maybe? What is the feature that makes them more enticing that joints?

noble crown
#

the rigidbody's velocity stays at zero, even though it's explicitly marked as nonkinematic and has a velocity change of 250 being applied to it

tender vapor
#

which object is supposed to move?

#

make sure the code is being called as well

noble crown
#

the fragments that come off. they're visibly moving, but they should be going extremely fast. currently they just fall

noble crown
tender vapor
#

show the code and the rigidbody setup

#

!code

gloomy lodgeBOT
noble crown
tender vapor
#

waiiit 3d rigidbodies do have info..

noble crown
#

indeed they do

tender vapor
mellow cradle
#

use force impulse on your rigidbody 24/7

tender vapor
#

don't do that.

mellow cradle
#

ok fine add an input command first then do it and become superman

tender vapor
#

impulse isn't a continuous force

mellow cradle
#

multiply it by 100

tender vapor
#

that's not at all relevant to what i said

tender vapor
mellow cradle
#

its a rigidbody command

tender vapor
#

have you tried debugging the overall force you're applying, eg force * mult * 100

noble crown
tender vapor
#

though i guess you'd just have to debug force, it's the only possibly-zero one there

#

and you've debugged that it's indeed velocitychange?

noble crown
#

yes

tender vapor
#

are you doing linearVelocity = ... anywhere?

noble crown
#

nope

#

nor do i set the velocity manually in any other way

tender vapor
#

well, that's all my ideas

timid dove
noble crown
#

ok, it looks like destroying the fixedjoint before adding the force fixes it. the only problem is that i don't want to guarantee that damaging the thing will kill the joint...

timid dove
noble crown
#

i’d assume there would be a null reference exception, which i would definitely consider an error

timid dove
noble crown
halcyon sentinel
#

funny bug i came across while trying to sort out some movement

dapper arch
#

what's the best way to check how much distance a raycast/linecast "spent" in a collider? i have an idea to just raycast in two directions (first raycast from A to B, another one from B to A), check their raycast hits and calculate the distance between their points, but maybe there's a better way to do that?

crisp owl
#

hit.fraction

#

tells you the fraction of the ray to the hit point

#

the other part is past the hit point, which you could assume is inside the collider

#

it gives an answer from 0.0 - 1.0 so youd have to multiply by ray length to get the actual length

#

if you want something more complex, like also being able to tell when the ray leaves, I would use RaycastAll

#

itll give you all the points, and you can feed that into some system to figure out how much distance the ray was inside the collider. Its probably kinda complicated tho

#

since there will be multiple points

#

im also unsure if you would get the exit point actually

#

you may have to raycast in the opposite direction

dapper arch
#

alright, i'll try that. though if there's no other way to get the exit point, then i'll probably stick to my 2 ray solution :/

#

or i could also raycastall from both points (A-B and B-A), collect all the hits, sort them by dist from A and then create pairs from that (if a linecast between two points finds an obstacle, it means that these two points are probably start/end of a line IN the collider) and check the dist between two points in each pair.

crisp owl
#

there may be edge cases, but im not 100% sure

dapper arch
#

well, i think it should be quite accurate but there may be some physx quirks that i dont know. but it should be ok

umbral minnow
#

if i have a question about colliders and how the Collider.bounds.Contains works, do I ask it here?

barren gorge
#

yep

umbral minnow
#

okay so, super simple question, and the docs are all telling me that I'm right here but just checking, if I have a mesh collider with two cubes stacked on top of eachother, with the second cube on top being much bigger, and im checking the meshcollider's bounds.Contains, what is the actual bounds of this? is it gonna extend the small cube's bounds when calculating to the bounds of the bigger cube? i dont know if this makes much sense lol

#

basically, if the mesh collider is the black part, is the bounds.Contains simulating the inside as the green part?

tender vapor
#

collider.bounds.Contains doesn't check for something being in the collider. it gets the bounds of the collider, and it checks if something is in those bounds

umbral minnow
#

thanks for the clarifications :p

deft belfry
#

Can I calculate a rigidbody's velocity so it moves around a point in an orbit?

deft belfry
#

I tried some methods, but they all involve also rotating the rigidbody, which I dont want

tender vapor
#

that's basically how circular motion works physically

deft belfry
tender vapor
#

In kinematics, circular motion is movement of an object along a circle or rotation along a circular arc. It can be uniform, with a constant rate of rotation and constant tangential speed, or non-uniform with a changing rate of rotation. The rotation around a fixed axis of a three-dimensional body involves the circular motion of its parts. The eq...

tender vapor
#

your interpretation is correct

deft belfry
#

@tender vapor thank you

bleak umbra
tender vapor
#

how are those 2 things related

#

you can just set the linear velocity for a dynamic rigidbody just fine

deft belfry
#

Maybe they meant angular velocity?

#

Which I dont want to use

tender vapor
#

that wouldn't be related to the position, so im not sure

#

a kinematic rigidbody (or no rb at all) might be easier to work with depending on what the overall goal is, but i'm not seeing how that decision relates to rotating it or not

#

like a kinematic rb for an obstacle that shouldn't stop for anything, as if it had arbitrarily high mass

bleak umbra
#

maybe you can give a bit more context. Do you actually want a physics simulation regarding motion of that orbiting object or do you you just need that object to have a trigger? why is it a rigidbody? this would illuminate which approach would be the most practical for your project.

worn mantle
#

Ello, I'm currently trying to figure out how to test if a box intersects with a Concave mesh repersented by an SDF. If you need to figure out if a box overlaps other things without direct physics methods, do you just raycast 12 times(1 along each edge of a box) to figure out if something is intersecting without containing the box? (ps: if a sdf contains 1 vertex of a box, but not all of them, then it has to intersect.)

pulsar canopy
#

How much of a wizard must one be to get rigidbodies not to shake and jitter with precise movements and frequent collision?

unique cave
timid dove
pulsar canopy
#

it even works with addtorque and addforce, it tries to get there, but there is just a whole lot of shaking

#

the issue is the hands (what I'm trying to rig like this) scrape along terrain etc. and I can't get them to be stable

timid dove
#

animation + IK + physics is almost certainly the issue

#

It's not something I've ever worked with so I don't know what steps you need to take to make that work, but it's a complicated setup

pulsar canopy
#

the animation ik and rb are completely unrelated in this context

timid dove
#

those are two completely different systems competing over setting the pose of the objects

timid dove
pulsar canopy
# timid dove well how would I know that?

Point is, I do the logic for the IK. The animations play and all that.

Then I have a completely separate hand model that just gets the transforms and rotations of each of the components (arm, forearm, etc) and use AddForce and AddTorque to match that transform, but with physical collisions and reactions

#

so the fact that animations and ik are used is completely unrelated to the rigidbodies

#

But even before this, I tried a simple test. I didn't use animations or IK or anything. I literally just stuck a hand with configurable joints that was anchored to the player, that's it. And even that would jitter and shake.

Like, I just cannot get rigidbodies to not shake when they are doing constant collisions and trying to move (in that instance, the joints were trying to spring back to the default position)

silver moss
#

@pulsar canopy Do you mean really fast jittering (direction changing ~each frame) or slower oscillations/wobbliness?

#

You might just need to add some damping to the forces to avoid overshoot

#

Joints and physics also have a lot of settings that can help with stability

pulsar canopy
pulsar canopy
#

what about "physics"? Any settings I should know about?

silver moss
#

And ofc Time.fixedDeltaTime

pulsar canopy
#

ah, that. To my recollection, I did increase solver iterations

silver moss
#

But I'm still unsure if you're having an instability issue or a damping/overshoot issue (or both)

#

A video could help

pulsar canopy
#

but I actually didn't know about velocity iterations. However, I use force, so that might not come into play?

silver moss
#

Forces are just another way of modifying velocity

pulsar canopy
silver moss
#

Just to rule one thing off, are you making rigidbodies children of other rigidbodies?

pulsar canopy
#

also, I made it so that forces stop being added when it reaches .1 of the position, and at that point my hand (last in the chain), just turns off like a circular saw, spins a couple of revolutions and stops lol

silver moss
#

And are you moving any of the rigidbodies via its transform (i.e. transform.position = , or an animator controlling it directly)?

silver moss
pulsar canopy
#

strictly addForce and addTorque

silver moss
#

A rigidbody being a child of another rigidbody (unless kinematic i guess) counts as its transform being modified

#

Because a child tries to follow its parent transform

pulsar canopy
silver moss
#

So avoid rigidbody parenting. Have them as "siblings" instead

pulsar canopy
#

ok I will try that

silver moss
#

That's how i've done my active ragdolls

pulsar canopy
#

because

#

so a little bit of a backstory

silver moss
#

You can still have them under an empty parent "container" object so they aren't just loose in your scene

#

(And don't move that parent)

pulsar canopy
#

a little while back, I tried using puppet master for this very thing and it had the same issue of jittering and shaking. Couldn't get it to be stable.

That also automatically set it up so that the rigidbodies are in the default armature chain

#

and used character joints, but that's unrealted

pulsar canopy
silver moss
#

Yeah I'm a bit confused because IIRC unity's built in ragdoll wizard also creates joints that are parented to each other. But I've never had good experiences with rigidbody parenting

pulsar canopy
silver moss
#

Definitely, I'd say you should never do that

pulsar canopy
#

well then, I'm confused as to why they're done that way but ok

#

also, I find the character joint to be the most stable. Other ones behave weirdly for me.

Maybe character joints are good too but they don't have a force driving them back to the default position, so you use them as ragdolls (they are limp like fish)

But I suppose if I'm just adding forces towards positions and rotations, they should work ok for me?

silver moss
#

Idk, I opted for ConfigurableJoint because it exposes all the properties and can do everything that other joints can do

#

It's obviously more complex

#

But I'd say you can do most of it with forces/torques too

#

That's how I make the ragdoll bone follow the animated target bone's rotation

pulsar canopy
#

I figured out the code, I just didn't add any damping

#

should I just damp the force based on proximity or something?

silver moss
#

I think you'd usually do damping by taking the current velocity into account when calculating the force

#

I just used builtin damping of ConfigurableJoint springs

pulsar canopy
#

oh

#

yeah I do use damping there tbh

#

I guess I'll have to play around there. But I'm curious whether unparenting will solve anything for me

silver moss
#

For goofy games it isnt that bad

pulsar canopy
#

I need to solve other problems. Probably change the physics material to low friction and some logic, then modify a lot of the values

proud trellis
#

Just saw 6.4 beta launched. Does anyone know when this is coming 👀

pulsar canopy
torpid hollow
barren gorge
#

I guess PhysX (game object physics backend) still more stable

bleak umbra
# barren gorge I guess PhysX (game object physics backend) still more stable

physx and unity physics also solve different problems, the latter being a deterministic (non-iterative) solution that is, because of that, simpler and easier to sync/parallelize than iterative solvers like physx, it also likely means that its not as complete on the solver side and can't solve complex constraints as robustly as physx.

tame python
#

Hey everyone. I just encounter an issue can anyone help me?

#

when i shoot or fire shells at my tanks it flew far that's shouldn't happen but it happened..can anyone tell me what i did wrong?

#

or how can i fix it?

tender vapor
#

that's nowhere near enough info to help

tame python
#

and sometimes it flew far like.... alot far out of the arena.

#

anyone?

silver moss
# tame python something like this?

Still not enough info. What objects have rigidbodies and what type of colliders do they have? Like maybe the shell's rigidbody and collider is pushing the tank. What does your code do, etc.

twin bramble
#

that can fix some inconsistencies with physics forces

vague sentinel
#

not sure if this is the right channel but how can i possibly fix this

vague sentinel
#

okkkay

tame python
#

you can see that on unity hub learn

tame python
#

shell have rigidbody and capsule collider?

#

is this an issue ?

deft belfry
#
            //add groundSpeed, positionVelocity and the platform's velocity
            rb.linearVelocity = groundSpeed * (Vector2)getTransformVec(Vector2.right) + positionVelocity + platformRBVelocity;``` This is my movement function. groundSpeed is the player's regular speed, and it has acceleration and deceleration. platformRBVelocity is the velocity of a moving platform, and it is added to the overall velocity to keep the player moving with the platform. As you can see in the video, it works normally when the player is moving in the same direction as the platform, but because groundSpeed is larger than rb.linearVelocity.x when moving the opposite direction, the deceleration makes the player move slightly to the right.
#

How do I fix this?

arctic echo
#

ah so you have applied the acc/dec to the combined velocity not just the player

#

couple of options - make sure you subtract the platform velocity before applying the acc/dec calculation

#

or you decouple the groundspeed entirely so it's never influenced by the platform

deft belfry
#

groundSpeed and acc/dec happens before applying every other needed velocity

arctic echo
#

ah no, groundspeed is being updated by the final velocity which will include the platform

deft belfry
#

So, what exactly do I do?

#

I still need to make the player move accordingly with the platform

arctic echo
#

i'd separate them out

do the vector 2 calc: groundspeed * etc

then add the platform in on the next line down

rb.linearvel = player + platform

arctic echo
#

what's the new code?

deft belfry
#
            //add groundSpeed, positionVelocity and the platform's velocity
            rb.linearVelocity = groundSpeed * (Vector2)getTransformVec(Vector2.right) + positionVelocity;
            rb.linearVelocity+=platformRBVelocity;```
#

@arctic echo Again, groundSpeed is unrelated to the platform's velocity, its just that the linearVelocity is composed of groundSpeed+platformVelocity

arctic echo
#

yeah so replace groundspeed with relative speed and then add a float first step reset relativespeed = groundspeed

deft belfry
#

relative speed?

arctic echo
#

then the prior value doesn't stack and re-enter the loop

arctic echo
#

float relspeed = ground speed

relspeed = { xxxx}

vector 2 playervel = { yy}

and then the linervel

deft belfry
arctic echo
#

everywhere except the first line

deft belfry
#

Even in the accelDecel function?

arctic echo
#

yes

deft belfry
arctic echo
#

lol no you need to replace that with the calculation for it - ie. linearvel - platformvel

#

placeholder variable

deft belfry
#

like is xxxx just my accel

arctic echo
#

the content of your existing code

#

i'm trying to avoid doing a copy paste solve for you :p

deft belfry
#

Honestly a copy and paste might be better than this guessing game

arctic echo
#

so long as you get the idea - make the two vel calculations separately

#
float relativeSpeed = rb.linearVelocity.x - platformRBVelocity.x;

relativeSpeed = generalStaticFuncs.accelDecel(
    relativeSpeed,
    maxMoveSpeed,
    groundAccel,
    groundDecel,
    groundFriction,
    dir,
    Time.fixedDeltaTime,
    isGrounded
);

// 2. Convert to world velocity
Vector2 playerVelocity = relativeSpeed * (Vector2)getTransformVec(Vector2.right) + positionVelocity;

// 3. Add platform velocity LAST
rb.linearVelocity = playerVelocity + platformRBVelocity;```
arctic echo
#

its been replaced by the explicit calculation in the first line

#

groundspeed = linearvel - platformvel

deft belfry
#

Again, groundSpeed is already UNRELATED to the platform's velocity

#

it's its own variable, with its own calculation

arctic echo
#

that's in theory but you need to decouple them in practice to avoid these artifacts

prime lagoon
#

does anyone have an idea as to how I can keep the player momentum during a jump without them having control over it? this is my current code and the problem right now is that the momentum is based on where you looking

if(isGrounded && velocity.y < 0f)
{
    velocity.y = -2f;
}


if(isGrounded)
{
    x = moveA.action.ReadValue<Vector2>().x;
    z = moveA.action.ReadValue<Vector2>().y;
}
mouseX = Mouse.current.delta.ReadValue().x;
mouseY = Mouse.current.delta.ReadValue().y;


xRotation -= mouseY * settings.Instance.mouseSensitivity * 0.5f;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);

cam.transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
Player.Rotate(Vector3.up * mouseX * settings.Instance.mouseSensitivity * 0.5f);

Vector3 move = transform.right * x + transform.forward * z;


            // x = horizontal movement, z is vertical movement


rb.Move(move * speed * Time.deltaTime);


if(isGrounded && jump.action.WasPressedThisFrame())
{
    velocity.y = MathF.Sqrt(jumpheight * -4f * gravity);
}

velocity.y += gravity * Time.deltaTime;
rb.Move(velocity * Time.deltaTime);```
if possible I would like the character model to still change the direction it's looking without it impacting the trajectory of the character
twin bramble
#

if thats what u mean

prime lagoon
tender vapor
#

wouldn't a dynamic rigidbody handle this pretty easily

prime lagoon
#

but now you can still controll where you're going with your camera

tender vapor
#

might want to consider that if it's viable for your usecase

twin bramble
tender vapor
#

otherwise, you'd want to affect the velocity rather than recomputing it just from the input every tick

#

so there's an effect of momentum

#

wait, is this a CC?

#

why is it named rb

prime lagoon
tender vapor
#

that's not what Rigidbody.Move takes, so assuming it is a CC - make sure Move is called once per frame for consistent results, you have it being called twice here

tender vapor
#

(also, i'm aware it's c#, cc is short for character controller.)

prime lagoon
twin bramble
#

ngl i have never used cc's i dont even know what they are to be exact

#

i always just used a rigidbody

prime lagoon
twin bramble
prime lagoon
#

yeah something else is happening now, but now it's always walking the same direction and the camera doesn't do anything as to what direction I'm going in

tender vapor
#

you do need the transform.forward bit

#

you might consider, for example, applying it as an acceleration instead assigning it as the velocity

#

if that feels too slippery you could add drag or counterforces to oppose momentum when you try to go a different direction

sharp carbon
#

Hey, I’m making a VR sailing game in Unity using the XR Interaction Toolkit and I’m stuck with a physics/joint issue.
I have a rudder GameObject with: Rigidbody, HingeJoint (limits set, connectedBody = boat Rigidbody), XRGrabInteractable set to Velocity Tracking
When I grab and move the rudder by itself, it works fine. But when it’s connected to the boat, grabbing it makes the boat accelerate insanely fast and it starts spinning/torquing like crazy, even on axes that are frozen in the boat Rigidbody constraints. I also tried unparenting the rudder outside the boat and connecting via HingeJoint connectedBody and it still happens. It feels like the grab velocity/forces are getting transferred through the hinge into the boat and injecting huge impulses.
Has anyone dealt with this?

prime lagoon
tender vapor
#

might want to step back from the code and design/analyze it in terms of physics first

timid dove
tender vapor
#

it's a CC

timid dove
#

If it's a CC please tell me you didn't name the variable rb 😢

tender vapor
timid dove
#

but yeah currently your code is always directly applying the input to the velocity, so there will be no momentum

prime lagoon
tender vapor
#

it's 4 keypresses

prime lagoon
#

CC.Move(velocity * Time.deltaTime); here it's changed

twin bramble
#
if (Physics.Raycast(LFrontPoint.position, -LFrontPoint.up, out RaycastHit hit2, 0.1f))
{
    Vector3 PointLeft = BoardRB.transform.forward;

    Debug.DrawRay(LFrontPoint.position, hit2.normal * 2, Color.yellow);

    //cross products
    Vector3 left = Vector3.Cross(hit2.normal, Vector3.up);
    Vector3 down = Vector3.Cross(hit2.normal, left);

    Debug.DrawRay(LFrontPoint.position, left * 2, Color.green);
    Debug.DrawRay(LFrontPoint.position, down * 2, Color.blue);
    //flatten
    Vector3 planeNormal = Vector3.Cross(left, down).normalized;
    Vector3 flattenedEdge = PointLeft - Vector3.Dot(PointLeft, planeNormal) * planeNormal;
    Debug.DrawRay(LFrontPoint.position, flattenedEdge * 2, Color.red);

    Vector3 LFrontV = BoardRB.GetPointVelocity(LFrontPoint.position);

    float sideSpeed = Vector3.Dot(LFrontV, flattenedEdge);
    Vector3 sideV = flattenedEdge * sideSpeed;
    Debug.DrawRay(LFrontPoint.position, sideV * 2, Color.magenta);
    Debug.DrawRay(LFrontPoint.position, LFrontV * 2, Color.cyan);

    //calculate the force
    Vector3 CalculatedForce = (sideV * TEMP_FrictionFunction * (1f * 9.81f * 0.4f));
    float forceX = Mathf.Clamp(CalculatedForce.x, -3, 3f);
    float forceY = Mathf.Clamp(CalculatedForce.y, -3, 3f);
    float forceZ = Mathf.Clamp(CalculatedForce.z, -3, 3f);
    Vector3 fullForce = new Vector3(forceX, forceY, forceZ) * -1;
    Debug.DrawRay(LFrontPoint.position, (fullForce) * 2, Color.black);

    BoardRB.AddForceAtPosition(fullForce, LFrontPoint.position, ForceMode.Force);
}

I have this script which rotates the board to face down the hill. problem is that the front point (which is this script) rotates the board backwards and goes down the hill backwards. its not accidentally rotating backwards cuz it stabilizes itself after it has done so. all of the axis are correct since i checked with the 1 million debug ray's. basically this front point is acting like the rear.

#

this script might be confusing but any help will be appreciated since im not good at math and stuff

timid dove
#

I'm realizing now you probably mean like... a snowboard or something?

#

Anyway this code doesn't seem to rotate anything

#

it only adds a force

#

unless the rotation is coming from the torque generated by adding the force off center

twin bramble
#

I can give SS's and more details tmr if needed

#

Oh and btw BoardRB.transform.forward is the left side of the snowboard not the front. Just cuz of how it's rotated

timid dove
#

I think the best course of action is to go in and fix your 3D model so that forward is actually forward

#

then your code can be simpler and easier to think about

twin bramble
short sable
#

When it comes to physics I know when using addforce.force gives you better physics, does the same apply when using addforce.acceleration?

tender vapor
#

force is acceleration times mass. applying force takes mass into account. applying acceleration does not.

that's all they differ by

unique cave
old abyss
#

hi, has anyone ever tried the limits of determinism in unity?
And by determinism i mean only the physics. Considering a simulation that requires no user input, and considering that it only needs to be deterministic on one platform/architecture, how much can we expect from Unity?

pulsar canopy
#

what is the "main axis" in a joint? If it's allowed to move in 3 axes, what makes the main axis the main axis? I don't understand what changes there.

Furthermore, if the joint is locked in 1 axis, does that just mean that it's rotation/movement is locked while trying to move/rotate directly in that axis?
It has got to be able to move via translation of Eulers, right?

low breach
vagrant ingot
#

Hello
I want to check if there is a collider in front of my object, so can be my player or an enemy.
This method is :

public static bool CanMove(Vector3 direction, Vector3 currentPos, bool isCheckObject = false)
    {
        // True if no obstacle in the direction, otherwise false
        
        int layerMask;
        //Get the bitmask and not the index of the layer (so 0010 0000 instead of 6)
        if (isCheckObject)
        {
            layerMask = LayerMask.GetMask("Obstacle", "Object");
        }
        else
        {
            layerMask = LayerMask.GetMask("Obstacle");
        }
        
        //Start the raycast at the center of the object 
        Vector3 rayOrigin = currentPos + Vector3.up * 0.5f;
        
        Debug.DrawRay(rayOrigin, direction, Color.green, 1f);
        
        //If nothing is hit, can move
        return !Physics.Raycast(rayOrigin, direction, 1f, layerMask);
    }

And its call in the player class here :

private void CheckToMove(Vector3Int targetGridPos, Vector3Int moveDirection)
    {
        if (!Toolbox.CanMove(moveDirection, transform.position))
        {
            Debug.Log(moveDirection);
            StartCoroutine(BumpAnimation(moveDirection));
            return;
        }

        StartCoroutine(MoveCoroutine(targetGridPos));
    }

When I go in front of a wall or not, the CanMove method return always true, meaning the raycast return always false. Why ?
There is the screen of my drawRay going through my wall with the properties show

old abyss
#

ive read the docs and on a single platform and architecture say 64-bit intel processor running windows 11, every run should be deterministic

#

ive been testing and playing around with this stuff for months and i just wanna see if anyone else has some findings related to determinism so i can compare my results to theirs

timid dove
#

Especially these two

pulsar canopy
#

How can I make it so that the x and y axes switch? I have tried EVERY possible combination of axis values but none of them can do it

#

I can actually get close to it, but it seems impossible to get there

#

ofc I get it after right after I posted, even though I've been trying for a while...

I had to switch the secondary axis

vagrant ingot
#

But in simulation mode, what is the difference between fixed update and script ?

timid dove
vagrant ingot
#

In which context you want to simulate physics only on code ?

timid dove
#

When you want full control over it. Could be for a simulation-style game, or a non-realtime game. It is also useful for networking frameworks when the physics engine needs to be syn ed up with networking stuff.

#

In your game it's potentially useful if your game is not realtime.

#

it would mean simulating physics only manually when you want to instead of it happening automatically all the time

vagrant ingot
#

Okay I see, thanks for the explanation 👍

edgy kite
#

Hey guys. I cant seem to work this out even though it looks like it should work. Maybe a second pair of eyes will help.

I want to have a knockback on the player when they get hit from a moving object.

Scripted on moving object

private void OnTriggerEnter2D(Collider2D collision) {
    if (collision.CompareTag("Player")) {
        hitDirection = (transform.position - collision.transform.position).normalized;
        StartCoroutine(KnockBack(collision.gameObject));
    }
}

IEnumerator KnockBack(GameObject player) {
    player.GetComponent<Movement>().canMove = false;
    player.GetComponent<Rigidbody2D>().linearVelocity = Vector2.zero;
    player.GetComponent<Rigidbody2D>().AddForce(hitDirection * hitForce, ForceMode2D.Impulse);
    yield return new WaitForSeconds(0.2f);
    player.GetComponent<Movement>().canMove = true;
}

And this is my movement script

void Update() {
    if (canMove) {
        moveDir = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")).normalized;
        if (moveDir != Vector2.zero) {
            Quaternion toRotation = Quaternion.LookRotation(Vector3.forward, moveDir);
            transform.rotation = Quaternion.RotateTowards(transform.rotation, toRotation, rotationSpeed * Time.deltaTime);
        }
    }
    else moveDir = Vector2.zero;
}

void FixedUpdate() {
    rb.linearVelocity = moveDir * moveSpeed * Time.deltaTime;
}

As you can see this should work? shouldn't it?

inner thistle
#

The movement script sets the velocity to zero every frame that the knockback is in effect

edgy kite
#

of course cause that is there to stop the player still moving when a shop is open. Thank you

#

That actually still doesn't work.

#

But in saying that adding the condition to the fixedUpdate to only run while im allowed to move did work.
Told you a second pair of eyes always works

inner thistle
#

Unrelated but velocity shouldn't be multiplied by deltatime

edgy kite
#

Is that because its physics based?

inner thistle
#

Velocity is already a frame-independent value (units per second) so it doesn't need to be converted

edgy kite
#

Ah no worries. Thank for that too.

granite geyser
#

Is there a way to make collision sounds that works for objects that are already colliding ?
Like for example a very tall plank that falls over wouldnt trigger OnCollisionEnter because it is already toutching the floor, but if i use OnCollisionStay it just plays sound every frame, is there a proper way to make this work or should i just use a cooldown or something like that between sounds?

timid dove
#

Play the sound when they exceed a threshold, and/or modulate the volume by that threshold

granite geyser
#

yeah thats what im doing but it does still play every frame if the object is dragged/ is sliding across a surface

timid dove
#

Second, like I said you need to vary or modulate the sound based on the impulses and velocities of the contact

#

You can see if the motion is parallel to the contact surface and play a dragging sound instead of an impact sound

#

All of the information you need is in the Collision object

granite geyser
#

thanks!

bold yew
#

Could anybody help me figure out why my Physics Debugger won't show collision meshes? Unity 6000.3 Neither Scene or Game view show them, Gizmos are on, "Collision Geometry" is checked.

#

All of the colliders are Default layer convex mesh colliders.

#

but not even cube colliders or the ground (quad with mesh collider) are showing.

timid dove
bold yew
#

Cube is here just to see if the collision geometry just wasn't rendering for my vehicle. It's not rendering for anything.

#

But it does have a cube collider.

#

Box collider rather

timid dove
timid dove
bold yew
#

Thats because I'm selecting them

#

Previously when I have collision geometry selected with the physics debugger it renders them all the time, and with a translucent shader instead of wireframe

#

I don't think I've changed anything but the debugger has stopped working on even archived versions of the old project where I use it.

#

Drawing contacts/forces does still work, just not collision hulls.

#

The shot with them shown is just to show that the colliders are there.

timid dove
#

hmm...

It's not working for me either... trying to see what I'm missing

bold yew
#

Thats bizarre. On 2022.3 (old revision of project) it worked for me, but even on that archived backup it doesn't work anymore.

#

I was worried it was my machine. I'd think it's a unity bug but since it stopped working? I really have no clue.

golden island
#

trying to do a char controller with movement a bit like octodad

#

I've got a rigged character with iks on legs

#

was going to try and use those to move him around and use ragdoll generator for the rest of the rig

#

dunno if that will work but regardless of that the physics is super whack for some reason

#

everything just kinda spazzes and slides about

#

no intersecting colliders

#

any ideas?

twin bramble
#

And the setup of the character

glad cargo
#

yo, I'm trying to get this sort of floppy driven-by-IK locomotion working in 2D, anyone got any pointers? https://youtu.be/ZRLibDF-JGQ

Developed by Free Lives

Swing bats and throw balls through the intertwined histories of humankind and cricket in this one button, physics-driven game. Over a thousand years ago the human race teetered on the edge of extinction. Our ancestors were helpless against the mighty behemoths of the land. And then, salvation…the game of cricket was in...

▶ Play video
twin bramble
#

shouldnt be too hard to replicate i think

upper helm
#

is there an inbuilt way to have strong gravity, but after the player jumps around the peak of their jump for a bit longer and then accelerate downwards

#

because my movement is server authoritative it wouldnt be good for players to calculate on script by themselves

timid dove
#

The physics engine provides basic newtonian physics.

inner thistle
#

Also the premise doesn't make sense, it makes no difference to server authoritative if it's custom or built-in physics

upper helm
granite geyser
#

Dumb question but why is there include and exclude layers on colliders ? why not just include or exclude ? what happens if something is on both include and exclude ? or neither ?

unique cave
# granite geyser Dumb question but why is there include and exclude layers on colliders ? why not...

The Layer Collision Matrix in the physics settings is what defines which layers interact with each other. The Layer Overrides can be used to override that behavior for specific collider. Includes are layers that the given collider can interact with even if the collision matrix says they shouldn't interact and exclude layers are ones that should not interact with the given collider regardless of the collision matrix. You can check this page https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Collider-layerOverridePriority.html for more information on how conflicts are resolved if two colliders collide where one should and the other shouldn't interact with each other.

I did not find any information of the situation where you put the same layer on both include and exclude layers. Since that is a contradiction by nature, I would not recommend doing that. The behavior might be undefined and differ between editor versions.

#

Basically LayersThisColliderInteractsWith = LayersInCollisionMatrix + IncludeLayers - ExcludeLayers

granite geyser
#

Ohh i forgot about the collision matrix ^^'
Thank you, this is all i needed

floral estuary
#

cinemachine camera following zooming out and sometimes zooming in of following target, i just want it to follow the target at a specific area

#

i have changed the update mode to fixed

#

the target its following is an aircraft btw so it can get pretty damn fast

frigid pier
peak cloak
#

I'm trying to make a bike script, everything works well except the steering of the wheels since it just flips over instantly like the bike flips and becomes upside down. https://paste.myst.rs/8i3y4tyg that's the code and I also attached the input asset and the values of all my components.

silver moss
#

I mean like way below the rigidbody itself

#

Been a while since i worked with wheelcolliders tho

#

Also a joint or corrective forces/torques can be used for balancing

peak cloak
#

I fixed it by making the turning a bit smoother and disabling z rotation

worn summit
#

hi, I have two objects with a rigidbody and they both have 2 colliders, one with a non-trigger collider and one that's a trigger. they belong on 2 separate layers. how can I make them go through each other (non-trigger colliders get ignored) but have their triggers still interact with each other? or something that produces this effect?

what i had done originally was create a child object just for the non-trigger colliders and that child object would live in one of the two layers that i want ignoring each other. the trigger collider would then reside in, say, the parent object that lives on default or something so its ontriggerenter can run. is there a better way of doing this?

#

example: i want my player and enemy to move through each other (enemy layer and player layer ignore each other) but i still want their triggers to interact with each other so they can do stuff like inflict damage

timid dove
peak cloak
#

I have this ragdoll human. I'm working on a bicycle rage game that will have 2 people on this bike but the ragdoll sometimes gets loose and ends up under the bicycle which results in the bike clipping through the map. I have fixed joints on his feet and hands, I want him to move a bit with the movement but not too much. Also sometimes the hands start to jitter alot in place which isn't too much what I want. How can I fix these issues?

peak cloak
kind shadow
#

Why is the capsule collider shown in physics debug smaller than the character controller capsule?

craggy raven
#

Any idea why the textures look so weird when importing into unity?

timid dove
inner thistle
#

CC might use a "normal" collider internally to interact with the physics system but it's an implementation detail, not really something that's useful to dig into

kind shadow
umbral zinc
#

Can someone please help me with this when i play the game the character stucks in the ground like this whats the issue @everyone

timid dove
#

just post your problem.

#

Check the positions of your colliders and/or your animations

umbral zinc
#

Sorry

umbral zinc
timid dove
#

Click on the object that has the collider

#

make sure gizmos are turned on

#

and see how the collider is situated relative to the visual elements of your character

umbral zinc
#

Ohk

glass nebula
#

I made geometry dash physics

tender vapor
pulsar canopy
#

What is the practical difference between acceleration and velocityChange?

I am currently using acceleration for some rigidbodies to follow and rotate towards some other objects (better than ForceMode.Force).

Would VelocityChange make a practical difference and why?

twin bramble
inner thistle
#

VelocityChange is meant for instant velocity changes and acceleration for continuous change over time

timid dove
#

They both effectively do the same thing (adjust the velocity), just by different amounts

barren gorge
#

(note that you can change physics update rate from fixed step to dynamic step so in that case instead of the Time.fixedDeltaTime there will be Time.deltaTime)

timid dove
#

(never do that though)

barren gorge
#

(yep)

#

(btw Time.deltaTime in FixedUpdate method is equal to just Time.fixedDeltaTime, nice unknown feature!)

pulsar canopy
#

ah ok so acceleration is best in this case

pulsar canopy
#

is it wrong to move and rotate something in a coroutine, and the follow it with rigidbody force movement and torque towards it in fixed update?

Should I move everything to fixed update?

timid dove
#

The details matter

#

If you're modifying the Transform directly that's wrong to do anywhere for a dynamic Rigidbody

pulsar canopy
tender vapor
#

you should not addforce/addtorque with continuous forcemodes in the update loop

timid dove
#

You can use yield return new WaitForFixedUpdate() to do that

pulsar canopy
#

Didn't know that

#

Thanks

#

There is some jittering and overshooting

#

Might be out of sync

tender vapor
#

you said every frame

pulsar canopy
#

every fixed update tick, whatever

tender vapor
#

these details are kinda important lol

pulsar canopy
#

I did say in the message above that I'm using fixed update

tender vapor
#

and my recommendation was in response to a message where you said it was not in fixedupdate...

timid dove
#

Maybe if you just showed the code...

pulsar canopy
tender vapor
#

ah, i see. you didn't make that particularly clear
but yeah that won't have too much of an issue. generally you'd want to have stuff happen in Update regardless, because that's when frames are rendered - that's what interpolation on rbs handles

#

with a transform you'd definitely want to be moving it in Update

pulsar canopy
#

Cause the occasional jitters I get might be from the lack of interpolation? (I use interpolation on the rigidbodies)

tender vapor
#

oh the AddForce should be in FixedUpdate

#

i meant there should be something in Update, not everything in update, i didn't phrase that well

#

(in the case of rbs, that's handled for you with interpolation)

naive ferry
#

Bonjour

pulsar canopy
#

cause that's how it is now

#

addForce and addTorque are in FixedUpdate

#

the source objects that the rigidbodies move to move via transform in coroutines

timid dove
pulsar canopy
timid dove
#

there's a reason the physics engine uses a fixed timestep

pulsar canopy
timid dove
#

you are moving them towards the Transform object

#

since the Transfrom object is moving with a non-fixed time delta, its exact position per physics frame is going to vary depending on the framerate

#

if the object was moving with a fixed delta it would move to the same exact series of positions every time you do it

#

it's not necessarily a problem for your game, but your game will not be deterministic.

pulsar canopy
#

right but I don't think this should make a difference in my case, as it moves with a constant velocity

#

Basically, I don't see how it might cause issues

timid dove
#

it really depends. It could be the difference between the rigidbody hitting a corner and squeezing past without hitting it, or something

pulsar canopy
#

but if the rigidbody itself is interpolated, isn't that an impossibility? Cause I move them by addForce and rotate with addTorque.

Isn't that taken into account?

timid dove
#

the actual physics happens with a fixed timestep

pulsar canopy
#

so I have a setup when I have an origin arm object that moves via animation + IK.

Then I have a puppet rigidbody object with configurable joints.

I made it so that the puppets move and rotate towards the origins via addForce and addTorque in Fixed update.

I was trying to solve some jittering there. There are always some jitters. I've tried various settings.

However, AI is telling me to simply get the rotations of the origin joints and update target rotation in the puppet joints, rather than adding forces. Is this correct? Could this reduce jitters?

kind mauve
#

is there an API to specifically toggle on/off collision between two colliders?

#

I think I found one to be able to toggle collisions off but I need the opposite

#

to describe the whole story I decided to make a jumping mob but then realized that it shouldn't be able to jump through targets

#

intuitively I could just make it collide with all it's enemies
but there are multiple factions and I am not sure if making a layer for each faction is a good idea
and if they wont' have own layers it would get stuck while jumping from within friendlies (agent without avoidance)

tender vapor
#

are you in 2d or 3d?

kind mauve
#

3d

tender vapor
#

ah, rip. if you were in 2d you could probably use the oncontactfilter thing

kind mauve
#

yeah this one.... can only be set to ignore it seems

tender vapor
#

no?

kind mauve
#

I ll try, tho I read one forum post describing that this API couldn't help them

tender vapor
#

did you read the signature/docs for that method

kind mauve
#

it's ambiguous tbh

tender vapor
#

it really is not

kind mauve
#

"Whether or not the collisions between the two colliders should be ignored or not." like if it's not ignored does it mean that layers matrix still applies or not?

tender vapor
#

they do apply

#

it's just "is this ignored or not"

#

if it is ignored, no contact
if not, check further

kind mauve
#

so like
that's what I meant by
can only be set to ignore

#

there is no option to enable collisions ignoring matrix

tender vapor
#

it can be set to not ignore too

tender vapor
kind mauve
kind mauve
tender vapor
kind mauve
#

no wait you weren't
I fail to pinpoint miscommunication spot

#

full story short I want to enable collisions between two colliders
IgnoreCollision don't seem to do that

#

unless I manually disable all unwanted collisions... which is kinda pita

tender vapor
#

yeah i think the overall philosophy is to filter out unwanted stuff rather than specify wanted stuff

tender vapor
kind mauve
#

do you know perhaps a good way to imitate collision through code? assuming I don't care about y dimention and good precision
currently I am detecting the intersection through OnTriggerStay and do RigidBody.MovePosition... kinda rough, maybe I could polish that but is there a better way?

#

basically what I do now looks like a headcrab which only collides with it's target

tender vapor
kind mauve
#

no I mean I detect collision with a target and push away the mob which is unsurprisingly not working well

kind mauve
#

I mean borderline acceptable but I don't really know what am I doing and why so much jitter

public void OnTriggerStay(Collider other)
    {
        if(is_in_jump && other == target_collider)
        {
            float y = body.position.y;
            Vector3 direction_away = body.position - target.position;
            direction_away.y = 0;
            if (!is_dropping)
            {
                is_dropping = true;
                body.linearVelocity = new Vector3(0, body.linearVelocity.y, 0);
                distance = direction_away.magnitude;
            }
            distance += Time.fixedDeltaTime * step;
            Vector3 new_pos = target.position + direction_away.normalized * distance;
            new_pos.y = y;
            body.MovePosition(new_pos);
            Debug.Log("Teleported");
        }
    }
#

still jittery (interpolation set on extrapolate)

#

right, I am moving it each fixed update afterall

pulsar canopy
#

Instead of applying addForce and addTorque to a desired position and rotation for a configurable joint, I tried just setting target rotation(yes, I used inverse).

I figured it would achieve the same thing but maybe more stable. It doesn't, it just rotates to an unpredictable direction.

Is this because target rotation is aware of joint constraints so it tries to rotate in weird ways to reach thay position? While addTorque brute forces it and somehow manages to do it?

drifting drift
#

Hello! Im trying to make a sausage that behaves "realisticaly" (Basically, it shouldn't be a static capsule, it should be able to bend a little). I tried to make it by joining multiple capsules with configurable joints, but they easily clip through other colliders (apart from other weird artifacts when bending). The rigidbodies are set to interpolate and with a continuous dynamic collision detection, but they still clip. Is there a solution to this with/without joints?

#

This image is when the pan is static. If I try to move it it easily clips through

drifting drift
#

the capsules in the sausage are rigidbodies, none of them is kinematic. I move the pan with a fixed joint. The pan is not kinematic either

#

@timid dove

short sable
pulsar canopy
#

and then you define the limits to which they can rotate

pulsar canopy
drifting drift
raven edge
#

Hello!
I'm trying to figure out how to implement collide and slide (for walls only) for a kinematic character controller.
It mostly(?) works, but there's some strong jittering when I try to move directly against a corner.
The jittering only happens when I push into a spot between wall A and B in such a way that the slide pushes me back from A to B (and vice versa).
It stops as soon as the movement points await from the range that pushes me back into the previous wall.
I'm hoping someone could point out the (maybe obvious) mistake I'm making or give any kind of suggestion

Here's the code https://paste.myst.rs/9pyy3sah and a video of the jittering

naive badge
#

I have been having this issue for the past few days. I tried thinking about how to solve this, but can't rly come up with a solution.

#

I genuinly don't know what the problem even is...

raven edge
#

using a very small skin width also helps in this case

timid dove
#

you're only doing one raycast

#

you're not accounting for if that slide brings you into a second wall

#

Check if your newly calculated trajectory hits any wall and repeat the process

#

until you run out of movement distance

#

or until you reach some present number of iterations

raven edge
#

I capsuleCast from the new position towards the slide calculate in the previous iteration

timid dove
#

there are only 9 lines in the code you pasted

#

oh sorry

raven edge
#

I mean the paste to the message you replied to

timid dove
#

wrong paste, hold on let me look closer

raven edge
#

sure

#

actually, I can just paste the new version with what i was talking above

timid dove
#

I'm pretty sure this calculation was just wrong:

Vector3 movementInsideWall = movementDisplacement - movementDirectionToWall;```
#

actually nvm

raven edge
#

they should both represent the same unit
but it's 100% possible I did mess up some calculation

#

I'm not that good with doing vector math

raven edge
naive badge
raven edge
#

we're probably talking about 2 different things

naive badge
#

OOF

#

Ya, ur talking about a sphere colliding with a corner, ima talking about triggers being detected between a circle and a box collider

raven edge
#

Kept working on this and my guess is that walking inside the right wall slides the character into the up wall, which then slides it back again towards the first wall on the next frame.
I'd appreciate a lot if someone could point me in the right direction on how to solve this.
The current fix, as mentioned above, is to simply stop in a corner that is (arbitrarily) sharp enough, but it doesn't feel like a good solution since it causes a lot of sticking.
Here's the current code: https://paste.myst.rs/ee0mmmaq

raven edge
#

The sticky corners are most likely caused by the sweep (green lines) hitting the same wall until the input (blue line) is angled in such a way to the sweep completely points away from the left wall and only towards the front wall

cold rivet
#

I have a 2d phyisics material attached to a set of circles connected by a spring joint, yet despite setting the material to max friction, they slide around

tall rover
#

So I’m trying to make a physics arm like one armed robber where the arm lags bevind and kind of like swerves around and it’s kind of working but I can’t seem to get it stiff I set spring to 125000 and the arm and bones in it still swerve around really hard, any help would be greatly appreciated

upper helm
#

is it okay to do a spherecast on a per-frame basis

#

my game isnt running that well already so im not sure if i should use it over raycasting, raycasting is buggy for me

tender vapor
#

it's probably not gonna be much different perf wise

#

compared to other stuff

pulsar canopy
tall rover
#

Between every bone

pulsar canopy
#

You need to be a rocket scientist to set them up correctly

tall rover
#

What do you recommend me to do for a physics arm

#

I want it to kind of lag behind and bend when going into a wall

#

With some overshoot

pulsar canopy
#

You don't want to move it forward etc?

pulsar canopy
#

ok can you screenshot the settings, so I can see where to begin?

pulsar canopy
#

Ok guys, do you think it is possible to eliminate all rigibody jitter this way:

I have a ghost object matching the rb's rotation and position every frame. I let it detect erratic shifts in velocity direction by, for example, matching the rotation/position only if the rb has had a consistent velocity for the past 3 frames.

Basically something like that. Do you think 3 frames is enough? Does that idea sound legit?

terse ginkgo
terse ginkgo
#

Imma be real you're probably doing something quite wrong then if you have interpolation on it and still dealing with noticeable jitter

haughty parrot
#

Hey, can anyone tell me how to import the fbx file of a cloth animation from Blender to Unity?

Problem Statement: The Alembic file is working perfectly. In the fbx file, model and animations are getting downloaded, but animations are not working in the scene, they are shown working in the animator, but in scene the cloth is not at all moving.

Can someone please let me know what is happening?

pulsar canopy
terse ginkgo
#

I'm saying it for the sake of you are potentially handling the rigidbody movement incorrectly if you are noticing jitter. It's not a jab at you, I'm just saying the setup is likely misconfigured

random palm
#

Can it be the camera movement that is causing the jitters?

terse ginkgo
#

If you're doing any transform movement for example, that'd very likely be a large cause of it

#

Can you show what you're doing perhaps?

pulsar canopy
#

It works pretty well, I added damping and everything, but there is jitter when constant collisions happen

#

there is no jitter when in mid air, but for example, when my origin rig has a wall grabbed, there is jitter in the final position (possibly due to constant collisions with the terrain)

terse ginkgo
pulsar canopy
#

to be clear, the animated rig doesn't collide (it only raycasts), the rigidbody following rig collides

terse ginkgo
#

Interesting, I mean using heavy forces with joints is likely to cause jitter so I do apologize for the original misinterpretation, I thought you were using a kinematic rigidbody or something of the sort. The most ideal way to work with joints is through direct target rotation / target angular velocity but that goes quite deep into config joint knowledge haha

pulsar canopy
#

it always tried to rotate to a rotation I didn't specify

#

and I know joint space is different from local space is different from world space

#

I basically did double Quat inverse to specify target rotation but it just didn't work. I don't know

terse ginkgo
#

Yeah it goes deep, I've run down this rabbithole and do it for my hobby projects and day job, I would not recommend it lmfao

pulsar canopy
terse ginkgo
#

The edge cases you have to account for :P

pulsar canopy
#

Wait, could it be because the target rotation is a vector3, rather than a quaternion?

terse ginkgo
#

target rotation is a Quaternion

#

target angular velocity is a vector3

pulsar canopy
terse ginkgo
#

all quaternions show like that yeah

pulsar canopy
#

Yea yeah, true

#

Idk man

#

What do you think about my third rig idea?

terse ginkgo
#

Elaborate?

pulsar canopy
# terse ginkgo Elaborate?

The third rig would just be a skinned mesh with nothing attached and would match the position and rotation of the puppet rig.

However, it would wait for a few frames to detect erratic changes in velocity of the rb rig. For example, if dot product of frame 1 movement and frame 2 movement is low, don't update position and rotation.

If dot product is high for 3 frames in a row, only then update. Does that make sense?

terse ginkgo
#

Yeah I understand what you mean, but I feel eliminating the jitter entirely would be a better alternative. Trying to drive the joints directly could be good but also difficult ofc

pulsar canopy
#

I wish I could

terse ginkgo
#

Hm got it, then you could attempt what you're talking about, you could also try bumping up your physics project settings solver iterations, or anything else to help with joint slop

pulsar canopy
#

it may also just be due to the fact there are many colliders

terse ginkgo
#

Yeah, anything above 32 for a single rigidbody is overkill

pulsar canopy
#

I have joints on each of my fingers (yeah I know)

#

so it may be impossible to achieve stability with just rb

terse ginkgo
#

That will create joint error for sure

#

You can try simply boosting your inertia tensors too

pulsar canopy
#

I actually have 3 joints per finger lmao

#

I considered switching them to an articulation body but they either don't work or idk how to use them

pulsar canopy
terse ginkgo
#

You could just simply multiply the whole vector by 2 as a test

pulsar canopy
#

I will check

pulsar canopy
#

essentially I'd need to make another rig for fingers that follows the rb rig

#

but I tried doing some articulation body tests and they didn't seem to work, idk

terse ginkgo
pulsar canopy
old abyss
#

hey, sorry for the ping out of nowhere. i was skimming through old messages to see if anyone's experimented with the limits of determinism in unity. Seems like you did just that. Did u get anywhere with ur tests?

void hemlock
#

Anyone know which version of physx Unity uses?

timid dove
#

Depends on which version of unity

void hemlock
#

6.3

old abyss
void hemlock
unique cave
#

It seems they changed from physx 3 to 4 already in 2019 and haven't changed since

#

Back then I think they had a blog post about the changes at least

void hemlock
#

sounds like PhysX has much improved and has 3d wheel colliders now so don't know what happened but maybe is a big leap to change to a different physics setup

#

seems v5 was a major change in direction to simulation and GPU

unique cave
void hemlock
#

Yeah Unity Physics is annoying to me as built for ECS/Dots (do not use) and may be a long project to complete

dull jungle
# void hemlock Yeah not exactly shouted out by Unity is it! I think they are well behind as may...

its more about being scared of breaking changes, they have a history of tiptoeing around improvements cause it could break legacy projects on upgrade, on one hand its nice to have a relatively simple upgrade most of the time, on the other hand it stops progress right in its tracks sometimes and led to things having 3 different implementations at a time cause they didnt want to remove the old one

#

Well beats removing the old one before the next version of it is remotely ready 😄 (looking at you, Unet)

gritty plank
#

ooo i will be reading down this thread

old abyss
terse ginkgo
#

6.3 is PhysX 4.1.2

signal wyvern
#

Anyone know the differences here between these 3 ways of setting my boats position & rot to the server Authed state before resim? The top one directly setting transform has worked best for me but it comes with a bit of a performance cost as all colliders need to be re-synced, from reading the other two are maybe what i should be using and seem to be cheaper but they ruin the re-sim somehow as my boat become super jittery and clearly don't align

tender vapor
#

iirc for one of (2d, 3d) but not the other, MoveX is only interpolated correctly for kinematic rbs (as that's what it's intended for), that may be the cause of the jittering

#

if this is for "resim", do you even need physics? couldn't you just set the value every frame/tick manually (or maybe with kinematic rbs to get interpolation, if you're using the fixed time step)

#

also,

#

!code

gloomy lodgeBOT
tender vapor
#

that's a very small screenshot that's hard to read

signal wyvern
tender vapor
#

is the jitter just due to network desync of the simulation

#

is the rb kinematic or dynamic?

signal wyvern
#

Its NOT kinimatic

#

would breifly setting it to kinimatic first maybe solve it?

tender vapor
#

am i understanding this right that you have some simulation on the server that you want to sync to the client?

signal wyvern
tender vapor
#

are these snapshots every physics tick or less frequent?

signal wyvern
signal wyvern
#

Clearly rb.position results in a slightly different outcome compared to directly setting transform, does rb.positon update the position of the object immediately? or does it require another physics step before its truly updated to this position

tender vapor
#

If you change the position of a Rigidbody using Rigidbody.position, the transform will be updated after the next physics simulation step
apparently yeah, it takes a step

#

if you're doing this in FixedUpdate, the step should be immediately after though

signal wyvern
#

is there any way i can force it to update immediately, or does this require running physics.simulate()?

tender vapor
#

im running physics in script mode
what do you mean by that? i don't think ive heard of that

signal wyvern
tender vapor
#

huh, interesting

old abyss
#

in your case where your physics is running in script mode, you can use PublishTransform() after modifying the rb pos and rot directly for the rb and transform to sync

tender vapor
old abyss
#

rb.move is different from transform.moveposition and transform.moverotation

signal wyvern
old abyss
#

rb.move and rb.moveposition are kinda similar. Ive used both on kinematic rbs and non-kinematic rbs. Didn't see any difference

signal wyvern
#

does publish.transform() need the rb to be kinimatic?

old abyss
#

i dont think so no

#

PublishTranform() just syncs rigidbody and tranform pos and rot

tender vapor
old abyss
#

but ive tried rb.move on kinematic and non-kinematic rbs and rb.moveposition on kinematic and non-kinematic rbs and i didnt see any difference

#

is your interpolation setting set to none or interpolate or extrapolate?

tender vapor
#

i don't have any rbs to test right now, but from what ive heard from helping here, MovePosition breaks interpolation on dynamic rbs (though, that might be for 2d) so i'm curious as to whether Move has the same behaviour

old abyss
#

rb interpolation is frame rate dependent. im not sure how it affects multiplayer setups but interpolation can give different results on the same machine since every run would be at a different frame rate

#

move and move position respect the interpolation settings btw

#

says so in the docs

tender vapor
#

empirically, MovePosition does not respect interpolation on dynamic rbs

#

i'm not referring to this specific multiplayer set up. i'm referring to the behavior of rb.Move in isolation

signal wyvern
#

Thank you both, Think ive made some good performance gains there ❤️

kind mauve
#

What's the good practice when it comes to making colliders for a whole level (low poly but not dumb simple geometry?
Inserting many many boxes?
Using meshes as colliders?
Making and importing simplified meshes of level geometry and using them as colliders?
Also how bad is the idea to make a huge bounding box alike collider as one mesh?

dapper arch
kind mauve
dapper arch
kind mauve
#

tbh this is confusing because it feels like in every game there is many mesh colliders everywhere

timid dove
#

It will also of course depend on the complexity of the scene and the target hardware

kind mauve
#

what will happen if an object happened to fall off the map

#

do I expect some crashes or issues due to some overflows or I can just safely ignore that that may happen?

dapper arch
#

it won't crash the editor

kind mauve
#

indefinite time freefall of a rigidbody

dapper arch
# kind mauve indefinite time freefall of a rigidbody

oh, sorry. thought you're talking about the mesh collider :P

if an object falls out of the map, it will eventually fall so far from the origin that there will be problems with floating point precision because of how far the object is. generally you'd have some system that would just destroy the object if it falls out, but that depends on your game

kind mauve
#

so I actually have to take care about it, huh

dapper arch
#

yeah, that would be the solution. i guess the object is not that important if you let it fall of the map?

kind mauve
#

yeah I don't mind them being deleted

#

of course I assume such can only happen during some extreme physic interactions

dapper arch
#

yeah, e.g. if the player has the ability to carry objects (like in R.E.P.O.) and there's a hole in the map

kind mauve
#

but like is there a game where a prop not suddenly getting mach 10 speed and fly through something

#

I don't trust those terrain/mesh colliders to be 100% impenetrable

dapper arch
#

i mean, if an object is moving extremely fast then it can just phase through another collider. rigidbody's continous collision mode does kinda solve it, but i'm not sure if it's that reliable

#

you'd usually set the collision detection mode to Continous if an object is very important, e.g. like puzzle elements in amnesia the dark descent (i remember when a pipe just fell through the floor and i had to load last save 💀 )

kind mauve
#

as I read about collision modes it's either fail to detect phasing through or fails to detech phasing through if big angular speed and weird trajectory

#

sometimes, given high speeds, but anyway, nothing is 100% impenetrable

dapper arch
#

true. i think you can also make a linecast between the last pos and the current pos - to check if the object didn't just penetrate through something

kind mauve
#

gee I guess

#

maybe worth it for puzzle elements

#

but in general I discuss about some random minor items

dapper arch
#

then i don't think why it would be worth the struggle. this linecasting thingy can get very expensive for many items

kind mauve
#

I would expect unity to outright delete objects extremely far or something

#

but I guess I have to do it myself?

south granite
#

i mean yeah

#

what if you dont want it to do that

kind mauve
south granite
#

now imagine how many of these kinds of problems maybe exist

timid dove
#

That's just... such a bespoke thing that it's not worth being part of the engine

south granite
#

and how many toggles would exist

timid dove
#

The engine should not take opinions on most things

dapper arch
#

it's easy to implement, e.g. every N seconds just check the dist from 0,0,0 and destroy the object if it's over some threshold.

south granite
#

respectfully thats an insane solution

#

just chuck a trigger collider down there

timid dove
#

It's part of why I dislike Unreal engine. Unreal practically begs you to be making a first or third person shooter game, and you have to start changing settings to make any other type of game.

kind mauve
kind mauve
south granite
#

dont make things that fast

kind mauve
#

it just sound like the thing that may cause a savebreaking situation one time out of a billion or something which is still bad

south granite
#

dont worry about one time out of a billion

kind mauve
#

notlikethis anxiety noises

frigid pier
#

For fast things there's a continuous collision mode for the Rigidbody.

#

Actually several of those

kind mauve
#

I wish I had a link for that Unity's(?) page comparing them
even dynamic one might ignore angular collisions
I suspect that may lead to some object getting stuck in geometry and potentially falling out

frigid pier
#

Long time ago when there was just one continuous collision option and I was making a bricks game it wouldn't be reliable enough at high ball speeds, even with very thick border colliders, so I had to handle it myself placing ball on the last position it would've been when it went through collider.

kind mauve
#

I mean the current one might be good enough yet not impenetrable and inevitably in a usual goofy game with props and stuff setting where rigidbodies even sometimes spawn inside each other or some random stuff like that some thing will get outside

#

or at least this is what I believe

kind mauve
#

exactly that page, yes

#

so what if we got a compound collider on a sweep based detection rigidbody flying into a wall with a high angular speed?

#

I suspect one of colliders might get through and something terrible will happen leading it to phase through by one end or the other

silver moss
#

The rotation stays the same during the sweep

runic torrent
#

Ok, so let's say I have a camera with a FoV of 60 degrees rotated along the x axis at 30 degrees. I want a given subject's transform point to appear at a viewport point of (0.5, 0.3). How would I go about calculating where to place the camera?

#

I'm not sure I worded this well, so here's a diagram

timid dove
runic torrent
#

Also I'm not sure how I would use Cinemachine that way

timid dove
#

Literally just by setting the "screen position" property in the inspector for the Position Composer

runic torrent
timid dove
#

It could be but there's probably not a reason to

#

Unless you need to adjust those values at runtime a lot

#

But yes anything can be done in code

distant oasis
#

so im using rigidbody to make this item can be thrown but on specific scene this object somehow broken and before i think it because mesh collider but i copy the area to testing scene it somehow not broken? is im doing something wrong in my game scene using the same rigidbody setting it just bypasse the collider and fall

timid dove
#

but also - moving it around via the gizmo in scene view at runtime isn't really a test of anything

dry shell
#

Heyy SUPER new noob question. I'm trying to learn about different joints and I'm watching a youtube tutorial for it. In the video the guy sets up a fixed joint with one cube connecting to another one. With the fixed joint, he's able to grab and drag one of the cubes to make them both move.

When I added the fixed joint, I am not able to make the both move, but when I got to play mode I can see the cubes fixed and hovering. How is he able to make these physics active while in Scene view?

timid dove
#

So you would enter play mode and look at scene view during play mode

dry shell
timid dove
#

just drag the windows around however you want

upbeat lantern
#

i wish unity adds a cylinder based character controller by default instead of making a custom one using rigidbody

twin bramble
frozen timber
#

working with a custom 2d physics engine, none of the scripts have any code in OnEnable or OnDisable, but a bug i have gets fixed when i disable and enable the gameobject with the bug. So basically lol im just trying to figure out exactly what does unity do internally during these events.

timid dove
upbeat lantern
# barren gorge why do you need cylinder?

there is few source projects i was working on that had multiple issues with some jumps not being possible unless you adjust the map or just make a custom collider

upbeat lantern
frozen timber
#

will have to live with it

pulsar canopy
twin bramble
#

i mean why would u want to anyways

pulsar canopy
#

I had to use a horizontal capsule for my game, so I had to switch from char controller to something else

deft barn
#

Hello i am creating a billiards game in unity and i am having some problems seeing realistic break physics. I have tried plenty of friction, bounciness material combinations however it just doesnt look right. Do you think this is a limitation of the physX engine and should i rather try implementing my own simulation physics? I can also provide footage how it looks now if it would be of any help.

timid dove
#

Billiards physics is pretty simple you'll be better off with custom physics.

deft barn
timid dove
#

All the objects involved are spheres, which are the simplest possible shape. You can even continue to use physx for the colliders and spherecasts and just do the motion part yourself. It's all just linear motion and vector reflection off collision normals

deft barn
#

so this would mean using unity's On collision events and then manually calculating the movement based on current linear and angular velocities?

deft barn
#

Seems like moving the object while still using the collision system can be achieved with the Rigidbody.MovePosition() method. Any thoughts on using this?

deft barn
#

I am sorry i dont see how i would use a sphere cast in this way. Would this run in realtime or would i have to precalculate all collisions?

#

Or is every ball gameobject sphere casting on itself and seeing if it hits another ball?

timid dove
#

to see if there will be any collisions

deft barn
#

so you are checking to see for next frame what happens

#

sorry my bad every timestep right cuzt this is not the regular Update method

#

Wouldn't this get really resource intensive calculating every next position with fixedUpdate for every ball in the scene?

timid dove
deft barn
#

yes

timid dove
#

it's fine

#

you can even do them all in a batch with the job system

deft barn
#

Okay so with this system i calculate a sphereCast that is where the ball will be next time FixedUpdate is called. This means that i should calculate a position, rotation every [timeStep] seconds, having it as a function of time?

upper helm
#

is AddTorque only visual?

#

if not what does it change on a rigidbody

timid dove
#

It's the rotational equivalent to AddTorque

#

Not sure what you mean by "only visual"

dry shell
#

Can someone help me find out why my dude just falls through the map?

I'm following a ragdoll physics tutorial. Each piece of mesh has a mesh renderer, rigidbody, and a joint connected to the relative part of the body. The cube I have stays but not my model. I also put a rigidbody and mesh collider on the full model to try and stop this but it didn't work.

frigid pier
#

With physics based movement you need to use physics methods properly with FixedUpdate frames, so it won't get pushed through colliders and interact correctly. See physics movement tutorials

timid dove
#

for an animated character especially you should not use a mesh collider at all. Generally a character like this uses a capsule-shaped collider for the basic world movement/interaction

pulsar canopy
#

Let's say that I have a rigidbody sword and a rigidbody axe split into handle and blade part.

I make the axe more top heavy due to the blade having more mass and I make the sword bottom or mid heavy.

Now, if I apply torque with the hilt being the pivot, does physx understand that the axe applies more force on impact, but takes morw torque to spin?

Is this something physx thinks about?

timid dove
dry shell
timid dove
#

How many Rigidbodies are involved?

#

If it's a single rigidbody the only way you can distribute mass is with the shapes of colliders. And all colliders are assumed by the system to have uniform mass.

What you can do is set the center of mass manually by disabling "automatic center of mass"

pulsar canopy
timid dove
#

ok you didn't mention multiple rigidbodies before. YOu will need to connect them with joints yes

#

and the yes the masses will be taken into account when applying torques and forces

pulsar canopy
#

I did mention two parts. I guess I didn't specify they are both rbs, I thought that was imied

timid dove
#

the parenting doesn't make a difference if they're dynamic bodies

pulsar canopy
timid dove
#

the physics engine basically will ignore the hierarchy. Joints are the only way to connect multiple dynamic RBs

#

it may interfere/fight with it. It's best to not have them in a parent/child relationship ideally

#

What's the end goal here though? I expect this is probably more complicated of a setup than you need/require

pulsar canopy
#

Yes, that's what I did (unrelated to this, but also with joints and rbs)

timid dove
#

a single rigidbody with a custom center of mass may be a better solution

pulsar canopy
pulsar canopy
timid dove
#

I mean it depends on what the game actually needs

pulsar canopy
#

Shifting center of gravity would work in the case of a symmetric staff, but not an axe or mace

timid dove
#

why not

pulsar canopy
#

Oh, I could shift it more upward the heavier the top, right?

#

That might result in the same thing, yes

reef stratus
#

have anyone ever had this issue? all i do is spawn the car and sometimes wheels dont function

silver moss
timid dove
reef stratus
#

wheels dont have a field for that

timid dove
#

it's a Rigidbody property not part of the wheel collider

silver moss
#

And the unity car tutorial uses a Rigidbody mass of 1500

viral beacon
#

I built a rigidbody extrapolator and made a camera follower for my car, however Im observing an inconsistent jitter between plays. It seems to be consistently smooth on the first compile, but repeated plays seem to get weird jitter. Is there a common cause for this?

Left video is almost perfectly smooth. Right video is jittery. No changes made to code or scene between both.

timid dove
#

Is there a good reason you don't use the built in Rigidbody interpolation/extrapolation?

viral beacon
#

the built in extrapolation drastically altered the simulation and caused massive issues

#

(my car started doing wheelies)

timid dove
#

What about interpolation?

#

Afaik neither is supposed to change the simulation at all

viral beacon
#

Its a car game so delay is kinda catastrophic

#

I think it has to do with the fact that the built in extrapolation/interpolation directly affects the rigidbody position, I would prefer to have these processes be cosmetic only

timid dove
#

I think it doesn't affect the RB position at all.

#

It affects the Transform position

viral beacon
#

I can show ya what happens when I turn on extrapoliation

timid dove
#

So maybe if you have code or logic depending on the Transform that could be the issue

viral beacon
#

I mean I do raycasts so I guess that qualifies

timid dove
#

You can do the raycasts based on the Rigidbody instead of the transform

viral beacon
#

interesting proposition

#

ill try it

#

hm, I am doing these raycasts from a child object, do I need to do rb.transform.position+transform.localposition?

timid dove
#

that's the issue in the first place, remember?

viral beacon
#

right I meant rb.position, because I have a rigidbody on my vehicle object, but I need the offset of the wheel which is where im doing these casts from

timid dove
#

If you want the world space position of a child object you would do this:

Vector3 worldPos = rb.position + rb.rotation * transform.localPosition;``` but this assumes you have 1,1,1 scaling too
viral beacon
#

ill give it a go and let you know whether unitys extrapolation works better or if my issue persists

viral beacon
#

however regular extrapolation works now

#

so you were right, thanks

dapper crescent
#

Is there anyone who explains realistic Unity car physics? I have a few questions I’d like to ask.

dapper arch
tender vapor
#

please don't crosspost

dapper crescent
#

ok sorry

rugged kindle
#

I’ve got a flick/plunge mechanic working, but it just doesn’t feel right. Weight feels off, launcher strength feels inconsistent, and endless tweaking isn’t fixing it. I even added some overlays to the game where I can tweak the values while playing.

Single dynamic shape, kinematic launchers, static rails. Using PhysicsMaterial2D on the dynamic shape with bounce and friction values.

At what point do you simplify / restart vs keep tuning? What would you check first? I feel like I am missing something important. Could the scale of my objects/scene be the issue? I didn't really consider that when building it out.

rugged kindle
#

Is it true that Kinematic to dynamic energy transfer in Unity 2D is not a stable “power delivery system”? That's what my research has been telling me. Should I instead use a impulse-driven launch using AddForce?

bold aspen
#

I'm in Unity Alpha, seems like 3D physics has a bug: When using any IContactsJob and there's a dynamic body, if there's no AABB contacts, the system floods with errors:

ArgumentException: Actual value False does not equal expected value True.
Unity.Physics.SafetyChecks.CheckAreEqualAndThrow[T] (T expected, T actual) (at ./Library/PackageCache/com.unity.physics@b51efcbbfd90/Unity.Physics/Extensions/SafetyChecks.cs:143)
Unity.Physics.IContactsJobExtensions+ContactsJobIterator..ctor (Unity.Collections.NativeStream+Reader reader, System.Int32 forEachIndexBegin, System.Int32 forEachIndexEnd) (at ./Library/PackageCache/com.unity.physics@b51efcbbfd90/Unity.Physics/Dynamics/Simulation/IContactsJob.cs:406)
Unity.Physics.IContactsJobExtensions+ContactsJobProcess`1[T].Execute (Unity.Physics.IContactsJobExtensions+ContactsJobData`1[T]& jobData, System.IntPtr additionalData, System.IntPtr bufferRangePatchData, Unity.Jobs.LowLevel.Unsafe.JobRanges& ranges, System.Int32 jobIndex) (at ./Library/PackageCache/com.unity.physics@b51efcbbfd90/Unity.Physics/Dynamics/Simulation/IContactsJob.cs:336)
timid dove
bold aspen
#

IContactsJob has the following code:

                    int forEachIndexBegin = 0;
                    int forEachIndexEnd = jobData.ContactReader.ForEachCount;

                    if (jobData.IsParallel)
                    {
                        if (!JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out forEachIndexBegin, out forEachIndexEnd))
                            break;

#if ENABLE_UNITY_COLLECTIONS_CHECKS
                        JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobData), forEachIndexBegin, forEachIndexEnd - forEachIndexBegin);
#endif
                    }

                    var iterator = new ContactsJobIterator(jobData.ContactReader, forEachIndexBegin, forEachIndexEnd);

And the ContactsJobIterator has the following cctor:

            public ContactsJobIterator(NativeStream.Reader reader, int forEachIndexBegin, int forEachIndexEnd)
            {
                SafetyChecks.CheckAreEqualAndThrow(true, forEachIndexBegin >= 0 && forEachIndexBegin < forEachIndexEnd && forEachIndexEnd <= reader.ForEachCount);

When there are no broadphase pairs (no AABB overlaps), the contacts NativeStream is allocated with ForEachCount = 0. In the non-parallel path, this means forEachIndexBegin = 0 and forEachIndexEnd = 0. The check 0 < 0 evaluates to false, failing the assertion.

This can easily be checked with the debug system, which uses the Interface (DisplayContactsSystem) and the Kinematic Character Controller, which is how I found the error, in DisableCharacterDynamicContactsSystem. Disabling both systems which schedules jobs makes the log stop happening

silver moss
rugged kindle
#

but yes I can make a video today to show you what I am talking about. I am going to try to implment addforce version now to see if that works the way i think it will.

#

also this is in regards to 2d physics.

timid dove
rugged kindle
#

One thing that is not related but still physics.... How in the world do i use a vector file as my collision map? I can't seem to find anything in the docs or any tutorials or anything. Saving my svg collision map as a png and then generating the collisions in unity produces the stair step effect on straight lines. In my vector its already exactly the way I want it

timid dove
#

the 2D physics engine doesn't support colliders defined as vectors

rugged kindle
#

but i can't generate a collider from SVG data?

timid dove
#

you can generate a sprite from SVG using the vector graphics package and generate a collider based on the sprite, but no it does not support SVGs directly