#⚛️┃physics

1 messages · Page 4 of 1

bleak umbra
#

there is no explicit overload with 3 args

quartz wyvern
#

yeh 😦 lame

#

ill just use float.MaxValue then

#

@bleak umbra thanks for that, i wouldn't have realised it was taking the wrong overload

potent notch
#

is there anyway i can make sure that all start() things have finished running before the first physic frame happens?

#

wait actually, if one fixed update takes too long, will another one occur without bothing for the other one to finish fully?

potent notch
potent notch
potent notch
timid dove
#

Only one piece of code runs at a time

potent notch
abstract tusk
#

this is the script

timid dove
urban rover
#

is there any overhead to enabling and disabling a collider in an object? (not attached to a rigidbody)? im mixing boxcasts with ComputePenetration, but I have to disable the collider to do a boxcast

timid crest
#

Is there a way to execute Physics.OverlapMesh? like we have for other shapes?

dapper eagle
#

I was wondering if wheel colliders expose anything that would be the torque that resists the rotation?

#

You have a torque driving the wheels and an opposite torque to resist it which i want to use to feed back into the engine

glacial zealot
#

Hi! I am working on a simple billiards-like game with checkers sliding over a board, and I noticed that there is some jittering while it's rendering the pieces. Even when I build it

#

Here, you can see that the pieces are not moving very smoothly.

#

I've tried several things which I managed to google: using "Interpolate" on the checkers' RigitBody, changing the physics timestep from 0.02 to 0.01 or 0.03

#

I think setting it to 0.01 made it even worse

#

I am also not even using Update, I just have my pieces positioned on top of the board which has a Physics material with low friction. And the I use RigidBody.ApplyForceAtPosition and watch how it moves

#

Any ideas what's going on and how can I make that pieces movement smoother? Thank you!

viral beacon
#

should joints be configured on the child to the parent or vice versa?

timid dove
#

You're thinking about the inertia tensor of the Rigidbody

dapper eagle
split elm
#

https://www.youtube.com/watch?v=37O5ysbQXjo how would one start to work on a 2d physics system like this.

The new release of King Arthur's Gold features collapsible physics. This means you can build a castle and then bring it down! This video shows how to build ladders and castles with the use of supports and then shows how the constructions fall down.

King Arthur's Gold is free multiplayer game that you can beta test right now. KAG is a 2D blend o...

▶ Play video
timid dove
#

What sucks about polygon colliders? If you want a non primitive shape you use a polygon. Another option is to use multiple primitive colliders

timid dove
#

how do you know the lag is coming from polygon colliders

#

also "lag" is a weird word to use. That usually implies networking latency

#

you're having framerate issues you mean?

#

See what happens if you build the colliders from multiple primitives instead

#

Every game is going to be a tradeoff between perfect simulation accuracy and performance

split elm
timid dove
#

you'd literally just do like:

int maxDistance = 5;
Vector2Int candidatePosition = whatever; // the position you want to place
Vector2Int checkPosition = candidatePosition;
bool canBuild = false;
for (int i = 0; i < maxDistance; i++) {
  Vector2Int checkPosition = default;
  checkPosition.y = 1;
  checkPosition.x = candidatePosition.x + i;
  if (HasStructuralTileAt(checkPosition) {
    canBuild = true;
    break;
  }
  checkPosition.x = candidatePosition.x - i;
  if (HasStructuralTileAt(checkPosition) {
    canBuild = true;
    break;
  }
}```
#

this is very cheap you can do it every time you place a block with no issues

#

it depends how big maxDistance is but as long as it's like 100 or less it will be extremely fast.

#

You'll also need to do a check to make sure you're building next to an adjacent block of course as well

split elm
timid dove
split elm
#

and this have to be checked everytime a block is broken i guess ?

#

can you link me to read up on BFS or DSF not sure what it stand for hehe ^^

timid dove
#

Breadth First Search and Depth First Search

#

they are graph traversal algorithms

#

The 2D grid is a subset of a data structure known as a graph.

ripe pivot
#

Hello, I'm trying to create my own articulated body. For that I took this as a guideline https://github.com/Unity-Technologies/articulations-robot-demo.git

Since my manipulator looks different I changed the meshes and the anchors of each element of the articulation body. When I hit play the arm moves randomly in all directions (completly crazy). I have no idea what's going on since I just changed the appearance and geometry of the arm.

GitHub

Contribute to Unity-Technologies/articulations-robot-demo development by creating an account on GitHub.

#

Has anyone faced a similar problem? Any ideas where to look (since I'm not getting compilation errors)?

ripe pivot
#

OK, I solved it. For some reason a rigidbody collider got bigger and the articulated body was basically inside the collider, which generated the messy behavior

#

Hope this mistake helps others in the future (or myself not to trip twice with the same rock).

viral beacon
#

Does anyone know what the spring constant is for the spring joint?

timid dove
viral beacon
#

I saw that but its also 10 years old so I figure there might be some new information on it

viral ginkgo
#

Thread

viral beacon
#

I figured out how to estimate the amount of error of the spring based on the physics step.

#

Progress.

jovial wraith
# viral beacon I figured out how to estimate the amount of error of the spring based on the phy...

reading through the thread PB linked, I actually think that's exactly how I'd expect a simple approximation of the spring equation to work in a simulation with discrete time steps. If you assume they're using the simplest approximation of the ODE for the object's movement (that is, they're using Euler's method https://en.wikipedia.org/wiki/Euler_method) then you'd consistently underestimate the force applied by the spring (and observe more motion than the equation would imply), and the size of the error would be proportional to the time step. Ultimately, it is a tradeoff between computational intensity and error of the method.

Here's why:
The force applied by the spring is proportional to the displacement of the object. F = kx. However, x has a different value before you take the time step and after you take the step. Euler's method assumes that F is constant through the whole time step and just picks the start value of x as the value to use to calculate F. But since F will be a little larger at the end of the time step than the beginning, every step you slightly underestimate the amount of force applied by the spring. Since the force is a bit too low, the object moves a bit too far during that step. Over all of the time steps required to get from the rest position to wherever the mass ends up with your force, you end up with the error you observe

If you want a more accurate spring simulation you could use another numerical approximation (example: https://en.wikipedia.org/wiki/Predictor–corrector_method) and do a bunch of work to get it to play nice with the rest of the physics system. Or if you just want spring behavior without any interaction with outside systems, you can solve the ODE analytically and get an explicit, exact solution that places the objects correctly.

Or you can use smaller timesteps and get less error. 🙂

I can't say for sure that this is what's going on without seeing the code, but it seems very plausible to me.

viral beacon
#

uh

#

didnt really expect a response

#

neat

jovial wraith
#

lol, good (that you have a simple solution that wokrs for you)! I think the reason it is inaccurate is because 99.999% of people using the spring joint don't care if it matches the physics equations without error

viral beacon
#

I just found that -(2*(constant force)*(the time step)^2)-tolerance = the error

#

I guess you could take out tolerance since thats more of a config thing but it helped me to remember to reset it so my calculations werent off

#

and my whole equation is based on resisting gravity so thats what fits into the constant force

#

I didnt really test changing gravity, but it seems odd that the equation would be scaled by 19.62 (exactly 9.81*2) and not have anything to do with it

jovial wraith
#

your equation seems plausible to me as the result of the issue I described

#

I haven't done the math, but it could easily look like that

viral beacon
#

I plotted points on desmos using the time step as X and the error as Y and just threw together a quadratic.

#

Reason im so fixated on springs is because im trying to make a vehicle suspension system using physics joints and I want them to be as straightforward to configure as possible.

jovial wraith
#

adding in your equation to the solver would be very similar to changing from Euler to predictor-corrector. That's the kind of thing you do to improve numerical methods.

viral beacon
#

I was looking a lot at how damping changes the rest position of a sprung object, and found that if the spring strength equals the mass*gravity then for every additional unit of strength you need to add 2.54856 of damping to restore the rest position.

#

I have no idea what causes that number to work, but it was accurate all the way up to thousands of units in difference.

#

It can be scaled proportionately to the ratio of strength to mass so it doesn't have to be perfectly at mass*gravity to work.

jovial wraith
#

nice! I love this kind of tweaking systems to figure out their rules from the outside

#

very clever!

viral beacon
#

Thanks, I just hope to find what causes that number because I would rather it be something that could be generated.

#

but who knows, maybe its just some random physX constant.

jovial wraith
#

it was something like F = springConst * x - damping * velocity, but I think there was a bit more going on in the velocity side

#

in theory you could use that equation to manually calculate the error in each timestep

#

and see if it matches up with your measurements

#

to validate if my theory is correct about what's wrong

#

and then you'd have an equation

#

but that sounds like a lot of work to me

#

😛

viral beacon
#

im more concerned with keeping the car physics from imploding when you configure it, I think the error is something like .0078478 at a time step of 0.02 so I just wanna make it easy to say where you want the sprung object to be and how strong/dampened the force keeping it there is

jovial wraith
#

yeah, then just finding the magic number based on a bunch of measurement/curve fitting is probably the easiest path

viral beacon
#

the thing about suspension springs is that they are compressed to some degree when the vehicle is resting, so Im trying to make a script where you can specify the amount of compression

#

so if you say its 50% compressed at rest then the anchor point will be 2x the distance of the rest position, but the force will keep it at half that distance at rest

#

and overall something that rests at less compression will be stiffer

jovial wraith
#

I don't know much about car suspension systems, but the spring equation assumes a perfect spring that behaves the same across all ranges of compression. So the amount of compression at rest doesn't matter. So if your looking for something that cares about where you are in the compression range it'll have to be something more sophisticated than the spring equation

viral beacon
#

unity's spring works by applying the spring strength as a force times the distance between the anchor point and spring object

#

so its actually pretty achievable

jovial wraith
#

okay, yeah, that works with the spring equation

viral beacon
#

on my first test with springs I had a bit of misconceptions since I was aiming for the anchor point to be the target position. So without that rest compression the wheels were more like door stops than springs.

#

so I needed a tremendous force to keep the wheel where I wanted it

#

but this new system will essentially let me obtain intuitive configuration and realistic behaviour

#

Im rather excited since I just recently learned about handles so I can make some neat editor visuals for the springs.

stiff sinew
#

someone please help, my ball keeps sticking to the platform. when the ball lands it just won't move

#

this is my code for moving the tilting the platform

viral beacon
stiff sinew
stark flare
#

That script is rotating the platform, not the ball. Should be fine

viral beacon
#

oh

#

nvm then lol

#

might just be friction or something.

stark flare
#

Try pausing the game and seeing what the ball's Rigidbody looks like. Does it say that it's "Asleep"? Does the ball roll off properly if you tilt the platform and then press Play?

stiff sinew
#

I don't see anything that says "Asleep" when I let the ball drop on the platform it just seems to stick to it, it only rolls if I preemptively move the platform with the script I gave it

stark flare
stiff sinew
split solar
#

Pretty particular question here.

Let's say I have one parent GameObject with a Rigidbody 2D

And two children with Polygon Colliders

And the two children are overlapped.

How do I prevent the two objects from being explosively thrown around when they're moved by a player, while still allowing this grouped object to be affected by gravity?

#

Essentially I want the object to be treated as one.

wide nebula
split solar
#

....and I'm assuming there's no other way? Because the game I'm working on has already used all Unity layers

wide nebula
#

How have you managed to use them all, that's insane

split solar
#

I'm sorta bound by NDA not to explain that

#

but uhhhhh

#

TL;DR: LittleBigPlanet-style layer system

wide nebula
#

Its fine. But no, Im not sure how you would handle it otherwise.

#

Aside from generating the polygon collider as a single one at runtime. Assuming these children are dynamically added.

split solar
#

They are.

#

Problem is, the in-game level editor uses the polygon collider as well to determine what object you click when you select something. So if two objects are grouped together like this, and there's only one polygon collider... it can't differentiate the two objects

wide nebula
#

Ah right. I'm not sure to be honest

glossy sable
split solar
#

But the grouped object still needs to collide with other objects on the same layer

#

Think gluing two materials in LittleBigPlanet together. The two materials can't throw each other around because they're attached to each other as if they're one single object. But they can collide with other objects in the level on the same layer, can still be pushed around, have gravity, etc.

glossy sable
#

IgnoreCollision doesn't care about layers so this shouldn't be a problem.
For having them act as one (somewhat), you probably also want joints if you aren't using them yet https://docs.unity3d.com/Manual/Joints2D.html
But I'm assuming you'd still want to call IgnoreCollision on these 2 even when you joint them together

split solar
#

So the only thing that worries me about IgnoreCollisions is I don't want the two grouped objects to have individual gravity

#

That is, if two squares overlap in such a way where it looks like this

+----+
|    |
|  +---+
|  |   |
+--|   |
   |   |
   +---+
#

I don't want the higher square to fall through the lower one and hit the ground

viral beacon
#

is there any way to constrain a spring to only stretch on one axis, like a slider?

glossy sable
# split solar So the only thing that worries me about IgnoreCollisions is I don't want the two...

As far as I know, this is not possible.
If you connect the two squares with a joint, this shouldn't happen unless the whole thing rotates so that the higher square is now the lower square, which is probably an effect you actually want. Maybe I'm being dumb right now, but even without a joint, as long as the objects move together (so that the higher square didn't have more time in free fall than the lower), the higher square shouldn't be able to accelerate past the lower one through gravity alone anyway, right?
You could also synchronize velocities between the 2 rigidbodies through scripting, but this will probably be a hell of edge cases until it feels somewhat right.

split solar
#

Joints worry me because the two child objects don't have rigid bodies, only the parent group does

glossy sable
split solar
#

Yes. The way this game's level editor works is

#

You can place a bunch of props, platforms, etc.

#

Each prop or platform or whatever is called a Level Object

#

Each Level Object is parented to a Physical Group

glossy sable
#

Then why would the 2 objects have individual gravity?

split solar
#

A Level Object is just a mesh renderer, mesh filter, some custom scripts, and a Polygon Collider 2D

#

a Physical Group is a Rigidbody 2D and some custom stuff

#

The game has a grouping feature where you can select two Level Objects in the scene

#

And the game takes the second Level Object and merge it into the Physical Group of the first, deleting the Physical Group of the second

#

The idea is, if you move around the first object, the second object goes with it too.

#

And this should also work in gameplay. If the player smacks a Level Object, then all the other Level Objects in that Physical Group should get affected by the slapping force

#

And they will. Because they're all grouped under the one rbody.

split solar
#

And LittleBigPlanet has this feature too

#

You can dephysicalize a Level Object

#

This is useful for creating levels with lots of decorative props in an area where the player will never reach. You can dephysicalize them to make the level run better

#

Or if you want a part of the Physical Group to have collision but another part of it not to

#

The parts with collision shouldn't fall through the parts without

#

Everything should fall as one object

#

But to be honest I'm not even sure if that's a bug in the game right now because I've not yet run into a situation where this happens

#

BUT

#

The problem I AM having

#

Is if two objects are overlapping and grouped together under the same Physical Group

#

And I use the game's Level Object Cursor to pick up and MOVE the group

#

The overlapping objects freak out as a result of their colliders overlapping, and one of them ends up being thrown way out into the distance

glossy sable
#

So have you tried Physics2D.IgnoreCollision as I suggested?

split solar
#

Haven't had the chance yet

#

I have it pinned for later

stuck bay
#

Err, what's wrong here?? I checked Freeze Rotation for X and Z, yet clearly the car rotates not only along the Y axis!
If this matters, here is how I rotate it:

if (horizontalInput != 0)
{
    rb.AddRelativeTorque(Mathf.Clamp(horizontalInput * Mathf.Abs(turnPower / transform.InverseTransformDirection(rb.angularVelocity).y), -maxTorque, maxTorque) * Vector3.up);
}
timid dove
stuck bay
stuck bay
#

how long does the force act with ForceMode.Impulse in AddForce?

#

is it Time.fixedDeltaTime

inner thistle
#

It changes the rigidbody's velocity, once

stuck bay
#

so thinking with abstract logic, its like a force acting for fixedDeltaTime.

inner thistle
#

Not really but if that fits your mental model of how it works then sure

stuck bay
#

yep got it

stuck bay
inner thistle
#

Not sure how you can come to that interpretation from that

void bronze
#

I read that when dealing with things like player collisions with the environment it's better practice to use rigidbody rather than transform. Is that true?

tender gulch
timid dove
whole dagger
#

Hey yall, i've spent some time away from unity doing other stuff and I've picked it back up to try some things. I'm having the well known jittery movement problem with rigidbodies but I haven't found a solution yet while googling a whole lot.

#

so, to cover my bases: I'm using AddForce to move the rigidbody, it is being moved in FixedUpdate, and it's moving at a constant speed. The effect occurs with both None interpolation and Interpolate. It occurs with gravity turned on or off. i wondered if it was colliding with the ground,but it also happens in the air. Based on the clip, i assume the issue is with the RB movement and not the camera, because you can see that the motion of the camera across the ground appears perfectly smooth, only the RB jitters. What can I do about this?

unique cave
whole dagger
#

I haven't tried extrapolation. What does it do?

#

The camera is being moved in Update

unique cave
whole dagger
#

ok, will I need that?

unique cave
#

I dont know, just something to try

whole dagger
#

so i've removed the camera motion enttirely and just parented the camera to the rigid body

tender gulch
whole dagger
#

here's what happens (check the border of the shadow)

#

i'm not sure where my script might be going wrong, i do have a transform.rotation in there

#

transform.Rotate(transform.up, rotation * Time.deltaTime);

tender gulch
#

Yeah, you don't want to use extrapolation. It's not really useful in most cases.

whole dagger
#

you reckon?

#

even though i'm not using the rotation in the gif

tender gulch
#

Yes. Not only position changes, but rotation can break interpolation as well.

whole dagger
#

I see

tender gulch
#

You'll need to rotate it in a physical way.

whole dagger
#

gotcha

#

so i've removed the rotation now

tender gulch
#

Did it help?

whole dagger
#

the motion is like this now:

#

i'm going to turn on the camera motion and check that too

tender gulch
#

Looks better I think?🤔

whole dagger
#

yeah, it does

#

camera next
here's the camera following:

#

oh, my interpolation was off

#

turning it back on made the camera motion smooth :)

#

thank you for the help, that was perfect

whole dagger
#

@tender gulch if you have a moment, could I please ask some more advice?

tender gulch
whole dagger
#

so the method im using to move the rb is by calculating the new velocity and then applying the difference between it and the current

#

if i'm not inputting any velocities then this shouldn't change the motion from like regular tumbling, right?

#

as it stands though im getting inconsistent motion from the object rubbing on the ground

#

i tried to set friction to zero but that didn't seem to help

#

it seems to get 'caught'

tender gulch
tender gulch
whole dagger
#

it's one big plane

#

it's not getting caught on the edges or verts, but rather

tender gulch
#

Try setting 0 friction on both the ground and the object colliders.

whole dagger
#

oh, that helps.

#

what is the threshold for physics object freezing?

#

like when you leave them alone for a long time

tender gulch
lapis latch
#

physics material friction doesn't act like actual friction does it?

#

there doesn't seem to be a terminal velocity

#

for terminal velocity it seems like I should use drag instead

vapid nexus
lapis latch
#

yeah

#

irl if you apply a constant force on an object, friction eventually evens out

vapid nexus
#

I see, I did clamp the velocity in FixedUpdate, but don't really know if it's a good idea, but could not find anything better yet (in 2D):
_rb.velocity = Vector2.ClampMagnitude(_rb.velocity, maxSpeed);

lapis latch
#

Yeah I can do something similar.

lapis latch
vapid nexus
#

I think the friction is meant as friction between 2 objects. And you can use the (linear) drag for slowing things down

lapis latch
#

you mean it is the friction force and not the friction coefficient?

#

the documentation says that it is the friction coef

vapid nexus
#

i don't know exaclty, what i saw it is, when you i.e. have one object moving over the surface of another object

lapis latch
#

ForceMode.Force is the default for AddForce right?

#

and I am assuming ForceMode.Force is just applying constant force on the rigidbody

#

if so as I apply force, the object should stop accelerating at a certain speed but it didn't even slow down on a 5000 unit track

#

am I just confused?

#

fck, of course

#

and I am a physics graduate lmao

timid dove
#

Going faster doesn't increase friction with the ground

#

Only aerodynamic drag

#

You are a physics grad, right?

lapis latch
#

yeah, now I remember

#

somehow I got confused

#

it's been a while since the last time I dealt with regular friction I guess

timid dove
#

I deal with it every day 😉

#

Walking around lol

reef tiger
#

Anyone knows Best way to handle slopes in unity 2d

timid dove
#

In what way would you like to "handle" them? What kind of game is it? What gameplay experience are you looking for?

reef tiger
timid dove
timid dove
#

there is no best way

reef tiger
# timid dove there is no best way

I am trying to make player controller but mine is not function can i show you live what's happening if possible can you help me out to fix it

timid dove
#

I've already made a suggestion

#

But I'll elaborate.
Raycast to the ground, and if it's not the expected distance away, change your position and velocity to match the ground:

  • be the appropriate distance away
  • have velocity orthogonal to the ground normal via vector projection.

You will need to track if/when you do actually jump though to disable this behavior until grounded again

ripe pivot
#

Hi, I’m trying to implement a flexible beam. Do you know if Unity allows for that sort of thing? Basically I want one end of the beam to be attached to the ground and the other end to be free. Therefore, if a force is applied to the beam (at different locations) I’d like the physics engine to emulate some bending and maybe even vibration.

unique cave
stuck bay
#

I want to make my car rotate to the side that it goes to, but I want it to rotate with some boundaries, for example -90 - 90 degrees. How can I do that?

#

My movement script

ornate bison
#

Does anyone know how I could create gravity around several central points, Sort of like planets

bleak umbra
ornate bison
#

Sweet thanks

stuck bay
stuck bay
#

Ok, nevermind I did that

mint plank
#

Hi guys, I have a question regarding the movement of an object, which has rigidbody2d attached to it

#

Currently I am moving it by assigning its transform's local position a new vector, whenever a certain button on the keyboard is pressed

#

But it seems like it's jittering spontaneously some times

#

Is this because I am trying to manually assign new position to an object with physics?

strange girder
#

So I found this cool nature asset on the unity asset store, So I got installed and made a simple scene to see what it does. I added a tree and a wind zone. At the first time I went to play mode(without a player controller, only the main camera facing the tree) it worked(The tree reacted to wind). Next I made a FPS player added the camera bla bla bla. When I went into play mode after doing this the tree's didn't react to wind. I have attached a video so you guys can understand what I mean. Please help.

mild hinge
#

I want to create a big snake of snorts that is connected by balls that are linked by joints. What type of joints should I use?

hearty crown
#

no way this is unity

timid dove
whole dagger
prime flower
#

alright..... realistically will i be able to get away with a simulation game running at 360hz physics? 😆

fallen roost
#

hi, im making a simple fps game. i have a raycast to detect objects when i shoot. for some reason it seams to detect the objects in the oppisite direction of the ray. i have a Debug.DrawRay to prove this. any ideas?

#

nvm, i fixed it

hearty crown
whole dagger
#

it's just a box ;-;

hearty crown
#

But SHADOWS ARE CASTED PERFECTLY

#

You'll find out what i mean

whole dagger
#

um

#

idk what to tell you

whole dagger
#

contrary to opinion, unity is pretty good

hearty crown
#

Lighting sucks so hard

whole dagger
#

it's just hdrp

prime flower
#

Does anyone know of any games running with a physics tick rate higher than 120hz?

fleet adder
#

It's tough to learn but super cool for this stuff

prime flower
#

But thinking more about it, Rocket League runs at 120hz and when playing online runs state rewinds.

That means Rocket League is potentially simulating like 1200hz of physics in a single tick

#

So I feel like this might be plausible

fleet adder
#

I don't think so

prime flower
#

all game state info in rocket league is in the past

#

so a state correction involves rolling back the physics state, and then re-simulating up to the current point

#

physics re-simulations are a case of simulating multiple ticks of physics in a single frame

#

So if Rocket League had to rollback 10 frames and resimulate, that would equal 1200hz would it not?

#

@fleet adder

#

Someone with 100ms latency is absolutely getting packets over 10 physics ticks in the past

fleet adder
#

I'm not 100% sure how it works
but if accurate, a sub-ms physics step is possible only in a game like rocket league, where you really dont have much going on, physics wise

prime flower
#

it's not a sub-ms step though?

#

each tick is still fixed at 120hz

#

or do you mean the idea of simulating more than one frame of physics in a single tick?

prime flower
#

right obviously the meshes are mostly primitive with 1 single mesh collider for the arena

fleet adder
#

either way
default unity physics is 50hz and it's not really expensive in most cases
I think you can easily get away with 120hz

prime flower
#

right

#

but i guess my point is that if RL can do up to 1200hz on an Xbox 360...

#

maybe we're in an era where games can be pushed further

#

and devs are just reluctant to do it because of habits/fear?

#

I'm working on a golf game which has 1 ball, 1 club, an basically 1 TerrainMesh

#

so it's not like my physics Scene is loaded with shit

fleet adder
#

oh yeah absolutely you can push stuff further
the fact that a game like factorio can exist is mind-blowing

#

and many games dont use the resources they have at their disposal

#

but then again - cant go overkill, because of older hardware

prime flower
#

I guess i was just curious, because personally I have never heard of a game tickrate above 120hz

#

and im wondering why

#

it has to exist somewhere lol

fleet adder
#

but then again, I once simulated like 100k objects colliding on my phone with a compute shader...

#

anything that can come to mind is kerbal space program

#

idk, but that'd be my guess if any game is so high

prime flower
#

yeah eventually we arrive at a point where the new common low-specs are higher than they were

#

and since my game is only gonna be PC only (being all mouse-based), maybe i can pull this off

#

I haven't had a single person have CPU problems yet

#

at 360hz

fleet adder
#

I have a i5-3570 at my main pc at the moment, and it's stupid what I can do with it
12 yo cpu and it's absolutely ripping in most stuff I throw at it basically

prime flower
#

yeah like im pretty sure an i5 would have no problem with this

#

so like...

#

maybe i need to work on finding out which CPUs struggle with my game

#

if any

fleet adder
fleet adder
prime flower
#

yah sorry i was referencing older gen i5s haha

#

linux will come eventually but i don't have a lot of experience building for it yet

fleet adder
#

send me the windows version, I'll run it with wine

prime flower
#

my project is all Unity 2022 native so should be easy to do though

fleet adder
cloud fossil
#

Am I worrying too much, that a raycast isn't "dynamic/speculative" so a moving object that's raycasted might miss another moving object?

raw glacier
whole dagger
#

hey everyone

#

i'm wondering why my RB doesn't really tumble or roll much when landing on it's end?

#

hmm maybe it's the bounce value

#

but when increasing the bounce it still doesn't really tumble:

timid dove
whole dagger
#

the collider is a mesh collider roughly following the outline of the model

timid dove
#

What physics material does it have

#

(and the floor)

whole dagger
#

the center of mass is offset towards the base of the RB (i thought COM might be the problem but seems not)

#

there aren't any constraints enabled, angular and normal drag are zero

#

the physics material has 0 0 frictions and .1 bounce

timid dove
#

Com is part of the problem. Other part is lack of friction

whole dagger
#

the floor is just the null physcs material

timid dove
#

Friction will be what would cause the rotation to happen here

#

That's the only way a torque would be applied here

#

Since there's no friction, there's no torque

whole dagger
#

is that true?

#

that doeesn't make intuitive sense

timid dove
#

It's that plus the center of mass I think

whole dagger
#

shouldn't a perpendicular force offset to the the COM cause a rotation?

timid dove
#

Wait also what about inertia tensor?

#

Did you play with that at all

timid dove
whole dagger
#

i don't know how to change the inertia tensor

#

i thought that was an internal property of physx

timid dove
whole dagger
#

what does the inertia tensor do?

#

what's the effect of modifying it

timid dove
#

It's the rotational equivalent of center of mass

whole dagger
#

why is it so high in the screenshot 🤔

timid dove
#

For example a long stick has more rotational inertia along it's long axis than its short axis

timid dove
whole dagger
#

rigidbody.centerOfMass = rigidbody.inertiaTensor = centerOfMass.localPosition;

#

it didn't change 🤔

timid dove
#

Uhh is that your existing code?

#

I wouldn't set them as the same

whole dagger
#

do i set it to zero?

timid dove
#

Trying setting inertiaTensor as Vector3.one for now

#

Or zero

#

Try them both

whole dagger
#

i didnt see it change in the info window

timid dove
#

Are you changing other things after this

#

Like mass

whole dagger
#

lets see

#

im changing the rb velocity and rotation every frame

timid dove
#

Wait

#

You're changing the rotation every frame?

whole dagger
#

oh wait

#

i just realised that

timid dove
#

Yeah that'd definitely be a problem lol

whole dagger
#

well i mean

#

my script that does that, i disabled it when i started debugging this issue, for obvious reasons

#

but that means that my change to the inertia tensor is also disabled lol

timid dove
#

Oh 😂

whole dagger
#

lemme fix that

#

well changing the IT to one caused problems

#

my rb glitched into the ground lol

timid dove
#

Oof

whole dagger
#

i guess that it must be a problem with the friction but idk what to do about that

#

it doesn't make intuitive sense to me that friction plays any role on a force that is perpendicular to the normal of the collision face

timid dove
jagged flower
#

How do I bounce off walls in 2D with the momentum of a jump like you do in Jump King?

#

I can only find tutorials on wall jumping and not many on bouncing off walls

vernal spindle
#

I have a 2d Car controller setup like this. Regarding the last formula I'd like to have a minimum and maximum "drag" so that my car breaks out with higher velocities and stays in control in lower velocities

#

How would I do that?

jagged flower
# jagged flower How do I bounce off walls in 2D with the momentum of a jump like you do in Jump ...

You can use it to bullet bounce from wall without phsycs2d .i was trying to make my character bounce from side walls. But i couldn't make it. I really look for solution 12 hours. All unity forums have questions but not answers. I solve it with Vector3.reflect. You can do it vector2 reflect function it's not that hard. I found solution here:
htt...

▶ Play video
whole dagger
#

@timid dove I think I misspoke

#

I'm not sure what it's called but this is what I mean:

prime flower
#

I know they use a custom engine and it’s probably a little more performant than PhysX but that’s really relieving to hear

prime flower
whole dagger
whole dagger
#

@prime flower @timid dove i wanna elaborate on some things

#

so basically my goal here is to do a very cartoon approximation of vehicle movement, that makes use of the rb physics in order to handle collisions

#

the movement is achieved by taking the rb velocity and position/rotation, doing some things to that vector, and then updating the rb with new velocity and angular velocity at the end of the frame

#

and this works great for the most part, my vehicle is represented as a simple box and it drives around nicely

#

but since im handling things like rolling resistance and tyre grip in the code, i want those things to not be handled by the physics

timid dove
#

That should restore your confidence the engine works

whole dagger
#

oh i don't believe it's broken

#

im just ssaying that you're probably right about the friction thing, but in that case, how should i handle things?

#

currently i have my friction at zero so that the rb will 'slide' which is like effectively the car rolling once you factor in the other stuff

timid dove
#

Have you thought about using WheelColliders?

whole dagger
#

my simple box that behaves like the car

#

i did consider it, but i wonder what would happen if the car body impacts the ground anyway, on like a bump or just compressing the springs very hard

prime flower
#

@whole dagger if you’re setting the angular velocity manually like you said, it’s your main problem

#

The car can’t rotate when it hits the ground cause it can’t increase its angular velocity to do it

whole dagger
#

i had that stuff disabled while testing this rotation thing

prime flower
#

Then I’m pretty stumped tbh

whole dagger
prime flower
#

Rocket League’s car controller is a great implementation tbh

whole dagger
#

that's unreal though is it not

prime flower
#

Talking about the concepts of how it works

whole dagger
#

i dont know how they did it

prime flower
#

All forces are applied to COM, friction is completely scripted, and wheels are just spheres that are raycasting to detect if they are grounded or not

whole dagger
#

hm

#

ok well

prime flower
#

There’s a Unity clone called RoboLeague on GitHub

whole dagger
#

oh?

#

you say the friction is completely scripted

prime flower
#

It’s incomplete but it shows how the CarController works

#

Yes

whole dagger
#

this is true in my project as well, which is why i set the physx friction to off

prime flower
#

Basically, friction is only sideways

odd crater
#

I have a script that uses .AddTorque to spin a rigidbody with key inputs (and have no angularDrag to simulate the rigidbody being in a vacumn) and now I need to make a script that will stop the object rotating, ideally using .AddTorque, to "stabilise" the object. But the catch is I need it to not stabilise an axis if their is a key input spinning it so that axis can still be spun with the stabilisation one in the other script. I'm using this code atm to just stabilise the rigidbody regardless of inputs Spaceship.AddTorque(-0.001f * GasThrusterStrength * Spaceship.angularVelocity.normalized); but can't figure out how to stop it "stabilising" an axis if it's have .AddTorque applied to it in the other script with code like this Spaceship.AddTorque(transform.right * GasThrusterStrength * 0.001f);

whole dagger
#

because i handle it in my script

prime flower
#

Because rocket league wheels don’t slip when accelerating

whole dagger
#

yeah

#

but if the friction is off and that's the cause of my issue which is what prae said tthen that presents a problem

prime flower
#

Friction should be as simple as calculating the sideways velocity of each wheel, and adding velocity in the opposite direction

whole dagger
#

im already calculating it

#

please listen

#

how about i send the game project

prime flower
#

I’m just explaining how they calculate it

whole dagger
#

right

prime flower
#

Where are you applying the friction forces?

#

Because you need to apply them at each wheel

#

If you just apply them directly at the COM they won’t rotate the car

#

They need to be applied at COM height, but directly above each wheel

#

video is timestamped

whole dagger
#

appreciate it

prime flower
whole dagger
#

here's the build of my box car consisting of a single rb and box collider

#

and here's a gif of the same

#

so i control the motion mostly through script and use an rb primarily to resolve collisions and gravity and like yknow the physics part

#

if i have to turn on the friction to get normal tumbling motion, i worry about that significantly impacting the way the vehicle moves in ways im not sure how to compensate for

#

primarily by massively increasing the 'rolling resistance' in ways that i can't easily compensate for since it's the physics system doing it after i hand off the new velocity every frame

#

@timid dove similar for wheel colliders, the springs from them is useful but i don't want the car influenced by their simulation of tyre grip if i can avoid it

prime flower
#

i feel like it would be easier for you to just post the physics code with the friction

#

But tbh i don't really think it's 100% friction related @whole dagger

#

it looks like your car was falling pretty straight down

#

and yet it still barely rotated when it hit the ground

whole dagger
#

yeah

prime flower
#

are you faking gravity?

whole dagger
#

no, it's real gravity

prime flower
#

and applying downforce to the car in the air?

#

okay

whole dagger
#

my movement code was disabled while doing that test

timid dove
#

Yeah I think it's largely to do with the center of mass and inertia tensor

#

something's fucky with those

whole dagger
#

to me what it seems like is the vehicle having an extremely high "angular momentum" i guess you would call it? but that's not a property that i have

timid dove
#

inertia tensor pretty much == angular momentum

prime flower
#

^^

timid dove
#

or "angular mass" at least

prime flower
#

inertia and momentum are tied together

whole dagger
#

yeah i though the inertia tensor gets automatically calculated though

timid dove
#

it does, except that you said you changed the center of mass

prime flower
#

have you tried it without a custom COM?

timid dove
#

so that may be messing with it

#

where is your car's custom center of mass?

whole dagger
#

it's here

#

slightly below and forward

#

i actually implemented it to try and solve this issue in the beginning

prime flower
#

i don't get that then since that's a pretty basic COM position

timid dove
#

e.g. is that COM directly under the main car body?

#

Or deeper

whole dagger
#

this is where the parent origin is

#

the heirachy is like this

#

the rb component is in the parent gameobject with the monobehaviour, and the collision mesh is attached to the prefab package that's there

timid dove
#

see if it helps any

prime flower
#

Gotta start with basically everything custom turned off and go from there

#

And narrow it down between code or physics config

#

There’s too much going on to keep guessing lol

whole dagger
#

i'll pick this up ttomorrow and let you know how itt goes

prime flower
#

Here's the basic vehicle i did yesterday 😆

odd crater
#

If I'm using something like this to spin a rigidbodySpaceship.AddTorque(transform.right * 0.001f * GasThrusterStrength);Then how should I tweak the code bellow to still allow the code above to spin the rigidbody when the code below is running to stop it spinning endlesslySpaceship.AddTorque(GasThrusterStrength * -0.001f * Spaceship.angularVelocity.normalized);

prime flower
#

@odd crater if GasThrusterStrength > 0, do your current code

#

Otherwise, find the angular velocity in that direction and just add an equal force in the opposite direction

#

That will bring it to rest in a single tick

#

Hopefully that makes sense lol

odd crater
#

Cheers

prime flower
#

If you want it to slow down over time, multiply the angular velocity force you’re adding in the other direction by a percentage

#

Force* .05f * Time.FixedDeltaTime will cause the object to lose 5% of its speed every second

odd crater
#

I restructured the code a bit so now the stabilising code looks like this```void ApplyCorrectionTorque(Rigidbody rigidbody)
{
rigidbody.AddTorque(-0.001f * GasThrusterStrength * rigidbody.angularVelocity.normalized);

    if(rigidbody.angularVelocity.sqrMagnitude < 0.002)
    {
        rigidbody.angularVelocity = Vector3.zero;
        Stabilizing = false;
    }
    
}

void FixedUpdate()
{
    if(Stabilizing)
    {
        ApplyCorrectionTorque(rigidBody);
    }
}```
#

And to spin the object instead of doing .AddTorque for each individual key for each axis, it builds a TorqueVector then applies that in one go each fixed update - made this change so if multiple gas thrusters are firing the modulus sum of their forces will always be equal as if they are all connected to the same pressure system

serene jolt
#

So I'm trying out a character controller package and he opts to normalize a vector3 by clamping its magnitude to 1f instead of just normalizing it. Is there a particular reason this would be desirable? Vector3 moveInputVector = Vector3.ClampMagnitude(new Vector3(moveData.Horizontal, 0f, moveData.Vertical), 1f);

odd crater
serene jolt
#

Sure. I thought perhaps I was missing something since I'm pretty novice with vector stuff but it must just be stylistic. Thanks.

stuck bay
#

(Not using Unity physics)

If I have an oblique collision between two circles would a smart way to get the new velocities be to rotate the velocities around the origin so the line of centres is parallel to the x axis
Then solve for the velocities and rotate them back

Currently trying this and not getting great results so I want to know if I even have the right idea before I go crazy trying to make it work

#

Here's what I have so far

public void Collision(Vec hitPoint, Shape shape2) {
        
        // hitPoint is the point where the two shapes collided
        
        // Angle between line of collision and x axis
        float theta = (float)Math.atan2(hitPoint.x - pos.x, hitPoint.y - pos.y);
        
        float m1 = mass;
        float m2 = shape2.mass;
        
        float e = Settings.coefficientOfRestitution;
        
        // Old velocities
        Vec u1 = velocity.rotate(-theta, Vec.zero());
        Vec u2 = shape2.velocity.rotate(-theta, Vec.zero());
        
        // New velocities
        Vec v1 = new Vec(0, u1.y);
        Vec v2 = new Vec(0, u2.y);
                
        // ASSUMES COLLISIONS LINE OF CENTRE IS ON X AXIS!!
        
        // Newton's Law of Restitution & Principle of Conservation of Momentum
        // (Subbed one equation into the other and solved for v1.x)
        v1.x = (m1 * u1.x + m2 * (u2.x + e * (u2.x - u1.x)))/(m1 + m2); 
        
        // Newton's Law of Restitution
        v2.x = e * (u1.x - u2.x) + v1.x;
        
        v1.rotate(theta, Vec.zero());
        v2.rotate(theta, Vec.zero());
        
        setVelocity(v1);
        shape2.setVelocity(v2);
        
        collisionsThisFrame.add(shape2);
        shape2.collisionsThisFrame.add(this);
    }```
And yeah it's java but I don't really know any servers who'd be as familiar with this stuff as you guys, let me know if there is 

I have two collisions set up: A horizontal and vertical one 
With velocities in the directions (1, 0)  + (-1, 0) and (0, 1) + (0, -1)

Theta is returning 1.57 and 0 for some reason
And even when I hardcode theta to the correct values they are going in the completely wrong direction, always seems to be 45 degrees away from the collision
timid dove
jagged flower
#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerBounce : MonoBehaviour
{

private Rigidbody2D rb;

Vector3 lastVelocity;

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

// Update is called once per frame
private void Update()
{
    lastVelocity = rb.velocity;
}

private void OnCollisionEnter2D(Collision2D coll){
    var speed = lastVelocity.magnitude;
    var direction = Vector3.Reflect(lastVelocity.normalized, coll.contacts[0].normal);

    rb.velocity = direction * Mathf.Max(speed, 2f);
}

}

#

code for the bounce

stuck bay
stuck bay
#

Thanks

summer sentinel
#

i wont be available so ping me in replies, but i just had this question.
if you can convert the speed of a moving rigidbody to kmph, can you create an object in unity that moves faster than light (more than 300K kmph / second)?

#

i dont need advice or something its just pure curiosity

inner thistle
#

yes

#

Unity doesn't simulate general relativity

#

or is it special relativity? anyways

summer sentinel
#

aight thanks for explaining

vocal steppe
#

Is there a way to have a Rigidbody use gravity but not be affect by other Rigidbodies? The caveat is that the main Rigidbody is controlled by root motion; so simply checking all the axis in Freeze Position won't work (because that won't allow root motion to work).

For example, I don't want this character to be moved by physics if they're hit by another Rigidbody during gameplay.

timid dove
vocal steppe
timid dove
#

probably better making the player kinematic and simulating gravity yourself then

vocal steppe
timid dove
vocal steppe
#

So you're thinking just manipulate the transform directly in the "gravity" code?

timid dove
#

no you wouldn't manipulate the transform directly.

#

You'd use MovePosition in FixedUpdate

#

and yes as I mentioned, simulate gravity yourself

#

it's very simple

vocal steppe
#

Ok. I forgot about the MovePosition function in a Rigidbody.

timid dove
#

if you go to about 1:05 in the first video

#

it has the behavior you want

vocal steppe
#

Got it. Thanks.

potent notch
#

is the default physics thread-safe, for stuff like adding forces?

slim olive
#

I'm making a 2d topdown game, that's going to have ice surfaces
the only way I know to make slippery controlls is to use


rb2d.AddForce(InputMove * speed * Time.fixedDeltaTime);```
on a rigid body with no linear drag
is this the right approach?
#

and if I want to switch to normal controls I would just set the rigid body's velocity directly, right?

whole dagger
#

@timid dove @prime flower i'm investigate this issue again
here's what i figured out:

  • friction coefficient has no effect on the problem
  • a default cube and RB behaves normally
  • a box collider on the car instead of a mesh collider doesn't effect it.
  • the inertia tensor in the default cube is like .8 magnitude but on the car it's like 2500 for some reason, this is the automatically calculated one
#

ok it seems to be caused by me using continuous collision detection on the RBs.

#

this is a problem because if i don't use continuous, the RBs will penetrate the ground if the velocity is high enough

#

so with discrete checking, a drop from a height that i showed in my GIF causes the car to penetrate the ground

#

ok so here's my updated question:

#

this is collision using the continuous collision mode:

#

this is collision using the discrete mode (desirable behaviour):

#

oh, shit. I'm not sure what i changed but i can't reproduce the issues with penetration i was having earlier

whole dagger
#

ok, so does unity have any current packages that provide deterministic physics ?

whole dagger
#

I heard that the DOTS one is not deterministic cross-platform

arctic flare
whole dagger
#

i've been trying to integrate this one

#

i had success with the cloned repo from it, but what would be really fantastic is if i could get it running in more recent versions of unity such as 2021, because i want to also use HDRP.

#

atm i'm getting compile errors in this package com.unity.serialization, maybe this package needs to be updated but i can't find it anywhere to do that

arctic flare
whole dagger
#

this package doesn't seem to appear

arctic flare
whole dagger
#

yes

arctic flare
whole dagger
#

well uhm

#

forgive me but would that not simply install an additional package

#

so then i'd have two

#

like these errors are necessarily coming from files that are already installed in the project somewhere

#

so it's like installed but not in the manager

#

oh, maybe it's actually a part of Collections.

#

However, Collections is already up to date.

whole dagger
#

where's it's repository?

arctic flare
whole dagger
#

oh, i'll try that.

arctic flare
potent notch
#

is it thread safe to add forces?

whole dagger
#

@arctic flare ok so it seems like i might be able to get the project into a working state with a lot of work, following guides like this:

#

but i've decided that i won't make this change at this stage, and I'll wait for the author of the package to update it themselves.

timid dove
#

almost nothing in the unity API is thread safe

jade crescent
#

Could someone help me understand something about RigidBodies in Unity?
I'm making game with time rewind as one of it's key features and because not every object is beeing rewinded the same way, I decided to split every rewindable aspect to different components (TransformRewinder, AnimationRewinder, RigidBodyRewinder etc.). In the case of the last one mentioned, logic sugested to me that I dont need to rewind RigidBodies velocity each frame, intead I can only apply velocity AFTER rewinding time is complete to a value from that point in time, but somehow flying object does not fallow its previous trajectory after its been rewinded. However when I changed it to set velocity from corresponding point in time each frame while rewinding, despite all rigid bodies beeing set to Kinematic for the time they are beeing rewinded, everything worked fine.
Why?
I feel like im missing something in my understanding of how RigidBody work in Unity.

timid dove
jade crescent
#

code-wise?

timid dove
#

sure yeah

jade crescent
#

sure, give me a moment

#
LinkedList<dataABoutRigidBody> storedPointsInTime;
void HandleRewindeChange(){
  if(RewindisBeeingSetToTrueThisFrame){
    rigidbody.isKinematic=true;
  }else{
    rigidbody.velocity = storedPointsInTime.Last.Value.velocity;
    rigidbody.isKinematic=false;
  }
}
IEnumerator Cycle(){
  while(true){
  if(isRewinding){
    storedPointsInTime.RemoveLast();
  }
  else{
    storedPointsInTime.AddLast(dataAboutRigidBody);
  }
  yield return null;
  }
}
#

simplified ofc

#

but you'll understand

#

basicly there is constantly running corutine that saves data or removes data depending on some state of game (code "isRewinding")

#

and some method that replies to event of this state beeing changed

timid dove
jade crescent
#

sry my bad, in an actual code order is opposite

#

however i dont think it would make much difference if I made that mistake, after all Physics will be calculated after whole frame is done and velocity and isKinematic are beeing set the same frame

#

Any ways I changed it to work like that:

LinkedList<dataABoutRigidBody> storedPointsInTime;
void HandleRewindeChange(){
  if(RewindisBeeingSetToTrueThisFrame){
    rigidbody.isKinematic=true;
  }else{
    rigidbody.isKinematic=false;
  }
}
IEnumerator Cycle(){
  while(true){
  if(isRewinding){
    rigidbody.velocity = storedPointsInTime.Last.Value.velocity;
    storedPointsInTime.RemoveLast();
  }
  else{
    storedPointsInTime.AddLast(dataAboutRigidBody);
  }
  yield return null;
  }
}
#

and now its fine

#

if it makes any difference here is an actual code:

timid dove
jade crescent
#

Also: actually its not "each frame", data is beeing saved over some fixed period of time and then beeing interpolated for optymalization reasons, but it's deffinitely not reason for what is happening, this makes only a small margin of error

timid dove
#

First,
Your reliance on WaitForSeconds is going to add a lot of error into the timing. WaitForSeconds is not accurate. The way it actually works is to wait for the first frame that occurs after that many seconds passed So the error for every wait is up to the duration of a full frame. This is going to matter a lot for a system like this

Second,
While rewinding you are still simulating physics. This is going to have all kinds of effects like triggering collisions, changing your velocities etcs out from under you. You should probably disable the physics simulation during rewind (Physics.autoSimulation = false)

#

now I'm not totally sure if and how either of these contributes directly to the problem you described but they seem important in a system like this.

#

also the if (!IsRewinding.Value) if block seems to me like it could never possibly run, right? Since it's inside an if (IsRewinding.value)

jade crescent
#

but how does Physics affect this object that is beeing rewinded if its Kinematic for this duration?

jade crescent
timid dove
#

Third - For a system this heavily involved in the physics engine, you should probably largely be using WaitForFixedUpdate to keep everything synced with the physics update

#

since that's when Rigidbodies will actually move

#

That's just my 0.02 on all this.

#

Not sure what's going on with what you said other than there is probably some weirdness with the object being kinematic

#

I'm not sure if setting velocity while it's kinematic is going to actually do anything

#

and if that will persist to when it's no longer kinematic

jade crescent
#

and im aware of this margin of error coused by WaitForSeconds, but my game can store only up to 10 seconds back in time, so I cant imagine this error propagading to such degree that object after beeing rewinded have its velocity from 1 or 2 seconds into future

timid dove
#

no, that's not the cause of that issue, I agree

jade crescent
#

btw. you can see that im trying to mitigate this small error in upper part of this loop by not reseting interpolationTime to 0

#

actyally ive been thinking about making it more around FixedUpdates or so, but there is not many RigidBodies in my scenes, most of the job is rewinding animations, position and AIs

timid dove
slim olive
#

I'm trying to make "slippery controls"
currently I'm using rigidbody2d.addforce(direction * force) on a rigidbody2d that has small amount of linear drag
in fixed update
is there a better way? will this cause any problems?

verbal wing
#

Quick performance question! Mesh colliders can be more expensive than primitive colliders for physics calculations, this I understand. But if collider is static and will not be doing any physics whatsoever, does it still have a performance cost?

I need super accurate colliders for some editor scripts, but that's about it. It's easier to leave them attached to the object than remove all of them before building, but I'm unsure if there is a performance cost there.

stuck bay
#

yes, and the way i do complex meshes is avoid using mesh collider, and usually use a bunch of sphere or box colliders, just disable them if your not using them. This is better then adding and removing them at runtime.

verbal wing
#

If there is, I guess I'll just write another script to disable them all

stuck bay
#

well a common way to do what you want is to use layers and then you just change your collision mask on your detector. also try doing an A B compare with profiler hooked up and look at memory, GC, and refresh speed is compared to your implementations

mighty apex
#

I have question.
I have applied force on an object. It doesnt move for a single frame for the first time but it never happens again.

Context: I am making a racing game. As soon as the Race starts, Input are applied on vehicle as force and torque in fixed update. I also record the state per fixedUpdate

#

As you can see below:

#

I have an additional recorded frame which is messing up my timings by 0.001s

#

this only happens once when a scene is loaded

#

Bottom view shows the states after I do a soft reset of my vehicle and restart the race

#

note no extra frame

mighty apex
#

nvm I solved it

#

inb4 someone says how?

#

When a race completes I deactivate my vehicle when a replay is played

#

restarting the race activates its again

#

this reactivation was not happening at the first start

#

I did a deactivate and activate before the first race. and the additional frame disappeared

#

now I get exact same timing per race

sonic blaze
weary burrow
#

Hey guys, I made my rigidbody character controller but feels like unity's default CharacterControler.cs will always move smoother no metter what I do. I made sure that my rigidbody is interpolate and that my camera is in LateUpdate. Do you guys have any idea?

rotund lagoon
#

Is there some way to do Physics.OverlapBox for a rectangle? I'm trying to check a Bounds box for overlaps

timid dove
#

or what

#

OverlapBox is a rectangular prism

old tundra
#

How come I'm getting these errors?

Script:

    void FixedUpdate()
    {
        foreach (Wheels w in wheels)
        {
            if(w.wheelRearLeft)
            {
                if (Physics.Raycast(transform.position, -transform.up, out w.hit, w.maxLength + w.wheelRadius, groundedMask))
                {
                    travelL = (-wheelRearL.transform.InverseTransformPoint(w.hit.point).y - w.wheelRadius) / w.springLength;
                }
            }

            if(w.wheelRearRight)
            {
                if (Physics.Raycast(transform.position, -transform.up, out w.hit, w.maxLength + w.wheelRadius, groundedMask))
                {
                    travelR = (-wheelRearR.transform.InverseTransformPoint(w.hit.point).y - w.wheelRadius) / w.springLength;
                }
            }

            antiRollForce = (travelL - travelR) * AntiRoll;

            if(w.wheelRearLeft)
            {
                rb.AddForceAtPosition(wheelRearL.transform.up * -antiRollForce, wheelRearL.transform.position);
            }

            if(w.wheelRearRight)
            {
                rb.AddForceAtPosition(wheelRearR.transform.up * -antiRollForce, wheelRearR.transform.position);
            }
        }
    }
timid dove
#

you're trying to add a force that has a value of infinity

#

good chance you're doing a divide by zero or something along those lines

#

perhaps here?
travelL = (-wheelRearL.transform.InverseTransformPoint(w.hit.point).y - w.wheelRadius) / w.springLength;

old tundra
timid dove
#

Don't divide by zero 😊

old tundra
robust pilot
high cloak
#

Are there any alternatives for getting a non-convex mesh collider working with a rigidbody?

unique cave
jagged brook
#

Question on best way to tackle this functionality?
I have a co-op local multiplayer game where players fight enemies, and one of their movement abilities is a dash. When players are dashing, I want them to be able to pass through enemies, but not environmental objects (trees, rocks, etc.). I've tried a couple approaches, and none of them seem to quite hit the mark

  1. Use Physics.IgnoreLayerCollision, placing players in a Player layer and enemies in an Enemy layer, then briefly ignoring collisions between the two layers during the players' dash and un-ignoring afterwards. The problem with this is that this disables the collision between the two layers entirely, meaning other players can phase through enemies when any player is dashing
  2. rigidbody.enabled = false while the player is dashing. This already seemed sketchy to me to begin with as I thought it may bring unintended weird behaviour down the line if I ended up going with it, but it didn't work anyways cause it allows players to phase through everything, not just enemies
  3. Physics.IgnoreCollision seems to almost be it, but I want the player to ignore collision between their own colliders and all colliders in the Enemy layer (it seems I want a hybrid between IgnoreLayerCollision and IgnoreCollision?)
  4. Technically, I could go with 1) and make 4 layers, giving each player their own layer to work with, but that just seems like a poor, inflexible solution

Any ideas? Thanks in advance!

hollow echo
#

You don't need a layer for each player, they just need to not collide when dashing, no?

jagged brook
#

Ah, that sounds pretty elegant, I didn't even think about switching layers on the fly haha 😅, are there any downsides to that?

hollow echo
#

Nope, should work as expected.

jagged brook
#

Sounds perfect, thanks for the solution and quick reply!

storm badger
#

Mornin! Quick question about mass/force.

On my Rigidbody, if I wanna add a jump force, is there a simple way to set the force to 1, no matter the mass?

My character has a mass of 75 (75kg), I'm using a leveling system where jump skill is involved.

Is there a way to ignore the character mass, and only use the jump skill to calculate the jump-height?

#

2nd question: I'm using .velocity on my RB to create movement, I'm using my camera "forward" to decide where my character should move (left is always left, etc).

But this also puts my velocity.y to -0.1962 for some reason, does anyone know a solution for this?

#

[[]]``` void FixedUpdate()
{
// Movement
Vector2 movement = playerControls.Land.Move.ReadValue<Vector2>();
Vector3 moveOld = new Vector3(movement.x, 0, movement.y);
Vector3 moveNew = mainCamera.forward * moveOld.z + mainCamera.right * moveOld.x;
moveNew.y = 0f;
moveNew = moveNew.normalized;

    if (playerRunning)
    {
        // Player running
        // controller.Move(moveNew * Time.deltaTime * playerStats.runSpeed);
        playerRb.velocity = moveNew * playerStats.runSpeed;
    }
    else
    {
        // Player walking
        //controller.Move(moveNew * Time.deltaTime * playerStats.walkSpeed);
        Debug.Log(moveNew);
        playerRb.velocity = moveNew * playerStats.walkSpeed;
    }

    // Rotate player
    if (playerOffhanding)
    {
        // Rotate player towards offhanding

        transform.eulerAngles = new Vector3(0, mainCamera.eulerAngles.y, 0);
    }
    else if (playerMoving)
    {

        // Make character rotate direction going
        transform.rotation = Quaternion.LookRotation(moveNew);
        
    }
} ```
timid dove
storm badger
#

Re-wrote my move-part

unique cave
#

Any ideas why these ghost collisions happens when adding rotation to those apples using rb.angularVelocity? I remove the apples and Instantiate that particle effect when OnCollisionEnter occurs (for the apple script). Theres no any colliders besides the one box collider on the bucket (apples can't collider together because of layer collision matrix). I don't control the apples fall in any way, I only add the angularVelocity once when instantiating the apple (it moves down that slowly because I made the drag very large for debugging purposes). The apples sphere collider follows the visual shape very accurately

tardy spear
#

in such cases I advise to turn on the physics debugger view, it is capable of showing you the actual collision geometry in your project

#

Windows -> Analytics -> Physics Debugger

unique cave
#

btw, by debugging some stuff the Collision class returns, I can confirm that this light blue box collider of the bucket is the collider that all the apples are "colliding" with (also the ones that disappears very high on the sky)

unique cave
#

In this case I could just rotate the apples using transform.Rotate every frame but I just want to know whether this is a bug (which it seems a lot) or some physx "feature" that Im not aware of

brazen vine
#

having issues with collisions, i've got the following objects:

  • Player (On "Default" layer, has Rigidbody2D set to Kinematic, character controller on it)

    • Pushboxes (Empty parent object)
      • Box (On "Environment" layer, has BoxCollider2D on it)
  • Environment

    • Colliders (Empty parent object)
      • Box (On "Environment" layer, has BoxCollider2D on it, set to static)

Issue right now is if I try to move my character, the player object is able to pass through the environment collider. Any ideas as to why?

timid dove
#

How does your movement script work? By "character controller" I hope you mean your own custom script not Unity's CharacterController

brazen vine
#

custom script, it just changes transform.position right now

#

what would be an approach that could support this then?

bleak umbra
timid dove
brazen vine
#

gotcha, thanks.

gleaming gorge
#

Is it me or OnCollisionExit is just unreliable? It sometime doesn't get called when the object is losing contact to the ground

    void OnCollisionStay(Collision collision)
    {
        Vector3 normal = Vector3.up;
        normal = collision.contacts[0].normal;
        Vector3 forward = transform.forward - normal * Vector3.Dot (transform.forward, normal);
        transform.rotation = Quaternion.LookRotation(forward, normal);// * transform.rotation;
        isGrounded = true;
        OnGrounded?.Invoke(true);
    }

    void OnCollisionExit(Collision collision)
    {
        isGrounded = false;
        OnGrounded?.Invoke(false);
    }

I even tried to make the OnCollisionExit calls a coroutine which reset the isGrounded, just in case that the OnCollisionStay is called (for some reason) after the object is leaving the ground

timid dove
#

btw if you want the contact normal it's a bit more efficient to use collision.GetContact(0) rather than collision.contacts[0]

gleaming gorge
#

🤔 Now that you've mentioned it, I'm moving and modifying the ground mesh when the player is moving to a certain threshold, could it also considered as deactivated?

gleaming gorge
timid dove
#

changing the mesh for a MeshCollider is probably in that list of weird shit that causes it not to work

gleaming gorge
#

I guess I should just use the ol' reliable raycast for checking the ground then, thanks mate 🙂

timid dove
stuck bay
#

how do u do blender mesh collider bc i dont like the unity mesh collider.

unique cave
molten topaz
#

how can i optimize physic for mobile?

#

do mesh colliders kill performance?

bleak umbra
molten topaz
#

like trees

#

i am not using nav mesh

#

simply is it a performance killer?

bleak umbra
molten topaz
#

so, use box, capsule, sphere colliders instead of mesh collider , is that what u mean?>\

molten topaz
#

bump

torn stream
#

Did anyone here try out that physics character controller in the store bundle? Mine seems to be pretty borked. Animations are too fast, all the textures are broken, and the camera is in their chest in first person mode

unique cave
molten topaz
#

thanks..

unique cave
# molten topaz thanks..

But the ones that do does impact the performance, if the meshes are low poly, that shouldnt be a problem

chilly karma
timid dove
atomic ledge
#

on god

jovial depot
#

Hi 🙂 Im trying to jump with my car (yeah, an F1 car like a rally xD car), everything is ok but when the car leaves the ramp, the suspension INSTANTLY expands, already tried the wheel.suspensionExpansionLimited = true; but the behaviour is the same. Any ideas? Thank you 🙂

#

I expect a smoother expansion when the car is in the air/falling

tender gulch
jovial depot
#

oh, I thought I did something wrong ahaha but I observed the same behaviour in some youtube tutorials

#

thanks @tender gulch, I will try that! 🙂

latent drift
#

how do i make something like a wagon where when i drag it the wheels move?

timid dove
#

If you follow the Unity roll a ball tutorial they do a fake rolling with a ball. You can probably carry that technique over to a wheel

potent notch
#

wondering if i could fake 2 way collision, by detecting a collision, then adding an impulse at that position to both objects, or are there better ways to fake 2 way collision?

potent notch
# timid dove why do you need to fake it?

im using nvidia flex, and for large rigidbodies it is much more worthwhile to use unity's built in support for physx 4, so to get the 2 to interact i have to fake it somehow

#

nvidia flex does have primitive collision atleast, that isnt made of particles, so by just constantly moving these primitive collision types around i can get rigidbodies to interact with flex, but trying to get the rigidbodies to be affected by the particles hitting them seems to be harder

#

(sorry for using microsoft paint...) in this terrible diagram, blue represents flex particles, red represents the physx 4 rigidbody, and green represents the collision position, then im wondering could i use the add force at position function to perhaps fake a 2 way interaction?

timid dove
#

I mean sure, why not

#

could even use AddForceAtPosition

potent notch
#

ok, good, thanks a ton!

potent notch
#

any inbuilt way of getting inverse mass, or should i just do 1/mass?

unique cave
potent notch
ripe meadow
#

Hey, I'm not sure if this should be posted in physics or ai, but I have a simulation where 2 robots battle eachother. They have three different modes: hunting, food and melee. In meleeMode the 2 robots will get closer to eachother and the navmeshAgent will be turned off and addRelativeForce is used, but the robot keeps bouncing after the addRelativeForce even though it's just using vector3.back

potent notch
#

wondering if anyone has run any performance tests with amd gpus on nvidia flex, or nvidia flow? Trying to compare the performance to nvidia cards, and see if there are any major differences in flex peformance and simulation quality!

mental yew
#

i'm trying to set up a ragdoll, but for some reason the character's stomach gets pinned into the air where he spawns. can anyone help me?

warm flicker
#

I'm getting an error that I have never seen before when trying to implement a black-hole style pull for enemies in our fps

#

the objects calling this only have box colliders and rigidbodies, so I'm not sure what the issue is

timid dove
#

Setting scale or size to zero or NaN or Infinity will do this

vagrant cloak
#

Negative scale also produces warnings, but I think it works anyways

warm flicker
timid dove
#

simply moving things won't cause this

dusk oasis
#

question:

Working on a 2d game and I want to implement a mechanic like path of exiles "projectiles return".

That is, at the apex of a projectiles life (half its duration), it changes course so that it now returns to its origin (assume it hasn't moved, else it attempts to follow it)

My fixed update is something like this, where target position is a normalized vector of the original target.

What would I need to do to make it so the projectiles return to the thing that fired them?

#

I tried something like this but... things got weird

Where origin here is the initial transform position but normalized

wraith junco
#

Question for someone who has made wheel colliders:

Is physics.ignorecollision the secret recipe for allowing tires to collide with other cars and other cars' tires?

#

while still behaving and not colliding into the car body it's connected to?

#

assuming we're sweeptesting

upbeat birch
#

The only way to estimate a surface of a given area in Unity is with a array of raycasts, right? Because Boxcast and other casts return just the first contact point per collider.

#

I need to estimate a size and a slope of the surface whether I can fit an object on it or not.

grave igloo
#

Why is the OnTriggerEnter function not being called. I have two 2D objects, both with CapsuleCollider2D. One isTrigger is kept true. Both have rigidBody2D and are kinematic

#

I have assgined OnTriggerEnter function script in one of them and just for demo Debug.log but it's not showing up

inner thistle
#

Because OnTriggerEnter is for 3D physics. Try OnTriggerEnter2D

white spire
#

how can i get the overlap area between two trigger box colliders in unity2d

viral beacon
#

does anyone know how to convert a rotation into a joint "axis" so it matches? I was able to do it on one rotational axis but not two.

gloomy stirrup
#

Hello, I am trying to create a 3D reinforcement learning ai that should learns to walk. I was wondering the best way of getting something to walk based on leg movement (as in as the legs move they stay in place and move the body)?

upbeat birch
#

Most if not all controllers represent a character as a capsule with a single ray or a rigidbody to check ground.

gloomy stirrup
#

I have a 3D model with joints connecting its limbs (broadly in the shape of a dog) it can control the rotation of each joint but I was wondering how to get the legs movement to get it to walk (ie the legs push it forward) it is a reinforcement learning model so root motion wouldn’t work

west mountain
#

I have a question (i'm a begginer btw) I'm working in this simple xr project of a little house and I can't figure out how to not clip through walls or if so, not move them. Thanks. Sorry for low fps forgot to set it to 60.

bleak fiber
#

Can someone help me

#

I can’t move the character

#

Please help

#

Never mind

tender grove
#

is there a way to slowly lower the downwards velocity of something until its 0

#

but have the same line of code not lower the upwards velocity

tender grove
#

nvm

leaden gazelle
#

Can anyone help me with something

#

I use Crest Ocean which goes through Terrains

#

What should i do?

inner thistle
#

Crest has their own Discord server. You'll probably have better luck getting help there.

bleak umbra
leaden gazelle
leaden gazelle
gloomy stirrup
#

I have a model of a creature (call it a dog) that I can change the rotation of each of its joints. How can I make it so that as its feet move the actual dog moves too instead of just the feet. I wish to have it learn (using a reinforcement learning algorithm) how to change these joint values so I do not think that an animation would work.

upbeat birch
#

Oh, you mean that you need to move the game object along with the motion of joints? I guess you need a rigidbody for that and calculate impulses.

white spire
bleak umbra
# white spire anyone have an idea about this?

assuming the rectangles are all axis aligned relative to each other

        /// <summary>
        /// The <see cref="Rect"/> containing both vectors.
        /// </summary>
        public static Rect BoundingBox(Vector2 a, Vector2 b)
        {
            Vector2 min = Vector2.Min(a, b);
            Vector2 max = Vector2.Min(a, b);
            return Rect.MinMaxRect(min.x, min.y, max.x, max.y);
        }

        /// <summary>
        /// Determines the <see cref="Rect"/> that represents the intersection of two rectangles.
        /// </summary>
        public static Rect Intersect(this Rect a, Rect b)
        {
            Vector2 min = Vector2.Min(a.max, b.max);
            Vector2 max = Vector2.Max(a.min, b.min);
            return BoundingBox(min, max);
        }
white spire
light sedge
#

do spring joints take priority over colliders? i coded a simple grapple/swing for 2d but my player just ignores all collision when swinging. im a beginner so sorry if stupid question

viral beacon
#

does anyone know of an easy way to manage the rotational freedom of the connected body in a joint?

#

Ive been doing a lot of tests and I would prefer to not have to add another joint onto the connected body of my current joint to get the effect I seek.

timid dove
light sedge
viral beacon
#

is it possible to keep a cylinder mesh in contact with the ground while it spins at a high rate?

acoustic bluff
#

hello everyone, i’m trying to simulate macpherson strut, which is a type of suspension for a car. the system consists of the wheel being attached with 2 lower hinge joints (lower control arms) and one upper spring joint (the shock absorber). i’ve managed to implement this system, however the wheel tends to sit slightly inwards/outwards, however i want the wheels to be completely straight (no camber in other words) i can’t just freeze the x / z axes of the wheels to fix this, so what else could i do to keep the wheels upright?

#

i can provide pictures of my current system if necessary. thanks

#

i’ve also considered adding other joints, however this would change the type of system and i would prefer to keep the type of suspension the same.

acoustic bluff
viral beacon
acoustic bluff
upbeat birch
gloomy stirrup
#

But anyways thanks I will look into the rigidbody impulses solution.

bleak fiber
#

Hey y’all guess who’s back

#

I keep getting this error message and it won’t let me play

bleak umbra
bleak fiber
#

Yes?

bleak umbra
#

Ever heard of copy & paste?

bleak fiber
#

Wdym

onyx timber
#

hello. im tyring to set up my player so that it has a character controller which i am using just for ground collision. so the parent layer has a character controller. then all children which are body parts have box colliders on them. these children are set to one layer and the parent to another. in the collision matrix ive set the layer "player"(character controller layer) to collide with "ground" layer set objects, and to not collide with "obstacle" layer set objects, and for the layer "player2"(this is the layer the children are set to) to collide with "obstacle" layer set objects, and to not collide with "ground" layer set objects. the character controller works when colliding with ground. but the box colliders on the children don't collide with a box collider ive set up on a cube with the layer set to obstacle. is this normal? can i get it to work?

wide nebula
#

You need a rigidbody to have the physics detect collisions between colliders. However, the CC isn't compatible with a rigidbody since they're two different things.

#

You can probably get away with some combination where a child rigidbody is used with trigger colliders, but having solid colliders to prevent movement against obstacles while simultaneously using the CC is going to be weird.

onyx timber
onyx timber
errant orchid
#

do you also need a rigidbody for raycasting?

wide nebula
errant orchid
#

could i move my question in here?

#

i cant make this work with raycasting

onyx timber
# errant orchid

not sure if this is correct but ive found mesh colliders dont work very well.

errant orchid
#

im just trying everything

#

when i check my physics/collision world there are 0 bodies

onyx timber
#

do u need individual tiles or can you just paint terrain ?

hollow echo
#

You're unlikely to get help here specific to it

onyx timber
#

does anyone know why adding a rigidbody to my player stops my root motion from working

errant orchid
#

the package is com.unity.physics

#

that's where the documentation snippet came from

onyx timber
#

but ive tried both

bleak umbra
#

a kinematic one doesn't conflict with your rootmotion, a non-kinematic one does

onyx timber
errant orchid
#

is it ok to post a screen shot instead of a code snippet @hollow echo

hollow echo
errant orchid
#

look at the red box

#

it belongs here

hollow echo
#

Well, you're using ECS, so you're going to continue to not get an answer

errant orchid
#

ok

onyx timber
errant orchid
#

i did

#

it just went unanswered

#

i deleted then posted it here so i wouldnt double post

bleak umbra
errant orchid
#

its like the most basic of all questions

#

its against the rules

#

to double post

bleak umbra
#

the point is, nobody knows, and thats why you dont get an answer

#

no amount of advertising your question will help

errant orchid
#

im waiting 24 hours between posts

#

you cancheck my history

hollow echo
#

My only point is that if you post ECS questions outside of #archived-dots nobody will know what you're talking about, and everyone will think you're talking about non-ECS worlds

#

If you're not getting an answer in #archived-dots , just repost the question/reply to it with more context

errant orchid
#

you can answer in a non ecs way

hollow echo
#

There is no non-ECS answer to your problem.

errant orchid
#

forget the ecs pacakge

#

i am literally trying to do a single raycast

#

i do not know what i need to attach to my prefab

#

to accomplish that

#

with any system

hollow echo
#

Have you actually tried without ECS? Because it's simple, just have any collider, and perform the cast

errant orchid
#

im trying with the 3rd person controller

#

the starter asset

hollow echo
#

I have no idea what that has to do with it

onyx timber
#

have u tried adding a child to the third person controller and casting from that. position it at the feet if ur trying to raycast to ground or something

#

unpack the prefab if u want to edit it

#

@hollow echo whats the rules regarding posting vids to show ur problems?

hollow echo
#

You can post anything you want within reason

onyx timber
#

is it best to do it through youtube or something?

#

so its a link and not a upload

#

@hollow echo

hollow echo
#

It doesn't matter

onyx timber
hollow echo
#

It's not relevant outside of the short time it was running.

onyx timber
#

can i use root motion with a rigidbody or do i have to script the movement?

upbeat birch
upbeat birch
errant orchid
#

i found my answer, thank you

unique cave
# unique cave Any ideas why these ghost collisions happens when adding rotation to those apple...

This only seems to happen when using Continuous Speculative Collision Detection mode which makes sense as it is the only one that takes the rotation into account. Still I'm confused whether this is desired behaviour or bug of some sort. It seems the impulse of the collision is always Vector3.zero for those ghost collisions but I can't really use that information to easily ignore those as OnCollisionEnter will not be called again when the actual collision happens because the engine thinks that the collision never ends between the first ghost collision and the actual collision. I could just use some other Collision Detection mode in this case but this still disturbs me... @tardy spear

onyx timber
#

@upbeat birch hi thanks for your response. is there specific settings needed as when i add a rigidbody to my player its like hes glued to one spot and when i stop the run anim he kinda falls forward. < kinematic not checked

upbeat birch
west mountain
#

Hi, i'm a begginer creating a very simple project and i don't know how to stop it from walking through the wall

upbeat birch
#

I think Unity requires a rigidbody on one of the objects for most type of collision events.

west mountain
#

and should i add it to the wall or to the xr rig?

upbeat birch
sudden flame
#

Hi. Does anyone know how can I rotate a gameobject towards like the direction of its velocity but with angular forces please?

upbeat birch
sudden flame
#

torque I meant, sorry😅

#

and yes, I guess I can know the velocity of the direction

#

okay I think I'm kinda figuring it out, but I'm just trying until I get to something, which is probably not the best way😅 If anyone knows a way please let me know

upbeat birch
gloomy stirrup
#

But thanks nonetheless

woven spire
#

How do you work with fast and small projectiles? I have bullets, that are fairly small, but since they move pretty fast they go through walls. I already tried continuous detection. I can't make the bullet go slower since it's not a proper solution, neither making the colliders bigger

timid dove
rare pike
#

My rigidbody is jittering when MovePosition, any ideas why this can be happening?

unique cave
unique cave
woven spire
#

@timid dove @unique cave Sorry forgot to update. The problem was that the bullet had the collider as trigger, and that ignores the physics..

unique cave
woven spire
#

Didn't know that, thanks for the info! n.n

rare pike
unique cave
rare pike
long fossil
#

Hello, I am trying to figure out how to get this working.

So basically the concept is the blue circle is an object which moves at high velocity to the left

The green block is the player

The red square are walls and stuff

I want it so that the blue object collides with the player and pushes it to the wall, which is easy using normal collision and rigidbody

What I want is for it to die when it gets crushed between the wall and the block

I dont want it to just die when it comes into contact with the blue ball but get crushed, cant figure out how to get it done

split solar
#

When does CompositeCollider2D generate its geometry?

I'm creating a bunch of colliders at runtime as children of a GameObject with a CompositeCollider2D that's also created at runtime.

The composite collider is created first.

The collider is falling through the world...

timid dove
#

It happens at edit time normally but obviously in your case that doesn't apply...

split solar
#

Well I'm calling it manually, buuuuuut my object's still falling through the world

timid dove
split solar
#

It'll be complicated but I can try

#

It's complicated because I actually have three composite colliders

#

basically the way it works is we have

Physical Group

  • Level Object
    • Mesh
    • Rear Layer Colliders
    • Main Layer Colliders
      • polygon collider here
      • polygon collider here
    • Front Layer Colliders
#

Physical Group has a RigidBody2D

#

LevelObject is essentially just a container

#

Mesh is the visual object

#

The three "Colliders" objects (Rear, Main and Front) are the composite colliders

#

Each are on a different Unity physics layer

#

Main Colliders is on the same physics layer as the PhysicalGroup itself

#

This is the generated Composite Collider 2D for the Main Layer

#

This is one of the child poly colliders

#

And finally the PhysicalGroup rigidbody

#

@timid dove

#

Wait what the

#

It's internally creating its own Rigidbody2D

unique cave
rare pike
# unique cave Eh, maybe that could be possible but id like to see the code that converts the m...

Had problem with the model axis before(so my Vector3 might be coupled the wrong way), axis is fixed now(Z fwd) and the ray for touchdirection looks correct when debug.drawray. Ignore MoveAndRotatePlayer(). In Dragging() tried to limit delta change based on magnitude(so it won't jitter for minor drags) but that isn't effective so it's just dead code atm. Other than this all of it is normal Input.GetTouch. 3D camera, 2D Input.
Video: https://youtu.be/m6MHD3ZmRYE

unique cave
#

You you can easily test this by capping Application.targetFrameRate at different values, if you multiply by delta time, you should see that the movement is 10x faster when its capped at 10fps compared to 100fps, thats not what you want

rare pike
#

Solved(Mostly): ProjectSettings->Editor->Resolution->Normal. Didn't even know this settings existed, I think Downsize squashes the pixels so you get erratic input.

#

Another Issue: I need to have the player collide with other objects that are kinematic and dynamic, but the player has "Mesh Collider" which needs to have kinematic enabled. I can't make the collider convex as it is "C" shaped and I need to retain the curve on the collider. How to retain "C" shaped collider while not being kinematic? Thanks in advance.

unique cave
unique cave
rare pike