#⚛️┃physics
1 messages · Page 63 of 1
{
RaycastHit hit;
if (Physics.Raycast(PlayerCamera.transform.position, PlayerCamera.transform.forward, out hit))
{
Debug.DrawRay(PlayerCamera.transform.position, transform.forward, Color.magenta);
Debug.Log("Did shoot");
Debug.Log(hit.transform.name);
Debug.Log(hit.transform.position);
}
}```
Can anyone tell me why my ray casts aren't visible?
Time.deltaTime is used to make things "framerate independent". So transform.position += Vector3.right * Time.deltaTime in Update() moves something 1 unit to the right per second, regardless of whether you are running at 30fps or 60fps or 60000fps
in FixedUpdate you accomplish the same with Time.fixedDeltaTime
AddForce and similar methods do not need it, they automatically apply it
Is it possible to use rigidbody to do movement like you would with Lerp?
@modern laurel you gotta give more detail on what you want
you should be fine setting velocity however you want
you can also limit how much the velocity can change per frame in your code if thats something you may want
I'm really new. I have this code, but because i'm not using physics movement, the coins on top of the pusher are not moving with it. I read that it's because if I want that interaction I need to use rigidbody to move. https://pastebin.com/jz02YfVJ
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
@modern laurel is this your project?
ye
or you want to make the same thing
live right now lol
yea i see
the coins aren't moving with the pusher
well it looks like they do?
they're floating on top of it
oh i understand
you have to move pusher with physics
heres what you can do
make a kinematic object, call it PusherHandle or something
right, but like, will the physics items there push it back, or is it possible to move it while it's clipping through walls and such
Make your current pusher into a dynamic rigidbody
attach them to eachother via a fixed joint
and move the kinematic body the same way
with the transform
ooh
you get it?
yeah
what kinda stream is this
So, i hooked up a new object and it's working great, but for some reason everything is drifting to the right now doing some troubleshooting myself brb, the object I made in blender was not fully straight, so that explains it lol. using a primative fixed the drifting
is there a way to remove momentum?
Yes. One way is to move your object with velocity instead of adding force.
ah, it's a coin pusher. not sure i can do that
Hi, I'm trying to make the physics/animation of the vehicle driving around feel more realistic, and not so stiff. I want to make driving feel cooler. Do any of you have any tips?
Slippier with higher speed would be cool
ohh
how is this now?
hey so im trying to get a very 'stiff' solid connection between rigidbody cubes, what would the best joint be? I tried fixed but it bent a bit
basically want them to act as a solid model until I get a collider hit and then I will let them 'break' up
@native trench fixed joint should work for your purposes, but a configurable joint with all axes locked would also work
Yes, you can see a matrix at the bottom of this page that describes when events are/are not fired: https://docs.unity3d.com/Manual/CollidersOverview.html
How would I make my circular object decelerate? it spins in both directions. I commented out stuff that I tried. I want to make a smooth acceleration and deceleration.
What property does acceleration/deceleration affect generally speaking?
ayo, nothing really to do with coding but uhh how do i do a detailed analysis of how instantaneous speed is measured On a bicycle using an analog device (non GPS)
is it possible for my partical system to effect my player speed. if so how because it's the last thing i implemented before bed and now it's slow as hell. any ideas guys?
Maybe your movement is framerate-dependent and the particle system slowed down your framerate? Particle systems won't affect the speed of anything unless you jump through some hoops to make that happen.
Hi, I am currently working on a VR game using OpenXR in unity 2020.4. I have created a physics system for both the VR hands and body but the problem I am having is that when I press play the hands collide with the body and throws it off of the map. I am trying to get the body and hands physics systems to ignore each other so this is no longer an issue, but I have looked through documentation but I couldnt find anything that worked for me. Any help would be great!
Did you try with the collision layers matrix ? https://docs.unity3d.com/Manual/LayerBasedCollision.html
@supple sparrow Just sorted that problem thanks, but now my issue is that I have a rigidbody on the XR rig for the full body physics, but when I am in VR the head jsut falls into the ground (The head is currently represented by a sphere and the body is a capsule.) Is there any way that I can have the shpere ignore the rigidbody without taking the rigidbody from the xr rig?
So to explain my problem that I am having: I want the player's rotation to follow the direction of movement. However due to the spherical gravity used in my project, angles and movement is made x10 more complicated...
Currently I have a gameobject within the player that follows its movement. This gameobject will move up and down when the mouse moves up and down and it will also move left to right when the mouse moves left to right. The camera then follows the rotation of this gameobject and is offset a certain distance from it. The player's transform is separate to the rotation of the gameobject - and it is crucial that this gameobject is parented to the player since it allows me to skip some steps with the spherical gravity.
Here are the 3 main scripts that allow this to happen and I was wondering if anyone could give me suggestions on how to do this, because it is really confusing. Any help would be greatly appreciated:
FPController: https://hatebin.com/dsfsshdfta
CameraFollow: https://hatebin.com/rbglwlztos
GravityBody: https://hatebin.com/czafvrfahj
any1?
I know the pain too lmao
Hey, guys, do cloth colliders collide with eachother?
Anything is possible if you put your mind to it.
For something to "effect player speed" it'll have to be part of your player control system regardless. Your particle system might define an area inside which the player decelerates and ALSO spawn particles in there. 🤷
I read all that and still don't know what you're asking
What don't you get? @foggy rapids
what are you asking?
@foggy rapids hey and thanks for answering, it was working ok two days ago, after that evening of working the day after my player went extremely slughish, i've reduce the mass and drag down to a silly amount, however i don't think i should be doing this as it was working ok before hand. so far i've only implimented megawhatts bolt controller which worked perfectly. since then i've created the jumping, however not implimented yet, as not yet created the animation. i did also add some bubbles, 3 partical effects on the bodies head. which also worked. any ideas where i may have clicked what i shouldn't have. i'm pretty new
in short i've had a working model and now extremely slow. i've also reduced the rigidbody mass and gravity to compensate. but still extremely slow. any clue?
I don't know how to face the player in the direction of movement. It sounds simple, but the player is always rotated at weird angles anyways, so it is difficult to rotate the player as such so that it faces the direction of movement
oh i see, i thought you wanted to do it on purpose but you're saying it's happening and you dont know why
indeed
does it have a wind zone affecting it?
nope
Oh okay i get it now. Have you checked out Transform.LookAt It depends on transform.forward being the actual direction the model/sprite is looking maybe that's what's wrong?
i'm using bolt and using the velocity movement, why because i'm under water
i think it's not the code button something else. in the settings. unsure as to what tho
you can use transform.LookAt(moveDir * 50) as long as 50 is bigger than the volume the player takes up
ah right, ty!
Perhaps it thinks you are underwater when it is not
question would particals push my player down if they are going upwards ?
particles shouldn't do anything unless you gave them rigidbodies and your player also has a rigidbody
yea i didn't think so either. that was the last thing i did before saving and ending that night,
last working state
i think the best i can do is recommend using git or any version control system so that in the future you can go back to yesterday 😄
ok cool, yea maybe
there is a particle module for particle collision events... it's probably possible to use that to implement forces from particles hitting your object, but can't say anything about what sort of performance you can expect
(in most cases, adding forces manually along with the particle vfx is the better solution anyway)
Is it possible to have premade animations that also account for physics
i'm trying to go for smash bros like attacks but I also want to incorporate a kind of stickfight the game-esque feeling
How would I rotate the player on Local Euler Y Axis, when there is also a quaternion taking place on the player at the same time? It sounds complicated - I know - but here is why:
I am working with spherical gravity and the script that keeps the player onto the sphere uses this: transform.rotation = SmoothDampQuaternion(transform.rotation, targetRotation, ref currentVelocity, OTS); to rotate the player onto the sphere. However since I am also working with the camera movements of the player, I need to rotate the player on the Y Axis, whilst it is orbiting the planet
Depending on what you want - either rotate the player around its local up axis, or rotate the player around the current "antigravity" vector
by which I mean the direction directly away from the planet's center through the player
alright I will have a try now
when I do this: transform.localEulerAngles = new Vector3(transform.localEulerAngles.x, 50, transform.localEulerAngles.z); @timid dove
it does this: https://gyazo.com/d01cf619f7715c246e09a24bb22b0c0c
why would you do that though?
do what?
that code
rotate it around its local up axis or the direction away from the center of the planet
that just sets the Y euler angle to 50
which... ignores all of that
Try this: https://docs.unity3d.com/ScriptReference/Transform.RotateAround.html
transform.RotateAround(transform.position, transform.up, 50);
that will rotate it around its own up axis by 50 degrees
one time
oh ok
Or if you want to do it in Update:
transform.RotateAround(transform.position, transform.up, 50 * Time.deltaTime);
50 degrees per second
there's all kinds of goodies in the Scripting Reference
well I will make sure to be looking there next time then, since that would have saved me 7 hours worth of thinking
i guess that is the thing with learning to code, you waste time in the beginning and then realise that you could have done that thing within a few seconds
but thank you anyways!
Hi,
Working on our game I've found the issue described here:
https://forum.unity.com/threads/interpolation-doesnt-work-when-simulating-physics-manually.676489/
Using a manual simulation (calling Physics.Simulate() during an update cycle) the RB interpolation is not working. I suppose this happens because the engine handles RB interpolations between FixedUpdate() and Update() cycles. Is it correct? Any idea for a workaround?
Any reason to use it manually, what do you need form the RB when using it manually?
We are calling Simulate() manually because we need to do some computations before and after a PhysX step, so we have written a manager that call our pre-physics callbacks, then Physics.Simulate() and then call our post-physics callbacks.
The interpolation seems to work if we run this cycle under a FixedUpdate callback, but this seems to be a strange limitation
From what I see here https://docs.unity3d.com/Manual/ExecutionOrder.html , this is just as it is intended to work in the unity execution order. Could you hook into one of those events upfront and after physics computation?
The problem is that normally FixedUpdate is called before the physics step, and it's perfect for Pre-Physics logic, but there are no entry points for a Post-Physics callback
Anyway, the main problem is this: if we manually call Simulate, in a way similar to the one described here
the interpolation doesn't work
In terms of Execution Order, I can't find any detail about the RB interpolation - when is it executed? From our tests it seems that Unity interpolates RB after the PhysX step and before the Update cycle. If it's the case, I suppose that is not possible to interpolate RB when running Physics.Simulate() during Update
Yep I ran into this exact issue some time back. Oh wait that's me in that forum thread!
Never found a solution
😄
The only solution I can see is to run Physics.Simulate() during FixedUpdate - executing a single step for each FixedUpdate call
But this is somehow doubling the physics simulation, isnt it? 😄
But maybe, thats the only way if there is no hook upfront or after to use
No, we're not "doubling" the simulation, because we've disabled the automatic simulation step. We're simply controlling it in our flow 🙂
Any other suggestion? It's very strange that the engine doesn't support interpolation with Physics.autoSimulation turned off
Oh okay, you disabled it, alright. Well if its off, it is off, right? Guess thats just decision of design here
Mmm, I don't think it's a decision related to design. We're simply controlling when the Physics.Simulate() is called - I don't think that this should compromise the RB Interpolation. In any case, this detail is not documented at all
So Physics.Simulate is not accounting RB interpolation, right?
No - that call only wraps a PhysX step. From what I see I suppose that RB Interpolation is handled somewhere internally between FixedUpdate cycle and Update cycle, but I can't find any detail about that
I think the problem is that Rigidbody interpolation is a completely black box and apparently tied into the automatic update cycle with no visibility in the API at all
As far as I know you can't even manually do the interpolation either because the rigidbodies also get synced automatically to transforms?
Or is there a way to turn off automatic transform syncing too?
🤯
maybe this is the key?
Turn this off, and do the syncing of the transform manually from the rigidbody position before and after physics sim?
or is this actually only the Transform -> RB sync and not the RB -> Transform sync
I don't think that autoSyncTransform is usefull in this context. That flag is used in order to control the propagation FROM Transform TO RB, not vice versa
I think you got the point - there's no way to do manual interpolation using the built in rigid body
T_T
you don't have to use built-in rigidbodies. How complicated is your physics? You might be able to use a separate physics library altogether or make your own
If you wanted before/after callbacks you can implement your own fixedupdate as well just using update
but yeah that's a tough one 🤔
you can also use multiple Physics scenes too
Would that somehow help the interpolation problem?
whats your interpolation problem?
uhh... the whole discussion above 😄
when you manually call Physics.Simulate(), Rigidbody interpolation doesn't work
(for rigidbodies set to interpolate)
its part of autoSimulation
the Interpolate setting on rigidbodies is Transform --> RB
you can easily do the interpolation yourself in Update or LateUpdate
what pisses me off the most about Unity is that the default physics rate is 50hz
what is this? PAL TV and mains frequencyland?
You can't do a custom interpolation because you can't move the transform without affecting the next physics step. Maybe it's possible to move the transform and then move it back in the next FixedUpdate, but is seems a dirty workaround
Can't you turn that off with https://docs.unity3d.com/ScriptReference/Physics-autoSyncTransforms.html ?
Or will it still sync when you run Physics.Simulate()
(taking a deeper dive into this one for reasons...)
in real PhysX y ou could totally do this. in Unity you basically cant
you'd need a proxy object
AutoSyncTransforms doesn't affect the alignment during Physics.Simulate(), so it's not so useful for this purpose
oof
hello
çi'm ghaving some problem with the colliders
i guess is the collider
but i'm not sure
i have a cube as a ground
with z 1000 and x 15
the player is another cube
i'm truing to make infinite map
so i generate the ground over and over
the problem is when i reach the end of the first "ground"
my cube stop
i guess is the colader
but 'm no really sure
idk whe the cube stops
any idea?
also some weird gliches like the ground i collided with another thing,
i'm stuck for two hours in this...
it's probably stuck on the gap between colliders
using a sphere or capsule may help, otherwise you might need some code to actually grow the collider. In most infinite runners the path moves along beneath the player but the collider doesnt so he never has to leave the collider he's sitting on.
any guide?
if i move the ground still ned to create new one
the ground size is 1000
stoick at 990
the only fix i found, but its kind bad
this.nextPosition.y -= 0.01f;
I switch to mesh collider, select plane mesh and mark convex and now seems working
Can anyone help? My 3d model character falls through the terrain when a rigidbody is applied, I've tried adding a capsule collider to the character but still falls through for some reason.
does your terrain have a collider? Is either collider a trigger?
Yes it has a terrain collider and no they don't
I'm trying to make a sprite jump but whenever I add ForceMode2D.Impulse, it doesn't move compared to if I just left the forcemode it out
Could anyone advise me on what to do?
CharacterController and Rigidbody generally don't go together
wait
nvm
that's your own custom CharacterController not the builtin Unity one. Carry on
anyway the reason it doesnt move with Impulse vs normal force is that you have too little force I'd say
Since your mass is .1
Forcemode2D.Force is going to have 10x greater effect than the same force vector in Impulse mode
if you mass was 1 they would have the same effect
and if your mass was 10 then Impulse would have 10x greater effect than Force
These two will do the same thing:
Vector3 force = new Vector3(1, 0, 0);
rb.AddForce(force * rb.mass, ForceMode2D.Force);
rb.AddForce(force, ForceMode2D.Impulse);```
it's sort of "reversed" because your object's mass is less than 1
normally Impulse moves the object MORE, but only if the mass is > 1
Yeah that makes a lot of sense
I changed the mass to 10 and jumpforce to around 1000 but I'm still getting no movement for some reason
is "Jump" logging?
Yeah, I put a debug log in the function after the add force, and it comes up in the console
Are you sure that's the log from that function? From your screenshot it looks like Jump() is not being called anywhere (the name is greyed out)
Ah yeah sorry I updated the code after I posted it
Waaaait just a moment, I've just fixed it, the fixed update must've been messing up something, I got rid of it and the impulse force works now
oh.. yeah if you're doing MovePosition that will overwrite the force stuff
How are raycast stuff handled in kinematic character controllers?
I'm thinking do a couple raycasts from within the collider, towards movement direction.
And then do the same thing treating the gravity as movement direction.
Can i go wrong with something like this?
Hm, if i choose a raycast origin at the tip of the feet, the character wont be able to climb tiniest slopes
How many raycasts per frame is needed to archieve a nice kinematic controller?
Hey, I was wondering if there were any resources I could read up on figuring something out regarding colliders on ramps.
I currently have this issue where a sphere will bump over the corner of a ramp (at the top) instead of smoothly falling off by just going forward:
The ramp itself is positioned through scripting to be attached to the top platform, but I guess the collider is still detecting the normal of the corner of the ramp and causing the bounce to trigger there
I tried creating the same scenario using the ProBuilder tools and seem to get the same results
(In the image, red is the current result, green is what I ideally want)
you could make the ball heavier
Hey, I have an issue with the foreach loop. The code is supposed to send a raycast from each connector to see, if it hits a true gate. However I know that only one raycast is sent which is prompted by the console that hit doesnt exist in the second run as well as the debugray draws only once. I'm out of ideas on how to fix that ;c
Here is the code on pastebin https://pastebin.com/uA3TbBUP
Inb4, the connectors a loaded okay, the code goes as expected but only the raycast is not send as i even get an output in console that the hit variable does not exist in the second foreach run
your link doesnt work
Thanks for the reply. That wouldn't solve the issue of the collider responding to the normal, but I'm realizing this issue is the same as the more general one of having two floor objects connecting and colliders reacting to the seams inbetween. So I'm gonna try looking at how people tackle that.
did you try putting the ramp collider down a lil' bit ? like .1 unit. So it kinda falls on it. Yeah kinda hacky and might not solve your PG case
I have a trouble with rigibodies it drives me crazy
rigid.AddForce((SpellCaster.transform.position - Target.transform.position).normalized, ForceMode);
This code launch the projectiles exactly flipped. Both should hit the red cube in the angle.
So I just put a minus before the vector and :
rigid.AddForce(-(SpellCaster.transform.position - Target.transform.position).normalized, ForceMode);
It just fire both of the laser right in front. Everytime I try to rotate the setup to make it fire at the right place the lasers just merge on the vector forward which is totally no intended
Do you guys have an idea of what could cause this issue ?
I did actually try that as well. But that introduces the same issue when going up the ramp. I'm probably gonna do better management of normals on multiple collisions.
How are you going about rotating the vector that's causing it to go forward?
Found out my problem was multiple instantiation, they collided all together at starting position. And because of the the impulse on the addForce messed up because of the collision
Now it works
Oh nice 👍
Thanks though @verbal cargo !
Yeah, the best is to use a composite collider or a polygon collider 👍
Question: how do I stop cold instead of "decelerate" with a rigidbody? Also, I'm trying to turn left, then keep walking forward, but as it is, this only allows me to walk forward and back, even when I'm facing the other way (or left / right).
if (_moving)
{
// Move
Vector3 Move = new Vector3(0.0f, 0.0f, move.y) * Time.deltaTime;
_rigidbody.AddForce(Move * 800f);
// calculate the distance and stop
moveDistance = Vector3.Distance(transform.position, prevPos);
if (moveDistance > 0.5f)
{
_rigidbody.velocity = Vector3.zero;
_rigidbody.angularVelocity = Vector3.zero;
_moving = false;
}
}
Trying to do a legend of grimrock type of walk
But I've stumble upon this issue, mainly because I still do my math with my fingers and this is physics.
btw, I'm using rigidbody only because I want a collider (walls, doors, etc). I tried using a raycast, but it got me nowhere but to the drugstore for aspirins.
if I do transform.translate, it works, but I have no way of stopping before a onEnterTrigger collider without clipping like Casper the friendly ghost all over the place.
Should I quit and go ask my uncle for a job at the gas station?
GOOD NEWS! I Solved it myself!
In case someone comes with a similar issue: I needed to use AddRelativeForce, not ``AddForce`.
Bad news: I have to start pumping gas on Monday now.
@shy onyx use Lerp, MoveTowards, etc.
_rigidbody.velocity = Vector3.Lerp(_rigidbody.velocity, Vector3.zero, Time.deltaTime * 10); //replace 10 with a variable or some number that works for you
any way to stop cold instead of sliding like if I was on ice?
thank you man, you've got yourself a free gas coupon.
Why is my rigidbody dragging like a snail? I'm adding a high velocity number and still drags like a snail!
Vector3 Move = new Vector3(0.0f, 0.0f, move.y);
_rigidbody.velocity = Vector3.Lerp(_rigidbody.velocity, Vector3.zero, Time.deltaTime * 650); //replace 10 with a variable or some number that works for you
_rigidbody.AddRelativeForce(Move);
_rigidbody.velocity = Vector3.Lerp(_rigidbody.velocity, Vector3.zero, Time.deltaTime * 650)
This will reduce your RB's velocity to zero very quickly
Unless your game runs at about 700 FPS+ Time.deltaTime * 650 will always be greater than 1
Therefore Vector3.Lerp(_rigidbody.velocity, Vector3.zero, Time.deltaTime * 650); will always be equal to Vector3.zero
Well, unless this is in FixedUpdate, in which case Time.deltaTime * 650 will evaluate to 13 every time regardless of framerate (unless you changed your fixed timestep)
Which will also give you Vector3.zero from the Lerp
I'm going to sleep, but I want to know if there's a way to make my coins stop flinging into the air. I have gravity to 20 and static friction to .01 (so it should be easy to push the coins) but they still get flung into the air pretty often. Here's a clip, it's the silver coin on the right https://clips.twitch.tv/AwkwardProudCatDatSheffy-Q3-7XJ78lz7c3WZS
hello im new and im trying to make a multiplayer game but im struggling could anyone help me
Your tried pulling the fixed deltatime to small values? @modern laurel
@rose arch new to unity?
yes
got programming exp?
no just new to coding and unity
people will probably suggest following a plain c# tutorial without unity context first
gotta get some basics down
i got variables using brackeys tutorials
i mean
learnt
ye my english is kind of bad
anything wrong?
make sure you can write and understand some c# code
the lists, arrays, loops, conditionals, classes, objects etc
then you could make a small consoleapp project for practise
then you do some basic unity tutorials
learn stuff like gameobjects, components, raycasting, collision detecting, referencing stuff via public fields etc etc.
then you make a small, simple game or just keep building on top the tutorials code
and then you choose a networking asset, (i recommend mirror).
do some tutorials to learn about RPCs, Commands, maybe use some of the built in components
then you should have all you need to start a simple multiplayer project
@rose arch
but the codes are different arent they?
if you dont have intermidiate experience in programming, you will just have a hard time in unity
if you dont know most of the unity's basics, you will have a hard time making a game
ok so i have to start learning how to write a C# script and then start everything else right?
and understand
ik python
Am having a problem with bullet(Rigidbody). If i use OnCollisionEnter it works perfectly but my bullet needs to go through the player collider (Capsule Collider) in order to hit the enemy body parts.
So i am using OnTriggerEnter but my bullets move at a speed of 1000(Add Force units,Impulse) so they cant detect the collision but they do detect in low speed. H E L P ! ! ! ! !
I tried adding a raycast to them but that also didnt work(Raycast on the bullet prefab)
Just in case
I would still use a collision, not a trigger
and solve that player collision problem
you could put your player and bullet prefab in different layers for example
is that how it would ignore the player collider and hit on the body part collider
If i understand well what you describe, yes
hope I understood it well :p try it
but that's also strange that your bullet collides with the player in the first place 🤔 should not happen
you should shoot from a "barrel tip" gameobject, offset in front of the player
Sorry for the nudity there
NOT from player's position
i need to hit his internal colliders
oh player and enemies have capsule collider + body part collider ?
its kind of a multiplayer
yeah just put the capsule collider in another layer than the bullet prefab, should be enough
- adjust layer matrix
so if i put the capsule collider and in another layer and enable collision (Disable istrigger) on the bullet the bullet will be able to go through the capsule collider but hit the internal colliders
you're welcome, happy coding 👍
does anyone know how to fix rigidbody characters sticking to walls
It works like a charm thanks Mr.K
So I'm trying to move objects into subscenes with physics, I'm dynamically creating scenes using the scenemanager and moving the game object I care about into them once they finish loading
but the problem I'm having is that the transform of that moved game object seems stuck
I can see forces being applied and dampened on the attached rigid body
but the object never moves or rotates
anyone have any idea what I might have missed?
The fixed update method on the game object is being called, and I'm simulating the child subscene's physics from the parent
should say that in the parent scene the object does move around
if I don't slide it into the child
Which scene is the object in? There's a phase of the physics simulation where Unity syncs the rigidbody changes back into the transform of the object. I wonder if that doesn't work properly if the scene of the object doesn't match its physics scene?
I move the entire object
I've never done multiple physics scenes so forgive me if that doesn't make sense
so I move the parent
and that parent has the rigid body
so the rigid body + the thing being rendered are in the physics scene
Yes. I don't want it to get too laggy, not sure i can have it any smaller.
@modern laurel maybe you can just lock coins x-z axisces
after they havent been sitting flat for some time
im getting this wierd issue where this ball get stopped by nothing
its trying to move to the right, but it stops right there
ive tried clicking there, but nothing shows up
im pretty mad too
Or maybe there's a collider there
Couple things youc an do - add an OnCollisionEnter and print the name of what it hit
or just search your scene for cxolliders
t: Collider
in the hierarchy window
and look at them all
yes except... this looks like 2d right?
So
void OnCollisionEnter2D(Collision2D col)
With what?
I added a box into the scene and a capsule as player but the capsule isn't colliding with the cube it just falls through it
Did you make any changes to the collision layers matrix?
nope
Then I can't think of anything that could cause it. Unless you're running some code that modifies these objects at runtime.
let me start from the new scene
hi does anyone know how to implement knockback my enemies in unity
Multiple ways. Did you do a search / watch a video to see how others do it ?
Detect collisions and add forces to one/both of the colliding objects
ok so I still had this issue in a total new scene when I was using Unity 2020.1.17f1 (64-bit) but I opened it in Unity 2019.4.20f1 (64-bit) and it worked perfectly fine
should I report it?
im repeating the whole thing in two channels oh god
Perhaps. It might be a known issue though.
before coming here I saw people on google talking about things like this but they got their fix at some point
or they just managed to get it working somehow
there wasn't a reliable fix
So i just saw a video of Shell Mechanics Overhaul for Post Scriptum, and im wondering how i'd do something similar in unity, as Post Scriptum is made in UE4. I'm planning on getting a demo done for my game first and im going to add just about every mechanic i have planned by the time im ready to release my game proper.
how do i program how to push/pull blocks in unity 3D?
Be more specific. There are many ways
wait i'll show a screenshot
here
look at the yellow blocks he's holding
Again there are many ways
Object parenting
Physics joints
Or just moving the object in script
Simple question: How can I bounce an rigidbody multiple times while decreasing it's height every time it bounces off?
it should stop bouncing after hitting the ground like ~6 times
i tried playing with the bounciness in the phsyics material but even if i set it to 1, the height is not as high as I want it
@primal thicket if you want real precose control on this, you cqn do your own simple physics via raycasting
or sphere/circlecasting
have your own velocity code and handle your own bouncing behaviour
@primal thicket or you just needed to also lower the drag in rigidbody settings
I've actually found a solution which is just adding a force each time I hit the ground
I multiply it by the counter and reduce the counter by 1 each time
I dunno if that's optimal though
but it definetly works
its probably losing its energy too fast because of drag
hmmmmm i should try to play with the drag as well
i think you can make it preserve its energy and pretty much bounce forever
if you also disabled drag
id also make friction 0
so no energy is wasted on angular momentum
on the physics material?
Yeah I will try to scale them accordingly. Thanks!
np
if it works, then you can adjust the velocity in OnCollisionEnter
you could multiply velocity by 0.9 for example
and that should make the bounce height to 0.81
if its dropped from 1 i mean
@primal thicket
works OnTriggerEnter too right?
if you multiply velocoty by 0.9, jump height should be %81 each time
@primal thicket OnCollisionEnter
triggerenter is for trigger collisions
I have both a RB and box collider attached to the gameobject, need to change it accordingly, but this should work
My Physics2D.OverlapPoint doesn't work on Tilemap colliders. How can I fix this?
hiya
i have a quick question
so i have a breaking script( snippet) on my rigidbody veichle
https://hatebin.com/jqipdqpkbz
it works fine when i move it and it needs to brake but if i drive up a slope it slides down regardless
how to make it stop the sliding down without modifying other the drag and friction (friction doesnt work because rigidbody is floating and i dont want to modify the drag because it makes the movement and physics reactions of the object sluggish)
@slow rock Rigidbody wheels tend not to work out so well because of the nature of "Tire" physics. real-life tires aren't rigid, they're flexy and grippy and generally have 2 types of friction (lateral and rolling resistance).
the Wheel Collider provides a decent simulation of this as well as a suspension, steering, and motor simulation
I'm trying to make building destruction but it is just way to laggy someone said to use a compute shader so does anyone know how to make one?
This really isnt about the rigidbody rather the character controller, is there a way to make a jump that doesnt feel so floaty
Does anyone know a good way to make projectiles? And I mean projectiles, not hitscan. I hear Unity’s movement system is unreliable with collisions at high speeds, but does anyone know what those speeds are? (Roughly)
Use Rigidbody and the speeds are pretty much any velocity where the collider of your Rigidbody will move more than (the thickness of your obstacle's collider - the projectile's length) in a single fixed timestep
You can try continuous collision mode and/or doing your own Raycasts in FixedUpdate to detect obstacles
Is it more efficient to have one script manage many game object projectiles of for each projectile to have its own script to handle its own collisions/etc?
Not one script for all, but say one script per “gun”
depends on the number
but probably better to manage them all with one script
to save <number of bullets> Update calls
It's really difficult to manage collision events in particular from a single script
Because Unity will only send collision events to the objects involved in the collision
but it's better to put that stuff on the things getting hit
Hey how do I change a single instance of my physics material?
Like I have a standard asset pack and I have a physics material "Bouncy" applied to two objects, how do I change the setting of one without changing the setting of the other
use collider.material
you have to assign different materials to each.
I have a dumb trig question. In 2D. I have a vector 2. I want to find the clockwise angle from this point to another point. So that if the second vector2 is due east of the first it will be 90, if the second vector is due west of the first I get 270.
Unity provides Vector2.SignedAngle, you can convert it to a cw angle by checking if it is < 0, and if so adding 360 to it
So I have hinge joints on my car doors, but whenever they open and then slam shut and go back to angle 0, they fucking spazz out and like fly open instantly
collisions are disabled on the joints
Quick question.
I have the player attached a capsule collider 2d and the platforms with box collider2d, when if the player hits on edge of the box colliders player bounces and if hits while jumping its velocity increases.. However if i have a box collider on player it works fine. So is there a way i can come out of this. Thanks
Is there any setting to limit the minimal distance between two colliders before OnCollisionEnter gets triggered?
Having issues with it being called, where all contact points have a relatively large separation value (> 0.1 units)
Image showing the distance between the two bodies (a mesh and terrain collider)
The separation distance on all contact points in this case is 0.45 or further.
You don't have wheel Colliders?
Not in this case no.
No other colliders at all?
I'm using simple raycasts to keep it off ground (applying a force based on a simple spring model)
So its basically a hover-car.
Have you tried debug drawing the supposed contact points from the collision?
And no, no other colliders. I've double checked the collision matrix in the physics settings etc.
Yes. the contact points are the four corners of the bottom of the collision mesh on the car
Hail mary: you don't happen to be far away from the origin do you?
I feel like something else is happening here..
Tried switching to continous mode on the rigid body as well.
Like maybe there's some stray geometry on your Mesh or something
.45 is A LOT
The physics engine wouldn't just be approximating by that amount
I've redone the collision mesh just to be sure 🙂
This issue seem to be the cause for something that happens randomly. Where the car goes flying off, as if a huge force has been applied in order to separate the two.
happen when driving straight forward, on a terrain that is completely flat...
All of a sudden the car just goes into orbit (more or less). Double checked the forces I apply manually, but they dont sum up enough to make such a impact.
Have you made sure it's the terrain thay you're colliding with?
Maybe you have some invisible Colliders you're running into
That you left around by accident
Double checked that as well.. I only log if the layer of the colliders triggering the callback match
Even made a test scene, where there is only the car and the terrain. Everything else has been removed.
Its driving me crazy
Argh, did another test scene. Started completely from scratch. And so far, not a single contact point that reports a positive separation
can someone explain to me why this code snippet doens't work?
Vector3 position = transform.position + transform.right * _speed * Time.deltaTime;
Vector3 localPosition = transform.InverseTransformPoint(position);
transform.localPosition = localPosition;
It works as expected if I assing the position variable to the transform.position. I want to understand why it breaks when I try to convert the position variable to local position. The parent game object isn't scaled nor rotated
does anyone know if ragdolls take up a significant amount of performance when they are laying still? Im asking because im wondering if i should disable ragdolls of dead enemies after a certain amount of time, or just leave them be for the rest of the level
will probably be around 100 ragdolls per level in total
ragdolls are made of Rigidbodies
rigidbodies have an optimization called "sleeping" where they are removed from the simulation loop when they have been stationary for a little bit
but their colliders will still be there, their renderers will still be there, and they will still take up memory
that will all affect performance still
Hi, anyone can help me with the movement in the X axis? I've tried to disable the rotation on X axis under rigidbody constraints and it didn't work
Heres the sourcecode
Hi guys, I have recently experienced an issue where my player teleports on the upper side of the Enemy whenever it gets too close. I have no idea why it is occurring though.
Regarding the setup: My player has a Character controller and a rigidbody (kinematic) components; the enemy has a Navmesh, a mesh collider and a rigidbody (kinematic) components.
I worked on fixing it by turning the mesh collider into convex and turning 'is kinematic' off. That seems to work but I need to keep the mesh collider without it being convex, since my enemy is a donut and you have to be able to shoot through its hole. Some forums suggest that changing the height of the Navmesh Agent may be able to fix it, but it doesn't seem to be the case. It doesn't work changing the Character Controller slope limits either. I tried reducing the slope limit and the step offset to 0 but it didn't work. I would really appreciate some help :D (video below shows the problem)
@dim solar Hey! I think it would be best to just not change the x and z angles if you do not need to. I would just change the targetrotation before the sleep to (rb.rotation.x,targetrotation.y,rb.rotation.z) with eulers so it does not change it during your slerp
Quick question. I'm making an air hockey game. Both handles and the ball have Rigidbody set to continuous... But when handles shoot very fast, the ball goes through the handle! But not through the walls at all
Wall is static by the way
What can I do to fix this ?
Thanks :D
( and to be clear, I move the handles with one of those ForceMode s , not by changing the velocity itself )
Here is the link
https://forum.unity.com/threads/rigidbodies-set-to-continuous-ho-through-each-other.1063208/
@round hinge is the handle rotating by any chance?
@viral ginkgo not the handle , no , but the ball is
Could the rotation be the issue ?
If you got this kind of situations that is
if ball is round and it doesnt rotate fast, i guess not
either way, that would be solved by switching to continious sceculative collision detection that comes after continious col. det.
i think thats not the case though
Does any of those "interpolate" or "extrapolate" could have caused this issue ?
Because I have set the handles as extrapolate
I see
also the value of transforms
This is a known issue, right? I saw no answered thread online about this topic... All are unanswered
if you use interpolation, you should access rb.position/rotation instead of transform.pos,rot
@viral ginkgo yes I know
i dont know whats going on, whats causing the issue
do you have any transform disturbances?
It's the physics. And potentially my addforce method
I set the force mode to the third option I guess ( before the "change velocity")
( btw I'm also curious if the "change velocity" affects velocity directly)
even if you directly change velocity, it shouldnt go through i believe
It's a dangerous thing to do anyway, I didn't change velocity directly at all, since I'm not physics professor and tend to keep the game real as possible
It says in docs that it changes velocity instantly
Yes, that's why it's dangerous
so the effect is something cant be replicated with just Addforce
because addforce wont do instant velocity change
i dunno, maybe try doing that with addforce
Sorry , I didn't get what you mean , can you be more exact at this ?(I'm not natively EN)
@viral ginkgo sorry I forgot to mention your id
@round hinge i meant you could try doing this without velocitychange mode
dont put anything
i think this most likely wont solve your issue but since its going to be easy to try, i guess why not
Yeah I'm gonna try it. ... And mayyybe it could be because of that there are two Continuous rigidbodies colliding ? Maybe this continuous method doesn't work with itself?
I have a feeling that's the case , because the ball doesn't go through the wall at all . Only through the handles
@round hinge did you try speculative mode?
maybe you should do some custom here
i'm talking raycast based stuff
Custom how?
Yes . That works fine, except that it's like acceleration mode, meaning it rises the speed over time , which isn't what I want with the physics of the handles
@round hinge https://answers.unity.com/questions/1742415/forcemodevelocitychange-not-behaving-as-expected.html
Looks like the velocity change isnt really instant
I dont think you'll see that rigidbody.velocity will change after appling any kind of addforce including the "velocity change" mode
You issue is probably because the per-frame acceleration gets too big one the rod is hitting the ball
because it gets slower for one frame because its got hit
and then you set the velocity to same value again after that
which makes a real high velocity difference
and i guess that glitches the physics
.
i would keep using velocity change mode
and limit how much the velocity can change per frame
ill give it some value so that velocity wont change more than 10.0f for example
with some little math
@viral ginkgo yeah, that's a pretty good idea ! Thanks :D
is there any way I can get my acceleration and speed faster I'm using unity wheel colliders
I made the motor Torque very high but still nothing
Increased friction. Lower mass of car. Higher torque
is the friction the Extremum Value
friction is a property of the PhysicMaterial attached to the two Colliders that are touching
Hello, I'm in dire need of some help with applying force (apparently I skipped that class long ago).
Problem is, I want to move my object down by applying force at points F1,F2,B1,B2 and I want my object to NOT spin at all.
So if total force I want to apply is 10 then how do I calculate the distribution on those 4 points?
If you want to apply forces and have the object not spin at all, there's no reason to do all that fancy math
just apply 10 units of force directly at the object's center of mass
e.g. with the normal Rigidbody.AddForce method
But that's exactly what I don't want to do.
just please assume it's not the same. center of mass is the wrong way for me.
you have to solve a system of equations here...
10 = F1 + F2 + B1 + B2
then you need to make sure the torques cancel out for each axis.
Torque equation is T = FD (torque is force * distance)
where distance is the distance that the force is applied at from the center of mass
but you need to do that for each of the three dimensions
for each point where you're adding force
and make sure that the x, y, and z torques all add up to 0
Hey, not sure if this is the right area. I use root animation which moves my capsule collider controlled character. However, when it comes in contact with another capsule (my character attacks an enemy with melee) the player capsule will often "slide" up to the top of the enemy capsule. And it is then...floating in the air until the capsule beneath moves.
I don't want to lock Y position because I have a jump mechanic.
I asked some animators/root motion people but they said it was a physics issue. Any ideas how to stop that from happening?
thx
anyone have any thoughts how we can resolve the kind of rubberbanding happening here? It happens on a rare occasion, player uses a hinge, puck is a few box colliders in a radial array, stick is a collection of box colliders that make a curve.
Can anyone help me understand or provide a resource on the logic behind collisions? I've been doing research on Kinematic Controllers and detecting collisions between stuff like walls and the player and it has had me thinking all day haha.
I've seen a bit of Physics.ComputePenetration but i'm not 100% sure if that's a common tactic or not, any input is appreciated!
is there a way to check for a sweeptest for rotations?
Im trying to make like a basic car controller
for velocity, i check if the object is going to go through an object if moved using this particular velocity using SweepTest
But i want the car to rotate and im not sure how to do that?
Im thinking like a sweeptest to the final position of the all the vertices from their current positions and checking if it collides but i think it wouldnt work fine for large collisions
sorry a raycast from all vertices for the rotation part instead of a sweep test
im using the famous MouseLook.cs for camera control but i dont want it to go through the terrain and the colliders dont work because its not rigidbody controlled. Any ideas?
Continuous collision detection is a feature to prevent fast-moving colliders from passing each other. This may happen when using normal (Discrete) collision detection, when an object is one side of a collider in one frame, and already passed the collider in the next frame. To solve this, you can enable continuous collision detection on the rigidbody of the fast-moving object.
Can you set a collider so that it only collides with objects with the tag walls?
Hi I'm thinking to switch to unity but before I wanted to know if there's a function to move objects in space (with slopes) or do you have to make it yourself with raycast (I'm making a 3D side view game, like mario for example).
If there's such a function does it work well ? are the physics good ?
I'm coming from godot and I can tell you that the physics are completely broken and need several workarounds...
Is there a way to calculate a surface world angle that get hit by a raycast ?
@stable shadow you can get normal of the hit
if you want a float out of this, i think you want to do Vector3.Angle(Vector3.up, hit.normal)
im trying to change a tossing function to just place the object on top of the surface if its leveled
@stable shadow if thats the case that number should be what you are looking for
i just dont know if its in degrees or radians
but it is the angle of surface hit by raycast no matter which direction you cast the ray
nice thnx
I'm trying to figure out the force to apply to a point on a rigid body, to stop that point from moving. Began with a simple test based on the point being the center of mass. But when trying to do the same thing when the point is off center. Things blow up. I guess I need help on how to adapt the force depending on the leverage gain due to the point not being at the center of mass.
Vector3 stopForce = -Vector3.Project(velocity + Physics.gravity * Time.fixedDeltaTime, -transform.up) * rigidbody.mass
This is how I've done it until now.
I tried grabbing the velocity using rigidbody.GetPointVelocity() to get the velocity at the point I want to "stop". But using the same stop force calculation and applying it on the stop-point, results in waay to much force being applied. Causing the rigidbody to spin away out of control.
@pine warren you can't stop both linear velocity and angular velocity of an object via applying one force to a predefined point?
i think there has to be at least three points and three forces for that to be possible
only want to stop the point, not the whole object.
But that might be the same issue I guess.
if the object rotates, and this point is not the center of mass
you cant stop this points movement?
working on spaceship stabilization?
No, actually a suspension-thing for a car.
I want to calculate a "stop force" when the suspension is fully compressed.
that prevents the car from rotating further into the ground.
At the same time I want it to be generic enough to allow for multiple "wheels" to be attached to the same rigid body.
Simplified scenario:
black X = center of mass. Green X = points that I want to apply force to, when the green "sticks" become to short.
this is for preventing extreme suspension cases?
isnt that already what your joints are doing?
Its to prevent the wheel/suspension from sinking into the ground (and letting the black box handle the intersection-problem)
The green sticks in my case is currently simple raycasts. If the distance to ground is shorter than the minimum suspension-length, I need to apply a "stop force" that prevents further movement of the green X
oh wait wait
so this would be like "stiffness" of the suspension
you just wanna try to stop that points velocity
right?
Yeah
Yeah. I'm using that to get the velocity
and counter it
Indeed.
Not really. Simply multiplying by arbitrary number will need constant calibration if the "wheel axis" changes...
I'd choose this method i think
Afterall, all joints always have some sort of paramaters
I'd find a nice multiplier and multiply it with the weight that suspension carries when the car is flat on ground
With some torque math
where the weights sum must equal to cars weight
and torque sums must equal zero
That would just be automatically "tuning" the suspensions pretty much
Yeah, tried a super simple approach. But it doesnt even come close to work:
var velocity = rigidbody.GetPointVelocity(suspension.attachPoint);
rigidbody.AddForceAtPosition(-velocity, suspension.attachPoint, ForceMode.VelocityChange);
It sends the whole "car" spinning away like crazy.
ForceMode.VelocityChange is equilevant to adding to velocity or setting it?
rigidbody.AddForceAtPosition(Vector3.zero, suspension.attachPoint, ForceMode.VelocityChange);
I mean maybe this is what you needed to do
But i dont know
I'm reading the docs but it doesn't seem very clear to me
@pine warren
using the basic AddForce(), and it will calculate a force that adds/reduces velocity in the given vector.
But with AddForceAtPosition, it doesnt seem to work at all. Doesnt seem to take angular momentum etc into account at all.
yeah it seem to calculate the force as if applied at center-of-mass. Comparing to my initial apprach, it gives the same result.
which is off by a LOT
Oh well, need to look up that whole interia tensor, angular velocity etc I guess.
@distant mango If it moves like 10 meters every fixedupdate, and does a 2 meter radius overlap sphere, it will not cover some area
maybe you wanna do spherecasts instead of overlapspheres
you undestand the problem here?
if thats your case, you should use spherecast
it basicly sweeps a sphere and gives you the first or all colliders it touches
spherecast has a point, radius and a direction
@distant mango it looks like you are trying to detect objects in a trajectory some lerping object makes
and if you do that with overlapsphere, you get this issue (if the object is moving fast enough)
yes
spherecast is raycast
but with spheres
Spherecast:
a sphere with this point,radius
move it in this direction for this distance
tell me what it hits
OverlapSphere:
a sphere with this point,radius
tell me what colliders is this colliding with
Do you understand what i mean here?
@distant mango
spherecast is basicly overlapsphere but in a capsule shape
because it sweeps a sphere
when you sweep a sphere, you get capsule
@distant mango spherecast will look like a capsule
and endpoint will be the next position you are going to have in your coroutine
@distant mango if you cant calculate next point, store and use the previous point
do it however you like
you should get the idea of spherecasting now
paste the code
private IEnumerator Record_Collisions()
{
Vector3 centerOfSphere = ballShoot.visualsRootObject.transform.position;
float radiusOfSphere = mainTriggerCollider.radius;
LayerMask layerMask = targetLayerMask;
float projectileDistance;
Vector3 projectileDirection;
RaycastHit hit;
Collider hitCollider= null;
while (hitCollider == null && triggerActive)
{
projectileDistance = Vector3.Distance(centerOfSphere, ballShoot.visualsRootObject.transform.position);
projectileDirection = (ballShoot.visualsRootObject.transform.position - centerOfSphere).normalized;
centerOfSphere = ballShoot.visualsRootObject.transform.position;
Debug.DrawRay(centerOfSphere, projectileDirection.normalized * projectileDistance, Color.white, 1000); // debug ray
if (Physics.SphereCast(centerOfSphere, radiusOfSphere, projectileDirection, out hit, projectileDistance, layerMask))
{
hitCollider = hit.collider;
break;
}
yield return null;
}
CollisionDone();
}
@distant mango i added a drawray
on top of your spherecast
try like this and tell me if you see a fully connected line on projectile trajectory
then its either your layermask or radius
or maybe the object you are trying to detect doesnt have a collider
maybe its about the "triggerActive" or something
i have no idea
Hey, not sure if this is the right area. I use root animation which moves my capsule collider controlled character. However, when it comes in contact with another capsule (my character attacks an enemy with melee) the player capsule will often "slide" up to the top of the enemy capsule. And it is then...floating in the air until the capsule beneath moves.
I don't want to lock Y position because I have a jump mechanic.
I asked some animators/root motion people but they said it was a physics issue. Any ideas how to stop that from happening?
does physx have a default speed limit of 100 m/s?
no
wierd
I have a rigid body that i'm applying forces to
and it just doesn't go more than 100m/s
but I'm not doing anything to cause that
the code that applies the force is still applying it
How do I make configurable joints less springy?
I want them to be more responsive and snappy
https://gyazo.com/75bf1379e62b05ebb8e2c08e9db8baeb
https://gyazo.com/12c4193c3997f4c4fda579e75af6a320
right now it looks like this
Trying to implement a simple balancing board with a hingejoint, but as soon as anything touches the board the physics spaz out and it starts spinning like crazy. Feel like I'm missing something simple anyone have an idea? 🙂
when my player object hits the board it spazzes out completely. I've locked the X, Y rotations so it can only rotate in the Z axis, but somehow it gains ridiculous amounts of velocity as soon as my player object touches it.
@median umbra you shouldnt need to lock the rotation axices
i think you didnt configure the hinge joints axis*
np
Unity physics is driving me crazy. Been debugging a issue with my hover-car implementation. Finally did a test vehicle consisting of a single rigidbody with a sphere collider. Which is pushed along my road objects. And for some reason, Unity makes the sphere bounce when moving over edges. For no apparent reason. The edge vertices of the objects both have the exact same world position.
(ignore the gray box, its simply moved to the spheres position in its Update-method, its there to make the issue even more apparent)
What could cause this issue?
Trying to find an old unity answers post i made about this issue years ago
It's a physics quirk
There's a way to mitigate it from physics settings but not totally eliminate it
The best way to fix it is find a way to turn your track into a continuous Collider
You must be kidding me?! A single huge collider sounds like a bad idea for so many reasons.
There is no way to update Physics for some objects before others, right?
It goes
FixedUpdate
PhysicsUpdate (everything updated at once)
and any physics applied at any point past physics update just gets updated next simulation frame (FixedUpdate/PhysicsUpdate)
When I turn on use gravity add rigid body still my cube stays floating in air
How to fix this
is it marked Kinematic?
@dreamy pollen what do you want to archieve by that?
@viral ginkgo 3d platformer. I am manually managing my player controller's rigidbody velocity. He raycasts the ground to determine if he's standing on ground. As part of the ground sensing, I am having the raycast collect information about the point velocity of the other rigidbody at the location of where the player is standing. This allows me to apply that velocity to the player and having moving platforms. It works very well, as you can see here
Issue is, since the environmental velocity for this frame hasn't happened yet, GetPointVelocity is getting last frame's velocity. This can lead to desync issues, especially on rotating surfaces
I'm beginning to suspect my only out here to get this perfect is some really convoluted simulating the next frame and rewinding nonsense
when the physics system adds force on an object, that force is applied to velocity after the end of the simulation step
unless you directly set velocities or fiddle with positions/rotations etc... outcome of the physics simulation should not change even if you managed update objects in a different order
Yeah, what I really need is a way to simulate the environmental physics first, and the player after that. There's no clean solution that I can see because Unity does all the physics at once
i was trying to implement something like a handbrake for example, i had a sphere for wheel
after setting wheels angular velocity to zero everyframe, my car would still slip little by little
I wonder the implications of halving my fixed timestep to double the simulation frame rate, and have some messy system that alternates updating physics each frame,
frame 1 Environment
frame 2 Player
frame 3 Environment
frame 4 Player
you could set objects kinematic to do that kind of alternating i guess
but there might be cleaner solutions
That's what I'm thinking yeah
Hrmm, let me know if you think of something cleaner... it's the best solution I can imagine yet
help
its not working
when i add a force to the cube
it still doesnt follow gravity
nor does it follow my forces
did i do any mistake
@dreamy pollen
if you calculate the change in the velocity of the grounding point,
that vector is on the direction your character sways
could do a compansation force maybe using that
@dreamy pollen try taking the moving platforms velocity and add the velocity*fixedTimeStep on top.
For rotating bodies you probably need to take the platforms angular velocity into account. Otherwise your character will probably move in the tangent direction.
Right. That's interesting, basically just extrapolating off information I already have
It definitely won't be perfect, but it might be a better outcome
And I wouldn't need to do anything too crazy like alternating physics frames
Is there a specific order to the contacts from a collision?
that's not necessarily what I was getting at - but the idea would be to make it so your rolling object is not rolling over the "seam" between two colliders
I found the unity answer I was thinking about: https://answers.unity.com/questions/568974/sphere-collider-catching-edges-of-aligned-cubes.html?childToView=1075893#comment-1075893
There's unfortunately no satisfying answer in there
even if you dig down into the more recent comments from 2015 :). Damn I've been using Unity for a long time now
@dreamy pollen you can run more than 1 physics "scene" at the same time.
yea
that's what I'm doing to support my double precision coordinate world
I create physics subscenes
and you can just manually call simulate() on them
with whatever timestep they are supposed to be simulating
@summer fog @distant coyote Do you have issues with physics between the two physics scenes not interacting with each other and having to do some jank to make them "see" each other?
@dreamy pollen they implicitly dont interact with eachother.
You have to go to great lengths
you'd end up having to solve the penetrations and resolve the collisions yourself at that point
there's an implementation of Bullet for Unity
if you really want to do a deep dive
you'll get a ton more control
Interesting, I'll look into that. I am still thinking about this option I mentioned here: #⚛️┃physics message
But I can download Bullet in a test project and play with it
any time you have large-ish intertia (angular or linear) and you find your error is a bit high
crank the substeps up
see if it goes away
TL;DR looking at a problem at 50hz can look impossible, but looking at it at 1000hz makes it trivial
in the case of solving stuff like that rotational disc
you can get away with doing real math instead of relying on GetPointVelocity for sure
(assuming its rotation is normal and not eccentric)
(see the difference between Constant Angular Velocity and Constant Linear Velocity)
Hello everyone 🙂 Is there anything that can be done to improve the collision quality of a mesh collider (non-convex)?
Main goal being to reduce "fall-throughs"
(or eliminate ideally lol)
could anyone possibly help me figure out what's wrong here
does anybody know how i can apply an explosion force in 2d?
@sullen loom Haven't actually coded with unity before, but have done some documentation reading--circle collider where you take distance from center to apply force?
if it's a moving object exploding might want to take that into account too
but generally haven't seen that much in 2d games--usually just a radius
Meanwhile, I was working on an interface for an old, traditionally 2D level format recently in my free time, and discovered someone's been working on a client for the same game for a number of years--wants to use 3D. One thing I'm wondering is there a generally good approach for transforming the tilemap concept into box colliders? I guess also he's having some issues with collisions being indeterminate but don't really know why because I'm unfamiliar with Unity aside from what I've read in the documentation so far--said something about raycasters.
Note tilemap format is sparse.
Switch the collision detection mode on it to continuous dynamic
Instead of discrete
Do that on the rigid body it is connected to
Anything that can move quickly should probably be set to that
is there any way I can add extra camber angle to the wheels using unitys wheel colliders?
I am looking for water physics for vr ( pouring water between cups) I've been looking around but i cant find anything
Obi fluid on the asset store
Do you know how I would be able to take my Vector3 movement velocity and rotate it using angular velocity?
@dreamy pollen the angular velocity of what?
a spinning object that user is standing on? ( based on context of yesterday )
yes
Here's my stab at it, but it seems like it's overshooting somehow (instead of slowly sliding outward off the platform, player starts slowly sliding inward towards the center)
OtherRbVelocity = otherRb.GetPointVelocity(groundHit.point);
OtherAngularRbVelocity = otherRb.angularVelocity;
if (groundHit.transform.tag == "Spinning Platform")
{
var projectedVelocity = Quaternion.Euler(OtherAngularRbVelocity) * OtherRbVelocity;
OtherRbVelocity = projectedVelocity;
}
the var projectedVelocity line... I have no idea what the mathematical significance of this number is... but it produces a pretty good result:
var projectedVelocity = Quaternion.Euler(OtherAngularRbVelocity * 0.239f) * OtherRbVelocity;
maybe it just happens to produce a good result, not because it is remotely "correct".
Hey guys! I have a simple question, if I am making a 2d rap with a top view, should I code my own character controller and check every collision with a overlapAll or should I instead use rigidbodies. (I don't really like rigidbodies because I fell like they are more gonna a pain in the ass on the long run. On the other hand, I want to be able to use OnTriggerEnter and things like that because they are quite useful and I hate the fact that every tick, I check all colliders inside a radius)
If you want to perfectly keep your character on the spinning object, you can use the centrifugal force formula and apply an equal force towards the center of the disc
However if you want the character to slowly slide off then use that same formula, but scale down the force by a bit. E.g. multiply by .98 or so
(make sure your spinning disc has no friction of course, or it will throw things off)
There are no rigidbody physics at factor here, as my controller is a floating sphere above the platform in question and I am manually managing his velocities
it has to do with the fact that I'm raycasting down from the player and using GetPointVelocity to get the velocity and angular velocity of the point he's floating above
GetPointVelocity gets information from the last physics update, since Unity calculates all its physics at once.
this has the effect of always being outdated velocity information and pushes the player outward in a way that looks exactly like centrifugal force
@timid dove
https://docs.unity3d.com/ScriptReference/Rigidbody.GetPointVelocity.html I didn't even know this function existed
I've been kind of going at this for several days #⚛️┃physics message
regardless of if you're managing the velocity yourself - i believe that the centrifugal force equation is the way to go
adding force is the same as changing velocity
you can use just the overall angular velocity of the disc and the distance you are from its center
I'll do some more research, thanks for sharing
i have been researching and trying for the last few days now. and i still couldn't find a solution.
How can i keep 2 or more different force sources work independent from eachother,
as Example, I want the character move ( preferably using force/velocity ), and be able to be pushed or pulled around external forces such as gravity, world events, abilities and explosions.
adding external forces with only add force, works OK. But my game is an RTS type, and i need moveToPosition type of movement mechanic, and i can't move the character at constant speed without affecting the velocity of the external forces.
I need help, advice, suggestions, anything at this point.
PS: I have been trying to move the character with transform, and apply force to it. But when both combines, it creates networking issues.
The only way out I can see is too basically zero out the external forces and take it from there
Hey all! Pretty sure that this channel would be the best-fit for the question I have, but I've been researching the SkinWidth property of the built-in character controller and I'm trying to understand the benefit of using skinWidth instead of just increasing the radius of the collider. Are there any skinWidth experts around? 🙂
The documentation has some information about the Skin Width: https://docs.unity3d.com/Manual/class-CharacterController.html
Looks like it just allows colliders to slightly penetrate one another
Yeah, thank you 🙂 Was looking for a little more than what's shown there. Was searching through the github to see if I could see how it actually works
I personally quickly abandoned the character controller for my game because I found it too simplistic, I am much more satisfied with what can be accomplished with rigidbodies
(also there were some unsolvable problems using character controller)
Totally agree -- I'm making a video on my channel explaining how to use the built-in. The more I use it, the more I realize the video is going to need an asterisk at the start stating that this really can only be used with games that don't require much mobility (like a jrpg or something)
right, I'd agree that's a fine fit for it. Great for beginners to get started with too.
For sure 🙂 SimpleMove appears to be the simplest way to get the character moving without much work
If I wanted to store a collision between 2 rigidbodies OnCollisionEnter and apply the results of that collision at a later time, how would that work?
this depends what "results" are. If you mean the Collision class that gets passed into the callback, you can store that anywhere like any other variable and make use of the data later
@glacial jolt Yup, I've got that stored, what is the appropriate way to add the collision data to the collided objects such that the velocities are "resimulated", I guess for lack of better word
hmm, it depends what you're going for. Collision.impulse will store the actual impulse applied to separate collision pairs, so that's probably the closest to what you'd want
What I'm attempting is somewhat ludicrous, but I'm trying to split my Physics simulation in half by dividing FixedUpdate into two managed Update functions, FixedTick and FixedTock
Here with a really slow timestep
The issue comes in mostly with collisions being "missed" due to the physics simulation being cut in half, and the only thing I get is what I think is called "depenetration"?
The cube is running in Tick, the Capsule in Tock.
The pink spheres in Tick, cyan spheres in Tock
You can see that the cyan sphere does not produce the correct result when hitting the green cube, as I am attempting to get them to simulate in different physics timesteps
I just want to capture that collision data (in Tick) and queue it up to be executed in Tock
@glacial jolt Hopefully what I'm trying to do makes sense... imagine two alternating 60 tick simulations happening in 120 tick fixed timestep
what responsibilities do Tick and Tock have each? Not super clear on the use case
like, do half the objects get simmed in one and the other half in the other?
Right, that's the idea
do the worlds of Tick and Tock interact at all? If not you could use separate physics scenes: https://docs.unity3d.com/ScriptReference/PhysicsScene.html
They do interact
The end result intent is just to allow me to simulate some of the physics objects in the world before others, as Unity doesn't really let you do this by default with the FixedUpdate workflow
Some of the things that I want to do in Tock rely on stuff from Tick having happened First to work correctly
ahh. So I'm guessing you want to step all the objects in Tick, for any Tick<>Tick collision pairs play them out as normal, but for Tick<>Tock pairs delay the result of the impulse added to the Tock object until the end of FixedTock?
Yes, you have perfectly understood 😄
so yea, Collision.impulse should work, by adding that vector as a force at a later time. You'll need to I guess cache the state of the affected Tock object before any collisions are calculated and restore them after, since you can't stop PhysX from immediately applying the results
(there is an experimental api for direct contact modification: https://forum.unity.com/threads/experimental-contacts-modification-api.924809/)
Hrmm, pretty clean answer then -- I'll give it a shot as you've outlined
Thank you for your help!
Here's a problem for anyone that knows unity physics extremely well. My netcode requires me to, every 20ms, have the client receive a list of all entities and move them back to a certain position and apply velocity, etc.
One thing I have to do this to, are cars, which run on wheel colliders. The problem with this, is that whenever you set the car's rigidbody's position, the wheel thinks its moving, so the wheel just spins infinitely while the car is in place and not moving.
Does anyone have any suggestions for getting around this?
I've tried setting the brake torque to infinite while the car is getting re-positioned, and then unsetting the brakes after it's finished
but that didn't do anything at all
I've even tried making the rigidbody kinematic while re-positioning, still nothing
https://gyazo.com/9e2e718650c3df33e2c2cace792f2105 How can I make my active ragdoll move without dragging behind like this?
im using configurable joints to enforce the tpose and moving the ragdoll by setting a velocity to the root to reach a target position
which i am controlling
@edgy aurora when you wanna move the body, distribute the whole force onto whole mass
each limb will be applied addforce
proportional to their masses
thanks i finally got it to work
I have a pre-build fps character it doesn't have any collider but it do have a mesh and the floor has collider so when I run the game character falls half way through it, it start colliding from the hip but legs doesn't collide
I have a small question, what would be the best way to perform a ground check on a Rigidbody?
Check if velocity.y has been 0 for some time?
Check for collisions with raycasts/spherecasts?
Set a bool in OnCollision/OnCollisionExit?
I know it may depend on the project, but I'd like to get some pro/cons for the different methods
can someone help me with this problem?
in order of ascending personal preference:
checking if velocity has been zero for some time
- can't jump immediately after landing
- can't jump while moving on slopes
- involves a float equality comparison
- probably a buggy mess
raycasts or collider casts
+- introduces techs where perfect inputs let you jump before hitting ground e.g. celeste spike jumps
- uses a layermask instead of the collision matrix, meaning higher maintenance costs and more painful debugging
- can be unreliable if the ground is bumpy
foot collider + collision messages
- behaves exactly like you'd want it to
- requires a more complicated gameobject structure involving multiple scripts and colliders
I think foot collider is probably just a generally more stable + easier route overall
if you count trying to debug everything
mm, for sure
the matrix behaves a lot more predictably than layermasks
- collision matrix
Thanks for the detailed answer!
I tried the velocity.y == 0f approach as a placeholder, and while I expected it to be buggy as hell, it works perfectly like a charm, I am rlly surprised! My "character" is only a cube atm, so it may not work for complex meshes
I don't even check for KeyDown, I check for Key, and there have been 0 issues so far, works like every other ground check I did before, with a way easier setup
I'm trying to make the car fly up in the air when it enters the trigger but nothing happens
what am I doing wrong?
this might sound like a stupid question but how do you add physics like gravity
Edit -> Project Settings -> Physics to adjust the gravity in your game
ok
Object has to have rigid body and a collider afaik
ok
If the object is set as Is Trigger I don't think physics is enabled for it
Collider being trigger or not doesn't matter for gravity. You just need a Rigidbody
If I want to make a physics explosion at a certain point in the world what method do I use?
where all physics2d objects get moved away from the point
do I do a circlecast and then add an explosion force to all rigidbodies?
wantedRotation = Quaternion.LookRotation(this.transform.up - Vector3.up);
transform.rotation = Quaternion.Slerp(transform.rotation, wantedRotation, rotationSpeed * Time.deltaTime);
Im trying to "selfbalance" an object, if it starting to flip, i want to turn it to point it's up to world up, somehow this isn't working correct, it changes the direction sometimes
anyone has an better solution or fix? Lowering the center of mass is somehow not working correct, i think because im not on the ground.
We are using a rigidbody2d thats kinematic so we can do our own gravity and stuff, our trigger is completely inconsistent. I tried messing with the fixed step, but that would only if you using dynamic and moving things in the fixed update right?
Directly setting transform.rotation is not the right way to deal with a Rigidbody. You want to use AddTorque.
If we have a 2d sprite object with its pivot set to the bottom center, is there a way to still rotate the the object based on a center pivot using offsets?
The pivot being at the bottom helps with the spline following code we doing
Center of Mass is in Local Coordinates to the transform's origin
There's a bug with configurable joints: the "edit angular limits" gizmo should appear at the anchor point of the joint (defined by a localPosition relative to the joint's parent), but instead it appears relative to the connected body object
only seems to happen when the joint is created at runtime though
not sure if it is linked to any other issues but it's possible that the incorrect force points are being used in some cases
Say you have 200 rigidbodies in a scene. If those 200 rigidbodies are moving, is it going to be more CPU intensive than if they weren't moving?
@unkempt summit Look into the Sleeping mode. From the documentation: Sleeping Mode: Define how the GameObject “sleeps” to save processor time when it is at rest.
Want me to DM you the link?
I think I know what that is
just wanted to know how much CPU its going to save
Don't rigidbodies automatically sleep when not being fucked with?
Well, my educated guess is that it will skip the fixed update for the rigid body, so if it's only a rigid body, it will save a lot, but if you have a lot of custom behavior or other classes attached to it, it will not be as significant.
alright
But to answer you other question, a non-official source says: When Rigidbodies fall to rest - a box landing on the floor - they will start sleeping. Sleeping is an optimization which allows the Physics Engine to stop processing those rigidbodies. This way you can have huge amounts of rigidbodies in your scene as long as you make sure that they normally don't move.
uhh
something is wrong
my enemies have triggers that detect the player
they are all set to istrigger and have a layer that only interacts with the player
now I have on the player a trigger at the feet that collides with ground and stuff
but it still registers the enemy trigger colliders and adds them
which results in super weird behaviour
I can float in the air whenever I'm in one of the enemies range
Here is my ground detection collider
and here is the player detetion trigger on the enemy
both are set to istrigger
what's wrong?
I thought triggers don't interact with other triggers
They do (in terms of firing messages), the matrix looks like this http://help.vertx.xyz/?page=Programming/Physics Messages/3 Trigger Matrix 3D
They won't physically interact with each other though - triggers don't cause physical collisions
A way would be to have a custom filter in your OnPlayerEnterRange (or ther other one) that skips undesired hits
yeah, then no problem
I think you can have your trigger collidables all in a certain layer, and make them not interact with that layer
Or manage the layer based collision settings to filter them out if possible
I think I can just check
Or that 🙂
You can, but filtering with the layer would probably be more efficient. I'm not talking about significant difference here, though it really depends on your use case.
@timid dove i know it can cause issues it's just for the example, using torque makes it even more complicated, but if i know whats wrong and the wantedRotation is right, i can start using torque to reach the wanted rotation
@distant coyote i think i take that into account, i set the origin in start with rb.centerOfMass += new Vector3(0, -anynumber, 0);
hey Guys, i have a weird problem and not sure if its from the unity version or some kind of other problem
i'm going through Udemy tutorial with Unity 2019 version and there we have a basic code like this:
public class CheckpointController : MonoBehaviour
{
public string cpName;
// Start is called before the first frame update
void Start()
{
if(PlayerPrefs.HasKey(SceneManager.GetActiveScene().name + "_cp"))
{
if(PlayerPrefs.GetString(SceneManager.GetActiveScene().name + "_cp") == cpName)
{
PlayerController.instance.transform.position = transform.position;
}
}
}
private void OnTriggerEnter(Collider other)
{
if(other.gameObject.tag == "Player")
{
Debug.Log("hit cp" + cpName);
PlayerPrefs.SetString(SceneManager.GetActiveScene().name + "_cp", cpName);
}
}
}
and the idea is when player dies to respawn(reload scene) on last colided checkpoint (simple 3d box)
but im currently with Unity 2020.2 and this is buggy and it spawns me at center of the map and sometimes on the given checkpoints
i found about Physics.SyncTransforms(); and when added it after PlayerController.instance.transform.position = transform.position; its working normally...
is this the new way of working with player setting position?
this is how scene looks and each checkpoint have unique name
https://webmshare.com/1Z3jx
video example
anyone have any ideas?
{
public CharacterController controller;
public Transform cam;
public float speed = 6f;
public float gravity = -9.81f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
Vector3 velocity;
bool isGrounded;
public float turnSmoothTime = 0.1f;
float turnSmoothVelocity;
// Update is called once per frame
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;
if (direction.magnitude >= 0.1f)
{
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
transform.rotation = Quaternion.Euler(0f, angle, 0f);
Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
controller.Move(moveDir.normalized * speed * Time.deltaTime);
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
}```
im trying to make gravity but when i fall i stop moving if im not moving forward. so pretty much if im
not moving my character freezes and floats in the air
@twilit kettle looks like you arent doing any gravity where you should have, when these conditions are satisfied:
not grounded
&
velocity.y > 0
&
no WASD buttons pressed
so you jump, hands off keyboard and you character floats in the air as i see it
and if you try to move via WASD, it will fall down again
.
either way, you should be doing this: velocity.y += gravity * Time.deltaTime; anyways regardless of what player does
and also velocity.y = 0; when grounded
i dont know what will character controller do if you tried to make it move into the ground too hard
how can i improve this?
i'm using rigidbody 2d, capsule collider 2d and hinge joint 2d
this seems to be the max height too
Hello, where should I start if I want to code a custom 3D pendulum effect (like a character swinging a rigid rope) without using the configurable joint, if its even possible? When I look online, most of the thing I find use some type of Unity joint, and I feel like its either not what I am looking for (spring joint) or overkill and super complex to set-up ( configurable joint) . Is there an algorithm out there that could be my solution?
@fresh bane You asked that forever ago, but I would just tweak the inertia to have it come to rest faster.
There's this asset which uses its own optimized custom physics implementation: https://assetstore.unity.com/packages/tools/physics/obi-rope-55579
Why it is not shaky and natural?
Hello, I am trying to lift the Tire/Wheel using the bucket of the excavator. I have tried adding Rigid body and colliders but no luck so far... Any suggestions on how this can be achieved?
Has anyone messed around with this library yet?
We were trying some stuff but Unit's animation system isn't communicating with this i think
https://assetstore.unity.com/packages/tools/physics/ggphys-183465
@heady kraken That's going to be extremely weird and wonky with physics alone
not to mention, you're going to want a bucket that scoops upwards
not downwards
@unkempt summit I can control the bucket movement.. Any alternate solutions to make this work?? Attaching the reference to what I am trying to achieve
@heady kraken You will need a detailed circular collider for your rigidbody
with a hole in the middle.
for the tire
Oh okay... Circular collider as in Mesh collider? @unkempt summit
I'm not sure, I've never really used mesh colliders
You'll just need to find a way to put a hole in the middle of the tire
as a collider
so that the crane is able to grab it on the inside
@unkempt summit Yup that is exactly what I am trying to do... But not found a way yet... Thanks for the suggestion!
mesh collider will probably work, but they're very resource intensive
Another problem with mesh collider is that it has to be convex if a rigid body is used... And convex does not work for hollow Gameobjects (That have a hole)
Does anyone know how I can implement an aerodynamics system like Kerbal Space Program?
thank you
how about making a donut shape with box colliders?
might work decently
concave colliders wont work with rigidbodies
Guys this answer has been on Quora for 2 years, it has nearly 3k views and 3 up votes, but is it correct. Are those equations correct?
Distance=Speed/Time
Speed=Distance∗Time
Time=Speed/Distance
Shouldn't it be:
distance = speed * time
time = distance / speed
speed = distance / time
?
https://www.quora.com/What-is-the-product-of-velocity-and-time
if I jump into the wall and hold W it sticks to the wall how can I fix that?
@modest zodiac That looks like a troll answer to me. Yes, your equations are the right ones. To figure it out for yourself, use units.
For example: What's a units of Distance, Speed and Time? (an example)
Distance: m
Speed: m/s
Time: s
So if you use their distance formula, you'd end up with distance being in m/s² instead of m.
Gotcha. Thank you 👍
Can anyone help me with some simple physics
How would you rotate a rigidbody through code?
Add Torque rotates it endlessly
MoveRotation gives me errors about quaternion not being in a correct unity
and angularVelocity is the same as AddTorque
what is your code
I'm having trouble with Colliders
OnTriggerStay doesn't seem to function
correctly
Anyone have a good free interactive water asset you can recommend?
@last narwhal Don't cross-post. And this has nothing to do with physics.
Cross posted on general because I didn't know where this question falls. Has to do with physics because I want the water to MOVE based on colliders and forces. Thnx for mod-ing @frigid pier
@last narwhal Still has nothing to do with physics system. You'll need to fake it, preferably with shaders. Next time you'll get a warning for cross-post.
Thnx for the heads up. Will keep in mind. Found what I was looking for without having to mess with shaders 👍
I haven't written any yet, but im gonna write a script to replicate a car and fake the 'wheels'
hello there. I need help with collisions. I need my collider to collide with something, but not to transfer its force to the colliding object (when a bullet hits you, you don't fly 200 metes away) how can I achieve it?
howdy! Have a really newbie question...
I have a seat object and a character animated on it. Now im rb.AddForce-ing the seat hoping the guy the guy would move too (as he is "sitting" on the chair the force is being applied to...) But.... The force makes the seat float through the guy, leaving him in place... I feel like there is some parenting to be done... But how? Seat to the guy? Guy to the seat? Both to EmptyGameObject?
Shot in the dark but.... Delete onTriggerEnter?
I am not using one