#⚛️┃physics
1 messages · Page 4 of 1
yeh 😦 lame
ill just use float.MaxValue then
@bleak umbra thanks for that, i wouldn't have realised it was taking the wrong overload
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?
use Awake or OnEnable instead
ooh thanks!
i realise this question is a bit vague, what i mean is like can fixed updates collide with eachother, so say one fixed update takes long enough can then the next fixed update happen at the same time as the old one trying to finish
hmm, i am a bit worried that my other gameobjects might not be active yet then if i use those, or is this incorrect?
No of course not, Unity is single threaded
Only one piece of code runs at a time
ah ok, thanks!
Use GetAxisRaw instead
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
everything has overhead
You may want to use layers
Is there a way to execute Physics.OverlapMesh? like we have for other shapes?
Check out this method:
https://docs.unity3d.com/ScriptReference/Rigidbody.SweepTest.html
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
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!
should joints be configured on the child to the parent or vice versa?
colliders are literally just shapes. They know nothing about forces etc..
You're thinking about the inertia tensor of the Rigidbody
I am talking about the WheelCollider not regular Colliders, you do have the option to give it torque and stuff
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...
What sucks about polygon colliders? If you want a non primitive shape you use a polygon. Another option is to use multiple primitive colliders
hard to say because the totality of the rules are not clear, but it looks really simple from that video. It's just having any piece that is more than N blocks away horizontally from a block that's touching the ground collapse
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
thanks i was thinking that 2. but i wonder how expansiv that be whit big buildings . i guess i can just test it out.
also i guess it all have to be gameobjects and not tiles.
not expensive at all
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
and if you breakit from the buttom it need to go check every block to see if its connected somewhere els.
yes, you'll need to do a BFS or DFS in that case.
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 ^^
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.
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.
Has anyone faced a similar problem? Any ideas where to look (since I'm not getting compilation errors)?
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).
Does anyone know what the spring constant is for the spring joint?
I think... SpringJoint might not follow the physics formula(s) for springs:
https://forum.unity.com/threads/springjoint-spring-constant.48297/
I saw that but its also 10 years old so I figure there might be some new information on it
Thread
I figured out how to estimate the amount of error of the spring based on the physics step.
Progress.
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.
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
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
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
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.
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.
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.
nice! I love this kind of tweaking systems to figure out their rules from the outside
very clever!
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.
when I was poking around trying to figure out your question I'm pretty sure I saw an equation for how damping is applied in physx springs, but can't find it quickly now. My best guess is Unity's SpringJoint is a physx distance joint. https://documentation.help/NVIDIA-PhysX-SDK-Guide/Joints.html#distance-joint with the implicit spring behavior described
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
😛
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
yeah, then just finding the magic number based on a bunch of measurement/curve fitting is probably the easiest path
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
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
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
ah, I think I see what you're saying. Just that stiffer springs will be at rest closer to the relaxed spring position
okay, yeah, that works with the spring equation
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.
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
is the ball rolling or sliding?
rolling
That script is rotating the platform, not the ball. Should be fine
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?
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
Ah, you're using a 2018 version of Unity which doesn't have that debug info, looks like.
Try giving the platform a Rigidbody component and setting it to Kinematic. Then instead of changing transform.rotation, change GetComponent<Rigidbody>().rotation
I don't where to put the GetComponent<Rigidbody>().rotation, but it seems to work with me just giving the platform a Rigidbody and setting it to Kinematic. Thank you so much :}
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.
You need to put the children onto a layer which ignores itself for collisions in the collisions matrix.
....and I'm assuming there's no other way? Because the game I'm working on has already used all Unity layers
How have you managed to use them all, that's insane
I'm sorta bound by NDA not to explain that
but uhhhhh
TL;DR: LittleBigPlanet-style layer system
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.
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
Ah right. I'm not sure to be honest
Call IgnoreCollision on the two polygon colliders?
https://docs.unity3d.com/ScriptReference/Physics2D.IgnoreCollision.html
Still won't be treated as one, but generally should have the same effect as using the collisions matrix without having to use layers
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.
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
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
is there any way to constrain a spring to only stretch on one axis, like a slider?
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.
Joints worry me because the two child objects don't have rigid bodies, only the parent group does
I'm confused. You only have 1 rigidbody in this?
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
Then why would the 2 objects have individual gravity?
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.
Another feature in the game is
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
So have you tried Physics2D.IgnoreCollision as I suggested?
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);
}
Might be relevant: http://answers.unity.com/answers/1353745/view.html
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
Thanks for the link! It very well may be relevant since the car does have child colliders. g2g for a moment, will read this more carefully in half an hour or so
Worked! Thanks again!
how long does the force act with ForceMode.Impulse in AddForce?
is it Time.fixedDeltaTime
It changes the rigidbody's velocity, once
so thinking with abstract logic, its like a force acting for fixedDeltaTime.
Not really but if that fits your mental model of how it works then sure
yep got it
so it was actually 1 second and not fixedDeltaTime
Not sure how you can come to that interpretation from that
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?
If you mean for movement, then yes. Unity physics can't calculate/predict the collisions correctly if the object is not moved via physics.
If you need physical simulation, like collisions, momentum, or gravity, yes.
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?
How are you moving the camera? (also have you tried extrapolation?)
I haven't tried extrapolation. What does it do?
The camera is being moved in Update
It tries to predict the position between frames instead of smoothly interpolating using the earlier frames
ok, will I need that?
I dont know, just something to try
so i've removed the camera motion enttirely and just parented the camera to the rigid body
It means that interpolation doesn't work for the object. You must be doing something that breaks it.
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);
Yeah, you don't want to use extrapolation. It's not really useful in most cases.
That's it.
Yes. Not only position changes, but rotation can break interpolation as well.
I see
You'll need to rotate it in a physical way.
Did it help?
the motion is like this now:
i'm going to turn on the camera motion and check that too
Looks better I think?🤔
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
@tender gulch if you have a moment, could I please ask some more advice?
Ask ahead. If not me, someone else is gonna answer.
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'
Not sure I understand this question.
Is your ground just one big plane? Or does it consist of multiple colliders?
Try setting 0 friction on both the ground and the object colliders.
oh, that helps.
what is the threshold for physics object freezing?
like when you leave them alone for a long time
As long as there's no damping, no friction and nothing changes it's velocity, then it should keep on moving.
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
you mean a maximum/limited velocity or something else?
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);
Yeah I can do something similar.
I am just curious whether I am right about this or am just doing something wrong
I think the friction is meant as friction between 2 objects. And you can use the (linear) drag for slowing things down
you mean it is the friction force and not the friction coefficient?
the documentation says that it is the friction coef
i don't know exaclty, what i saw it is, when you i.e. have one object moving over the surface of another object
It does
then why does the object doesn't stop accelerating?
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
If you continually add force, the object will continually accelerate.
Friction is proportional to the normal force against the surface, not the orthogonal velocity
Going faster doesn't increase friction with the ground
Only aerodynamic drag
You are a physics grad, right?
yeah, now I remember
somehow I got confused
it's been a while since the last time I dealt with regular friction I guess
Anyone knows Best way to handle slopes in unity 2d
Can you explain what you mean by "handle slopes"?
In what way would you like to "handle" them? What kind of game is it? What gameplay experience are you looking for?
i am making player controller to run over slopes but its quite not working well
There's a few ways to do this. Almost all of them involve raycasts, and manually adjusting the velocity when the surface normal changes.
which is the best way
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
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
thanks bro
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.
Unity only allows rigidbodies but you could very well create that using multiple rigidbodies and (spring?) joints between them. You could rig the beam model and attatch the rigidbodies etc. to the bones so the mesh would move according to the rbs
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
Does anyone know how I could create gravity around several central points, Sort of like planets
Add a force to all object you want to affect by this „gravity“ that points to the center of mass of the „planet“ and scale that force by mass * 1/distance^2
Sweet thanks
Anyone has an idea how to do that?
Ok, nevermind I did that
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?
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.
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?
wow.... those beautiful shadows... HOW
no way this is unity
depends on how you want the joints to behave
?
alright..... realistically will i be able to get away with a simulation game running at 360hz physics? 😆
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
Does anyone know why?
Those are just perfect! My shadows looks like pixelated shit
it's just a box ;-;
But SHADOWS ARE CASTED PERFECTLY
Check #archived-lighting
You'll find out what i mean
Unity is good but lighting not
Lighting sucks so hard
it's just hdrp
Does anyone know of any games running with a physics tick rate higher than 120hz?
Might be tough, you might have to do some optimisations, but you could get away with it on good cpus
Heavily, heavily consider DOTS
It's tough to learn but super cool for this stuff
Yeah definitely will have some higher than average CPU requirements
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
1200hz of physics in a single tick?
I don't think so
yes
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
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
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?
was referring to this
right obviously the meshes are mostly primitive with 1 single mesh collider for the arena
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
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
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
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
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
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
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
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
I mean there's an i5 coming out every year, the important thing is the 3570
which means it's 12 yo, compared to 15- 13600 or whatever is the new one, which is 2 months old or less
if you make linux builds, you can send me, I can check if it works on my pc
shit cpu ok gpu
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
send me the windows version, I'll run it with wine
my project is all Unity 2022 native so should be easy to do though
you can just send me the windows build, most linux ppl dont mind windows builds because of recent proton development
just DM'ed it to you
Am I worrying too much, that a raycast isn't "dynamic/speculative" so a moving object that's raycasted might miss another moving object?
BeamNG runs it’s physics at 2000Hz
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:
What's the shape of the collider?
What's the center of mass?
What constraints are enabled?
the collider is a mesh collider roughly following the outline of the model
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
Com is part of the problem. Other part is lack of friction
the floor is just the null physcs material
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
It's that plus the center of mass I think
shouldn't a perpendicular force offset to the the COM cause a rotation?
Yes which is why center of mass is suspicious but actually remembering inertia tensor is even more important for it
i don't know how to change the inertia tensor
i thought that was an internal property of physx
Inertia tensor and COM can both be modified via script
It's the rotational equivalent of center of mass
why is it so high in the screenshot 🤔
For example a long stick has more rotational inertia along it's long axis than its short axis
Idk but that could be why it won't rotate
rigidbody.centerOfMass = rigidbody.inertiaTensor = centerOfMass.localPosition;
it didn't change 🤔
do i set it to zero?
i didnt see it change in the info window
Yeah that'd definitely be a problem lol
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
Oh 😂
lemme fix that
well changing the IT to one caused problems
my rb glitched into the ground lol
Oof
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
I mean that's exactly what friction does. Applies a perpendicular force to the surface normal.
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
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?
https://www.youtube.com/watch?v=RoZG5RARGF0 this might work maybe
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...
@timid dove I think I misspoke
I'm not sure what it's called but this is what I mean:
Thank you!!!
I know they use a custom engine and it’s probably a little more performant than PhysX but that’s really relieving to hear
Are you controlling angular velocity somehow?
not on purpose
@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
Let me put it this way. Put a standard unity cube in the scene and drop it, it should behave relatively convincingly
That should restore your confidence the engine works
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
Have you thought about using WheelColliders?
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
@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
i had that stuff disabled while testing this rotation thing
Then I’m pretty stumped tbh
i also would prefer not to use the wheelcollider's approximations of tyre grip and rolling if possible, since i made my own that work much less realistically
Rocket League’s car controller is a great implementation tbh
that's unreal though is it not
Talking about the concepts of how it works
i dont know how they did it
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
There’s a Unity clone called RoboLeague on GitHub
this is true in my project as well, which is why i set the physx friction to off
Basically, friction is only sideways
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);
because i handle it in my script
Because rocket league wheels don’t slip when accelerating
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
Friction should be as simple as calculating the sideways velocity of each wheel, and adding velocity in the opposite direction
I’m just explaining how they calculate it
right
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
@whole dagger https://youtu.be/ueEmiDM94IE?t=952
In this 2018 GDC talk, Psyonix's Jared Cone takes viewers through an inside look at the specific game design decisions and implementation details that made the networked physics of Rocket League so successful.
video is timestamped
appreciate it
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
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
yeah
are you faking gravity?
no, it's real gravity
my movement code was disabled while doing that test
Yeah I think it's largely to do with the center of mass and inertia tensor
something's fucky with those
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
inertia tensor pretty much == angular momentum
^^
or "angular mass" at least
inertia and momentum are tied together
yeah i though the inertia tensor gets automatically calculated though
it does, except that you said you changed the center of mass
have you tried it without a custom COM?
it's here
slightly below and forward
i actually implemented it to try and solve this issue in the beginning
i don't get that then since that's a pretty basic COM position
Where's the main object's pivot?
And what's the hierarchy look like?
e.g. is that COM directly under the main car body?
Or deeper
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
just temporarily, could you try using a basic BoxCollider instead of that MeshCollider
see if it helps any
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
i'll try it
i'll pick this up ttomorrow and let you know how itt goes
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);
@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
Cheers
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
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
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);
You could change the magnitude of the vector easier 🤷♂️
Sure. I thought perhaps I was missing something since I'm pretty novice with vector stuff but it must just be stylistic. Thanks.
(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
Just use Vector2.Reflect, no? The normal to reflect on is just the direction from one circle center to the other
why do I bounce on the floor but not on the walls?
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
Technically not using Unity, just not sure what other servers would know about this kind of stuff
This is kinda off topic then
should make your life easier
Thanks
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
yes
Unity doesn't simulate general relativity
or is it special relativity? anyways
so basically i have a plane that is 300,000 kilometers long (in unity measurements) and then an object goes from one side to the other in less than a second
aight thanks for explaining
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.
Use layer based collisions to make the player and the other object ignore each other
I would but I don't want them to ignore each other. I want the "ball" to be effected by hitting the player; but not the other way around.
probably better making the player kinematic and simulating gravity yourself then
That's what I was thinking; but you can't AddForce to a kinematic Rigidbody.
No but you said you're moving via animation
So you're thinking just manipulate the transform directly in the "gravity" code?
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
Ok. I forgot about the MovePosition function in a Rigidbody.
You could also try working with https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131
if you go to about 1:05 in the first video
it has the behavior you want
Got it. Thanks.
is the default physics thread-safe, for stuff like adding forces?
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?
@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
ok, so does unity have any current packages that provide deterministic physics ?
dots
I heard that the DOTS one is not deterministic cross-platform
ohh I'm not sure on cross platform then. This is a little vague to me. https://docs.unity3d.com/Packages/com.unity.physics@1.0/manual/design.html
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
you can select different versions via package manager no ?
doesn't appear to be installed ?
yes
if the package needs it, you should install it https://docs.unity3d.com/Packages/com.unity.serialization@2.1/manual/index.html
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.
i'm not sure how to install this :<
where's it's repository?
do you have the Add package by name in package manager ? Should just be com.unity.serialization as the link says
oh, i'll try that.
should be able to select other version after it's installed as well
is it thread safe to add forces?
@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.
no
almost nothing in the unity API is thread safe
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.
you'd have to show the details of what you did
code-wise?
sure yeah
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
rigidbody.velocity = storedPointsInTime.Last.Value.velocity;
rigidbody.isKinematic=false;```
^ you probably want to do this in the opposite order
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:
please share on a paste site #854851968446365696
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
a powerful website for storing and sharing text and code snippets. completely free and open source.
I think there's at least two major flaws in your system here
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)
but how does Physics affect this object that is beeing rewinded if its Kinematic for this duration?
it will as it is in another loop and this value can change while this loop is beeing performed
Triggers may still be triggered right?
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
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
no, that's not the cause of that issue, I agree
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
Even so a system like this probably would benefit a lot by being based on fixed timesteps vs variable framerate
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?
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.
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.
I was trying to avoid disabling them too because I'm talking about several hundred prop objects. I don't use optimized colliders because the colliders are only used the editor. My question was just if theres still a performance cost during runtime if the colliders aren't being used but still enabled. Meaning no physics, no rigidbodies, etc.
If there is, I guess I'll just write another script to disable them all
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
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
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
https://gyazo.com/8873b73705b49b87eb5310a750b7a45f
I'm trying to work on raycast suspensions but I'm having some issues trying to solve damping. Are there any pointers?
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?
Is there some way to do Physics.OverlapBox for a rectangle? I'm trying to check a Bounds box for overlaps
you mean a 2D rectangle?
or what
OverlapBox is a rectangular prism
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);
}
}
}
it's pretty clear
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;
Oh, I think the travelL is the one that reaches zero. How could I fix this?
Don't divide by zero 😊
Ok, lol. Thanks
Idk how to get the correct trayectory of the rigid body
https://github.com/xdanielc/unity_tests/blob/main/PlayerDynamic.cs
Are there any alternatives for getting a non-convex mesh collider working with a rigidbody?
You better use compound collider when possible, there isnt any easy way
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
- Use
Physics.IgnoreLayerCollision, placing players in aPlayerlayer and enemies in anEnemylayer, 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 rigidbody.enabled = falsewhile 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 enemiesPhysics.IgnoreCollisionseems 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?)- 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!
Is there a reason not to just have a layer for the dashing behaviour that only dashing players go on?
You don't need a layer for each player, they just need to not collide when dashing, no?
Ah, that sounds pretty elegant, I didn't even think about switching layers on the fly haha 😅, are there any downsides to that?
Nope, should work as expected.
Sounds perfect, thanks for the solution and quick reply!
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);
}
} ```
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?
Several ways to do this without getting into the weeds of the math (which btw is not complicated.f = mais the equation)
- Use AddForce with ForceMode.VelocityChange.
- Add or set
.velocitydirectly
I finally figured out a solution, and the .VelocityChange helped a bunch, thanks!
Re-wrote my move-part
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
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
that's something I haven't heard of before, thanks for that. unfortunately that doesnt seem to reveal anything too useful in this case
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)
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
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)
- Pushboxes (Empty parent object)
-
Environment
- Colliders (Empty parent object)
- Box (On "Environment" layer, has BoxCollider2D on it, set to static)
- Colliders (Empty parent object)
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?
Kinematic rigidbodies don't react to collisions or forces
How does your movement script work? By "character controller" I hope you mean your own custom script not Unity's CharacterController
custom script, it just changes transform.position right now
what would be an approach that could support this then?
detect collisions and make your character not move through them?
- Switch to a dynamic Rigidbody and switch your script to move VIA the Rigidbody, not teleporting it via the Transform
- Do your own manual raycasting/boxcasting etc and only move your object according to those results so you don't pass inside colliders
gotcha, thanks.
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
OnCollisionExit works perfectly reliably in my experience except in one case:
- one of the objects involved in the collision is disabled/deactivated/destroyed rather than simply moving away
btw if you want the contact normal it's a bit more efficient to use collision.GetContact(0) rather than collision.contacts[0]
🤔 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?
And, thanks for this info 👍
yeah this could definitely mess with things
changing the mesh for a MeshCollider is probably in that list of weird shit that causes it not to work
I guess I should just use the ol' reliable raycast for checking the ground then, thanks mate 🙂
You ostill need to be careful with this, especially if you're making changes to the colliders mid-frame
You may need to get friendly with https://docs.unity3d.com/ScriptReference/Physics.SyncTransforms.html
how do u do blender mesh collider bc i dont like the unity mesh collider.
In Blender
Yeah, you obviously cant use blender inside unity if thats what you are asking 🤔, inside unity you gotta use the tools unity provides
it depends
i'd avoid them on mobile and on everything that does not absolutely require them, its usually better to approximate a complex shape with multiple primitive colliders
so, use box, capsule, sphere colliders instead of mesh collider , is that what u mean?>\
bump
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
Shouldnt matter much, most trees will not pass the proad phase check
thanks..
But the ones that do does impact the performance, if the meshes are low poly, that shouldnt be a problem
how do I fix jump lag on Photon?? due to view actual jump is not laggy
- #archived-networking
- You'll need to be more specific about what you mean by "Photon". Photon is a company that makes at least 4 different networking products
- You'll need to share code
on god
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
That's just how unity wheel colliders work. Could try maybe lerp the suspension distance manually in code when the vehicle starts jumping.
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! 🙂
how do i make something like a wagon where when i drag it the wheels move?
Smoke and mirrors
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
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?
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?
ok, good, thanks a ton!
any inbuilt way of getting inverse mass, or should i just do 1/mass?
"Inverse mass" doesnt sound too useful in general, I think there is no way
ah ok, ill just do 1/mass then, thanks!
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
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!
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?
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
Are you scaling the objects or resizing the colliders?
Setting scale or size to zero or NaN or Infinity will do this
Negative scale also produces warnings, but I think it works anyways
Neither, just moving them
the error implies some invalid collider shape which typically involves one of the things I mentioned above
simply moving things won't cause this
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
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
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.
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
Because OnTriggerEnter is for 3D physics. Try OnTriggerEnter2D
how can i get the overlap area between two trigger box colliders in unity2d
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.
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)?
A root motion with a good set of animations?
Most if not all controllers represent a character as a capsule with a single ray or a rigidbody to check ground.
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
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.
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
Use an if statement?
nvm
plz help
Can anyone help me with something
I use Crest Ocean which goes through Terrains
What should i do?
Crest has their own Discord server. You'll probably have better luck getting help there.
thats how it works, you can however mask it so it doesn't display below terrain, but the mesh will be there
I am a beginner (kind of) but thanks I'll try it
Alright, thanks for the info I'll check it out
Here's a more clearly worded version
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.
Isn't the point of a neural network is to wiggle joints randomly until it figured out walking?
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.
Or you can try an approach used in the procedural animation: https://youtu.be/acMK93A-FSY
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);
}
what should i do if the rectangles aren't axis aglined
A generic solution would be a polygon clipping algorithm https://en.m.wikipedia.org/wiki/Weiler–Atherton_clipping_algorithm
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
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.
joints simply add forces to the rigidbodies they connect. They don't really do anything special with regards to colliders
oh ok thanks, I guess my best option would be to use raycasts to destroy the joint before that happens
is it possible to keep a cylinder mesh in contact with the ground while it spins at a high rate?
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.
Have you looked into articulation bodies?
i didn't know about these. thank you!
Hey I am doing the same thing if you wanna team up.
woah cool!
Thanks I will try
This channel has an overview of built-in systems to move a character and in-depth videos on each: https://youtu.be/e94KggaEAr4
Yeah I understand how to move a character normally but in this case it depends on actual physical walking (i.e. legs moving)
But anyways thanks I will look into the rigidbody impulses solution.
Hey y’all guess who’s back
I keep getting this error message and it won’t let me play
Are you for real?
Yes?
Ever heard of copy & paste?
Wdym
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?
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.
originally i was going to use a rigidbody on my player. but when i added colliders the root motion stopped working.
also do i need rigidbody on both objects?
do you also need a rigidbody for raycasting?
No, just the one that's moving
No
not sure if this is correct but ive found mesh colliders dont work very well.
im just trying everything
when i check my physics/collision world there are 0 bodies
do u need individual tiles or can you just paint terrain ?
How are you checking this?
This kinda feels like a #archived-dots specific problem
You're unlikely to get help here specific to it
Also #854851968446365696 shows how to post code here
does anyone know why adding a rigidbody to my player stops my root motion from working
did you make it kinematic?
a kinematic one doesn't conflict with your rootmotion, a non-kinematic one does
with kinematic im just floating. and no root motion.
is it ok to post a screen shot instead of a code snippet @hollow echo
when i check my physics/collision world there are 0 bodies
This kinda feels like a #archived-dots specific problem
Ask there
Well, you're using ECS, so you're going to continue to not get an answer
ok
just post it there dude. im sure vert knows what theyre talking bout
i did
it just went unanswered
i deleted then posted it here so i wouldnt double post
maybe take that as a sign
the point is, nobody knows, and thats why you dont get an answer
no amount of advertising your question will help
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
you can answer in a non ecs way
There is no non-ECS answer to your problem.
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
Have you actually tried without ECS? Because it's simple, just have any collider, and perform the cast
I have no idea what that has to do with it
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?
You can post anything you want within reason
is it best to do it through youtube or something?
so its a link and not a upload
@hollow echo
It doesn't matter
i feel like it would be best in a ask the experts post? but im not allowed to use it
can i use root motion with a rigidbody or do i have to script the movement?
I don't know much about DOTS, but you can't have a physics body without an entity to it, right?
In my experience a rigidbody works fine with a root motion and even receives velocity from it.
each instance of a prefab is an entity in dots(ecs), yes
i found my answer, thank you
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
@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
Did you freeze XYZ rotations of the rigidbody?
Also, in my case a player character consists of a model object, an armature objects, a manager object and a parent container object. So it might important on which object you put the rigidbody component.
Hi, i'm a begginer creating a very simple project and i don't know how to stop it from walking through the wall
First, I'm not sure you need both a mesh collider and a box collider on walls.
Second, you need either a rigidbody to enable a collision between colliders, or a manual physics cast to check for an obstruction.
I think Unity requires a rigidbody on one of the objects for most type of collision events.
how can i add a collision between colliders?
and should i add it to the wall or to the xr rig?
It's easier to add a rigidbody to a character and made it kinematic. There is a table at the bottom of this article for what collides with what: https://docs.unity3d.com/Manual/CollidersOverview.html
As for manual physics casts, it depend on your setup and goals.
Hi. Does anyone know how can I rotate a gameobject towards like the direction of its velocity but with angular forces please?
thanks for the support
By 'angular forces' you mean an angular velocity? Is the direction of the velocity known?
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
It seem what we both need is called 'active ragdoll': https://youtu.be/HF-cp6yW3Iw
I think calculating an equal and opposite force to the force exerted by the feet and applying that up a chain of joints works well
But thanks nonetheless
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
You can try doing your own manual capsule or sphere casting in FixedUpdate
My rigidbody is jittering when MovePosition, any ideas why this can be happening?
Physics only update 50 times every second by default (which doesnt match the screens refresh rate). Use the Interpolate option to enable interpolation between physics frames so it looks smoother
Continuous (Dynamic if the targets moves too) should work just fine. How are you moving the projectiles?
@timid dove @unique cave Sorry forgot to update. The problem was that the bullet had the collider as trigger, and that ignores the physics..
In addition to ignoring physics, OnTriggerEnter will not take the Collision Detection mode into account
Didn't know that, thanks for the info! n.n
Thanks for the reply, already tried interpolate. I'm speculating that it has something to do with touch controls, it main jitters when your finger becomes Stationary after Move. Not sure why.
Maybe you are constantly overshooting the target position?
Could it be that my phone is old so it's not able to capture input as fast? Scene has many cubes that the player drags, itself being kinematic interpolated continous rigidbody, moving with rigibody.moveposition
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
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...
It happens at edit time normally but obviously in your case that doesn't apply...
actually looks like there's a property to control when it generates:
https://docs.unity3d.com/ScriptReference/CompositeCollider2D-generationType.html
Well I'm calling it manually, buuuuuut my object's still falling through the world
can you show the inspectors of the two objects that are supposed to collide (you can pause the game when it's running to show them)
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
Eh, maybe that could be possible but id like to see the code that converts the mouse input to MovePosition, I think its more likely theres something wrong in that code
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
Dont multiply by deltaTime there. I think Touch.deltaPosition is framerate independent already (delta of the touch position since last frame
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
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.
That shape could be replicated very easily with only 3 box colliders
Downsize just moves the image to the phone at lower resolution, that shouldnt really affect inputs. Did you remove the deltaTime? Did that help?
No, time.delta remains, good to control player speed for now. No major issue with movement anymore. About box colliders, trying to get it close to their desired version, if I get desperate I'll cut C shape into 3 parts and use them convex...maybe.