#⚛️┃physics

1 messages · Page 24 of 1

timid dove
#

ok what's the intent of this code? You're trying to save the angular velocity at the lowest point?

#

because this is a bit sketchy

dull shuttle
timid dove
#

Due to the fixed timestep of the physics simulation you likely won't have a frame when it's exactly at the bottom point

dull shuttle
#

yes i know this

timid dove
#

To do something similar you would do:

float differenceFromDown = Vector3.Angle(transform.forward, Vector3.up);
if (differenceFromDown < someThreshold) {
  // it's close to straight down
}```
dull shuttle
timid dove
#

just a constant

#

or defined in the inspector

#

it's an angle in degrees

#

we're saying like "if the angle is within 5 degrees of straight down" for example

#

and insert whatever number you want there

#

The whole approach is a little sketchy because depending on your fixed timestep and the max speed this thing swings, it's possible to skiup that whole window if it's too small.

But if it's too big you'll record the velocity at too large a difference from straight down

#

honestly... if this is suppsoed to be a swinging obstacle for the player to run past, I think it would probably be better to just use an AnimationCurve for this

dull shuttle
timid dove
#

somethjing like:

public AnimationCurve curve;
float timer = 0;
float animationDuration = 5f; // seconds

void FixedUpdate() {
  timer += Time.deltaTime;
  timer %= animationDuration;

  float t = timer / animationDuration;
  float evaluatedRotation = curve.Evaluate(t);
  rb.MoveRotation(Quaternion.Euler(evaluatedRotation, -90, 90));
}```
#

ah so it can't be kinematic?

dull shuttle
#

i'm not sure what kinematic does

timid dove
#

turns it into an unstoppable force that you can move via script but isn't affected by forces or normal physics in any way.

#

you would do that to use an animated version like my code example above

dull shuttle
#

ok, well i see it is too complicated to make so i know - i'll use animator instead

timid dove
#

animator would be the same

dull shuttle
#

i mean i'll just make an animation for it

dull shuttle
timid dove
#

in terms of not being aable to interact with it - i.e. stop it

dull shuttle
#

@timid dove thank you for all of this

random moat
#

I had to solve a similar problem to this recently and what I found was that I needed to add a 'lateral-only' friction. If you get the dot product of the object's velocity and it's right direction, this will tell you how much of it's velocity is in it's right direction (conversely it will be negative if it's in it's left direction). If you then add a force to the object in it's left direction multiplied by the dot product you just calculated, this will immediately stop it from moving laterally but keep it moving in it's forward direction. If you clamp the amount of force you add then it will stop it moving laterally gradually, which is a more natural friction effect.

pallid gale
#
void Counteract()
{
Vector3 facing = transform.up;  // direction that the body is facing
Vector3 heading = RBody.linearVelocity; // the actual direction of the velocity

Vector3 alignedVelocity = Vector3.Dot(heading, facing) * facing;
Vector3 lateralVelocity = heading - alignedVelocity;

lateralVelocity *= Mass;
lateralVelocity *= -1;

RBody.AddForce(lateralVelocity, ForceMode2D.Force);
}```
#

I will have to do some slight tweaks once the rotation becomes very close to where it's meant to, as it gets to an angle of something like 89.998

pallid gale
zinc heath
#

hey, so i have an object 1 and object 2, they are on top of each other, on object 1 i have oncollisionenter and exit. but when i destroy object 2 the object one doesnt trigger the oncollision exit function. how do i fix this please?

timid dove
safe karma
#

I have a problem where this asset from unity stops in place while the walking animation is still playing, does anyone have any idea why this could be happening?, it seems to be in random places at random times he just gets stuck, I can show more parts of the code if it helps

zinc heath
timid dove
#

It's not clear why it should be impossible.

#

Nothing is impossible

zinc heath
#

yeah i mean im not going to change how the whole system works so i dont really know

timid dove
#

I think you're overestimating the change you would need to make

zinc heath
#

i mean what i could do is check on the destroyed object before it getting destroyed if it is colliding with the first object and if it is then tell it to exit collision

#

but i dont know how i would check that

timid dove
#

With variables and if statements

#

Or an event

zinc heath
#

how do i check with if statement if an object is colliding?

timid dove
#

You keep track of the objects it's colliding with in a variable

#

And see if that collection is empty

zinc heath
#

yeah that should work

#

i mean a bool would be enough

#

if its colliding or not

timid dove
#

Usually not especially if multiple simultaneous collisions are possible (usually they are)

#

But you could start with that

safe karma
#

Just plays the animation

safe karma
#

Let me test something

timid dove
safe karma
timid dove
#

What's the collider situation here

#

You gave no details

safe karma
#

Oh yea, it's a tilemap so it's 1 singular tilemap collider 2D

#

Could the issue be related to these wall sensors aswell?

#

It's weird because the places and times he gets stuck are completely random

timid dove
#

You need that to merge the tilemap collider into a single contiguous surface

safe karma
#

I'll try using that do I need an asset?

#

But what does that do exactly?

timid dove
#

It merges the collider into a continuous surface

#

No you don't need an asset

safe karma
#

But it also seems to give it physics like gravity

timid dove
#

No, it's just a Collider

safe karma
#

Since it needs a rigidbody or something

timid dove
#

You're confusing it with Rigidbody2D

safe karma
#

Yea but I need a rigidbody to have the composite collider

#

How do I make it not have physics?

timid dove
#

Then just add one and make it static

safe karma
#

Alr let me see

timid dove
#

You need to check the "used by composite" box on the tilemap collider as well

safe karma
#

This should do it no?

timid dove
#

Make it static

#

Body type static

safe karma
#

Alr done

safe karma
#

Is it the effector?

timid dove
#

Composite operation

safe karma
#

Merge?

timid dove
#

merge is fine

safe karma
timid dove
#

after we messed with them

#

so that your grounded check works properly

#

something along those lines

#

impossible to know without seeing the code really

safe karma
#

Ok I'll try that thanks

safe karma
tardy badge
#

I'm working on a VR Game, and I cant seem to get the net to interact with physics, its a Basketball Net colliding with ball, im not sure what the code to get it doing like that is, but i need help

worn mantle
#

Hello! Trying to make An axe chop a tree when it comes into contact with it, but dont know exactly the best way to do that. I want to make it where the axe leaves a bigger and bigger mark (based on the axe collider itself), just like irl, but i could also make it a square object that might be much easier to implement

#

any advice on how its normally done? (want to do it myself if possible to learn)

maiden belfry
#

the physics system can detect when the axe hits the wood, but actually deforming it is out of scope

#

you'd need to generate a new mesh with a chunk taken out of it

#

(or have many small mesh pieces you can remove)

worn mantle
#

i know a easy way would be to just, like use the vertex deforming feature of probuilder, but you would have to also change the material of all the faces affected

#

maybe i just need to look more into how to build a mesh for this purpose.

lilac vessel
#

so I was working on making my enemies to have a set path but the moment I turned is trigger the enemy goes down at an angle and just clips through the wall. The wall and enemy both have box collider 2d so I am just confused whys its not working when i ticked is trigger on the enemy

strong turret
#

Hi, I'm trying to create a crowd simulation using navmesh agents but I want to speed up the simulation by 30x or 50x while still maintaining the same physics behaviour as it would be at 1x speed.
I tried increasing the timescale and decrease the fixedDeltatime by the same factor like this:
Time.timeScale = customTimeScale;
Time.fixedDeltaTime = Time.fixedDeltaTime / customTimeScale;

But then the agent's movements are stuttering and the physics doesn't work as expected as the agents pass through the colliders. Is there are way to achieve this? I'm looking for a Timelapse kind of effect.

timid dove
maiden belfry
#

Yeah -- if you double the timescale, you get twice as many fixed update steps per real-world second

#

By dividing fixedDeltaTime, you're getting a crazy number of very small steps

#

I also happen to have a "timelapse" feature of sorts -- I use it to rapidly test the game

#

I don't mess with fixedDeltaTime there

#

I do mess with it for the in-game "slow motion" feature

#

that ensures that I always get 50 physics updates per real-world second

forest spire
#

Will Unity ever allow us using AABB character controller volumes? It is on PhysX, not sure why they don't expose it:

maiden belfry
#

Not that I'm aware of

thorny plover
#

Hello, is there any way of blocking the character in place when he falls because of the ragdoll? Because as you can see, the ragdoll tends to do anything and I'd like to avoid this kind of problem.

karmic hornet
thorny plover
karmic hornet
#

Just turn off the rag doll?

#

And the physics components

#

Or put it on its own physics layer

vapid latch
thorny plover
# vapid latch How do you do THE weapon Reccoil?

I've made a shooting animation, and when the animation plays I've made my character turn I think 2 degrees upwards, so if you only shoot without controlling the recoil the effect isn't incredible, but when you try to control it a little it gives this effect that I find rather nice.

worn mantle
#

hello im enabling a boxcollider when i do something ingame, and then using the boxcollider in calculations to place objects

#

why does it take 2 seconds for the boxcollider to be enabled?

timid dove
worn mantle
#

because when its enabled, i have a object placed as well to show its enabled, then using raycast on left click to place an object if the raycast hits the boxcollider

timid dove
worn mantle
#

tried to debug on my own first, seems to be its not reconizing the collider for a bit after enabling it

timid dove
# worn mantle

well first off your code isn't actually checking if the Raycast hit anything properly

#

you should do cs if (Physics.Raycast(...)) { Debug.Log($"Hit {hit.collider.name}"); } else { Debug.Log("Hit nothing"); }

worn mantle
#

it can hit other objects beisdes the plot, but cannot hit the ground

timid dove
worn mantle
#

i do

timid dove
#

right now your Debug.Log line will throw an exception if there's no hit

worn mantle
#

yeah it is, that was a test debug

timid dove
#

it's also more performant to just use the return value rather than doing a separate nullcheck

#

and you're not logging anything when there's no hit

worn mantle
#

alright, ill use the performance instead, as it is better performance, but both should have same outcome no? is that really whats causing the issue

timid dove
#

So it's going to be hard to tell what's going on

timid dove
worn mantle
#

if nothing hits, the first debug log throws an exception.

#

there, redid the code, thought it wasnt anything that could change.

timid dove
#

There's actually a hole in the logic there

#

it's possible you're hitting an object, but the object you hit doesn't have the Plot tag

worn mantle
#

huh?

timid dove
#

And you will get the "null" log here

#

but that could very well be part of what's happening here

worn mantle
#

if (hit && Tag == Plot) {Place} otherwise {print null}

timid dove
#

yes so in the otherwise part of that is also included that there IS a hit

#

but the tag is wrong

worn mantle
#

ok i did debug it, and it has to do with my camera's view being IN the collider when i enable it

timid dove
#

Yeah

#

that'll do it

#

raycasts don't hit things they start inside

worn mantle
#

but they do after going outside, and back in?

timid dove
#

no

#

wait wdym by that

worn mantle
#

oh nvm, you right. I need to do a check some way to store when the player is inside, but preventing placing outside

#

so ill work on that, thank you for the help

vale field
#

Hello! I've been tryin to make a script that scans certain trajectories to find a trajectory that an object can be launched at to reach its target. I made this script by following this forum:
https://gamedev.stackexchange.com/questions/71392/how-do-i-determine-a-good-path-for-2d-artillery-projectiles
The problem I've been encountering is that the object's trajectory is a bit lower than the one I predicted, meaning that I've either calculated a formula wrong from this forum or there is something about unity's physics system that I haven't considered that has been slowing down the object:
Here is my script,
https://scriptbin.xyz/ayesebilap.cs

Use Scriptbin to share your code with others quickly and easily.

timid dove
#

It looks like just the side corners are hitting the edge there as one might expect

#

It looks like the botom center of the box is directly on the trajectory line

vale field
#

well, in this case the lower right corner of this box should be following this trajectory

#

but it's slightly lower

timid dove
#

Looks like the bottom center is following it

#

double check where the pivot of the object is

vale field
#

I'm gonna be really embarrassed if that was my mistake

#

Checking rn

timid dove
#

The other thing is make sure your rigidbodies don't have drag or anything

#

Another problem is this:

        for (float i = 0f; i < t; i += 0.01f)
        // loop through positions of the trajectory
        {
            // Calculate current position
            Vector2 pos = position(launchPosition, launchVelocity, i, acceleration);```
You're using this arbitrary 0.01f value to iterate.

You should be using Time.fixedDeltaTime
#

And instead of this:

return startPosition + launchVelocity * t + acceleration * t * t / 2.0f;```
You can just use the exact calculation the physics engine is going to use
#

which is to track the velocity of the object and simply add velocity += Physics2D.gravity * Time.fixedDeltaTime; and position += velocity * Time.fixedDeltaTime

#

I think you're using the actual physics answer for ballistic trajectories which doesn't actually quite work in a physics simulation with a discrete timestep like Unity's

vale field
#

I double checked where the pivot of my object was, and I'm pretty sure it's correct

#

but I will try your other suggestions

pallid gale
#

I've switched over from a Rigidbody2D to a standard Rigidbody, and the rotational code that works fine in 2D, no longer works as intended. I've made sure that it uses the correct axis' like eulerAngles.z was eulerAngles.y when in 2D.

void ApplyTurnForce()
{
  Vector3 dirFrom = transform.forward; // the direction the body is facing
  Vector3 dirTo = transform.right * CurrentTurnAmount; // direction to the left/right of the body, perpandicular to the facing direction
  // the two directions to rotate between

  Vector3 targetDirection = Vector3.RotateTowards(dirFrom, dirTo, MaxRadian, 0f);
  // rotate between the 

  float currentAngle = Mathf.DeltaAngle(0f, transform.eulerAngles.y);
  // this is the current angle the body has
  float targetAngle = -Mathf.Atan2(targetDirection.x, targetDirection.z) * Mathf.Rad2Deg;
  // angle the target direction has

  float angleDifference = Mathf.DeltaAngle(currentAngle, targetAngle);
  // the difference between the two angles

  RBody.angularVelocity = new Vector3(0, angleDifference * Mathf.Deg2Rad, 0);
}```
#

I feel like I'm missing something when it comes to updating rigidbody2d code to work in 3d, I'd assumed it was just a case of making sure it used the correct axis

#

for comparison, thats the old version that was for 2D

void ComputeTurnForce()
{
  Vector3 current = transform.up;
  Vector3 target = transform.right * CurrentTurn;

  float maxRadians = CalculateMaxRadians();
  Vector3 targetDirection = Vector3.RotateTowards(current, target, maxRadians, 0f);

  float currentAngle = Mathf.DeltaAngle(0f, transform.eulerAngles.z);
  currentAngle = transform.eulerAngles.z;
  float targetAngle = -Mathf.Atan2(targetDirection.x, targetDirection.y) * Mathf.Rad2Deg;

  float angleDifference = Mathf.DeltaAngle(currentAngle, targetAngle);
  RBody.angularVelocity = angleDifference;
}```
timid dove
#

transform.right * CurrentTurnAmount; doesn't make much sense to me

#

or I guess - It's not clear what CurrentTurnAmount is doing. A scalar will not change the direction of a direction vector

#

Oh I see - if it's negative you get left?

#

Anyway this:
transform.eulerAngles.y is pretty much always a bad idea to do, especially in 3D

#

you cannot rely on euler angles read back from a Transform like that

#

you especially cannot reliably isolate a single euler angle and expect it to be sensible. Euler angles come in triplets and generally don't have a reliable meaning alone

#

It's hard to say exactly what you're going for since you have a function named "ComputeTurnForce" which actually seems to be setting an angularVelocity not computing any kind of forces or torques.

vale field
pallid gale
# timid dove Can you explain what the code is supposed to do?

#⚛️┃physics message heres the intended behaviour for the turning. Excuse the poor naming of the method and other things.

The way CurrentTurnAmount works is it gets set between -1 and 1, depending on the joysticks input so I can steer to the left or right. dirTo holds that direction.

targetDirection is found by rotating from the forwards direction, to the side direction. MaxRadian is used to control how tight the turn should be. The target is neeed so I can find the actual angle to set the angular velocity for.

To do that, I use the angle the body currently has (which rotates about the Y axis), and I take the targetDirection and find the angle it has. It's sort of the exact same idea as the first part of the method, whether there is redundancy for this, I'm not sure. But it's worked fine in the 2D version.

Once the target angle is found, its a matter of finding the difference from the current to target angles, this gives me the desired angle to rotate by. I set the angular velocity with that angle

timid dove
#

because velocity is a matter of how fast you're rotating per second

#

So really since it;s always ghoing to be 90 degrees off your current facing, I guess you're rotating at 90 degrees per second

#

So I mean couldn't you just do:

Vector3 up = transform.up;
Vector3 angularVelocity = up * 90 * CurrentTurnAmount;
rb.angularVelocity = angularVelocity;```
pallid gale
#

the first part is more or less doing this. The larger you turn to the side, the greater the angle becomes to rotate by

timid dove
#

yeah my code would do this too

#

based on CurrentTurnAmount

pallid gale
#

I'm not at my PC anymore so I'll have to try it out tomorrow, but ideally I'd like to keep using the method I already have. It gives exactly the right type of movement I need, but for whatever reason, it just doesnt work with rigidbody

#

the only behavioural change I've done is instead of the 2D body moving on the xy plane, it's now a 3D body moving on the xz plane. All intents and purposes, I'm treating it like its 2D as I never allow it to move upwards

#

the question is that as long as my code has made sure to use the right axis with its various Vector3's, why would the rigidbody not behave as intended?

timid dove
#

Also if it's always upright on the Z axis you can just directly use Vector3.up

#

No need to worry about transform.up

pallid gale
#

I used euler angle just as it was the first thing I found that returns the actual rotation value the body has

#

How else could I find the angle difference between dirFrom and dirTo?

timid dove
#

you don't need to

#

for this type of control

#

If you did need to, you would use Vector3.SignedAngle but it's not necessary

#

it's honestly just:

rb.angularVelocity = Vector3.up * 90 * CurrentTurnAmount;```
#

I think all of your code just amounts to that one line really

pallid gale
#

huh! I'll give that a go tomorrow. Though part of me is a little sad to think all the work I put in could be replaced by a single line 😅

ripe depot
#

Hi, the head of my rgadoll curves into the body. How can I fix it? 1st shot is the parameter of the head, and another one of the neck.

unique cave
#

one thing at a time, what does this even mean? how do you detect this "tunneling"?

#

Doesn't sound anything to do with raycasts does it? Maybe a video recording of this effect happening would help

#

I have no idea why you would use raycast for a ball

#

I wouldn't be here if I hadn't

#

yes?

#

like million things. does it matter?

proud nova
#

Best to spend this time providing relevant information to solve your problem instead of interviewing people willing to engage.

unique cave
#

I'm not in the mood to prove you anything. Whether it's me or someone else, it's hard to troubleshoot an issue based on half complete sentences alone. If you don't want help from me, I'll leave this for someone else with pleasure

unreal peak
#

I'm making a 2d top-down rpg
How do I stop my player & monsters from "pushing" each other? I'm ok with a little push, just not too much.
I'd prefer both to just being unable to move through each other and stopping when colliding.
I'm setting velocity to move my player and using addForce to move my monsters.

#

Or would the game just feel much better if I don't make them collide at all?

primal carbon
short bolt
#

Is continous collision detection broken in Unity 6?

#

It seems to make things fly around in a tornado sometimes

unique cave
# short bolt Is continous collision detection broken in Unity 6?

Have you tried if the same happens in older version? If it doesn't, you should aim to create simple recreation steps to make simplified case where it happens and submit a bug report. There are also many other things that could cause that though, hard to tell without seeing more of the project

zenith parcel
#

how do I make gravity and stuff for my 2d topdown game so it has depth and an efficient movement system?

#

I can't find a decent tutorial on youtube

digital berry
#

hey what is the best (most performant and least complex) way to create a character controller that checks collisions with the environment, but needs no other physics functionality?
Ie no gravity (no jumping/falling, ground height is set directly from terrain data), no pushing objects. I really only want to be able to stop the player from moving through static objects with colliders. I'm currently using the built-in character controller component (which extends capsule collider) but I'm having to work around its api in annoying ways so I want to get rid of it.
I'm also not simulating physics anywhere in the game (except potentially particles in the future but they can just get their own gravity calculations) and I've pretty much disabled physics altogether. I can turn it back on and I suppose I would have to if I'd switch to rigidbodies.
I came across old threads saying that moving primitive colliders without a rigidbody is not as performant and I was wondering if this remains true, but then again, we're only talking about moving a single object in the scene. Rigidbodies seem to have a ton of functionality that I simply don't need, so putting a primitive collider on my player and moving it through transform.position seems most attractive, but let me know your thoughts.

timid dove
#

What are the "annoying ways" you need to work around its API?

#

Sounds like it's exactly what you want

digital berry
# timid dove What are the "annoying ways" you need to work around its API?

most annoying is that movement only works through the move method with relative movement, so I have to do an extra step every time to go from absolute to relative. most notably, straight up teleporting the player kinda messes with the controller component because it stores a position internally and I have to do this little trick to re-record the changed transform.position

digital berry
#

but also yeah, this isn't too difficult to work with, only a bit annoying and obfuscating so if you say this is just what I need I'll stick to it!

timid dove
#

You could also make a MoveAbsolute extension that just does the little subtraction

#

I think two tiny extension methods would be easier than switching to a whole new system

digital berry
sage ice
#

Hello, Im not sure where to post this but I believe its a physics issue, Im not sure why but recently my game has started Jittering with my players movement. Does anyone know what might be causing this and a possible fix

timid dove
#

If you are ever modifying the object's Transform directly, that will break interpolation

#

It could theoretically also be a problem with your camera following code or setup

sage ice
timid dove
#

Lerp doesn't guarantee a lack of jittering

sage ice
#

True, its looking with a simple lookat function

timid dove
#

These vague descriptions are no substitute for showing the actual code

sage ice
#

oh yeah I got u mb

timid dove
#

most importantly where is this happening. In Update? FixedUpdate?

sage ice
#

1 sec

#

How do I paste code again?

timid dove
#

!code

flint portalBOT
sage ice
#
[RequireComponent(typeof(Camera))]
public class FollowCam : MonoBehaviour
{
    Camera cam;

    public Transform camPos;
    public Transform target;
    public float followStrength;

    [SerializeField]
    private Vector3 positionOffset;

    [SerializeField]
    private Vector3 rotationOffset;

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

    // Update is called once per frame
    void FixedUpdate()
    {
        transform.position = Vector3.Lerp(transform.position, camPos.position + positionOffset, Time.smoothDeltaTime * followStrength);
        cam.transform.LookAt(target.position + rotationOffset, Vector3.up);
    }

    public void SetCamTarget(Transform targetPos, Transform targetLookAt)
    {
        camPos = targetPos;
        target = targetLookAt;
    }
}
timid dove
#

of course it's jittery

sage ice
#

I've used both fixed and normal Update and it dosent fix it

timid dove
#

It's also not clear what this "camPos" object is

#

Anyway is there a good reason you don't just use Cinemachine?

sage ice
#

I just dont have much expirience with cinemachine

timid dove
#

Anyway camera movement code best goes in LateUpdate

#

But - we didn't finish the car movement investigation yet either

#

how does your car turn/rotate?

sage ice
#

The car rotates with Wheelcollider steerAngle

#

Lemme grab the car code

timid dove
#

Ok - so if the car is moving properly via physics and has interpolation enabled I would try:

  • Move camera code into LateUpdate
  • Get rid of your Lerp code for now as that could be the issue
sage ice
#

ok, Lemme try that

timid dove
#

Just like:

transform.position = camPos.position + positionOffset;``` for now
sage ice
#

yeah

#

Ok so after changing the Lerp function it seems like that fixed it

#

but i would still like a smooth camera, is there a different way to do that?

timid dove
#

SmoothDamp would be more appropriate

#

Or better yet - use Cinemachine 😉

#

then you don't need any code

sage ice
#

Fair, I should probably learn cinemachine, it just seems like a lot

#

Thanks for the help though

vital marlin
#

GUYS I'm facing problem using the mesh collider , im trying to give a cup mesh collider but the mesh keeps closing from the top and i cant put anything inside the mesh itself , i want to make the cup get filled with objects , does any one have any idea why is this happening ?

unique cave
wind cedar
#

Hey guys
thanks in advance. don´t know if this is the best channel.
I'm creating a 2D game, but instead of classic platforms i'm using slopes.
Thing is i've already set my basic movement script but the player is sliding down the slopes.
I've wrote some slide prevent script, but it still slide down the slope.
Wanna check this script and give me some hints?

vital marlin
unique cave
unique cave
vital marlin
unique cave
vital marlin
unique cave
#

so what are those used for? placing other objects inside?

vital marlin
#

yub liquid , particles , objects , it's a whole lot of lab equipment's so yeah it's hard isn't it ? notlikethis

unique cave
#

getting decent looking colliders is not too bad but liquid sims are tricky ones. Not sure you would want to rely on colliders for that to begin with

vital marlin
#

is there any alternatives ? ,it's sad that unity doesn't support concave colliders

#

something intersting that when we used convex collider in some of these breakers they were open normally from the top but when we transfered them to unity 6 they stopped working normally

unique cave
unique cave
#

PhysX consideres convex colliders volumes, therefore making dynamic objects go inside is not really possible

kindred oriole
#

how do i get more physics steps at the same speed?

#

like Time.fixedDeltaTime but it doesnt change the simulation speed

unique cave
kindred oriole
#

ill try again

#

thanks

zenith parcel
#

to setup a topdown game physics I use the same stuff from a platform game, like the same layers?

timid dove
zenith parcel
#

what about topdown games then?

timid dove
#

what about them?

zenith parcel
#

yea

#

idk how I make some movements work well in topdown, like gravity

#

and avoid making the player jump and fall weirdly due to colliding sooner or later than expected

timid dove
#

All of that is specific to your game, and you need to design exactly the kind of movement you want

#

"jumping" in particular is very vaguely defined in a topdown game

kindred oriole
#

how do i fix this? When im going high speeds my physics get wierd while sliding on something, and when i go in slow mo its fine

timid dove
#

(at the cost of more processing power)

kindred oriole
timid dove
#

using Update makes it inconsistent

kindred oriole
#

i cant make a smooth camera then tho 0:

timid dove
#

Yes you can

#

that's what interpolation is for

#

just turn on interpolation on your Rigidbody

kindred oriole
#

i tried that

#

ill try it again tho

timid dove
#

If it didn't work there's something wrong with your setup

#

for example you might be breaking interpolation with something you're doing in your code

#

or your camera settings or script are not set up properly

kindred oriole
timid dove
# kindred oriole very jittery now

If it didn't work there's something wrong with your setup
for example you might be breaking interpolation with something you're doing in your code
or your camera settings or script are not set up properly

kindred oriole
#

they are setup normally tho

timid dove
#

Define "normally"

kindred oriole
#

normal

#

its a normal camera setup

timid dove
#

There's no such thing

kindred oriole
#

in a lateupdate loop

timid dove
#

Show your setup

#

and show how the Rigidbodies are configured

#

and how they are moving etc

#

if there are any scripts

#

As well as your camera setup

kindred oriole
#

what specificly do u need to see?

timid dove
#

The things I just listed

kindred oriole
#

yeah but what bits of the scri[ts

timid dove
#

anything involved in moving or rotating the player or the camera

#

ideally just the whole scripts

kindred oriole
#

turns out

#

i just changed it back to fixed update

#

and made the time thingy 0.05

#

and now its perfect

#

thanks 🙏

#

what if i put it to 0.001

#

LAG

timid dove
#

The smaller that number is the more accurate the simulation will be, and the more CPU resources it will use up.

kindred oriole
#

true

#

ty

short sable
silver moss
#

And then attach that object to your character with a joint for example

short sable
#

When I grab and drag the object I want it to react with the ground when being pulled

#

Something like in a game called "Little big planet"

silver moss
#

Configurable Joint exposes all the possible joint properties so you can do any joint with that

#

It's a bit more complex than the other joints

#

You can also look at other joint types and see which one constrains the item like you want it to

random moat
#

For those who are familiar with the ghost collision problem, do you know of any solutions that aren't one of the following:

  • Using Havok physics to use their "contact welding" feature.
  • Ensuring there are no inside faces to the world collision geometry.
  • Making the rigidbody collider float slightly above ground.
  • Using a capsule shaped rigidbody collider.
#

I've done a large amount of Googling about this problem and it seems like there is no good solve for it. I am kind of shocked, because I feel like objects sliding over world geometry without unwanted collisions is something I've seen in a bajillion games in my lifetime.

timid dove
random moat
timid dove
random moat
#

Like a union boolean operation?

urban shard
#

Hi, im trying to calculate the acceleration for a falling object but the acceleration keeps on jumping from a negative value that shoes its falling to some random positve value and the returns back it accelerating at the negative value

inner thistle
#

You'll have to show how you calculate it if you want someone to tell what's wrong

urban shard
#

im currently calculating it like this in the update loop

// Calculate velocity
velocity = (transform.position - previousPosition) / Time.deltaTime;

    // Calculate acceleration (difference in velocity)
    acceleration = (velocity - previousVelocity) / Time.deltaTime;

    // Update previous position and velocity for next frame
    previousPosition = transform.position;
    previousVelocity = velocity;
inner thistle
#

And what are you logging? acceleration is a Vector3 but the logs show only one number

urban shard
#

Im logging the y value since I just want to see if its falling or not

inner thistle
#

You get that from velocity, not acceleration

#

in fact that's just transform.position.y - previousPosition.y < 0

urban shard
#

Im not nesasseraly trying to see if its falling but how fast its falling

#

Im trying to make a simulation for someone falling of a building and trying to detect if they fall from a high height

inner thistle
#

The velocity tells you that

urban shard
#

I guess but Im trying to simulate it as if its being read from an accelorometer which calculates acceleration only as far as I know

inner thistle
#

Gravity is famously constant so it tells you nothing about how long they've fallen or from how high

#

If you drop an accelerometer it'll show 0 all the way down

urban shard
#

then what does it record?

inner thistle
#

Change in acceleration

#

There's going to be a big spike when it hits the ground

urban shard
#

there will also be a spike when you start falling so I am calulating when there is a fast acceleration that is suddenly stopped

#

either way do you know why it is giving me both positive and negative values?

inner thistle
#

There's not enough context to tell

#

But it's a dead end anyway, velocity tells you all the information you need

urban shard
#

ok thanks

inner thistle
#

Dividing by deltatime twice is probably the mistake

spiral nexus
#

How can i make tilemap colliders have collision? I've tried to use it on it's own, in pair with composite collider and both on single tile and on parent object of all my tiles but there is nothing. I saw few youtube videos and on them it look like i just should add tilemap collider and it will work from the start. If i use box colliders tiles really have collision but player randomly stuck/bounce while moving if i use box/capsule collider

dense perch
#

I'm having an issue with a rigidbody player riding a moving platform. Funnily, the code I have works fine when dealing with rotations, even when standing on a long rotating platform where you orbit its central axis.

The green player object in the video is a rigidbody, there is zero friction or any other things at play, since I disabled them via a physics material applied to everything in the scene. The platform is a kinematic rigidbody, and is moving solely using MovePosition(), which I've found also sets its linearVelocity variable.
The code for handling the actual platform-riding is: c# private void RideObject() { if (isGrounded && groundRigidbody != null) { // Translate player according to linear and angular velocity of platform: Vector3 angularVelocity = Mathf.Rad2Deg * Time.fixedDeltaTime * groundRigidbody.angularVelocity; Vector3 linearVelocity = groundRigidbody.linearVelocity; Quaternion relativeRotation = Quaternion.AngleAxis(angularVelocity.magnitude, angularVelocity.normalized); Vector3 relativePosition = rigidbody.position - groundRigidbody.position; // Add rotation to player around Y axis only: angularVelocity = Vector3.Project(angularVelocity, Vector3.up); // Apply movement and rotation: rigidbody.Move(groundRigidbody.position + relativeRotation * relativePosition + Time.fixedDeltaTime * linearVelocity, Quaternion.AngleAxis(angularVelocity.magnitude, angularVelocity.normalized) * rigidbody.rotation); } } And yet, for some reason, the player stutters like shown in the video. My script-execution-order has the platform script execute before the player script, so I'd expect it to run its MovePosition() function first, and though I realize that this doesn't MOVE it by the time we get to the player script, I'd expect the same MovePosition() call in the player script to mimic the exact movement. Does anyone know what I am doing wrong?

silver moss
#

First, do you have interpolation enabled on the rb?

dense perch
#

Yes, on both of them.

#

When moving between path nodes of mine, the platform has a constant velocity of 3 units per second. When viewing it move from the sideline, it moves perfectly smoothly as well. I've tried increasing the fixed timestep value in project settings to something like 0.05 (so 20 times per second), which made the stuttering more pronounced. I'm considering trying switching the simulation mode to use the regular update function, but it would require a lot of changes everywhere in the code. I'm not even certain what physics-related functions work in that mode, such as MovePosition(). I've tried being very controlling of the physics, seeing as I only needed the system for the robust collisions.

#

Currently the fixed timestep is at the default (0.02)

dapper arch
#

Hi, what's the best way to make object holding system like in Amnesia: The Dark Descent? i thought about directly changing the object's velocity, but that would cause the object to fly when the player flicks their mouse, and it's not natural. is Configurable Joint fine for that?

timid dove
dapper arch
#

alright, i will try that.

elder citrus
#

Is there a proper way to instantly set a rigidbody's velocity to X m/s in a given direction without touching the velocity directly

inner thistle
#

That sounds like a nonsensical requirement

#

Is there some actual restriction that you can't access the velocity property?

elder citrus
#

I'm just confused since some documentation online says you shouldn't set the velocity directly otherwise bad things happen, so now I'm confused since if you can't do that what other way is there

inner thistle
#

It means that you shouldn't rely on just always setting the velocity, for example for movement, because it can make it look unnatural and cause issues with collisions. But there's nothing wrong with just setting it once especially if the requirement is setting it to some exact value.

elder citrus
#

Ah alright, thanks

timid dove
unique cave
# elder citrus Is there a proper way to instantly set a rigidbody's velocity to X m/s in a give...

There is actually, you can AddForce with a force that essentially sets the velocity. That doesn't help you though because those same "bad things" will happen regardless. As others said, there's nothing wrong in setting the velocity, it's just not very natural to instantly change the velocity of an object. In theory that would require infinite force which isn't obviously possible. In real world velocities tend to change over periods of time but if you need instant one in your game, you can just set the velocity

lost crypt
#

Hiya, I'm wondering if anyone here has setup a joint that can only rotate in 1 direction? Or would an additional script be needed for that?

simple hearth
#

I have a player with box collider and a cylinder object with a capsule collider which is a "Log".

I want the player to be able to climb up on the "Log", but I don't want it to fly with "momentum" as it does in the video. What may be the optimal solution for this?

#

Sorry for occupying here, apparently it was a problem in my code. It turns out I was multiplying gravity too, while sprinting

unique cave
unique cave
# lost crypt Hiya, I'm wondering if anyone here has setup a joint that can only rotate in 1 d...

So you mean an hinge joint that can rotate clockwise but can't anti clockwise for example? Like a ratchet? My first idea would be to enable limits for the joint and rotate the min and max of the limit dynamically (via code) so that one of them matches the current rotation all the time depending on the desired direction. Haven played around with it a bit, to me it looks like unity doesn't expose enough from hinge joints api to make anything useful with that approach. Other approach could be to directly restrict the angularVelocity of the rigidbody

elder birch
#

Hey there! Im working on a bike shop like game, and im stuck at these colliders. I dont know what is the problems source, but when im parenting the objects, the physics going nuts.

timid dove
#

And why are you parenting objects to each other

#

What's the goal here?

coral mango
unique cave
hoary estuary
#

Is there any way that editor vs. build can affect physics detection, e.g. with raycasts? I've found a really weird gamebreaking bug where my FPS enemies can sometimes see and shoot the player through walls, but only in builds and not in the editor.

#

So I can try things before going full scorched-earth and reverting all my recent commits

bleak umbra
hoary estuary
unique cave
elder birch
#

I dont know you know the game "My summer car", i want a similar part attaching system

timid dove
#

You need to use joints

elder birch
#

Okey, ill try to use joints

#

thanks

short sable
#

Hey so I was watching this tutorial and I followed everything (I think...) and when I tested it out the movement is weird when I move right it moves the opposite direction and my player does not face the right direction and its very slippery when I move and let go of wasd my player still moves a bit.

Script: https://paste.ofcode.org/f6sCfQBi4kzWHcnbYJJv4E

Video of me trying it: https://streamable.com/jxeqoz

Video I watched: https://www.youtube.com/watch?v=Weu305NLMqo&list=PLyDa4NP_nvPeSosMrZ0Gv03v5s4k7Le7N&index=1&ab_channel=PrettyFlyGames

Watch "Ragdoll fix" on Streamable.

▶ Play video

In this tutorial series I'll show you how to create an active ragdoll which works in multiplayer from scratch. Download complete Unity project 👇
https://www.patreon.com/posts/code-access-ep1-108262101

📍 Support us on Patreon and help us make more videos like this one ⏩ https://www.patreon.com/prettyflygames

In this episode we'll go through h...

▶ Play video
light hound
#

In our 2D project where players can fly using jetpacks. We've found if players hit a collider above them at a certain angle (like 45 degrees), they kind of get a horizontal speed boost. I can't figure out what is causing it. The above collider has no physics material. The player has a zero friction and zero bonciness material

unique cave
light hound
#

i was kind of wondering that too

unique cave
#

It's hard to give any suggestions though without knowing more about what the actual issue is (why the horizontal "speed boost" is an issue) and how you want your player to behave in different situations

wooden hinge
#

Hey guys I just wanna ask a simple question. I'm trying to implement a wire sculpture simulation with VR hand interaction.

So the wire sculpture is basically the thing you can simply imagine which is to manipulate a single wire to make a shape of rose, man, or animals or whatever you like for example.

The point is that I have imported the meta SDK and I know how to code hand interaction with it. But other than that, I have no idea how to implement this wire manipulating simulation physically.
I've got to be able to manipulate the virtual wire with hand by touching it, and the manipulation needs to be seemed to be physically accurate, as if the real world's wire.

I'd like to appreciate you guys if you give me some idea on which components to use, or how to implement it, thank you!

short sable
#

How can I make the ground slippery? so as soon as my player goes on that slope the player rolls down the slope.

viral bone
short sable
viral bone
#

material on players's collider should effect it too, i see it defaults to average combine

dim fulcrum
#

I spent a day ripping out my charactercontroller to replace it with a rigidbody, because my character can carry a box and I wanted to prevent it from getting clipped into walls. The theory was I can connect the carried box with a fixed joint and it will prevent my character from walking into walls with it.. but it completely messes my controller. with the fixed joint the character starts turning or flying, even if I move it onto a different layer that's set to not collide with the player character.

I also tried simply parenting a boxcollider to the object with my player capsule collider and movement script and it also messes with movement.

iron galleon
#

so I applied the same script on both the ragdoll cow and ball, they both are supposed to bounce when hitting the platform

#

I used the cow spine2 bone as the rigid body that bounces off the platform, was I supposed to use a different game object to make it jump?

timid dove
elder birch
light hound
lost crypt
dense perch
#

So I'm stumped here... I'm using the physics system purely for the sake of solid collisions, and I'm dealing with forces versus friction/drag myself, so I've set my default physics material to have no friction, and rigidbodies have zero drag and such. This is so I can get the exact movement feel that I want.

Anyway, I have a rigidbody player that steps onto a spinning platform (kinematic rigidbody), and correctly applying the relative velocity between the player and the point on the platform the player is standing on, is not enough, as it produces this almost natural centrifugal force pushing the player away from the platform. This is even when accounting for any drag/friction from simply just standing there. I thought I could simply cancel this centrifugal force by calculating it and subtracting it, but that doesn't appear to work at all. Either I end up being pushed away as before, or the opposite force I introduced overcomes the centrifugal force so much that I get pulled inward entirely. Here's the code:

#
// Ride dynamic objects:
Vector3 relativePosition = Vector3.ProjectOnPlane(position - platformPosition, platformAngularVelocity);
// The velocity in the direction of rotation, multiplied by the "radius" (distance from the player to the center of rotation).
Vector3 tangentialVelocity = Vector3.Cross(platformAngularVelocity, relativePosition.normalized) * relativePosition.magnitude;
Debug.DrawRay(position, tangentialVelocity, Color.white, default, false);
// Centrifugal force: F = V^2/R, scaled into the normalized vector of relative-position so we get it as an actual force vector.
Vector3 centrifugalForce = (platformAngularVelocity.sqrMagnitude / relativePosition.magnitude) * relativePosition.normalized;
Debug.DrawRay(position, centrifugalForce, Color.blue, default, false);

Debug.DrawRay(position, velocity, Color.green, default, false);

// Accumulate and apply extra platform forces relative to our current velocity:
var platformForces = platformVelocity + tangentialVelocity;
rigidbody.AddForce(platformForces - velocity, ForceMode.Acceleration);
//rigidbody.AddForce(-centrifugalForce, ForceMode.Acceleration); // Opposite centrifugal force (does not work).

// Add movement friction/drag:
float moveDrag = isGrounded ? DRAG_MOVE_GROUND : DRAG_MOVE_AIR;
Vector3 hVel = new Vector3(velocity.x, 0f, velocity.z) - platformForces; // No vertical friction/drag.
rigidbody.AddForce(-moveDrag * hVel, ForceMode.Acceleration);
#

And here's a video showing the centrifugal effect pushing the player off the spinning platform. The green vector is the player's velocity, the white vector is the tangential velocity applied to the player from the platform's rotation. The blue vector is the calculated/expected(?) centrifugal force.

#

I've tried also just calculating the actual difference between the next position that the player ends up in during the next physics cycle, versus the "ideal" position that the player should arrive at, by rotating the relative position by the revolution per fixed-deltatime step. Then I take this as a force-per-second type deal by dividing it by fixed-deltatime, but this also does not appear to work.

#

(And yes interpolation is enabled for all rigidbodies. Only the kinematic platform uses MovePosition/MoveRotation, where-as the player's velocity is entirely force-driven)

iron galleon
#

nvm I messed up the mass notlikethis

elder birch
kindred oriole
#

i love ragdive agdolls

#

(active ragdolls spelled in a strange way)

#

anyone ever managed to make a self balancing ragdoll without external forces?

silver moss
#

You'd probably need to simulate toe muscles properly

elder birch
sleek spruce
#

Hey! Im trying to make a 2d ragdoll fighting game using swords/lightsabers. I want both swords to be able to interact with each other like as if it's a real sword. I thought this was quite simple and to just use box colliders but they weirdly don't collide. I thought it may be because both are on kinematic so I switched the rigidbody2d to dynamic. The swords get weirly stretched out and dont follow the character. Does anyone know how to fix this or fix my original problem? (please ping me if you reply)

timid dove
sleek spruce
#

okay thank you very much. I would use something like a fixedjoint2d right? And while using a joint it should not be a child object of the limb

coral mango
autumn ridge
#

I’m using Unity.Physics collision filter and I want to set the CollidesWith to collide with all layers. How do I set that?

timid dove
#

e.g.:

uint mask = ~(uint)0;```
autumn ridge
#

Yep but what about more than one layer?

timid dove
#

what do you mean

autumn ridge
#

Collides with takes a bitmask. I’m guessing this bitmask only represents one layer?

timid dove
#

no...

#

each bit is a layer

#

that's the point of the bitmask

#

the code I shared above creates a mask that will hit ALL layers.

autumn ridge
#

Ooohh cool

timid dove
#

because all bits are set

timid dove
#

That has the distinct look of DrawRay being called incorrectly but it does seem correct... 🤔

naive rune
#

I have just tried with brand new camera without changing anything still nothing..

timid dove
#

Oh I think your problem might be the mousePos.z = mainCam.nearClipPlane; line

#

that doesn't really make sense for ScreenPointToRay

#

I would try getting rid of it

naive rune
#

Ok. let's try it.

#

Mouse position is working. Physics are messed up somehow

timid dove
#

How did you assign mainCam?

naive rune
#

drag and drop

timid dove
#

the problem we're talking about is the DrawRay looking weird, yes?

#

Or something else?

naive rune
#

No draw ray working fine. Physics.Raycast is problem after countless of debuggin.

timid dove
#

the ray drawing looks weird to me... it's converging on some point it seems like

#

but uh - what object are you expecting this raycast to hit?

#

Show the inspector for it

naive rune
#

you can give duration to it. It will stay still

#

Its in the video the ground and tiles.

timid dove
naive rune
#

Yes but ground.

timid dove
#

Is your time scale normal, or set to 0?
Is your physics Simulation Mode normal (FixedUpdate)?

naive rune
timid dove
#

Project Settings -> Physics -> Settings -> Simulation mode

#

In fact can you screenshot the settings there?

naive rune
#

Everything should be set to default.

timid dove
#

yes... seems ok... 🤔

#

Can you try a Physics.SyncTransforms() before the raycast

#

just to check something

naive rune
#

It is soo weird. I even backed up my project to 1 month old version. Still wasn't working. This problem has just started.

timid dove
#

what is that green squiggle saying?

#

ok not helpful

naive rune
timid dove
#

try using a large finite number instead of float.MaxValue? e.g.... 1000?

#

shouldn't matter

naive rune
#

it's already set to float.max 😄

#

i was using it at 100 and was working till last night.

timid dove
#

Are you using git?

naive rune
#

ill try reimporting physics package

timid dove
#

so... what changed since last night according to git log?

naive rune
#

As i said i have backed up the project to older working versions but it wasn't working.

timid dove
#

Have you restarted your pc?

naive rune
#

many times already.

#

Trying to reimport everything now..

frigid pier
#

Did you print out actual value of variables you are using?

naive rune
#

Yes, Input.mouspos and ray work just fine.

frigid pier
#

like maxDistance when you are using it. Is it serialized?

naive rune
#

watch the video here.

frigid pier
#

You are missing something really obvious there. Create an empty scene and basic case with raycasting. Make sure it's working there. Then put it into your current scene and compare.

naive rune
timid dove
#

you sure time scale is not set to 0?

#

can you show your Project Settings -> Time settings?

frigid pier
#

Would be project wide

#

Now swap in those elements and see what fails

naive rune
frigid pier
#

Elements like basic colliders

timid dove
#

a screenshot of the settings would have been sufficient

frigid pier
#

Yes, put the working model parts into your main scene.

naive rune
frigid pier
naive rune
#

I even updated unity version.

frigid pier
#

Then it's likely physics settings. Compare them in both projects

timid dove
#

Maybe Time.timeScale is being changed at runtime?

#

Debug.Log it

naive rune
#

Found it. It's This. I don't remember messing with this settings at all. But this is the cause.

#

Thanks for your time guys. I couldn't figure this out for another week by myself. UnityChanwow

timid dove
#

I even had you looking in the adjacent settings page to that

#

oof

frigid pier
#

Just remember sanity checks next time if nothing makes sense. Test in clean environment and compare.

naive rune
dull shuttle
#

i have a trigger below a player that controls onGround variable and for some reason when player walks on Terrain collider the trigger randomly stops working when it's clearly visible that it touches the surface, there's OnTriggerStay() that should continuously keep onGround be set to true

timid dove
#

The RB is probably falling asleep or something

#

anyway why doi you need OnTriggerStay

#

instead of just OnTriggerEnter/Exit

turbid ember
#

hey just letting you know that i was able to expand your "betterphysics" package to work with articulation bodies

#

so in my case I was able to make it so the "articulation bodies" for my VR hand fingers now no longer impart forces on grabbed rigidbody objects, so its a hell of alot more stable now

#

if you want the modified scripts just let me know

timid dove
#

That's great

turbid ember
#

I'll send in DM

dull shuttle
#

it never happened on mesh or box colliders

grand mountain
#

Hello I have this inner platform with in it little cylinders that have cubes on top which all spin
my inner platform can tilt and move up and down but whilst doing that the inner little cylinders don't move with the platform (look second picture) the cylinders have rigid bodies that have no constraints set to them what could I have done wrong
my hierarcy:

outerstructure
  emptygameObject
    innerplatform
      innerCylinders
        benches
grand mountain
#

fixed had a issue in my rotation script which is now fixed

pulsar canopy
#

How does friction work in physics material? Changing its value does absolutely nothing to, well, add friction when sliding down a slope

#

I want to make the object that is sliding slow down

timid dove
#

whether that matters or not will depend on your movement code.

pulsar canopy
#

what to you mean by matters or not? I have gravity movement of a ball without any scripts moving it

#

just dropping down

#

when it slides down a high friction slope, it behaves the same as if it were sliding down a 0 friction slope

timid dove
#

they roll

#

so it's not particularly affected by the friction

pulsar canopy
#

oh you're right

#

good point

timid dove
#

in real life they have something called "rolling resistance" caused by the deformation of the ball as it rolls

#

but in the game engine the sphere is perfectly rigid and doesn't deform

#

so there is no rolling resistance

pulsar canopy
#

aha

#

so I guess doing it with code would be the way to go

pulsar canopy
timid dove
pulsar canopy
#

don't exactly know what you said but it works for me

timid dove
#

although the difference would be that angular damping operates while in the air unlike actual rolling resistance which is only present on the ground

#

the other thing would be to simulate rolling resistance with AddTorque when grounded in FixedUpdate

pulsar canopy
#

So it won't make a difference

timid dove
#

what is

pulsar canopy
#

On collision exit I reset the drag values

timid dove
#

gotcha

dense perch
#

Does anyone have any idea why rigidbody.AddForce(force, ForceMode.VelocityChange); differs from rigidbody.linearVelocity = force + rigidbody.linearVelocity;? From what I know, and based on the documentation, ForceMode.VelocityChange applies a direct change in velocity, by just adding the given vector to the velocity (without accounting for mass). So overriding the velocity with a new value should be as simple as adding the new value and subtracting the existing velocity, right?

timid dove
#

not -

#

why would you subtract the existing velocity?

dense perch
#

Oh my bad yeah, I'll correct that.

#

Actually I think I meant to put the subtraction inside the AddForce method. But regardless, the two still have different outcomes. I've got these two lines for the player jumping, which is supposed to replace the Y component of the velocity with the jump force variable.

// The way I do it:
rigidbody.linearVelocity = new Vector3(rigidbody.linearVelocity.x, JUMP_FORCE, rigidbody.linearVelocity.z);
// The way I "ought" to do it:
rigidbody.AddForce((JUMP_FORCE - rigidbody.linearVelocity.y) * Vector3.up, ForceMode.VelocityChange);
timid dove
#

linearVelocity = is overwriting

#

idk why you think the bottom one is how you "ought" to do it

#

though yes I guess it should probably work out the same?

#

what different outcomes are you getting?

dense perch
timid dove
#

by doing linearVelocity = you are probably cancelling/overwriting some other pending forces

#

If you do Debug.Log($"Accumulated force : {rigidbody.GetAccumulatedForce()}"); before and after this code, what do you see?

dense perch
timid dove
#

Even when you do the AddForce way?

dense perch
#

Nope, there it does seem to accumulate the jump force. Interesting.

timid dove
#

yeah - AddForce doesn't modify the velocity right away. It accumulates it then applies it during the physics update (which is after FixedUpdate)

dense perch
#

But my assumption must be correct then, with VelocityChange behaving that way. The difference must have come from the cancellation of the accumulated forces

timid dove
#

Can you show the rest of your script?

dense perch
#

I just figured reading from and writing to LinearVelocity would use the values already set from the previous cycle, and not fiddle with any of the internal accumulation state stuff.

dense perch
timid dove
#

Did I? good

#

not sure I caught the moment we solved it though haha

#

Or what the issue was

#

I guess maybe you have other code that further modifies the velocity later in your script or something

dense perch
#

Not directly via assignment. Just another AddForce as acceleration.

worn mantle
#

I love a good crash course through raycast and vectors and getting / setting directions. Trying to make a ray from one collider, through another, and back is hard.

timid dove
#

to make a vector pointing from one position A to another B is just B - A

worn mantle
#

i need to get the face thats closest to where my collision starts, and the one thats the farthest away from my collider, of a mesh, to edit it using probuilder

#

have to use Physics.raycast because thats the only way ive found to find a mesh face without using my screen for calculation

#

i mean i just finished it, and it works! But had to learn quite a bit about vectors, direction is target-start, and i tried some other inefficient ways to do things, like trying a raycastAll or just using normalized vectors for direction instead of simple direction.

timid dove
worn mantle
timid dove
#

also is this 2D? I assumed you are talking about a MeshCollider

#

otherwise the raycast is not necessary

#

because you said you want to get a mesh face

worn mantle
#

Yes, using a meshcollider. Its not a 2d game, but the problem described is 2d because it throws out y in any calculation (uses mesh's center for all calculations

#

i have this log, and im trying to get the face hit by the axe, and start deforming a mesh according to an agorithm im creating that relys on health, dmg object does, and goal is to move the initial face back close to the other face, before destroying the object, and letting a tree fall. As more hits get added, the initial face falls back, uses Grow section to get other faces, deletes them, and continues.

#

ive gotten the in index and out, but i should probably use the colliders raycast instead of physics, to increase performance.

#

the problem im on is getting the quad face out of the triangle indexes, but thats a probuilder problem and i dont need help rn for that

timid dove
# worn mantle

honestly if you have a lot of knowledge beforehand about this log like how many faces it has, you can probably simplify this a hell of a lot. Just get the face you hit and then, just have a mapping of face -> face for opposite faces that you have premade and use that

#

like if this thing has 12 faces around the outside you can just add 6 and mod 12 to get the opposite face

#

as an oversimplified example

worn mantle
#

yeah, wasnt thinking about that as all, the code i was thinking id use was intended to be done on a full tree initially, which i was trying to sidestep mesh colliders and querying the face index using a world point.

timid dove
#

yeah it could be done simply via taking the angle around the center of the chop and figuring out which "pizza slice" it lands in

worn mantle
#

thank you for the advice, that saves some performance. im really new to dealing with modifying/finding specific mesh faces, so i dont understand the last thing yet. i want to just make this logging feel satisfying to do, so alot of work, but ill get it done.

glad musk
#

can i use the two sphere colliders as a grounded check? currently im just using one raycast out of the back wheel but that makes it kinda buggy

glad musk
compact hedge
#

I made a rudimentary (I'm still extremely proud of it) orbital sim. Can someone please tell me why the orbiting object does not perfectly repeat its previous orbit? Is it a problem with my code or is this a real phenomenon? The code below are the only lines that manage the orbital physics

public static float Gravity(Transform m2Loc, Rigidbody m1Mass, Rigidbody m2Mass, float gravityConstant)
{

    float force = (m1Mass.mass * m2Mass.mass) / MathF.Pow(m2Loc.position.magnitude, 2) * gravityConstant;

    return force;
}
            
i.mass.AddForce(i.pos.position * -1 * Equations.Gravity(i.pos, planetMass, i.mass, gravity), ForceMode.Force);
#

The object does NOT exert a force back on the Earth

#

The pink blocks together is the trail of the satellite

compact hedge
#

And, any ideas on how I can make it predict the orbit path before it completes it?

autumn ridge
#

i'm sure you seen this problem before. but my OnTriggerEnter is not triggering. I've checked the matrix, made sure the script is on the phsyics object. One of the colliders IsTrigger and has a rigidbody with IsKinematic. what is happening haha

autumn ridge
#

i just tried 2d physics trigger and that works fine. 3D is not working.

#

i'll mention that ive installed Entities so maybe that has something to do with it

autumn ridge
#

Reason: while ECS subscenes are open GO 3D physics is disabled

stuck bay
#

Hi, I want a rectangle rotate on the z "around" a sphere but rotate it like the hammer on getting over it, it's always attach to player

deft dagger
#

why is this coin not falling? it has rigidbody

timid dove
deft dagger
#

i figured it out, i was using a box collider for my tilemap instead of a tilemap collider

compact hedge
#

I made a rudimentary (I'm still extremely proud of it) orbital sim. Can someone please tell me why the orbiting object does not perfectly repeat its previous orbit? Is it a problem with my code or is this a real phenomenon? The code below are the only lines that manage the orbital physics. The pink is the satellite’s trail. The satellite exerts no force back on the Earth.

public static float Gravity(Transform m2Loc, Rigidbody m1Mass, Rigidbody m2Mass, float gravityConstant)
{

    float force = (m1Mass.mass * m2Mass.mass) / MathF.Pow(m2Loc.position.magnitude, 2) * gravityConstant;

    return force;
}
            
i.mass.AddForce(i.pos.position * -1 * Equations.Gravity(i.pos, planetMass, i.mass, gravity), ForceMode.Force);
random moat
#

Has anyone else experienced ContactPoint.normal being inverted?

#

ContactPairPoint.Normal also seems to be inverted sometimes too.

#

That is to say, the normal sometimes doesn't point from ContactPair.OtherCollider to ContactPair.Collider.

#

If I'm reading the Physx documentation correctly, Unity's ContactPair.Collider and ContactPair.OtherCollider are equivalent to Physx's PxContactPair.shapes[0] and PxContactPair.shapes[1] respectively. It also states that PxContactPairPoint.Normal (seemingly equivalent to Unity's ContactPairPoint.Normal) points from the second shape to the first shape. But, this doesn't seem to always be the case with ContactPairPoint.Normal, which sometimes doesn't point from ContactPair.OtherCollider and ContactPair.Collider.
https://docs.nvidia.com/gameworks/content/gameworkslibrary/physx/apireference/files/structPxContactPair.html#d4482d0d718415fbbd0c5852994f139f
https://docs.nvidia.com/gameworks/content/gameworkslibrary/physx/apireference/files/structPxContactPairPoint.html#36ae08a170895b4b57eaa1f6488bcd05

timid dove
random moat
timid dove
#

Collider is the one you hit

#

The normal is correct. The names are bad

#

It's the same in OnCollisionEnter

#

(on the Collision struct)

random moat
#

I should say I only get this issue if it's colliders both attached to rigidbodies colliding.

#

If it's a rigidbody and a static collider, the contact normal always points from the static collider to the rigidbody, and the static collider is always the OtherCollider.

timid dove
#

Weird, idk then

random moat
#

The only thing I've found which seems like it might be related is this flag CollisionPairFlags.InternalContactsAreFlipped. But from what I can tell there's no way to see if a ContactPair has this flag enabled.

random moat
#

(Leaving this comment here in case anyone else encounters this issue in the future and finds my comment when searching for a solution)
Okay, it seems CollisionPairFlags.InternalContactsAreFlipped does indeed represent when the normals/impulses are inverted. I've solved my problem by checking whether ContactPair has that flag enabled in it's m_Flags field, and then just inverting the normals/impulses of it's contacts if it does. However, that field isn't public, nor is the enum type itself, so you have to get it's value via reflection. This was my code to get it.

var flags = (ushort)typeof(ContactPair).GetField(FLAGS_FIELD_NAME, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(_contactPair);
var isInverted = (flags & (1 << 5)) != 0;```
#

("_contactPair" is my field for the ContactPair I'm trying to get the correct normals/impulses of).

thin lichen
#

Do I need to adjust the collision matrix when I'm using 'include layers' in the collider? According to my understanding when I select to include only 1 layer I should only get triggers for that layer, but it's not filtering correctly for me. It works if I set the matrix. Do I understand the include layer setting incorrectly or and I missing something else?

random moat
thin lichen
#

I thought if I add a single layer to include layers it will exclude all others.

#

if I use exclude it'd have to be updated every time I add new layers too

random moat
#

I don't believe so. Any layers not specified in either includeLayers or excludeLayers fall back to the collision matrix behaviour.

random moat
#

I'm also not sure what would happen if you specified a layer in both includeLayers and excludeLayers.

thin lichen
#

iirc it exclude will take priority and it'll remove it

random moat
#

You could probably write a bit of code that sets it to exclude all layers other than the one you specify in awake.

#

Then you wouldn't have to update it as you add new layers.

dull shuttle
#

i have a trigger below a player that controls onGround variable and for some reason when player walks on Terrain collider the trigger randomly stops working when it's clearly visible that it touches the surface, there's OnTriggerStay() that should continuously keep onGround be set to true
the script which is added to the trigger has all three methods (Enter, Stay and Exit)

thin lichen
#

Thanks George, figured it out. You put me on the right track, I did indeed misunderstand the include. Removing all from collision matrix for the layer and then adding just the specific one via includeLayers works as I wanted it to.

dark wren
#

Anyone have any ideas why my projectiles might be passing through my walls? Providing images of projectile inspect, wall inspector, and projectile code, respectively

timid dove
#

You would need a dynamic Rigidbody and to move it via the physics engine if you want collisions

dark wren
#

I don't want it to move through physics though, I want it to travel in a straight line at a constant speed

timid dove
#

You can do that

#

With physics

#

But if you want collisions you need an actual dynamic physically simulated object

#

You can certainly move in a straight line at a constant speed

dark wren
#

Oh ok I forgot about the gravity scale property. I got it now. Thanks!

worn mantle
#

Hello, i dont seem to get how this is working. I have a meshcollider that i instantiate within an object. once its spawned in, i cast a raycast hit on it to get the triangle index that was hit. However, when debugging, turns out that it gives me -1 as the hitindex, but it HAD to hit the meshcollider as thats the only one spawned in where i hit it with a collider, and it shows up on raycasthit.collider.name. https://paste.ofcode.org/qmU57k7RfeTLMPmGB6Us8m

timid dove
#

That paste site isn't readable on mobile 😭

worn mantle
cerulean lava
#

I'm making a 2D side scrolling platformer. Here's my current script for character controls (cut out the unnecessary details) https://scriptbin.xyz/viwoxodura.http

RN, I'm using the RB.linearVelocity.x OR RunMaxSpeed for the Speed Difference situation, which ensures tight turning speed. This method is not ideal for transient forces like jump pads which are horizontal, and negatively affects other forces. I want to switch out the RB.linearVelocity.x part for a new variable: PlayerVel. However, I don't know how to increase or decrease this variable and where, in order for it to make sense? Because it's all Forces

Use Scriptbin to share your code with others quickly and easily.

lone glade
#

I made a character and a ground and gave them the necessary components but when i click play the player hits the ground but the camera just continues to fall

#

this is my first ever project so im bad at this stuff

magic kindle
#

does anyone know why when I use an articulation body with a prismatic joint, the path of that prismatic joint follows the parent orientation, instead of staying in place

stuck bay
#

hi, quick question, when a wheel hits a wall, how could I make the wheel climb it, should I change the force direction or is there a way to simulate the physics

lament crown
lone glade
cerulean lava
obsidian raft
#

why does my sphere cast only sometimes hit the collider of the ground below?

bool hitSth = Physics.SphereCast(transform.position + new Vector3(0, .01f, 0), jumpCheckRadius, Vector3.down, out hit, distanceThing + .01f, LayerMask.GetMask("Ground"));```
everything is ground layer i sent a picture of one of the colliders it isnt hitting as well
#

the red ball appears when the cast sees a collision

#

Physics.raycast could hit with no issue with this code

random moat
obsidian raft
random moat
#

It would need to be a little bit more than .7 to allow for some inaccuracies in the cast

#

Try starting it .8 above the ground if the radius is .7

obsidian raft
#

alr

random moat
#

You would need to extend the max distance of the cast too though

#

In this case it would need to be at least .1, to account for the difference in height and radius

short sable
random moat
#

Btw, I think active ragdolls usually have a fake force holding them up off the ground. They don't usually actually hold themself up purely with their legs, as that is behaviour that is very difficult to achieve.

worn mantle
#

does anyone know why Physics.Raycast() doesnt return a triangle index on convex mesh colliders? it hits it, it can say the name of a mesh collider, but it gives -1 when giving the triangle index. i can confirm visually the point where it hits, and can confirm there is a visible triangle of the mesh collider where it hit.

short sable
short sable
# short sable The hips are kinematic and the legs rotate back too much is that why it falls do...

this is the tutorial I have been following. I did what he did and it ended up like this 😦

https://www.youtube.com/watch?v=iNLQCwCHEBM&t=357s&ab_channel=HappyChuckProgramming

Unity Ragdoll Tutorial - Animation With Physics - Gang Beasts Style - Part 4

Hey Buds,
If you are having issues with copying the animation, please look at the reply to the pinned comment.

Welcome to Part 4 of the Unity Ragdoll Tutorial Series.
In this one I show you how to animate your ragdoll while allowing the limbs to be affected by physics...

▶ Play video
random moat
short sable
random moat
#

Could you record what happens if you just set the target rotation to the target limb's rotation?

short sable
random moat
#

Try both .rotation and .localRotation

#

In the tutorial he uses .rotation but that surprises me, I would've thought it needs to be .localRotation.

short sable
silver moss
short sable
random moat
# short sable I added this to my script my arms are now behind the player and my legs are near...

You'll probably need to dig into how the target rotation needs to be transformed in order to make the joint match the target limb's local rotation. I'm not familiar enough with configurable joints to know how to do this, but the chosen answer to this forum post looks promising. https://discussions.unity.com/t/how-to-use-target-rotation-on-a-configurable-joint-to-make-the-object-point-in-a-certain-direction/45786/3

short sable
worn mantle
# silver moss What do you need to do with the tri index? A convex collider's triangles dont ma...

i need to deform the mesh collider at runtime, with the impact point. i need a way to deform the probuilder mesh behind the collider as well, but if the hit index doesnt matter, that means you arent able to deform meshes at runtime unfortunatly, which is exactly what i need to do (deform mesh at runtime, with changing material of mesh. specifically i need to acess the mesh thats behind the meshcollider to push it to specific points, and raycast makes it super easy (if hit index worked)

random moat
worn mantle
random moat
#

I think there's a few ways you could go about achieving this. One would be to simply find the closest point on the mesh from the raycasthit point and use that triangle instead. You can probably find an algorithm online to find the closest point on a mesh. Another way would be to have a second mesh collider that is non-convex, and either has no rigidbody or has a kinematic rigidbody, and raycast against that. This would give you a triangle index which you can use to deform the mesh, then once deformed assign the mesh to the convex mesh collider.

viral glacier
#

Hi i dont know if this is exactly a physics problem but i have a LookAt function but as soon as i added it my Enemy started leaning back and after 5-10 sec the enemy would be lying down atp so i figured it was due to the pivot point so i parented the enemy to an empty but it still leans ive spent 2 h on this problem and as yall can see in the screnshot how the one on the left is when it spawned but on the right is the leaned ones

#

this hapens both to box and capsule coliders

timid dove
#

Very simple solution is to just set the y component of the position you're looking at to the same as the enemy's

#

Thisisn't really a physics problem though

viral glacier
timid dove
#

it doesn't affect your code

#

Also you shouldn't really be moving or rotating an object via the Transform if it has a Rigidbody

viral glacier
timid dove
viral glacier
#

so i guess its using a transform

timid dove
#

but I'm tlaking about the LookAt that you mentioned

#

MoveTowards just calculates a position

viral glacier
timid dove
#

You're going to be using vectors no matter what lol

#

You should be using the methods on the Rigidbody to rotate it

#

and to move it

viral glacier
#

ill see about fixing it am still preaty new to all this stuff i dont realy watch many tutorials so my code is bad but thanks for the insight

compact hedge
#

Can someone please help me interpret the parameters for this eccentricity vector equation? This is for orbits. I believe I understand how to use the equation, but what I don't understand is how some of these variables can be used as both vectors and non-vectors

#

The image on the left uses v as vector and also a non-vector. On the first use, there's no vector symbol above it. Is this not asking to square my velocity vector's magnitude? Or is it asking me to get the dot product of the velocity vector?

timid dove
elfin dust
#

can anyone help my car is not moving when i press W

timid dove
elfin dust
timid dove
#

don't post your question in multiple channels

elfin dust
#

ok

#

can you help me with my project in unity

timid dove
#

I already responded to you in the other channel

#

don't crosspost

elfin dust
#

was that the code

#

i alreaady have the code for moving the car but it is not working

timid dove
#

why are you still posting here

#

I responded to you in the other channel

elfin dust
#

sorry the name of the channel

lament crown
stuck bay
#

Hi, two questions how can I fix when it hits the ground, it get kind of stuck for a few seconds and how do I make it when it hits the wall it starts climbing it?

#

the wheel colider it's in the front wheel

obsidian raft
#

im making a level for the first time, should each of the prefabs have a seperate collider or do i make bigger colliders for patches of tiles? not sure whats better for performance

worn mantle
#

hello, is there any way to acess the code behind BoxCollider.Bounds.ClosestpointOnBounds? Its stored in a external class but i cant get to it through the code or scripting api (i want to understand the implementation of converting a point in 3d space to a point on the outside of a box and thought unitys implementation would be helpful to learn)

worn mantle
#

i didnt get to the second one, so going to look at that. i did look at the first one before but i had a hard time wrapping my head around it. thank you blue.

timid dove
#

ClosestPointOnBounds is also much simpler than this

#

DO you want ClosesPoint or ClosestPointOnBounds

#

ClosestPointOnBounds is for the AABB

worn mantle
#

im basically moving vertexes of a mesh on one side of a rectangler box, to a point on the retangler box thats closest in starting point. i already found out the direction for every point, just didnt know how to transform it

#

cloestpointonbounds is what i think i need.

timid dove
#

ClosesPointOnBounds only gives you the closest point on the bounds

#

the bounds is a minimal AABB surrounding the boix

#

if the box is rotated at all off the world axes, it is not the same as the AABB

#

Closest point on the AABB is pretty much just Mathf.Clamp on each of the three axes.

worn mantle
#

Ohhhhh, so if a box is rotated at all, then bounds doesnt work, because of direction, doesnt it work as long as all the bound points are in world space and theres 4 distinct points with 4 more directly them

#

yeah, i think bounds are what i need, the box isnt rotated at all and theres no reason for me to ever need to rotate it. at least for this implentation

#

this is the most work ive ever had to do for a progress bar XD

timid dove
#

It's just Mathf.Clamp for each axis then

viral glacier
# timid dove It's just Mathf.Clamp for each axis then

thanks bro for yesterday i did what u suggested and used my rigidbody to move my enemy and to rotate it in the direction of the object i want it to look at. I didnt know u schouldnt use transforms to move and look if i have a rigid body and phyisic but i know nowUnityChanCheer

obsidian raft
#

im making a level for the first time, should each of the prefabs have a seperate collider or do i make bigger colliders for patches of tiles? not sure whats better for performance

gusty rampart
#

Hello, I'm coding a tetris. Here is how I created a tetris shape : I made a Square prefab, and used four of them to create a shape prefab (and square is the child of shape)
My question is : should I put the rigidbody in the parent or the child (as it is right now) ? because I think that the problem comes from that. also, should I use a composite collider, since I have different collider in the same shape ? as you can see in the video, the shape should not quit the grey rectangle but it does

inner thistle
#

If the problem is that it goes outside the gray area it's because colliders don't prevent you from going outside another collider when you're already inside. You should have 3 colliders for the play area (two for the sides and one for the bottom)

#

Also using a physics simulation isn't usually a good fit for Tetris. It's going to require a lot of tweaking to get it right for very little benefit

gusty rampart
inner thistle
#

Typically you'd have a 2-dimensional array that represents the board and it holds information if there's a block in that square or not. A falling block has coordinates that you can use to check if the block has reached the bottom or a filled space in the play area, and if there's space to move left or right or rotate. The movement is just animating with lerp at simplest

#

I'm sure there are a lot of tutorials for it

gusty rampart
#

ok thank you for the advice

slow quiver
#

Hey all. I'm just wondering if anyone might know why my character is bouncing off walls slightly when jumping against them. The player has a material that has 0 bounciness and the wall does not have a material.

worn mantle
#

hello, so here i have a box collider that covers this box. the problem is that when i check the bounds of this, its outside the actual bounds of the box. the problem is that the bounding box of the collider is not on the collider, even when at 0 rotation. (little boxes are at bounds min/max of code, and sheet is where box is) if box was at 0 rotation the bounds would be like 90 degrees parellel to the box) But, for some reason, ClosestPoint still works.

timid dove
#

Where's the collider gizmo?

#

And what does your code look like?

worn mantle
#

by checking the bounds i mean running collider.bounds.min, and collider.bounds.max

#

for this i basically need to get the outside most intersection of my mesh collider and the box collider repersenting the cube, to use for calculating where to put my mesh vertex points.

#

i got pretty close a single time, but the points were a bit more inside the collider then i needed

#

i tried using mesh collider with collider bounds, but the points were very off, using collider.closestpoint got me closer, but a bit off, i thought about taking a step back and turining the cube into a bigger cube that slowly grew to finish the entire area, but that wouldnt solve the problem with make the points turn back inwards after the middle

quick void
#

Hello, guys! I have a question. Does anybody know how to create climb up/down the stairs system using a Character Controller?

worn mantle
pallid gale
#

I've come across a lot of car controllers that tend to use wheel colliders, but when I've been writing my own vehicle controller, wheels arent something I've ever used. It's been more than enough to do a basic AddForce in the forward direction and to gradually rotate the game object as it turns.

I'm starting to wonder if wheels are actually something I should start using, I like the idea that they could make my own vehicle a bit more physically accurate, but I'm doing more of an arcade vehicle controller so it's not like I need something extremely realistic

#

suspension being one feature of the wheel controllers that isnt of any use to me

#

the main thing I'm interested in is if they could allow the turning of my vehicle to be physically accurate

timid dove
timid dove
timid dove
worn mantle
timid dove
#

You should just use a quad mesh instead of a cube, fix that scale back to 111, then adjust the box Collider instead of using scale

shell ravine
#

hi guys could you help me with my physics homework

unique cave
shell ravine
#

ok aleksi you are right I apologize

simple token
#

I can not stop the flippers in my pinball game from clipping into the ball. I've set the ball and the flippers to continuous dynamic, but still, the ball will occasionally clip into the flippers, usually when the ball hits the flipper on the far side from the hinge joint. Any secret unity settings I should try?

#

I also have interpolate on, not sure if that should be on tho 😮

timid dove
#

how are you rotating/moving them?

simple token
# timid dove Well the main thing is to make sure that you are rotating them properly with the...

I'm rotating them through these Hinge Joints. I don't really understand these, but pinball tutorials on youtube said this was the way. I was trying to just manually rotate them but the table is sloped, and me trying to figure out how to rotate them on a slanted axis like that was melting my brain.

 {
     hinge = GetComponent<HingeJoint>();
     jointSpringPressed.spring = jointSpringReleased.spring = hitStrength;
     jointSpringPressed.damper = jointSpringReleased.damper = dampening;
     jointSpringPressed.targetPosition = hinge.limits.max;
     jointSpringReleased.targetPosition = hinge.limits.min;
     if (flipperType == FlipperType.LEFT)
     {
         FlipperController.instance.OnLeftFlipperActivated += ActivateFlipper;
         FlipperController.instance.OnLeftFlipperDeactivated += DeactivateFlipper;
     }
     else
     {

         FlipperController.instance.OnRightFlipperActivated += ActivateFlipper;
         FlipperController.instance.OnRightFlipperDeactivated += DeactivateFlipper;
     }
     //defaultRotation = rigidBody.rotation;
 }

 // Update is called once per frame


 private void FixedUpdate()
 {
     if (isActivated)
     {
         hinge.spring = jointSpringPressed;

     }
     else
     {
         hinge.spring = jointSpringReleased;
     }
 }
timid dove
#

Yeah I would probably be using MoveRotation personally rather thawn a joint, but this should be alright... at least in terms of clipping stuff

#

I was trying to just manually rotate them but the table is sloped, and me trying to figure out how to rotate them on a slanted axis like that was melting my brain.
I mean one easy way to shortcut this whole thing is to just make two empty objects in the editor - one at the "rest" rotation and one at the "activated" rotation. Then you can easily just MoveRotation to each of those positions

#

like:

bool isActivated;
public Transform restObj;
public Transform activeObj;

void FixedUpdate() {
  Transform target = isActivated ? activeObj : restObj;

  Quaternion targetRotation = target.rotation;
  rb.MoveRotation(targetRotation);
}

void PressFlipperButton() {
  isActivated = true;
}

void ReleaseFlipperButton() {
  isActivated = false;
}
#

then you don't have to do or think about any rotation math

simple token
sour arrow
#

Can anyone help me recreate the weld tool from gmod in unity? or just give me some good ideas? Cause im really stupid and cant come up with something good.

timid dove
sour arrow
#

How should i set it up?

timid dove
#

Write code, using AddComponent, to add e.g. a FixedJoint to one object attaching it to the other.

proven lark
#

Hi, has anyone encountered an issue, after import of Unity.Physics, editor goes into infinite import loop. And knows how to resolve it? On empty project import of samples is fine.

pallid gale
#

https://docs.unity3d.com/Manual/class-PhysicsManager.html @simple token as youre doing pinball flippers physically, you'll want to increase the solver iterations. You will always get inaccurate results from having such a fast movement (like a 90 degree rotation over 2 frames), increasing the iterations will improve the accuracy

simple token
#

No more clipping in the flipper at least

pallid gale
# simple token What about fixed time step? I lowered the fixed time step value and it seems to ...

fixed time step is required for physics, as the it keeps the duration for every physics tick the same, delta time in the other hand can vary by tiny amounts which could generally lead to an unstable simulation.

Iterations are substeps that occur within a physics tick, the more substeps you have, the more accurate the simulation becomes. See how in the image that the blue registers the collision immediately, the red having less substeps caused it to detect the collision but not as fast (less accurate), and the yellow didnt receive any collision and teleported through the wall

#

the trade off is that it becomes very expensive to have very high iteration count

simple token
pallid gale
#

From the way I understand it, Default Solver Iterations impacts the accuracy of the position after each tick, like how the red square will need to be positioned to be on the walls surface. This is probably the only setting you need worry about

Default Solver Velocity Iterations is purely so the velocity of everything is as accurate as possible at the end of each tick, same sort of principle as the image, but just imagine the red being a little too fast, and yellow being a little too slow. Simple example is slowing down over ice, you'd expect to slow down after X amount of time

simple token
steep trench
#

excuse me where would i go to ask questions about specifically the particle system. I really want to learn it and shader graphs but the documatation wasnt helpful or i misused it somehow

feral holly
#

how would you guys make a ball bounce differently (less bounce, less speed, etc.) if it bounces on a different surface?

#

I basically want the ball to bounce lower if it touches grass and speed up or bounce higher if it touches concrete and slow down

anything less than Bounceiness of 1 makes the ball bounce too low in general... but I also want more control over the bounce itself

#

I know how to make the logic change based on a trigger/collision type... I am more concerned about what numbers to play with

modest oar
#

Guys, I am running into this problem. Does anyone know how to fix it? I checked the 2D collider and Rigidbody2D—everything seems fine, but...

timid dove
modest oar
#

@timid dove The object is going inside the other object. It is supposed to come out quickly, but after the collision, it goes in and does not try to come out
It's happening when the collision is triggered, and there are some objects in between.

#

The objects in between are getting stuck in the merged object.

timid dove
opal basalt
#

I have a question, im not sure if this is the right place to ask, but here goes:

We have a project where we are going to simulate collisions in space and we want objects to be hit by smaller objects and cause some destruction. Lets say a spaceship is hit by some debris, and the hit part would be a bit destroyed and become debris. How would you go about doing this without paying for tools like rayfire. And also if we were to pay for rayfire, would everyone working on the project have to pay for it, or just the person working on the collision parts.?

timid dove
#

as for the destruction - there are many ways to do it. You could have your ship made of many smaller MeshRenderers and when one gets hit you could replace that one renderer with a destroyed version (or nothing) and spawn some debris, for example.

Or you could go for a more advanced thing.

opal basalt
#

Ok, then rayfire might be an option. what we are doing atm is having 2 models, one whole and one cut-up, but im not getting it to work the way i want

feral holly
timid dove
feral holly
#

cause physics material bounceiness has too drastic of a change... like anything less than a 1 and the ball just feels like it dies or I cant make it bounce more

timid dove
#

Should be pretty gradual

feral holly
#

I can try .9999 but I usually feel like changes to the physics material bounceiness make it too drastic except for drag

timid dove
#

Make sure you understand the combine modes too

unkempt drift
#

Greetings. I have a bolt that can stick in walls with boxcolliders, but bounces off objects with rigidbody AND a collider. Why is that so?

tender river
#

Hi peeps, i was just wondering if anyone could help me with my npc character that moves around 2 feet off the floor on my terrain. Ive unchecked the gravity box on the rigid body which seems to work and not fall through the floor. but now he runs a couple of feet above. ive set the starting position directly on the floor by snapping it. but after a few steps he just levitates. if there is a fix to this that would be greatly appreciated 👍🏻

timid dove
#

look at your character in scene view when this happens and double check the collider compared with the renderer

tender river
#

thanks will do

tight dock
#

Hello

#

So the simulated doll is moving.. just not in the way that it should. It seems that the rotations are messed up

#

I'm stuck on this part, probably why
How do I set the axis and secondary axis? The numbers seem random to me.

#

like, is this facing the right way? How do I orient the axes?

cold gyro
#

Is there any documentation for what can cause a Collider component to recalculate its geometry? (3D)

silver moss
#

Are you talking about MeshCollider specifically?

light gate
feral holly
#

I guess I could just always change the linear damping after a bounce and then change it back if it touches a players hitbox but that seems like it'd get complicated fast and is at a risk of failing eventually

#

I did change physics materials a bit such as dynamic friction and bounciness which is a good start but I need more improvements as well. But I feel like linear damping just makes things more... complicated

light gate
#

There’s only so many properties to play with here I think.

feral holly
#

although the only thing I am running into right now is the ball doesn't seem to spawn with its default value

#
private void OnTriggerEnter(Collider other)
{
    if (!(base.isServer))
    {
        return;
    }

    if (other.CompareTag("Hitbox"))
    {
        Rigidbody rb = GetComponent<Rigidbody>();
        rb.linearDamping = 0.5f;
    }

    if (other.CompareTag("Clay"))
    {
        Debug.Log("Clay");
        Rigidbody rb = GetComponent<Rigidbody>();
        rb.linearDamping = 1f;
    }

    if (other.CompareTag("Hard"))
    {
        Debug.Log("Hard");
        Rigidbody rb = GetComponent<Rigidbody>();
        rb.linearDamping = 0.5f;
    }

    if (other.CompareTag("Grass"))
    {
        Debug.Log("Grass");
        Rigidbody rb = GetComponent<Rigidbody>();
        rb.linearDamping = 0.2f;
    }
}
#

I have the default value as 0.5 on the prefab, but when the ball spawns it uses the value of something else. but its too high and far away from any triggers tagged these objects.

golden terrace
#

So hello people.... I ugh, may have been developing my own deterministic physics system thinking that Unity's physics engine wasn't deterministic. I was just recently told that it now is. Ugh... can anybody tell me what their experience has been?

https://docs.unity3d.com/Packages/com.unity.physics@1.3/manual/index.html <== Says right there, it's deterministic.

In the picture; a snapshot of the unit tests behind my system to make a deterministic physics model (2D).

#
namespace OmiGames.Numerics.Fixed {
    using System.Diagnostics;
    using System.Numerics;
    using System.Runtime.InteropServices;
    using UnityEngine;

    [StructLayout(LayoutKind.Explicit)]
    [Serializable]
    public struct Fixed64 : IEquatable<Fixed64> {
        public static readonly Fixed64 Zero = new Fixed64(0);
        public static readonly Fixed64 One = new Fixed64(1);
        public static readonly Fixed64 NegativeOne = new Fixed64(-1);
        public static readonly Fixed64 Epsilon = new Fixed64 { _value = 1 };

        public const int FRACTIONAL_BITS = 16;
        public const long SCALE_FACTOR = 1L << FRACTIONAL_BITS; // 2^16

        [FieldOffset(0)] private bool _signPart;
        [FieldOffset(0), SerializeField] private long _value;
        [FieldOffset((64 - FRACTIONAL_BITS) / 8)] private Int16 _fracPart;

        // Constructors
        public Fixed64(long integerPart) {
            _signPart = false;
            _fracPart = 0;
            _value = integerPart * SCALE_FACTOR;
        }

        public Fixed64(double value) {
            _signPart = false;
            _fracPart = 0;
            _value = (long)(value * SCALE_FACTOR);
        }

        public static explicit operator Fixed64(double value) => new Fixed64(value);
        public static explicit operator Fixed64(long value) => new Fixed64(value);```
Here's the start of my "double" for some context as to the well of despair I might have set myself in.
timid dove
#

So it depends what you're comparing it with

#

It also depends on your definition of "deterministic"

wooden inlet
#

I'm making a game where the player is able to WallJump/Jump and shoot downards at the same time. My problem is when they shoot and jump at the same time the velocity in the upwards direction becomes way to high I've tried a bunch of things with limiting velocity and applying scaled amount of force depending on speed. But this is all extremely Janky any good suggestions to make this smoothly?

timid dove
honest river
#

Hello guys, does anyone have a function to calculate time to cover distance by a rigid body?

timid dove
#

so time = distance / rate

honest river
#

What rate, sorry?

#

So let's say a rigid body 2D weight 1kg was launched 10 m/s with drag 5 was just launched. Now I want to know how long it will take it to cover 100 meters and if it will even reach it.

timid dove
honest river
#

There's also drag, right?

timid dove
#

rate is 10

#

drag matters yes

#

if you want to incorporate drag it's more complex

#

with no drag this would simply be:
t = d / r
t = 100 / 10
t = 10 seconds

#

with drag you need to know how Unity calculates drag which is kind of opaque, but people have reverse engineered it. It might be better to use your own drag formula though so you know precisely how it works.

honest river
#

I found this for the future position:

    public Vector2 FuturePosition(float Time) {
        // Starting position
        Vector2 Position = RigidBody2D.position;

        // Drag multiplier (friction)
        float Drag = Mathf.Clamp01(1.0f - (RigidBody2D.linearDamping * UnityEngine.Time.fixedDeltaTime));

        // How much velocity is added per frame
        Vector2 VelocityPerFrame = RigidBody2D.linearVelocity;

        // How many frames are going to pass in the given time
        float FramesInTime = Time / UnityEngine.Time.fixedDeltaTime;
        for(int Index = 0; Index < FramesInTime; Index++) {
            VelocityPerFrame *= Drag;
            Position += (VelocityPerFrame * UnityEngine.Time.fixedDeltaTime);
        }

        return Position;
    }

But I'd also like to have time to coover distance and also how much total distance rigid body will travel.

honest river
#

Or would I have to use inheritance, or implement movement of everything myself?

timid dove
#

in FixedUpdate

#

why inheritance?

honest river
#

Yeah I was thinking more of virtual void ApplyDrag in RigidBody2D, so then I'd create a C# class, inherit from RigidBody2D and override that using the default physics formula.

#

But you say custom drag in a class, makes sense

timid dove
#

no

#

you can't do that

honest river
#

Can I find somewhere where people reverse engineered it?

timid dove
honest river
#

I thought you have something specific in mind

#

Wait, there's also a friction on the material?

honest river
#

So I took the formula of the next velocity: velocity = velocity * ( 1 - deltaTime * drag); from the forums. Does this look right:

    public float? TimeToCoverDistance(float Distance) {
        Vector2 CurrentVelocity = RigidBody2D.linearVelocity;
        float DistanceTraveled = 0f;
        int TicksToTravelDistance = 1;

        if(CurrentVelocity.magnitude > Distance)
            return Time.fixedDeltaTime;

        while(true) {
            TicksToTravelDistance++;
            CurrentVelocity = CurrentVelocity * (1 - Time.fixedDeltaTime * RigidBody2D.linearDamping);
            if(CurrentVelocity.magnitude < 0.01f)
                return null;

            DistanceTraveled += CurrentVelocity.magnitude;
            if(DistanceTraveled > Distance)
                return TicksToTravelDistance * Time.fixedDeltaTime;
        }
    }
lone shell
#

Can you give colliders custom callbacks for narrow phase detection?
I need to be able to raycast against different points inside my gameobject, but creating a bunch of child GOs is really wasteful for my application

timid dove
#

Can you describe the problem a little more?

lone shell
#

Like I have this curved road object which can have its bezier manipulated using the 4 control points, currently these are child objects
for a city builder which needs like 10k of them to exist I want to avoid needing an entire gameobject per point (both because of performance and code complexity) Ideally these 4 points are just Vector3 in my road
I will later explore ECS for performance, but wanted to stick to classical unity for now

timid dove
lone shell
#

No, my own custom vertex shader

timid dove
#

Let the physics engine handle the broad phase basically with a large crude collider for the whole road. Then you just have to do four ray-> sphere intersections to see if you hit one of the control points

lone shell
#

I guess there's no way to raycast against 'procedural' colliders?

timid dove
#

In general yes but not with Physics.Raycast

#

You can certainly write your own math as I am encouraging in my above suggestion

lone shell
#

Alright, that makes more sense anyway

timid dove
#

Interested to hear how it goes

lone shell
#

Though I also wanted my road selection to work based on the bezier curves, but 10k mesh colliders would probably be too expensive
I'd like to use AABB for broad phase, then a custom ray-bezier_road test for narrow phase, but there is no way to somehow reject box collider hits based on a custom callback?

#

So I would have to implement it myself from scratch? BVH and all?

timid dove
#

(make sure it's not rotated as well ofc)

lone shell
#

That's what I did, I'd like more accurate raycasting against the curve though, but not sure how to do that without generating a mesh for every single road

timid dove
#

And this is kinda why I mentioned the Unity spline package earlier. Because it has tools for this kind of thing already built in. Spline math can be complex.

  1. Do Plane.raycast (or sample your terrain or whatever) to find the point on the plane.
  2. Use https://docs.unity3d.com/Packages/com.unity.splines@2.7/api/UnityEngine.Splines.SplineUtility.html#UnityEngine_Splines_SplineUtility_GetNearestPoint__1___0_Unity_Mathematics_float3_Unity_Mathematics_float3__System_Single__System_Int32_System_Int32_ to find the distance to the spline
  3. if the distance is < a threshold, you can decide it's a "hit"
lone shell
#

How do I do that if I have >10k of these splines though?
I would need to manually build a BVH of roads first

#

actually, RaycastAll could give me all the box colliders so I can then manually compute the narrow phase curve intersections and pick the closest one

golden terrace
#

Like, from state 0, if we move objects by some transformation A and then apply a transformation B, we get some result in state 1. If I replay this simulation again at a later date, we get exactly the same state 1, given state 0 and the transformations A and B.

timid dove
#

If you're talking about on the same hardware, then all of the physics engines are deterministic

#

as there is no randomness in any of them

#

the main "nondeterministic" problem comes from floating point calculations across different hardware not giving precisely the same results

golden terrace
#

I would prefer different machines give the same result - that was my main concern.

timid dove
#

if you can always guarantee that it's the server that will be doing the same simulation then you have no issue.

#

as long as you only run it on the same hardware 😛

golden terrace
#

Yeah, my preference is to distribute authority and not use a server, but I was playing with the idea of rollback in a strategy game. My naive implementation was going to be lockstep, preferably with the simulation layer guarded so that I don't have to worry about different machines thinking up different results.

#

The network updates were going to be discrete and guaranteed to be applied in a certain order.

#

I was hoping to have a simulation that is robust enough to not require that positions of things need be reconciled.

#
public class Baker : Baker<UnitMovementDataAuthoring> {
    public override void Bake(UnitMovementDataAuthoring authoring) {
        Entity entity = GetEntity(TransformUsageFlags.Dynamic);
        AddComponent(entity, new UnitMovementData {
            movementStyle = authoring.movementStyle,
            moveMaxSpeed = new Fixed64(authoring.moveMaxSpeed),
            moveAcceleration = new Fixed64(authoring.moveAcceleration),
            moveStopDistance = new Fixed64(authoring.moveStopDistance),
            rotationMaxSpeed = new Fixed64(authoring.rotationMaxSpeed),
            rotationEasingThreshold = new Fixed64(authoring.rotationEasingThreshold),
        });
    }
}```

I hope this gets my intention across - basically, I am using Unity as a presentation layer as much as I can and was going to try to own the simulation in pure C# as much as possible.  The granularity that I actually need for this simulation doesn't have to be super-scientifically accurate so long as I know that the results will always be the same.  For trigonometric functions, I was going to back some lookup tables to take the worry out of getting results that differ between systems.
#

I am wondering if this is necessary now, if Unity's modern physics is deterministic in the sense that I was needing it to be.

bleak umbra
golden terrace