#⚛️┃physics
1 messages · Page 26 of 1
Here you can see with 1 object, the relative velocity (in the first Debug.Log message) is returning a value that's very close to the speedLastFrame value (second Debug.Log message). That variable is being updated every FixedUpdate cycle in my code
But when it's two objects connected with a joint, the relative velocity is significantly lower. In fact, before, it would sometimes register nearly ZERO. I found that attaching a physics material to the walls seems to have stopped it from being that far off, but it's still wrong? Not sure what's up here, could it have to do with the walls being set to static rigidbodies?
You can ignore the 'my speed at moment of collision' part. I know that rigidbodies tend to report their velocity wrong at point of impact. I'm comparing the relative velocity (aka Collision.relativeVelocity) to the SpeedLastFrame value.
**Okay... so I "fixed" it by turning off Enable Collisions, now it's showing values you'd expect. **
Why would that fix it, though? Is there some glitchy thing with the two obstacles hitting each other maybe?
I am making a first person game I have attached a physics material to the player to stop getting stuck on walls which fixed the problem getting stuck on walls but now when moving around the player slides how can I fix this?
Yeah but I can make collisions through script as well right? ... Since I'm already simulating gravity and rope physics through script, I can add collision detection and reaction through scripts too right?
you don't "make collisions through your script". The collisions happen in the game world. Your script can react to them
That's what OnCollisionEnter is for
I'm not making collisions, I'm creating detection for the collisions through scripts
So if the rope segment is too close to the ground collider I will reset it's position to where it isn't colliding with the ground
Using raycast
Yes Unity allows you to react to collisions in your scripts
Ok cool..let me explain a bit more what I'm trying to say
1 sec
I'm uploading a recording of what I made
the green lines are raycasts which i will use to check for collisions..(if ray hit too close to ray origin then resolve rope segment accordingly)
is this a solid method or does it need some tweaking?
Do the segments of the rope not have colliders?
Why not just give them colliders and let the physics engine handle collisions for you?
no they dont
if i give them colliders then i will have to resort to the blocky version of rope
i will try that if this doesnt work
but this way will be visually more accurate
i remember u said something abt bezier curves so it wont be blocky looking
Visuals don't need to match the physics representation.
I'm intending to make a flight simulator in Unity, I kinda know already how to build the physics but I'm having issues with the colliders, I can't make myself into the airplane without tresspassing it or getting ejected from it, do anyone have tips or videos to help with that?
You'll have to be more specific about what your issue is. Generally for such a thing if you have some kind of player that is walking around you would pretty much completely disable or destroy the player when you enter the vehicle
so collisions wouldn't be a problem
Ohh sorry for not being specific..
I mean, the whole game will be inside the cockpit
but i want the player to be able to "walk" inside the cabin just like Microsoft Flight Simulator
but I can't get the collisions to work
I've never heard of such a thing in microsoft flight simulator lol
but the best way to do that is to use a separate physics scene
with dummy objects
holding alt, with the arrows, you can move your camera onto the whole aircraft (when they have an interior made besides the cockpit)
that's just a child object of the plane
no physics involved
you wouldnt give the player a separate RB
ooooooh
Im having an issue in my game where the player character asset isnt falling down at all. I have a rigidbody on the player character, use gravity is on and gravity in the settings is set to -9.81. i havent frozen any of the positions, only rotations. when i play, the character is suspended in the air and only rotates around according to wasd key movement, but doesnt change x, y, or z coordinate. what is the problem?
sorry for the 'essay'
maybe it's resting on something
Or maybe your code or some other component is constantly moving it to the same height
could be a lot of things
you'll have to show more details
It would be helpful to see:
- The inspector of the character (showing all components and their setting)
- Your code
- scene and hierarchy especially with collider gizmos showing
Does anyone know why something with a rigidbody and box collider keeps clipping through a floor with a collider? The object moves using rigidbody force.
Does it also rotate using torque?
looks like an object your player is holding perhaps?
Can you show how the movement works?
surely not given the constraints on it
Yeah that's what I mean, it's strange that it's tilted but all rotation is constrained
yep
Oh I figured out what it was. There's a slight correction at the end to straighten it out and that correction wasn't slight enough.
Anyone know a tool, or have suggestions how to approach this problem?
I want to define "zones" in my game similarly as seen in the video. When the player enters a zone, I plan to module SFX and similar. To do this, I need to be able to quickly draw the zones (preferably in a similar way as shown in video - 2D); The zones can be non convex shaped but may consist of multiple convex colliders if that is possible to achieve quickly.
Also off topic, but what happend to ProBuilder :V The PB Window is no more 🤔
#🛠️┃probuilder for that question (no idea)
as for this - well where did you get this video from?
Looks basically like drawing a 2D shape and then extruding it. Dunno if PB can do that or if you would need to make a custom tool (or just use whatever tool is in that video)
I have a very odd problem.
I implemented crouching in my game by changing mesh in Mesh Collider, in editor everything works fine but in the game's build player falls through the ground when crouching. What should i do?
Why are you using a mesh collider for the character in the first place?
In most cases, a primitive collider like capsule would do.
i want use cylinder as collider
i used to use capsule but it allowed the player to jump too high with edges of platforms
This is my video, just used PB to illustrate what kind of behaviour I'm looking for specifically. Doing this by hand (placing collider triggers) is too time consuming
What I'm looking for specifically is and am curious if such a tool already exists (the detection part I already have):
- Draw a shape
- Make it into a volume
- Convert volume into smaller convex shapes if needed
- Set
isTrigger=true - Detect enter/exit events
I think that's way too niche/bespoke to have a prebuilt tool ready to go for it. You can build such a thing yourself as an editor tool with the ProBuilder API.
I have an issue with raycasts, im making a flight sim game and i want to do interactane cockpits(meaning being able to physicaly click on buttons in the cockpit with my cursor) however the plane along with the camera and colliders is moving at mach 1.2 meaning it doesn't register the hit even when the rigidbody is set to continous dynamic. is there anything i can do
You're going to have to do a lot of "smoke and mirrors" type things in such a game to get it to work properly.
I would probably have all the internal cockpit objects exist in a separate physics scene that isn't moving at all, and do the raycasts there, using the camera's local position inside the cockpit as if it were at the origin in the separate scene.
i guess that would be best but also the most complicated, on the plus side it would also get rid of the vertex snapping happening at long distances
yes
you'll still have to deal with that for the main game world though
You'll want to be using floating origin for that.
I'm trying to do raycasts from the camera to the world, and get a single hit. For game logic reasons, the ray shouldn't collide with the character the camera is following.
I remember reading somewhere that raycasts are not at all times guaranteed to be in order of closest to furthest, I'm asking because I'm interested in EarlyOutOnFirstHit so the engine just stops processing hits ASAP, but this wouldn't work as expected if hits aren't guaranteed to be in order?
a regular raycast always returns the closest hit
if you use RaycastAll, the results will not be sorted by distance
public struct IgnoreFollowingEntityCollector : ICollector<RaycastHit>
{
public bool EarlyOutOnFirstHit => true;
public float MaxFraction { get; private set; }
public int NumHits { get; private set; }
Entity followingEntity; // Entity to ignore
public IgnoreFollowingEntityCollector(Entity followingEntity, float maxFraction = 1f)
{
this.followingEntity = followingEntity;
MaxFraction = maxFraction;
NumHits = 0;
}
[BurstCompile]
public bool AddHit(RaycastHit hit)
{
if (hit.Entity == followingEntity || hit.Fraction > MaxFraction)
return false; // This is the very same Entity we are following, bad!
MaxFraction = hit.Fraction;
NumHits++;
return true; // This is valid! Winrar
}
}
the ray shouldn't collide with the character the camera is following
This is best accomplished via layermaskes
I know this is an alternative but I'd rather not mess around with layers with the player character just so the raycast from the camera that is following the Entity doesn't collide with it, and making a layer just for 1 game function seems silly.
But yeah the main reason is that the raycast doesn't have to collide specifically with the Entity that is following, meaning other characters has to collide
but if results are in order it'll be fine then.
is there a quick list about what returns in order or not? I'm also interested aboutSphereCastCustom
Not sure if I'm blinding it in the docs?
Hello
I want to override a box collider 2D by an another box collider 2D which will exclude a specific layer. So, I create a box collider 2D and put the layer Override Priority higher than the other collider 2D (put at 10) and exclude the layer I want (Player). But, when I launch, it doesn't work, why ?
I verify that my player have the player layer
I want to override a box collider 2D by an another box collider 2D
What do you mean by this? Colliders cannot "override" other colliders
are we talking about a prefab instance or variant or something?
And what does "launching" mean in this context?
I have a very small project; is there anything I can do about the skin width with dynamic rigidbodies? Do I just have to scale up the project or start using kinematic?
reduce the default contact offset and/or move your graphics down a little
I've tried the first option, but unfortunately it still leaves the noticeable gap. Any lower and the player does begin to bounce into the ground on contact. As for the second option, I can't see that working without making the probably worse in the other direction: the ceiling collision would look worse twice over, right?
not if you make the collider shorter
there's no reason the collider and the sprite need to be the same height
got an oddball "optimization" question and curious if anyone here knows but what is better?
- physics object with individual primitive collider game objects (that approximate the shape of the object)
- physics object with many primitive collider components on the same game object (that approximate the shape of the object)
my workflow for physics objects has generally been just spawn unity gameobject cubes/spheres/capsules and scale them to approximate the shape of the object, and then just disable (or sometimes remove) the mesh filter/renderer components
but is the latter here better? I imagine it is but just curious
does this seem like a correct way to have the hand pull the body around? its a very basic _torso.AddForce(-_pullDirection);, which works, but it feels a bit fake and floaty
It really depends on what you're going for. How about a spring joint?
i was using a spring earlier to attach them, and reduced the springs distance as the pull got stronger, but it ended up not working out. Currently only a distance joint connects them now
NEW stuff at Rungne! ► https://rungne.com/collections/all
Music and Sound Effects: http://share.epidemicsound.com/vSnfn
(30 day free trial)
- Drawn to You
- Sunset Road
- One Hundred Times
- Right There
- Woven
- Lasers And Stuff
- Drop dea...
Only hard bouldering!
Sponsors:
- Toyota
- Scarpa
#4K
im trying to match the way a hand would pull up a real body, like this guy does (minus any time where he pushes up with his feet)
should I have a spring that i can contract as the torso of pulled towards the hand, then start applying an upwards force once the torsos y position is higher than the hand?
Ok you're trying to do a rock climbing thing
that would be FixedJoints or DistanceJoints for sure
BOULDERING MENTIONED
Hey! I made a full body first person controller by watching a tutorial. Walking/strafing left-right doesn't cause any issues, but when I walk or strafe (?) forward or backward, my camera behaves weirdly. I've attached a video. What might be the issue?
This is my player controller script: https://pastes.dev/OHxU8FYs0J
I assume this is the right place to ask this, correct me if I'm wrong
Definitely not a physics problem
Also I don't even see what's wrong in the video
Thank you
When you walk forward, the camera behaves in a way it shouldn't, isn't it obvious?
I'm walking forward without even touching the mouse and the camera rotates to left and right, just a little bit
I have no way of knowing what you're doing with your mouse]
Turns out I didn't choose Bake Into Pose for walking animations, fixed now 👍
I am creating a ragdoll character by following Happy Chuck Programming's video, when I try to animate the ragdoll character to walk, it automatically faces the floor.
I can I fix this issue? I have added a physics material to my player cause he kept getting stuck on walls but somethings when I am on the edge like in the video it becomes slippery and sometimes the ground is slippery as well.
i import this model to unity, give it a mesh collider and it crashes
can anybody tell me why?
Are you aware that the model has 1208320 triangles? That is magnitudes too much for an game asset. Most likely just using a single box collider for the dice would be enough for a collider, depends what you need it for. If it is just a small prop among others, you would want to use at most couple dozen triangles on it and a texture to draw the dots. If you are making a game about ant walking on top of small everyday objects, then you would need bit more details, but definitely not million triangles.
but i love triangles :(
Computers don't
anyways thank you for the help :)
dw ill make unity love it
This is something you would see in a blender horror movie
@hazy hill so what is this asset supposed to be used for?
awwww its not that bad it just... alot of lines... yeah
oh just learning blender and making models, i should really go for low poly stuff but wanted to try some high poly stuff
that's more than million triangles that the GPU needs to render separately, let alone the amount of computation needed by CPU to do collisions with when used as a mesh collider. You would only want to use the minimum required level of detail and not add more triangles because you can. Even if you needed very high quality visual mesh, the physics shape can usually be much simpler (like a simple box collider or a mesh collider simplified by a lot). Btw. you can use different meshes for a mesh collider and the visual mesh so you can use simplified one for physics.
so wait if i just use a box collider im good yeah?
and yeahh i should remove some faces ig
sort of. If you don't need mesh collider, don't use it. It's in general bit heavier than the primitive colliders. You wouldn't definitely want to have the visual mesh anyway near that level of detail though. Game assets and high quality render assets are very much different
ohhhhh so like its fine for rendering but not for a game your saying
That would indeed be fine if you just wanted to use it to render something in blender. As said, in realtime applications you would only want to use the absolute minimum amount of complexity required to meet the visual quality requirements.
thats some helpful information actually thank you!
If it is just a small side prop, even something like this would be more than enough to look good when combined together with a texture that has the dots and a normal map to make the dots look 3D
I think in blender there's even an option to use the high quality mesh to bake the details into the low quality one in a form of normal map. Don't really remember how to do that exactly though
ive put it into my playlist thank you so much for the help!! :)
This is what I got with the above mesh with color and normal textures baked from the high resolution mesh. Especially if it is a small prop, the player would not notice anything wrong there
Even if I do change the value to stop the player sliding another issue happens where the player will slow down when colliding with the wall
and I get stuck on corners when jumping on something
and you used the vid you linked to do it?
yes, for the normals. It doesn't explain the color baking but it's pretty similar process
I apply force of (9999999999f, 9999999999f, 9999999999f) using AddForceAtPosition, Impulse mode, and the target rigidbody has 0 damping and 70kg mass.
And it doesnt move at all.
I set the mass to 0 and it flies to the end of the world
Im wondering whats going on, I know Impulse mode uses RB's mass but no way 70kg would cancel such huge force
rootRB.AddForceAtPosition(hitPoint, new Vector3(9999999999f, 9999999999f, 9999999999f), ForceMode.Impulse);
Got it to work with normal .AddForce
Hi! Any idea on why my player movement feels so floaty?
also the slope movement feels horrible, small bumps shoot you in the air
presumably... it's your movement code.
player movement is basically getting a vector2 from Unity's Input System and set X and Z velocity
you're probably inadvertently setting the y velocity to 0 in that process too
e.g. you're doing rb.velocity = movementVector;
and movementVector's y component is 0
i dont think so, i just set the X and Z values
that's a very common pitfall
exactly
so y is 0
show your code
i use playmaker / visual scripting so idk if you can help me but its simple
i basically set the X and Z floats every frame, and Y is none what means its usually unaffected
i don't really know how playmaker works but I would try feeding the rigidbody's current y velocity back into y here explicitly.
it changed nothing, im also pretty sure none means its unaffected so makes sense
unless ive done something wrong
then some other part of your script/code is doing it
how are you actually handling the jumping part
adding Y force/velocity
In C# "none" isn't really an option so i'll chalk that up to unfamiliarity with playmaker
show it
i mean jumping only activates after a key press, player is always floaty
What's the rigidbody drag set to?
check if grounded, true = "add force"
or having very large objects
(Linear damping in new unity versions)
i didn't change anything on gravity, nor did i scale the objects up (player is a 1x1x1 default capsule)
Alright then - this?#⚛️┃physics message
Ok thats not the issue then
We did discuss that
Oh
its a 1x1x1 default capsule
Based on everything you've shared so far it should not be so floaty. So... something is happening that's not part of what you've shared thus far
can you show the inspector for your player? What are all the components on it?
ive made a no friction mat for the player collision, but the default friction changes nothing (and makes the player stick to every wall/surface)
friction shouldn't matter while it's just in the air not touching anything
there is another script that sets the playerSpeed variable when pressing shift, thats all
can we see that one?
We actually haven't seen the full script yet for either script. I know it's in PlayMaker but it mnight be helpful
there is no "full script" in playmaker, its connected nodes and all the script is separately in every node
ok so the Move node looks like what
Ok really dumb question here. What happens if you just remove or disable the playmaker graph entirely and place your player high in the air in the scene?
Or any other random unity rigidbody cube without any script
does it fall at a normal speed?
already tried it, same thing
super floaty
What about a default cube
also floaty?
If so then you should just go check your physics settings
also your Time settings
it really feels like the player is a balloon, and hitting any bump or walking up a slight slope shoots the player up in the air
Check the default cube
where can i find the time settings?
Project Settings -> Time
those look normal... I still wonder if default cubes fall normally
everything is floaty
Not sure how to print things in playmaker but can you do like Debug.Log($"gravity: {Physics.gravity} time scale: {Time.timeScale}"); in Update in a script?
perhaps one of your scripts is changing the gravity or the time scale at runtime.
like read the gravity and time values at runtime?
using UnityEngine;
public class Test : MonoBehaviour {
void Update() {
Debug.Log($"gravity: {Physics.gravity} time scale: {Time.timeScale}");
}
}```
yes
you can plop this C# script on any object in the scene to do it^
and then look at the console while the game runs
here are some rigidbody "cubes" falling
those do look a little slow
Does it happen in a fresh scene?
I mean the default cube test, do that in an empty scene
No playmaker scripts, no extra objects or anything
Just to narrow the issue down
slope boosting might be the player movement script that tries to move straight instead of walking "up"?
(Also what is gravity weight? Are you using root motion or something?)
yes
So what about this @grim kernel
what does that mean
if you're talking about animations then no, player has no animations
Okay I just saw this in your video so I was wondering
oh thats just something that showed up because i searched for "gravity"
Anyway im out of ideas. Might be something related to playmaker that I dont know
Does the player have any children or other components you havent shown?
yes alot actually
but its mostly empty objects for pivots, and the camera
i just added playmaker scripts onto the cubes and they still behave normally
Does any of the children have rigidbodies or colliders?
nope
all pivots and a camera
oh and audio sources
plus a trigger area, just a collision
PlayerTrigger does not have a collider?
What kind of collider 2D can I use for meshes generated in mesh chunks?
Well no 2D collider will automatically work with mesh filters, but you can use PolygonCollider2D or EdgeCollider2D for arbitrary shapes.
and I suppose I have to code the collision shape since it won't just shape itself
I am creating a ragdoll character by following Happy Chuck Programming's video, when I try to animate the ragdoll character to walk, it automatically faces the floor.
Link the tutorial you're following, and where in it you are?
https://www.youtube.com/watch?v=iNLQCwCHEBM&list=PL9gnJgSxuivEf8D6upAd5aNj6H4OFWt4m&index=4 Around 11:40
Unity Ragdoll Tutorial - Animation With Physics - Gang Beasts Style - Part 4
Hey Buds,
If you are having issues with copying the animation, please look at the reply to the pinned comment.
Welcome to Part 4 of the Unity Ragdoll Tutorial Series.
In this one I show you how to animate your ragdoll while allowing the limbs to be affected by physics...
I created a script that add point to the polygone 2D collider here: But I don't see the gizmo line and player dont collide.
Note that the positions in the Collider should be in local space
It looks like your positions are starting approximately at the object's actual world space position so I'm guessing you used world space positions in your code here
By local space do you mean I should use integer for vector2D ?
or using transform position
No..
I mean local space coordinates
instead of world space
you can use transfom.InverseTransformPoint to convert world space coordinates to local space coordinates (just make sure you're using the right Transform)
I fixed it.
hey everyone
Given a track's metal barrier such as this, what is the best collider to use? Mesh collider is far too expensive for my taste and doesn't work when I use it either for some strange reason
I just need to collide with the barrier walls, so something as simple as a plane approximating the curve of the barriers should be emough but there is no way to collide with such a thing
My first instinct is to just use a bunch of BoxColliders
That is what I had in mind as well, but I felt it would be a messy way to apprxoimate it
especially if the track changes
There is no 'plane' collider in Unity from what I saw
if the track is using a spline system (i hope it is) it would be pretty easy to generate teh colliders programmatically
that is, a collider with a zero-thickness plane in 3d space
otherwise any time you want a collider that's not one of the primitives, your only option is MeshCollider
hand-modelled unfortunately, I modeled it by arraying road segments along a spline in Blender
the basic Plane object uses a MeshCollider that is like this
The spline is only in Blender
hold on give me a second
this is what I mean by a plane
A single-sided 3d object, or a 3d object that is infinitely thin
a mesh collider cant work with this since it is not convex right?
I mean I understand what you mean
MeshColliders don't have to be convex
they can be convex or concave
but then they significantly hurt performance right?
I still think BoxColliders are the best choice though
Hmmm I see
Could be - but the main limitation is Concave colliders can't be on a dynamic body.
well I have the splines representing my track as an SVG. How do you suggest I bring them into Unity? I've read about this technique before but I am not quite sure how to do it
I don't know of a quick and easy way to automate that particular workflow
probably find an SVG parser and then use the curve data to generate box colliders
you could also maybe do something with the mesh - like put some marker objects at each juncture and use those to generate the colliders
Sure!
thank you!
wait i didnt mean the colliders
I meant creating the road itself using splines
Oh - I would recommend Unity's Spline package https://docs.unity3d.com/Packages/com.unity.splines@2.8/manual/index.html
You can do it in many ways
you could do everything at design/edit time if you want
or you could set it up so it gets genrated at runtime
How to get gravity vector in C# that was set in project settings?
Physics.gravity.magnitude I guess
Just Physics.gravity, unless you actuall want the magnitude of it
is anyone a expert on raycasts? i have a strange issue were my raycast hits, but if its a object thats transforming towards the player, it hits slightly inside that object
(any suggestions?)
When are you doing the raycasts? How is the object moving?
The physics scene is only updated during the physics simulation step, which doesn't happen every frame and is right after FixedUpdate
if you're moiving the object directly via its Trasnform in Update, for example, then the physics representation of that object may lag behind a little.
just a simple object transform, no ridgid bodies etc
yeah that's your problem then
you have essentially two options:
- Raycasts need to go in FixedUpdate so they're happening in cadence with physics updates
- Youneed to manually sync the transforms to the phyics system before doing your raycast (can be nonperformant, depending)
as its a object transform and not a ridgid body, would it be classed as physics still?
this is my ignorance so my apolgies
lol
i will attempt those suggestions asap, thank you kindly dude
it currently uses a simple box collider, and sometimes mesh collider. it has no issues hitting if the object is hit as it transforms away from the player, or when it transforms side to side, it seems to only be head on.
il get to trying those changes and see what happens, thanks again 👍
yes of course
colliders
raycasts
these are all parts of the Physics engine
As a general rule of thumb though any object with a collider that moves should likely have a Rigidbody
even if it's kinematic
il keep that one in mind, as i have used it in other parts, as it seemed to help collision better.
fast moving bat can't collide with objects, i tried collision detection "Continuous" and interpolate to "Extrapolate" but still same result object pass trough without colllide
Check out this video by Bennet Foddy, he goes into this exact issue https://www.youtube.com/watch?v=NwPIoVW65pE&pp=ygUUYmVubmV0IGZvZGR5IHBoeXNpY3M%3D
In this 2015 GDC talk, QWOP creator Bennett Foddy explains how to make your game feel solid without writing your own physics engine or breaking your entire game.
GDC talks cover a range of developmental topics including game design, programming, audio, visual arts, business management, production, online games, and much more. We post a fresh G...
Hi everybody. I am dealing with an issue where I have small balls that are attached to my humanoid joint chain to visualize it's "joints" for the audience. For some reason they are flipping out and throwing the agent around the entire map.
It doesn't happen without these balls, and I believe it has something to do with the joint that it uses... I tried upping the linear limit in case it was freaking out due to being too constrained but no luck. Any ideas?
Is the physics debugger working for anyone in Unity 6?
For whatever reason everything is invisible. I'm trying to visualize stuff via the rendering tab and I'm not getting anything
Nevermind there were like 5 overlapping black menus bottom right and one of them were what I wanted
Can someone help me? I am (somewhat) following a movement tutorial, and I made my own dash system. whenever I dash into a slope / corner, my player will fly into the sky, depending on the angle.
https://youtu.be/FV8AezXf3vM
Excuse me, I'm having some problems dealing with rigidbodies themselves. I have a player character with its own rigidbody. I have items in the world that each have their own rigidbody. When i pick up an item, i want to "give" the colliders / object to the player, and parent to player. (make the rigidbody not work at all). When the player drops the item, i want to let the rigidbody come back on, and let it handle moving the items. If i did just Destroy(rb) and AddComponent(rb) i would have to store every single value on the rb to set them after adding. what ways are there to keep a rigidbody reference while "disabled"? (I need it to be able to collide while in players hand, and recieve OnCollisionEnter callbacks)
One option is to make the colliders and renderers of the object into a prefab (which is a child of the RB). When you grab the object you could instantiate just the colliders/renderers part as a child of the player. When you let go you could either respawn the original object or re-enable it.
Yeah ok, that is an option i didnt think of, thank you. I wanted to keep all the data of the objects, and didnt wanna have to create 2 seperate objects for ground/hand, but that would work.
How do you render thousands of particles to generate a fluid like simulation?
Compute shaders and/or the job system
Anyone know of a general performance comparison between PhysX and Unity Physics in DOTS?
hi, i have a question, im making a 2D game, and...why my character glues to walls?
everytime i jump towards a wall, this one sticks to it till i jump, how i can fix it?
very common pitfall
likely due to your code pushing hte object against the wall and then friction is holding it up
your options are:
- make your code not be able to push the object against the wall midair
- get rid of friction (via physics materials)
what if i have 0 friction on the player?
or what would be a desirable amount of friction for dont make consequences and not stick to walls
I mentioned that as an option, yes
no i mean, the issue is friction, but i thought the plan was to lower it no delete it, so if i delete it, it will be ok?
no consequences, like, it will be slippery?
how do you use joints to make a car im trying to do it but when im rotating the wheels the car jumps and doesnt move but when I dont rotate the wheels it can move
anyone ever had it where rigidbodys slow the game down to almost a freeze? only noticed it when i upgraded unity to latest
ah degraded to .45, is fine again, guess some issue with ..47
Normally you dont use physically rotating wheels, the physics engine isn't really built for that
Try wheelcolliders perhaps
one approach that I find works nicely, is to a box and sphere rigidbody, and connect them with a hinge. Force can be applied to the box, which will roll the ball forwards, and you can steer by applying torque to the box to rotate it
ive found the wheel colliders unity have are very jank, sometimes dont actually roll in a straight line, overall they feel really inaccurate
plus settings it has that arent always desirable, like slipping (which makes them more physically accurate, not great for arcade type vehicle dynamics), have no way to be fully disabled. The most you can do is change values until the effect becomes harder to notice
Hi, in my 2D plataform game, why when i dash towards a wall i normally get stuck to it?
i mean, i PHASE IT, and due that i get in the inside
I had a similar issue, make sure you have interpolate on, and continuous collision detection. If that doesn't work, you could check OnCollisionEnter, then teleport your player back out
em, how i do so?
sorry for my noobness...
in your rigidbody2d, you should have a box that looks something like this
(dont worry, i am also very new, and only slightly know what i am doing)
that depends entirely on how your dashing works
Interpolation doesn't affect the physics behaviour in the slightest, only the visuals and I'm surprised if the collision detection mode helps here either. I don't think they mean tunneling (going through walls) by getting stuck
Make sure the dashing moves the rigidbody in a valid way, so that it doesnt skip the physics simulation step.
Also depending on how the dashing works, if you still have tunnelling issues (phasing through colliders) due to the rigidbody moving too far between simulation steps, then you could do a raycast beforehand in the dash direction, so that you know the max dash distance
Sorry, wasn’t aware of that. I am also quite new to this, and in my projects, that usually solved it.
I might have also misread something. I thought they meant sticking to walls, not tunneling through them. In that case continuous collision detection might certainly help though it requires appropriate method of moving the player that respects collisions
Hello, i would like some clarification on how Collider.Bounds work. the green convex mesh is the mesh im using for this detection. the red box is the colliders world space bounding box. how can the collider be outside the bounds? physics.UpdateTransforms is on, and the bounds is called OnTriggerEnter, first frame that the collider enters the ground, and it enters from the right side of the screenshot i took.
how are you visualizing the box?
calling D.raw(meshcollider.bounds)
it certainly shouldn't be this way - it should be the minimal world space AABB surounding the actual collider
What is this Draw function?
Vertex's debugging package
I think you were the one that told me to use it way earlier
Can you show the code? It's most likely an issue with the gizmo drawing not the bounds itself
very possible
taking a closer look at this screenshot it appears there are multiple colliders here
there's a greenish rectangle-shaped collider inside the hold - maybe that's the one that's being drawn?
the box is drawing the bounds of the mesh collider, the green thats inside the box is the drawing for the terrain itself (what the terrain is editting)
the cyllinder collider on the tool shouldnt be a problem in this calculations as its not a trigger collider and therefore cannot call ontriggerEnter with the terrain
It looks like you're doing this in OnTriggerEnter - is it possible the tool moved since that exact moment?
maybe that's where it was when OnTriggerEnter happened and now it moved
ill do a OnTriggerStay draw as well to debug then, give me a minute
so somehow, the trigger mesh collider, "trips" the enter function before its supposed to enter the ground.
because what is supposed to happen is the tool comes from the left, hits the ground, then pulls itself right, tilling the ground
and it "hits" the ground way below where it is otherwise
as always, thank you so much for the help, solved one problem, created two more
it could be a problem with it trying to interprolate the velocity wrong, or a problem with physics being fixedupdate while animation is continious Edit: I think its a problem with shoulder width and animation
I would say - using OnTriggerXXX for this is probably not the best approach
seems like something you would just want to raycast or boxcast for
with the hoe itself being mostly a visual element
I want to eventually use the hoe's mesh collider for accurate collisions with the ground. Only reason i havent yet is that i cannot figure out a way to enable OnCollisionEnter while also allowing the collider to "Go into" the terrain. this way was mostly a prototype to debug whether i had the grid areas correct. what reasons would you give to advise against doing it the way im trying to?
It's harder to control
Is there a good reasons you need that level of accuracy
my game involves chopping trees, tilling ground, things that i want to emulate real life of. i want to make the gameplay feel "stylised realism" to the player. Going up to a tree, and breaking parts of the log till it falls, tilling the ground to plant seeds. i want it to have a ton of physics interactivity.
How would i go about mass simulating physics trials? the most common method, to my knowledge, is to have tons of simulations running at the same time that each record their own data. But is there a more efficient way that I'm unaware of?
Efficiency depends on optimizations specific to the simulation. Without more info, there are no suggestions
The only independent variable in my case is the force value added to a rigid body. So it's only one moving object in a static environment.
Make sure you're manually simulating with Physics.Simulate instead of "letting it run"
im making a grid based game and would like to use a box collider for the player but i remember in the past running into an issue where the players movement randomly gets stopped and stuck, so i would typically just make my life easier and use a capsule collider instead. but if i did want to stick with a box whats the best way to deal with this issue? i remember i tried a physics material with no friction but that didnt help
2D or 3d?
a 3d project but it plays like 2d game only working with 2 planes
If you use 2D colliders you can use a composite collider2D for the world and it will merge all the collider geometry into one mesh
you can use a tilemapcollider
Hi, I'm struggling with a problem. I have a character that consists of 3 rb's, one for the body, and one for each foot. The feet are seperate bodies that control the movement of the character, and the body follows. I have IK that uses the feet as targets for the foot. But my problem is the collisions. How can I make collisions that happen to lets say the knee, stop the foot from moving. I have tried some complicated joint system, but that influenced the movement too much. Is it possible to simulate collisions that happens one place onto another body? Can I make the leg-colliders work for the feet without them being childs of the feet? Where do I look to solve this?
would this work if im creating and destroying blocks during runtime? does it update in real time to merge the colliders so the player wont get stuck?
You can update it in real time yes
(sorry for reposting but last time I had to go and couldnt respond)
when I turn dirrection of my character, he does a little hop and for a moment looses contact with the ground. it only hapens on a tilemap (I checked the colisions)
the problems are the small hops not the jumps
any ideas what could cause this?
btf I am really new and not good at this
also this is the tilemap colider settings (dont know if it helps)
the players colider settings are in the video
Are you not using a CompositeCollider 2D?
Looks like not based on your collider screenshot
You should be.
well no I figured that I should use the tilemap colider for tilemaps
It works together with the tilemap collider
how?
It merges all the collision shapes into one shape so there's no bumps
so do I just add it?
Add it to your tilemap object
Set the composite operation on the tilemap Collider to Merge
And set the mode on the composite collider to Polygons
(forget what that field is called)
And the tilemap Collider now?
👍🏻
also if you dont mind, what exactly does the composite collider do and why do I need it?
so does it work with other colliders too? (like if I had multiple colliders on one object)
All of your questions are answered here https://docs.unity3d.com/Manual/2d-physics/collider/composite-collider/composite-collider-2d-reference.html
nice, thx
i am so confused. i have been trying to get shadow casts for when the animal is on the hole and its not working. does anyone have an idea? my mes renderers all have shadowcasts on and my cylinders do as well
the main goal i want is for the animals shadow to visibily be on the hole
ShadowCast?
what's that
doesn't sound like anything having to do with physics
what would it be under then?
Some people use a flat sprite of a dark shadow shape placed under the object. You could do the same, and when your bunny collider collides with the hole's collider, then the shadow object could be enabled, and disabled when collision ends.
I am trying to simulate UR robots, but when i tried with hinge joints + mesh colliders + motor control using PID,
joints started rotating crazy, my PID controller is perfectly fine,
there is something wrong with game physics, pls help me find the issue.
thx.
I think you should try Articulation Bodies for robotics
i followed this tutorial (https://www.youtube.com/watch?v=NsSk58un8E0) which uses the KinematicCharacterController by Philippe St-Amand (https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131), and i'm attempting to add a grappling mechanic much like in white knuckle. i got the spring physics working, i'm unsure of how to apply a damping force on it though, because right now the character will infinitely spring back and forth wildly around the grappling point
does anyone know how to rotate a gameObject with the center of the object being where the axis of rotations are? I notice that when i use the rotation tool in the editor, it works differently from just changing the rotation values in the transform of the object.
set your tool handle position to Pivot
how do I make sure the object uses center through code when I rotate it using its transform?
It always rotates around its pivot
Center mode is just a convenience tool in the editor.
If you want it to rotate around a different point you need to change its pivot or introduce a parent object and rotate the parent
I am trying to control the joints using force input, just like in the real robot, but i couldnt find a way to input force in articulation body
Articulation Bodies are pretty much purpose built for robotic things
Thanks, i looked through this, but as i said, i want to move things using torque, which in this case is done in background, i cant access the torque values.
I can only input target position or velocity, i need torque input.
In robots, you set certain current to generate certain torque.
AddTorque and AddForce are available on Articulation Bodies just as they are on rigidbodies
But there's also so much more.
Have you perused this?
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/ArticulationBody.html
add torque with hinge joint is currently working for me, i will look through this as well, thanks
Hi, I imported an .fbx file to Unity and put the model into my game, I added a mesh collider but when I go to drag the model into this Mesh field it doesn't let me
when I click the + on the right, it opens up other models in my assets folder which I can assign, but not the model itself which needs the mesh collider
The FBX itself is not a mesh, it's a collection of meshes
Drag one of its child meshes into that field instead
thanks, professor just said to use fbx and I didn't understand the difference
Hello, Wanted to ask something about controlling your character. I'm looking multiple places for info about how to handle first person game movement (look / move). I'm wanting to use a rigidbody for movement, as it allows my character to push things / interact. The problem ive found, is that if you try to look with rigidbody, you need to turn off y constraints. when you do this, other things you interact with turn your vision, and its incredably annoying to the player. How do you control movement fully with rigidbody, while allowing it to push / move other rigidbodies, and be stopped from moving by them. (but not have your rotation change) (For extra info, the rb is still 1 mass, and .02 angler drag, and the character using a capsule collider for physics)
The usual solution is that you don't turn the player, you turn the camera
you turn the camera for movement? then how do you have your character's model turn to "follow" the camera, as i need the model to be connected to the camera
Player container with rb + collider
↳ Container for turning
↳ Player model
↳ Camera
if you try to look with rigidbody, you need to turn off y constraints
Nah you can just rotate by setting the rotation in script or MoveRotation
You move the entire player container and turn the camera container
problem with moverotation, is that it doesnt work with interpolate on dynamic rb, and the staff memeber i was talking to yesterday advised not to set transform directly if im working with rb. not arguing, just want to know like is there a "best practice"? feels like im getting conflicting info from all sources when trying to figure this out. They said that moving with rb and looking with transform in update caused problems with antianalising.
ahh move containing rb for rigidbody, and set gameobject below it for rotation of model. that does solve it, if i set the lower transform directly, thank you for your input
MoveRotation does work with interpolation
but setting rb.rotation in Update also works fine for smooth FPS rotation
note that you're not supposed to touch the Transform
The Rigidbody is not the Transform
and it's not antialiasing that is the worry, it's interpolation
antialiasing it unrelated
oh, rb.rotation. thats, an easy way. thank you so so much for your time praetor. i really appriciate all the help you're giving me. and gotcha, worry about interpolation causing jitter
Would it be possible to pause the shadows of a directional light? like for an object, to pause the shadows and even if the object is moved/deleted, the shadow will stay there
maybe you could create a seperate object with the initial objects mesh, thats set to "render shadows only" and leave it at the initiall position?
oh, the directional light moved, thats more tricky
Yeah
Someone able to help with collision?
OnCollisionEnter2D will not trigger, even though they are colliding
Tried switching to trigger also, and no bueno
OnTriggerEnter2D doesn't get called either
added this and its working
under overrides
even though its in matrix. so not sure
hi
updatePreview();
Bounds bounds = new Bounds(currentPreview.transform.position, Vector3.zero);
Vector3 center = bounds.center;
Vector3 halfExtents = bounds.extents;
Quaternion rotation = currentPreview.transform.rotation;
Collider[] hits = Physics.OverlapBox(center, halfExtents, rotation);
Debug.Log(hits);
currentPreview has a Box Collider and i've checked on the scene and the box is accurate and i have a map where i gave it a Mesh Collider and set Convex to true. so why does this log an empty list? (im trying to detect if anything is touching currentPreview i dont need to know what just to know if so if anyone knows a better method im all ears
best way to narrow down why my box collider moves into the tilemap collider going down but will stop a square short of the tilemap collider going up?
Could be your movement code, the tilemap collider or the box collider
I'm having an issue that is probably very easy to fix but for some reason I can't understand how
Basically I have rigidbody A and rigibody B. A is parenting B. When B is pushed towards A and they collide, I want them to lose all their momentum and stick using a FixedJoint.
Here's how I'm doing it:
private void OnCollisionEnter2D(Collision2D other)
{
if (this.transform.Children().Any(e => e.gameObject == other.gameObject))
{
Debug.Log($"Room {other.gameObject.name} collided with parent {this.gameObject.name}");
var rb = this.GetComponent<Rigidbody2D>();
other.gameObject.AddComponent<FixedJoint2D>().connectedBody = rb;
ResetVelocity(this.gameObject);
}
}
private void ResetVelocity(GameObject go)
{
foreach(var c in go.Children())
ResetVelocity(c);
if (TryGetComponent<Rigidbody2D>(out var rb))
{
rb.linearVelocity = Vector2.zero;
//Debug.Log($"Settings velocity of {go.name} to {rb.linearVelocity}.");
}
}
They get linked together nicely, however they do not stop as you can see from the video, and I honestly don't understand why. Has anyone ever tackled a similar problem?
(Basically this is because I need to spawn different rooms in a grid, but to not make it look like a grid and be able to create rooms of various dimentions what I want to do is spawn them in a grid and then push each "node" towards its parent. These will stick together and rinse and repeat until they are all together nicely)
You're only setting the velocity of one of them to zero
Don't you need to set both?
But not the eoot
yeah this is called on the root
Root*.
Seems like you're only starting with the children
if (this.transform.Children().Any(e => e.gameObject == other.gameObject)) this line makes sure of that
If the other collider is a children, then do
It's not clear what Children() does but presumably it doesn't include the object you call it on
and since the collision happens on both of them only the root runs all that code
So yeah seems like you're not setting the velocity of the root to zero to me
It does because that debug.log fires
Oh wait I see you're setting it on the object itself AFTER the recursive loop
I misread
Can't you just set the one you don't want moving to kinematic?
You're repeatedly setting the velocity of the same object
DAMN
It should be go.TryGetComponent(...)
THAT WAS IT
Thank you so much
I've literally been trying for an hour with no result and it was this stupid issue
I still have a little misalignment, I don't think I can fix it without resetting the position to the one before the collision, can I?
Like with a checkbox
To be perfectly honest this doesn't seem like something you should be using Rigidbodies for
Too imprecise
I was trying to do something like this
https://youtu.be/NpS5v_Tg4Bw?si=F1xuhiMINgO95QrN&t=208
⁍ Play: https://mythfall.com
⁍ Wishlist: https://store.steampowered.com/app/3475620/Mythfall/
⁍ Discord: https://discord.gg/63YeahMKfJ
⁍ Patreon: https://www.patreon.com/UnitOfTime
⁍ Github: https://github.com/sponsors/unitoftime
⁍ Twitter: https://twitter.com/UnitOfTime
// References
⁍ Boris the Brave: https://www.boristhebrave.c...
(time included)
Is there a better way that I could have a rigged character have physics, than the very clunky way active ragdolls are always suggested. The vast majority of those use two different skeletons, one just for physics, then a rigged skeleton tries to match the position
reason why I dislike that is unity bones really arent designed for pose matching, so it gets really annoying to deal with
but if you could just have a dynamic skeleton right from the very start, that seems a lot more ideal
Active ragdoll is pretty niche, and only suitable for certain kinds of games. Most games would use a regular animated model and have its animations react to/get controlled by the player controller. The actual physics of the character would use a simple Capsule Collider, for example
you would use IK to make the foot touch the ground properly.
well the climbing character im making, needs the rigged model, but I've been getting really stuck with the physics part
I keep trying to make a series of game objects for the parts of the body, but I stopped using an actual rigged character. It was getting really annoying dealing with it
the only real way that seems right is like this. Climber is just an empty game object, but the 3 parts of it are rigidbodies
I think im on attempt number 10 at this point to try and make the climber, so maybe the initial approach im taking is wrong
I think you should focus on the physics first before worrying about the rendering
Hello, has anyone noticed any undocumented 3d forces/physics changes since 6000.1.0a9?
I have made a flying self stabilizing drone on 6000.0.36f1 which uses both VelocityChange and Acceleration force modes and ever since that unity version the drone flies faster and rotates out of control, indicating that something changed which made the forces much stronger. Tested pretty much every version from6000.1.0a9 to 6000.1.1f1 and it only works correctly before a9
thats fair, only reason why I'd want to work with the rigged character from the start is so I know its set up good from the very start
I worried that using a fake rig for the physics, could be really awkward when I have to move that over to working with the actual character
One possibility is that your code is framerate dependent, and there's a performance improvement or regression.
Another possibility is there is some actual physics difference.
I don't think it's framerate related as I appear to have the same framerate but I'll launch both versions simultaneusly and lock them to a specific framerate to test side-by-side again
can confirm it still happens
until the 13 second mark is 6000.0.48f1, after that is 6000.1.1f1
show your code
and "locking the framerate" isn't really possible so i'm not sure how you can confirm these are running at the same framerate consistently
well both 600fps and 120fps run the same in the earlier version and both are too fast in the newer version so..
ok that's a good datapoint. What's the code look like?
This is what I use for the drone to look at where it's going. Called in FixedUpdate as expected
public void RotateTowards(Vector3 target)
{
var pos1 = target;
var pos2 = rb.position;
pos1.y = 0;
pos2.y = 0;
var targetPosition = pos1 - pos2;
if (targetPosition.magnitude < 1f)
return;
var targetRotation = Quaternion.LookRotation(targetPosition, Vector3.up);
var deltaRotation = targetRotation * Quaternion.Inverse(rb.rotation);
deltaRotation.ToAngleAxis(out var angle, out var axis);
if (angle > 180f)
angle -= 360f;
if (Mathf.Approximately(angle, 0))
return;
angle *= Mathf.Deg2Rad;
var torque = axis * angle;
rb.AddTorque(torque * RotateSpeed, ForceMode.Acceleration);
}
silly question but is the time scale or fixed time set differently on the different projects?
unless the engine upgrade changes them I don't think so, as I've just copied it over and upgraded it
can check again
another thing to check is make sure the object has the same mass and same intertia tensor
and make sure the script hasn't been duplicated or something silly (two copies on the same object)
both are the same as expected
well.. that was multiple hours of reinstalling and debugging 🤦♂️
for some reason 6.1 does not have the overrides that exist in 6.0? Maybe related to the properties being renamed?
the code is the same
interesting - yes probably that's why
because the property names changed - but that's a poor user experience !
Maybe because 6.1 is alpha still
I would report ithat as a bug if you have a chance - that drag and angular drag don't get migrated properly
it happens with the non-alpha version as well, next to the lts
where would I go around reporting this?
as I am sure someone else will definitely get stuck on debugging such issue
I think it's still considered Beta, though it seems the hub is not labelling it as such?
https://discussions.unity.com/t/unity-6-1-beta-is-now-available/1580714
In the regular bug reporter
or on Discussions.unity.com
will look into it, thanks for your help
thanks for showing me something to look out for!
gonna have to go around reapplying values for all my prefabs now as I'm making my game use more physics objects where I can (kind of like what the half life series did)
hi guys, i wanted to ask : how do you handle 2d top down collisions that stop the player, esp for moving NPCs ?
I tried different methods and ended up using box raycasts and checking the distance between the closest contact point and the collider's point closest to it.
It works fine but it seems like a convoluted way to make something that is a basic for a lot of games.
Just basic Rigidbody2D with colliders and moving via the Rigidbody2D
I tried it but to stop the player i had to make the body dynamic. And i don't want the player to be pushed by NPCs, i don't think it's a common thing in 2d top down rpgs (forgot to specifiy mb)
Yes of course it needs to be dynamic.
Kinematic bodies are "unstoppable forces"
and how do you deal with your player being pushed around by moving objects in your project ? or is it fine for you ?
Depends on the project but It's not usually a problem.
oh ok, thanks i'll look a bit more into that
What do you want to happen when the player is on an NPC's path? If the NPC should just go through then you can use trigger colliders and prevent player movement when inside the trigger. If the NPC should stop as well then you can stop both on collision
i want both the player and the npc to stop. I did stop them on collision, but then they were stuck. I tried to move them to a previous safe position but it didn't work either (cannot explain why tbh)
void StabliseTorso(float strength = 0.1f)
{
Vector2 target = -Vector2.up;
Vector2 current = transform.up;
float angleDifference = Vector2.SignedAngle(current, target);
float torqueAmount = -angleDifference * strength;
_rb.AddTorque(transform.forward * torqueAmount);
}```is there a better way to keep a rigidbody in an upright position? this sort of works, but it oscillates forever unless I crank the angular damping up
I just want it to try and maintain the upwards direction. I get why it oscillates, once its too far to to the left it rotates but then it overshoots to the right, and that repeats
ive had this issue in the past, my only solution has been to reduce the torque to 0 once the body is actually aiming upwards. But it never gives very nice results
Just constrain the rotation in the inspector
that totally locks it from rotating, I still need it to be allowed to rotate, it just has to return to the position
What's the gameplay you're trying to achieve
You need a PID controller if you want to do this properly
The thing you're doing now is too simplistic
It would need to add a reduced force when closer to the desired rotation
the yellow box will be the torso of the climber, so I need to make sure they always try to keep the body with their head at the top
some rotation is allowed, I cant remove all torque like the constraint setting does
ill look into a PID controller
When a rigid body moves fast, it can jump over an edge collider and go into an area where it's not supposed to. What's the way of preventing objects going out of the edge collider?
Use continuous collision detection
Also consider using polygon colliders instead of edge colliders
I'd like to contain objects in an area, like a an area with fence around. The fence is comples, so putting 4 box colliders wouldn't work. How would I do this then with not the edge collider?
From what you just told me about continuous collision detection, looks like using continuous collision detection is the correct way to do this?
What does "the fence is comples" mean?
Yes continuous collision detection is a correct way to do this
Complex
Oh - sure it can be done with a polygon collider or many box colliders then
Imagine an edge collider but with some thickness
You'll want continuous collision detection either way
Strange bug of sorts: This is a spider controlled by IK limb movers. The blue dots represent the targets for the spider's legs to take steps to after a certain distance. When walking on a white colored surface (default sprites), the dots are able to move on them. However, when walking on a tilemap (gray area), the dots ignore it, despite the tilemap having a collider and the necessary physics layer.
This function sets the position of the dots:
{
RaycastHit2D hit = playerControllerFunctions.castRay(bodyTarget.position, Vector2.down, pb.groundRayLength, Color.red, pb.level);
if(hit.collider != null){
Vector2 point=hit.point;
point.y+=pb.bodyTargetYOffset;
bodyTarget.position=point;
}
} ```
Show the collider Gizmo for the tilemap
Where's the collider? You all the important things off this screenshot
I somehow fixed it
I just assigned "geometry type" as polygon
I was going to suggest that yes
Thanks i guess lmao
@timid dove sorry for the ping but a similar problem is still bothering me: Now, the dots dont collide with the edge collider of a sprite shape
is there some way to integrate unity physics with gameobjects? right now im planning on a hybrid ecs game and for most objects i kinda just need a simple rigidbody
Hi I currently have a weird Unity physics problem with the object grabbing joint. It works fine until I turn off the collider(s) of the object I'm holding, then it starts spinning around for some reason.
This is a problem because I want to turn off the colliders with a script that will check if the object is teleported inside of something when the hand grabs it, so it doesn't freak out when held, but turning off the colliders apparently does the opposite of helping.
How the system is set up:
The hands are connected to the body with a configurable joint where the target position is set to the position of the controllers.
The hands and object(gun in this case) have their own rigidbodies and colliders.
When the hand grabs an object, a fixed joint is created between the hand and object (see end of video for how it's configured)
For some reason if the colliders of the object are turned off it starts freaking out. Why does this happen? And how can I fix this??
I cant figure out a proper way to move the hands of my climber around. I need their position to follow the mouse, but nothing seems to work all that well.
In the video, the hand is moved like this
// stop the target (mouse) moving further than the length of the arm
Vector2 point = ClampWithinCircle(target, _shoulder.position, 2f);
_handRB.MovePosition(point);```This makes the hands movement feel responsive (it matches the mouse position), but you can move the mouse up very fast and it propels the whole climber up.
Just limit the speed the point changes at?
if I did that, then it'll feel like the hands are lagging behind the mouse position
its what I was doing in a previous attempt
Vector2 dir = _target - _rb.position;
Vector2 vel = -_rb.linearVelocity;
Vector2 force = (stiffness * dir) + (damping * vel);
force = Vector2.ClampMagnitude(force, 1f);
_rb.AddForce(force);```
that also created the same problem where you could fly upwards
I mean, like just use Vector2.MoveTowards when changing the point
It should effectively filter out too-fast mouse moves.
void MovePosition(ref Rigidbody2D rb, Vector2 pos)
{
Vector2 current = rb.position;
Vector2 pnt = ClampWithinCircle(pos, _shoulder.position, 2f);
rb.MovePosition(Vector2.MoveTowards(current, pnt, Time.fixedDeltaTime));
}```is this what you mean?
those fast movements are gone, but modifying the point like this makes it very laggy
https://youtu.be/S-4XZgARAuA?t=437 watching the hands of a real climber, I cant determine how I'd replicate the action of moving them around
quickly moving the hand up does cause their shoulder to be pulled in that direction, but nothing close to mine
I think the issue is that rb.MovePosition pushes the hand in some direction, which results in the shoulder and torso also being pulled towards the hand. So you get this
I have a question about AutoSyncTransform option in Physics2D. In play mode, I'm moving an object with 2D collider with dotween and I've noticed the collider is not synced with the game object (the gizmos in scene stays in the same place, if I'm using raycast to detect if object is clicked by mouse, raycast returns collider as null even though position is synced). If this AutoSyncTransform is enabled or I'm testing in build, collider is synced and everything works fine. So my questions is, regarding 2D development, should this option be enabled to debug in Editor? I'm kinda confused if this is the normal behavior (to not sync collider with moving object if there is no rb) unless I enable this option or there is something else may be causing it?
how are you moving the object with DOTween exactly?
I think ideally you should be calling DOMove on the Rigidbody2D of the object, not its Transform
using objectToMove.transform.DOLocalJump
yeah that'd be why
move it with the Rigidbody and you'll have less trouble
you should pretty much never move any physics object via the Transform
there's even a DOJump for Rigidbody2D
oh great thank you so much for the clarification
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I feel like its a problem that the only way I can think of to get a climbing characters hand that controls properly, is to try and model muscle forces to get the torque needed so the arm can be moved around
i know this is probably far too advanced than it would need to be
I just feel like having an external force to move the hand, that force is going to pull the body along with it, this seems unavoidable
but if parts of the arm itself rotates, that can move the hand to where it needs to be
Hi, I am trying to detect entry AND exit points on a collider using RaycastCommand. The QueryParameters provide me with the hitBackfaces and hitMultipleFaces which sounds like what I need, but seems to only apply to MeshCollider triangle faces. Is there a way to get the exit point of a jobified ray cast?
I specifically need it for sphere and capsule colliders
Would it be sufficient for you to do two raycasts - one in the opposite direction as the original to catch the backfaces?
I thought of that, but since these are analytic shapes I was hoping the back face flag would "just work". I guess not 🤷♂️
Alternatively, once you have all the "front face" hits - you no longer have much use for the spatial partitioning acceleration that raycast benefits from and you could figure out where the backface hits will be analytically, since capsules and spheres are quite well defined and understood mathematically.
You already know which spheres and capsules were hit and the "exit wounds" could be calculated from the RaycastHit information
If I have to redo the intersection tests I should just not use Unity at all. Thanks for the suggestions though 🙂
Well half of that magic is the spatial partitioning not just the individual intersection testing but I get ya
Hi I’m using unity physics whats the easiest way to not still have upwards momentum when walking off of the top of a ramp (stairs)
You would track a grounded state of your controller and always snap it to the ground unless it has exited the grounded state via jump or fall.
Sounds expensive
Can’t just snap feet to the floor since that would result in parts of the physics shape being inside terrain when moving up a ramp for example
Don’t really want to do a shape cast every frame
Not really, just one Raycast or CapsuleCsst per frame. Anyway you wouldn't need to snap anything just set y velocity to 0 on the first frame you become ungrounded
Aren't you already doing a grounded check anyway?
Hi, does anyone know how I can make this slider stop vibrating? I tried messing with the values already but when I do find some force/damper values that make it stop vibrating, it becomes very weak and/or makes it move at a very slow speed when I let go of the slider.
Is it really necessary to have a fully simulated physical slider on the gun?
with a joint and everything
it's probably better to animate this with code. The physics engine isn't built for precise mechanical precision like this
At the very least you should look into Articulation Bodies and Prismatic Joints for this particular mechanism.
It's for a physics based VR game, so you need to be able to grab it and move it around, I'll look into those things you mentioned
Idk how those would be used, why not do this? Is there no way to fix the current joint?
prismatic joints/articulation bodies are designed for mechanical simulations with higher precision
Rigidbodies aare just not precise enough
I think the easiest way would be to avoid physics entirely here though
and just do it with code
That would give the best result
My current grab scripts all work through rigidbodies and joints, so that would be too much to make work. I'll just stick with the decent values for now.
I noticed that all OnCollision and OnTrigger callbacks can be converted to Coroutines but I can't seem to make them work. For example i was trying to make a script that only calls OnTriggerStay a fixed number of times per second instead of every physics frame, but I was unsuccessful. Is there any special way to write the implementation to achieve this result?
OnTriggerStay definitely can't be a coroutine
Pretty sure only OnTriggerEnter can
And trying to run OnTriggerStay at some different frequency is extremely sus, that's not what making it a coroutine would achieve
All you can do with that coroutine feature is have a cute little shortcut that has the same effect as just calling StartCoroutine inside the method as it runs normally
Mmm i was looking at the documentation and it says this:
OnTriggerStay can be a co-routine, simply use the yield statement in the function.
Maybe I misunderstood what it actually means
Extremely poorly documented
But maybe if can be I guess
It means you also need to use IEnumerator as the return type
And then it acts like a normal coroutine
It will still also be called every physics frame
You can't change that
And you'd essentially be starting a new coroutine every physics frame that way
I think what you actually want is to start a coroutine on OnTriggerEnter and stop it in OnTriggerExit
Not the best idea then, that's why despite having a yield return _myWaitForSeconds; it still executed the following logic every frame
Yes it's going to start the coroutine every time OTS would run
To be perfectly honest, OnTriggerStay is almost entirely useless
There's nothing you can do with it that can't be done with OnTriggerEnter/Exit
Understood, thanks for clearing that!
Hi all,
I'm having a strange issue that I can't seem to figure out.
I'm trying to put together a very simple Jenga game, but I'm stumbling at the first hurdle.
I have my blocks set up, all with rigidbodies/box colliders. But I'm getting massive amounts of overlap/intersection on the box colliders and I really don't know why.
Would anyone have any ideas/pointers please? (Using Unity 6.1)
https://cdn.discordapp.com/attachments/748796358332383262/1373675337464156161/My_project_10_-_SampleScene_-_Windows_Mac_Linux_-_Unity_6_6000.0.29f1__DX11__2025-05-18_18-47-28.mp4?ex=682b465a&is=6829f4da&hm=fb21223ae5bbdd5a92e7c397f734d8d2045388e3c15e98ac57d07282770554c0& how do i make constraint tank threads?
hi I'm using unity 6.0 and building a 2d topdown rpg, following problem: i have a ground layer and over that a water layer and over that i have a bridge layer now i want the player to be able to walk over the bridge without running over or jump into the water. the water tiles has sprite collider and all 3 has tilemap collider set to merge rigidbody as kinematic and compostite collider polygons. the player itself hast a box collider and a rigidbody dynamic. i tried layer collision matrix but it seems i cant figure out whats wrong because i cant walk over water or i still bumb into water under the bridge. bridge tiles has no collider set.
if u need adittional info i can provide them
You should give the bridge tilemap a collider and set its Composite Operation to "Difference"
done but still crashing in the water under the bridge
this are my collision matrix
water tilemap hast tilemap collider (merge), rigidbody (kinematic) adnd compostie collider
Bridge tilemap has tilemap collider, rigidbody (kinematic) and composite collider
each tilemap is set to the correct layer
ohh and player is set to the player layer
wait you have three different composites
then the merge/diff interaction isn't going to happen
I was implying they should all be sharing one composite
and you don't need to do anything with the layer collision matrix
ok so just remove evry other composite exept for 1 ?
the composite needs to be on a parent object of all the tilemaps
ohh i understand now i think let me try then i report back ^^
Basically the composite makes a composite of all its child colliders
ok sry no i dont know how i would create a parent composite
if i click in hierarchy i can create one
this is my scene
evry tilemap is in the same grid
ohh i can add a composite to the grid itself
well i still cant walk over the bridge
and then sometimes i can walk over evrything o.O
if it would help i offer also the possibility of a video call so i can share my screen and u can see evrything live
can rly noone help i just dont get it whta i do wrong
found my issue but thanks
I have added box colliders on all,
the gripping boxes are articulation bodies and continuous dynamic
the object is normal rigidbody without gravity and continuous dynamic
how do i keep it gripped after the robot starts moving??
Hey folks. I've been stumpted on this for way too long. I'm hoping that somebody here can set me in the right direction. Maybe there's some obvious answer that I've been missing (that's always the hope, isn't it?)
For context, my game is a top-down, turn-based space-shooter with free movement (not grid-based). Some projectiles explode. My explosion algorithm has worked exactly as intended until I recently found a massive problem with it. Here's how it works:
-
Explosive object hits something, and it is stopped before an explosion object (child) is turned on and Explode() is called on it.
-
The Explode function does a Physics2D.OverlapCircleAll to grab all of the potential hits.
-
An initial raycast check is done directly from the explosion to the potential hit. If it reaches the target, it is considered a confirmed hit, and it is damaged and knocked away.
-
If the initial raycast misses, it could be because the origin point was behind cover, but some other part of the ship is exposed enough that it should be considered a hit. To catch this, a series of raycasts are fired from the explosion in 5 degree increments around it. If it hits, the loop exits, of course, as the target is considered hit.
The problem occurs with point-blank shots. Often, the point of the explosion will be inside the collider if either the firing ship or the ship/object I'm pushing up against. This, unsurprisingly, means that only that one object will be damaged. I can't even temporarily turn off the colliders of either the firing ship or the hit object because either one could be legitimately blocking other objects. I tried adding a bit of recoil to the firing ship so that it moves away a little bit first, but due to the timing, this doesn't always work either. I could implement a short delay to give the recoil time to move the ship back before the missile fires, but I suspect that it wouldn't look/feel right. I don't really want missiles to have recoil anyway.
Any help would be greatly appreciated.
I'm not sure I follow why only one object is damaged
It's due to the raycasts starting inside of either the firing ship's collider or the other object's collider. For example, if I'm up close against an asteroid, the explosion may spawn inside of the asteroid. The asteroid takes damage, but the firing ship doesn't because every raycast check only reaches the asteroid.
I think I solved it. I just made sure that the missile is kinematic with an enabled, non-trigger collider for one physics step before doing the target-checking stuff for the explosion. This lets the ship and/or other object to pop away slightly, which doesn't look weird because the explosions push immediately follows.
Good ole rubber duck programming, eh? Neglect the project for weeks because I don't want to bug people for help... make a post, and then figure it out the next day. 🦆
does the physics debugger show cast commands ?
im trying to debug why my sphere cast commands arent returning anything after migrating from OverlapSphereCast
Yes, under Queries
i dont see them (im using "show all" queries)
i switched to overlap sphere command, same result
Does anyone know of a way to get an effect similar to physics interp, but for articulation bodies?
I'm asking cause it's pretty distracting to have the birdie jitter
Activating physics interp on a rigidbody fixes this
But the brid aint a rigid body :/
(excuse my breathing)
Some people have written their own interpolation for them:
https://discussions.unity.com/t/interpolation-for-articulation-bodies/918497/8
Hey folks. I’m looking for some efficient way to detect the first time a rigidbody has become awake. This is so I can know which rigidbodies in a scene have changed, and therefore need to have their data saved (as part of a saved game file).
I’m hoping to avoid saving all rigidbody and transform data for every rigidbody in the scene, since the player might only interact with a fraction of them while playing.
As far as I can tell, there’s no ‘OnAwake’ callback for rigidbodies. That seems like it would be ideal - bummer.
Unfortunately, ‘OnCollisionEnter’ doesn’t cover enough cases to work for this. It’s possible for a rigidbody to wake up without that event being called.
Making a 2D pool game and having an issue trying to make the guidelines. I am using CircleCastAll to detect where the white ball will be at the point of collision, but when I use OnCollisionEnter2D it gives me a slightly different point. In the pic, the white circle with the little white dot in the middle is where the predicted center is, and the gray circle is where the collision actually occurs. Not sure if its just an issue with how CircleCastAll is calculated compared to OnCollisionEnter and if there is something I can do to make it more accurate
Are you using continuous collision detection?
Yeah, I've put it down to CircleCast and OnCollisionEnter both detecting things at different rates and went for a method that didn't use circlecast to get more accurate results
I'm confused, what white circle with a white dot? Which of the gray circles? Can you use other colors than just 2 so it's easier to see what's going on?
And what are you detecting collision with? Where did the ball come from, the thin white line?
Yeah my bad. The thick white line is the guideline. The horizontal line is the path the white ball is travelling, and the diagonal white line is where the black ball was predicted to travel after collision. The (only) grey circle near the elbow of the guideline is spawned on the white ball position where collision occurs, and the white circle with the dot (is the one that surrounds the elbow of the guideline) indicates where it was predicted to occur from the CircleCastAll.
Instead of using CircleCast I wrote a script that detects intersections along the line you are aiming by looping over the positions of all stored balls. Ended up being a lot more precise than using CircleCast
Hello all!
I have a quick question, I hope this is the right place for it.
I am making a horse in unity and I am trying to setup colliders, ideally I want to avoid using primitives but this leaves me with mesh colliders which are not supported (if non-convex) for rigidbodies
how should I approach the colliders for something like this?
What do you need the collides for? Generally primitives like capsules are great choice for skinned meshes
You would approach it by using primitives
Should I expect that
{
for (int i = 0; i < 10; i++)
{
do physics * physicsTimestep
}
}```
will accurately predict
```void FixedUpdate()
{
do physics * physicsTimestep
}```
?
Can you elaborate? It's not clear what you mean.
"do physics" is pretty vague.
A list of objects updating their position and velocity:
{
foreach (var body in bodies)
{
if (body.active) body.rigidbody.position += body.velocity * physicsTimestep;
}
}
private void UpdateVelocity(List<PhysicsBody> bodies, float physicsTimestep)
{
foreach (var body in bodies)
{
if (body.active) body.velocity += GetGravity(body, bodies) * physicsTimestep; // maybe is bad
}
}```
called in this function private void FixedUpdate() { PhysicsStep(bodies); }
They would be equivalent assuming nothing ever collides with anything.
The difference here is that between each FixedUpdate you will get a physics simulation step
What you really probably want to do instead of this is actually just to call Physics.Simulate()
Its for drawing / predicting trajectory lines in a orbital mechanics game using Newton's equation. I'm fully simulating each physics body in a trajectory manager and they all run beside each other, the accuracy seems off however.
You're not accounting for gravity, drag, collisions, angular velocity etc.
What you can do is copy the objects to a secondary physics scene and simulate it with PhysicsScene.Simulate
If you're not actually using Rigidbodies/ the built in physics engine then there's no reason it should be different unless you are calling different code or doing other things in between
Hmm, yeah the entire physics system is most detached from the built in physics but I'm still getting slightly different results.
Then your code is simply doing something different in each case
How are you doing a trajectory prediction without affecting the "original" objects?
Each GameObject that is being managed by the physics system has duplicated version of itself with only my custom physics component, in a separate prediction manager with the for loop. I think I did figure out the accuracy issue though at extreme performance cost.
The line did not have enough points so the inaccuracy was merely an illusion.
Hi, i am trying to make a Joystick to be moved with the player's hand positions in VR, i'm using a combination of a Configurable Joint and a script adding Torque to the Joystick's Rigid Body to move it towards the hand when grabbed, it works well enough when the hand pulls it away, but when at the center positions while grabbed, the Joystick keeps wobbling around and never stays still where the hand is, i've tried changing the Torque multiplier on the script and the Spring and Damper on everything of the Configurable Joint, but nothing works, any ideas?
For now, what i can do is make it as little wobbly as possible by reducing the Drive springs and increasing the damper while grabbed, while reversing back to original values when released so it can go back to its default position faster
I feel like using actual Rigidbody physics is kind of overkill for this, no?
What do you mean?
I mean I would just let it be grabbed and freely manipulated, and when the player lets go, pretty much just lerp it towards the upright position in code.
Issue: the object is bouncing infinitely (vibrating).
Physics material bounciness is on 0.5 (at time of recording)
Code only gives a start speed
setting rb to continues has mitigated the amount of times this happens, but it still does happen
same for drag, helps a little, but i dont want to rely on drag, its not the physics i want
Raycast behaves a little bit strange in this case.. Same angle, same origin. When I aim at the corner of the object, sometimes it detects collision, sometimes it does not. Any thoughts?
public GameObject ObjectOnFocus(LayerMask layerMask)
{
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.forward, out hit, grabDistance, layerMask))
{
if (hit.rigidbody != null)
{
return hit.rigidbody.gameObject;
}
}
return null;
}
Transform is the cam in this case
You need to add logs to your code
Log which object it's hitting, if any
And don't miss any branch paths
hmm.. I launched the project and tested again with logs, this time I couldn't replicate the issue. Probably I either changed something that fixed the problem, or some weird editor bug happened and I needed to restart for it to get fixed.
What is the go-to approach for handling player movement relative to another moving object the player is ON, i.e. a moving platform or a ship?
(for the sake of simplicity Im not doing groundchecks yet, not doing gravity, nothing. I just have a player that stays on the ship. the ship can move around, the player can move around on the ship, but never leave it)
CharacterController goes into a bin because it doesnt work with moving objects very well. We have rigidbodies.
Ive tried juggling Rigidbodies around and Ive got a semi-okay result, the player doesnt jitter, doesnt fall off, it can move and collide with the ship as it swims around.
The problem comes from Rigidbody interpolation: with 'Iterpolate' on the player juuuust slightly lags behind a moving ship and catches up when it stops. with 'Extrapolate' on the player outruns the ship by a slight amount and then falls in place when the ship stops.
I thought interpolate and extrapolate were just the methods which, uuuh, handle character's smooth movement between fixedUpdate cycles to sync with the Update?
I could share the code, but the calculations are correct, otherwise the guy wouldve fallen off the ship:
My ship script has a method that calculates its predicted position and through world-local transformations gives the player script correct vector of "how much it should move in the next frame to match the ship movement". My player calls this method when calculating its own movement. Ive made it so that the ship calculates its predicted movement twice - once for itself and once for the player JUST to account for the script execution order.
Either Im missing something, or there IS no way to eradicate this micro-lag, in which case Im screwed. Does anyone have any ideas about it?
This handles that well: https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131
I'll take a look, thank you!
although I assume this one doesnt deal with rigidbodies altogether and uses its own collision logic. damnit. I hoped I could avoid that, but maybe not. HNNNNNNNG
It kinda depends on what your requirements are but another option for vehicle physics are to use one scene for the vehicle and the outside world, and a secondary physics scene for the things inside the vehicle
Using... secondary physics scene? Could you elaborate a bit? I don't think I've ever heard something like that in the context of Unity 👀
oh. oh dang. thank you!
how do you people do with profanity? I have a story to tell
Hi. I have a pressure plate which works by spring joint, it basicly consist of 2 object (colliders and rigidbodies are attached to both object) and when i put an object on the pressure plate the upper part of the pressure plate gets closer to the lower part of the object and it triggers and when i take object back the upper part gets distance from the lower part.
Now the problem is really interesting. As i mentioned i have a pressure plate prefab and im using it at various parts of my level. The problem is some prefabs works very intersting like the upper part is sliding like its on an ice but when i change the corrupted prefab's world position it fixes (the world position is not an enormous number, it is just -200 or smthng) also if i remove the pressure plate from the parent object it fixes again (the parent object is just an empty object which scale is 1). I thing its an really interesting physics bug. Does anyone knows why it that?
Also im using unity 6000.0.32f1 version
I wouldn't bother with spring joints for a pressure plate. Way too finicky. Just use a simple trigger collider on top and animate the plate going up/down in code or with an animator
My game based on completly physics. Like you can scale an object and it gets hevaier so it triggers the plate also the player may but more than one object on the pressure plate so it can be triggered with 2 object without scaling them so i need to use joint.
Despite that I would probably still avoid using physics for the pressure plate
do whatever you need to do like use a trigger and just manually add up all the object weights and decide if it should press the plate or not
games are all about smoke and mirrors.
is this channel still ok for ECS physics or should I make a #1062393052863414313 thread?
Either is probably valid. You would probably get better answers in #1062393052863414313 though
thx ill consider it
For the rest of ppl who is facing with same bug i solved it by moving the prefab out of the parent object, i mean if the prefab has no parent this bug does not occurs idk why
need a bit of help with raycast, first time experimenting with it, just doesnt work really, ive used drawray and it should be colliding, literally just trying to get it to collide with anything and printing a message if it does and it just doesnt work :/ are there common setup/settings things to tweak first?
Care to share your code and screenshots?
99% chance you just did something incorrectly
ill get the code, when it comes to screenshots its basically an empty scene, two characters and a few tiles in the background, what screenshots would be helpful?
- a screenshot of the isnpector of the object you expect to be hitting with the raycast
- a screenshot of the drawray result in the scene
The code and the inspector are the most important though
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
using UnityEngine;
public class EnnemySight : MonoBehaviour
{
public int offset;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
Debug.DrawRay(transform.position + transform.right * offset, transform.right * 100, Color.red);
if (Physics.Raycast(transform.position + transform.right * offset, transform.right, out RaycastHit hit, 1000.0f))
{
Debug.Log(hit.collider.gameObject.name);
{
if (hit.collider.CompareTag("Player")) { Debug.Log("player detected");}
}
}
}
}
Ok now a screenshot of the player object's inspector?
Ok you're going to kick yourself
you're using a 3D raycast
but your game is using 2D physics components
You need to use Physics2D.Raycast
It has slightly different syntax so you should check the docs for examples.
omg 🤦♂️
its 1 am and its been 2hours of troubleshooting, i knew itd be something stupid like that
tysm
hey guys, sorry for the long doubt coming up, but, im on my first game project with unity and c# that im trying to do on my own (well its still 90% tutorials but hey), and so im trying to make this space invaders game to practice and i had my first encounter with 2D bullet projectiles, and so the bullets are succesfully spawning in the correct place whenever LMB is clicked, but for some reason the bullets are not moving upwards even though i crosschecked with some tutorials and its the same code that they have implemented as mine, ill attach the screenshot for the bullet script (attached to the bullet prefab)
public class bulletScript : MonoBehaviour
{
public Rigidbody2D rb;
public float bulletSpeed = 5f;
void Start()
{
rb.linearVelocity = Vector3.up * bulletSpeed;
}
}```
and this is the script for the gun if it helps with debugging
```using UnityEngine;
public class gunScript : MonoBehaviour
{
public Transform firePoint;
public GameObject bulletPrefab;
public float bulletSpeed = 5;
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
shoot();
}
}
void FixedUpdate()
{
}
void shoot()
{
Instantiate(bulletPrefab, firePoint.position, Quaternion.identity);
}
}
Show the inspector of the bullet prefab
Do you see anything in the console, such as errors when you run this code?
The rigidbody is effectively disabled
ah good catch
oh, i totally ignored that message, i thought that wasnt anything important
thank you guys!
its working now
does anyone know a solve for physics pulling configurable joints apart? I'd love for these to maintain their relative positions at all cost, but in this clip you can see me changing the weight of the joint at the end. as it increases, it pulls the chain segments apart
these are my settings for the responsible joints. They're connected to a kinematic rigidbody to anchor to the parent object
I'm trying to increase the weight of the end of this pendulum to give it a more lively feel, but when I do that, the segments start tearing apart
Have you tried setting x,y,z motion to locked?
Hi, is it possible to simulate both PhysX and Unity Physics at the same time? Ive found trying to simualte both freezes PhysX.
it sets Physics.simulationMode to Script
why is the rat getting some random rb speeds, rb says speed is going from -9 to 9, yet we see the rat is stationary, i have no scripts on it that affect movement, just a script that flips it based on rb velocity
nvm i just had to set a small velocity check for the flip script
Hi everyone, I had an issue before with a physics based slider joint and I have now changed it to a code based one. It now kinda works how I want it to, but it still has some weird issues.
When I shake the gun with the slider, and freeFloating = false, it visually stays in the same position like I want it to, but somehow it does trigger the reload, and that is only supposed to happen when the slider is pulled back. So is the slider somehow moving in between updates??
Tried Chatgpt but it fails at giving me responses that work
Hi, im experimenting with a 2D stacker game where the player is a sausage and collects other sausages to grow a tower. The problem im facing is the sausages randomly offset (in video). I have Hinge Joint 2D on every sausage to connect to the one below it. Anyone know what the problem is?
Code for activating sausage:
{
GameObject prev = sausages[activeSausageCount - 1];
GameObject next = sausages[activeSausageCount];
// Activate next sausage
next.SetActive(true);
// Place the new sausage above the previous sausage
next.transform.position = prev.transform.position + Vector3.up * 1.2f;
next.transform.rotation = prev.transform.rotation;
// Enable scripts and tags
prev.GetComponent<SausageController>().enabled = false;
next.GetComponent<SausageController>().enabled = true;
next.tag = "Player";
}```
When does this code run?
How are you moving the objects?
How are you attaching the sausages to each other?
Generally you should never be directly modifying the Transforms for objects that have RIgidbodies. You should only work via the Rigidbody.
Also you're always placing the next sausage directly above the previous one, even if the previous one is tilted, which will definitely result in some weird offsets.
You can also simplify this code by using a SausageController[] instead of a GameObject[]
You want the green position, not the red position
Well basically, it activates when the sausage on the ground is touched by player. I attempted to move it in the script, i guess its messing up there. I already created all the sausages in a list in a parent for the sausages that activates them, hingejoint2D connected rigid body is preconfigured
its weird because it works as intended for the first one added
hey is there anyone that can guide me how to implement a sort of realistic car controller without the built in physics ?
because there's no tilt on the first one. Refer to my beautiful diagram above
What you probably want is this:
Vector3 position = prev.transform.TransformPoint(Vector3.up * 1.2f);
next.transform.SetPositionAndRotation(position, prev.transform.rotation);```
oh i see, for some reason i thought adding rotation would fix it.
ok ill try it
No, it just rotates but the position is wrong. See my diagram
ok now this is happening, i think the reason i added the height was to make it go on the top of the sausage, is there a better way?
are the sausages scaled?
If they're scaled the code needs adjustment
yes
then you need this:
Vector3 position = prev.transform.position + prev.transform.up * 1.2f;
next.transform.SetPositionAndRotation(position, prev.transform.rotation);```
thanks a lot! it seems to work, although i think the angle limits i put in place cause it to lean more to one side than the other, but ill figure it out
Anyone know why this could be happening??
Does Mesh Collider not convexted have issues with OnTrigger / OnCollision ?
i have a ring where i need it's inside to server like fighting rig, if the inside is touch something should happened.
now since when i convex it its no longer hollow i cannot use convex for that so i am not sure
The ring itself doesnt move much it starts lowered then few seconds into the game its being raised up and scaled out
what am i missing ?
what weird is the rigidBody inside it, does collide with it and cannot leave it, but no OnCollision fires .
If it moves at all it has to be Convex.
Bah then what alternative is there to what i want to acomplish ?
what do you want to accomplish
A ring that is collidable - prevent players from leaving it and trigger some event when its being collided with for effects.
Are you sure it actually needs to move?
well i guess i could make a version of it that's already scaled and raised out without a renderer
and then just do the visuals on another ring
but would that matter ?
why not just disable it
and enable it
as needed
(and yes make the renderer separate)
Well currently what i've tried is disabling the mesh collider when its not fully positioned, then when it got to its final step the collider is enabled
Yeah I mean, why does the collider need to move at all? Just have it be in the "final" place at all times and disable/enabled it as needed
as for OnCollisionEnter/OnTriggerEnter executing - if that's not happening then you are likely not satisfying all the requirements for it
Ok so basically that ring is on a moving floor, basically its a game of 2 players trying to unbalance eachother that means that the floor tilts constantly, the ring is a child of that floor and titls with it.
i dont know if this counts as movement
@timid dove Will that count as movement ? considering local doesnt change ?
yes of course that counts as movement
You should make sure:
- All colliders in the hierarchy are convex or primitive
- There is a Rigidbody at the root of that hierarchy
- The whole thing is only moving via methods on the Rigidbody
if you want it to work properly
To get that collider shape for a moving object you will need to build up the collider out of multiple smaller Convex or Primitive colliders.
Yea i thought about doing many small box colliders but i'd need like 50 of them seem really ugly solution
i think alternatively i could use some ugly distance from center to solve this
hey can someone guide me how to impliment this :https://nccastaff.bournemouth.ac.uk/jmacey/MastersProject/MSc12/Srisuchat/Thesis.pdf
in unity
Thanks for the help, i will try other stuff and see how it goes
anyone ?
That's an unreasonably tall order. If you run into issues doing it yourself then feel free to ask but "guide me how to implement this" is way too broad
hey
anyone know any tutorials for setting up character with Unity cloth? There seems to be ZERO on youtube. Since years ago. And none by official Unity. And i mean characters with actual clothing not just samples of making a cloth( that doesn't go in a person's body) into a cloth with physics cause that i found a video of but it's from years ago. I already have a character and it comes with the clothing. But setting up the colliders and stuff i've tried and still the legs and stuff come out of the skirt/dress. The closest i come to any tutorial is from a video kind of demonstrating the process in VR chat related video but she was just going to quick overview, and not really explaining in detail.
how can i make realistic water simulation in unity 3d
either by buying https://assetstore.unity.com/packages/package/268614 or by DIY'ing the same stuff https://docs.crest.waveharmonic.com/Manual/SystemNotes.html (there are other assets but this is the most mature one you can use as a unified water solution in an ambitious project)
if you want to have an actual simulation of volumetric water flow you can check out this asset https://assetstore.unity.com/packages/tools/physics/obi-fluid-63067 or DIY that same stuff, which again requires some reading in conference papers.
There isn't much about water/fluid sim that is unity specific besides the rendering of the actual simulation.
I don't wanna pay money I wanna learn and that ain't simulation, it uses ai generated water texture then displaces it based on water texture, it won't be useful for my case
I want more of fluid simulation for gun shots
then maybe you want to watch this https://www.youtube.com/watch?v=rSKMYc1CQHE
Let's try to convince a bunch of particles to behave (at least somewhat) like water.
Written in C# and HLSL, and running inside the Unity engine.
Source code:
https://github.com/SebLague/Fluid-Sim/tree/Episode-01
Next episode:
https://youtu.be/kOkfC5fLfgE?si=1hXtw9nIiHllA6gn
If you'd like to support me in creating more videos like this, you c...
Anyone knows??
Hey! Does anyone know how to stop my character from floating when it moves?
It spawns at y = 0, but when I move it, the Y value changes to 0.79. The character controller height looks correct (see img1), but the skinny mesh renderer (img2) dips a bit below the model at the bottom. Not sure if that’s what’s causing it.
You didn't really give enough detail here but it's probably your animator.
Try disabling the animator to see if that fixes it to confirm.
Thanks! I tried disabling the Animator, but the issue still persists.
I'm still learning, so I might be missing something obvious. Is there any specific info I should provide to help identify the problem?
Show it with the scene view side by side
And gizmos turned on
Set your tool handle position to Pivot, not Center
And activate the Move Tool
Then take the same video
Looks ok I think. It's not .79 it's.079 and it's because your CC has a skin width of 0.08
Ohhh that was it. When I changed it to 0, the floating problem was gone.
tysm for pointing that out!! Really appreciate the help 🙏
Hello everyone. I have a system similar to the one in the video. When a force is applied to the black platform, the mechanism rotates around its center, just like in the video. What I want is for the player to move with the platform when standing on it while not moving themselves.
Since this involves a physics system, making the player a child of the platform didn’t work (I learned that this approach isn’t functional). I also tried taking the platform’s velocity and assigning it to the player’s velocity, but that didn’t work either. Honestly, I couldn’t find any other solutions online. Most tutorials cover platforms moved via Lerp in code, but mine moves completely freely, using its own weight, applied forces, etc.
When I add other non-input objects, they stay properly on the platform and move with it. Only the player (which has input) behaves this way.
I don’t have a specific script to share because my last approach with velocity didn't work and all the script is messed up. If there is another way to achieve that behavior, I would like to hear that Thanks in advance!
Hey everyone. I was wondering if anyone could help me with this physics issue ive been having. I'm trying to make my golf ball have "spin" to it, such that it will quickly roll in a direction after it lands. For example backspin would roll the ball backwards quickly after it lands and settles. My problem is that when the ball lands after its initial bounce, the rotation briefly janks out / corrects itself for about 1 second before settling into a backspin (see the video). Does anyone know what I'm doing wrong here?
I would really not try to use actual spinning to simulate that.
void BackSpin()
{
if (spinTime < 0f) return;
float curSpinAmount = math.lerp(0, rollBackForce, spinTime / maxSpinTime);
Debug.Log(curSpinAmount + "cur spin amount");
rb.AddTorque(targetSpinAxis * curSpinAmount, ForceMode.Acceleration);
if(ballLaunch.landed) spinTime -= Time.deltaTime;
}
this is called on collision stay currently
just track your own spin thing and apply forces in e.g. OnCollisionStay
sorry could you clarify a bit?
use your own variable to tarck spin
it could be a float or a vector or whatever
then just use AddForce when contacting the ground
(and reduce the spin too)
using actual angular velocity here is too much for the physics engine
Would anyone know how to implement custom 2d joint using code. I tried all the joint available and none of them made what I needed. I want to make a climbing game where your arms are attached to your body and you can move them around. I am right now using simple impulse force directed toward the point I want the hand to be acting as some kind of spring then I am adding a force to dampen the movement, but that is where I am stuck, I am trying to get the relative velocity from the anchor point to the hand , and multiplying it by a factor smaller than 1 to dampen the movement but now everytime, I set it close to one, instead of not moving, every hand start going in every direction
Is there any easy way to implement dampening between two object with code while avoiding bug
Hi for some reason rigidbodies aren't falling down when gravity is turned on i have static disabled and is kinematic also disabled and no lock on positions
even if i create a new cube and add a rigidbody it still doesn't fall down
hmm i have installed an asset that adds rigidbodies to an object and drops the object when i press a button ( for level design purposes) maybe its interfering with normal rigidbodies
cause when press the button they do fall down
deleting the asset doesn't fix the issue
sounds like it
Check these project settings
I mean this is a smoking gun though, right?
Your asset maybe set time to zero or otherwise messed with project physics settings
nothing looks out of the ordinary
ohhhhhhhhhhhhhhhhhhhhhhhhh
THis is from your asset
Hey everyone, I'm currently prototyping an on rails Starfox game with off rails sections but having trouble figuring out how to do the collisions. My "player" gameobject is going to be the child of a dolly object that moves along the level path... But if the player child has a rigidbody, I don't know how that will behave with collisions (since move position is in worldspace I'm pretty sure?)
I've been giving it some thought but I'm a bit stumped on the best way to handle this
I thought about just making colliders triggers, but that doesn't help if I need any extra info from the object passed into OnCollisionEnter
I thought about faking it by having an on rails player that handles collisions differently and then switching to an off rails player that uses a rigidbody but I don't really like that solution either
Most of my googling and asking a friend makes me think that you NEED a rigidbody if you want to use OnCollisionEnter or exit which kind of complicates things, so I'm not really sure what to do
What information do you need that isn't available on trigger collisions?
I am on a quest to make my own joint in 2D since the available joints don't fulfill my needs.
I need a joint that can stretch linearly like a spring and wobble angularly like an angular spring.
For that, I am able to make the forces using distance and some math but I am stuck at calculating the damping. I am able to calculate the current relative speed between the anchors point of the two objects using linearVelocity and angularVelocity with some trigonometry. I would reduce the relative speed by applying an Inpulse force that is opposed to the relative velocity multiplied by a factor smaller than 1 (1 would stop the part from moving). But I just don't know how to apply that force so it makes physical sense (do I apply different forces to both objects if they have different masses, or the same, etc.)
Is there any easy way to apply damp to two objects using code?
Hello, anyone available to help fix physics in my unity project? They object keeps glitching through the terrain despite the terrain having a terrain collider already
Hello, I'm back at it with raycasts, and again, to no avail. this is the relevant code:
void CheckForPath()
{
futurePosition = new Vector2(transform.position.x + speed*moveDirection, transform.position.y);
RaycastHit2D hit = Physics2D.Raycast(futurePosition, Vector2.down, 2.0f);
Debug.DrawRay(futurePosition, Vector2.down, Color.red, 2.0f);
if (hit.collider.tag == "Ground" || hit.collider.tag == "WallJump")
{
canMove = true;
}
else
{
canMove = false;
}
}
}
