#⚛️┃physics
1 messages · Page 19 of 1
constant speed relative to the platform or in world coordinates?
relative to the platform. if we are on it
everything is understandable, but creating impact in various elements of the game e.g. combat, would be more difficult
Afaik moving platforms are usually implemented using kinematic rigidobdy and moving it with rb.MovePosition so that you can read the velocity of the platform with rb.velocity or maybe even rb.GetPointVelocity if you also rotate it with rb.MoveRotation
this was tested by me but without the expected results.
I need to spend more time on this
thanks anyway for confirming my approach
What you mean by "without the expected results"?
the player was moving much faster than he should in the direction the platform was moving and vice vera
So if you didn't move at all, the player would still move in the direction of the platform moving?
it happened once yesterday
I generally use physics material set to 0 friction
controls this via script
public void Run(float interpolationRatio)
{
float targetSpeed = CalculateTargetSpeed(interpolationRatio);
float accelerationRate = DetermineAccelerationRate(targetSpeed);
float speedDifference = targetSpeed - RB.velocity.x;
float finalVelocity = RB.velocity.x + speedDifference * accelerationRate * Time.fixedDeltaTime;
RB.velocity = new Vector2(finalVelocity, RB.velocity.y);
}
Is this 2D?
yes
Does the moving with the platform logic happen in CalculateTargetSpeed?
no. At first I asked** what was the best way**. Currently, I have already removed the code that does not work
oh
not sure if this is the right channel but my character is designed to jump only on "Ground" layered objects. but it can jump off of the sides of the object (vertical side). how do I prevent that and ensure it only jumps on top of the platform?
well that depends on how your ground check works
how does it work currently?
Vector2 direction = Physics2D.gravity.y > 0 ? Vector2.up : Vector2.down;
float extraHeight = 0.1f;
Vector2 bottomLeft = new Vector2(boxCollider.bounds.min.x, boxCollider.bounds.center.y);
Vector2 bottomRight = new Vector2(boxCollider.bounds.max.x, boxCollider.bounds.center.y);
RaycastHit2D hitCenter = Physics2D.Raycast(boxCollider.bounds.center, direction, boxCollider.bounds.extents.y + extraHeight, groundLayer);
RaycastHit2D hitLeft = Physics2D.Raycast(bottomLeft, direction, boxCollider.bounds.extents.y + extraHeight, groundLayer);
RaycastHit2D hitRight = Physics2D.Raycast(bottomRight, direction, boxCollider.bounds.extents.y + extraHeight, groundLayer);
isGrounded = hitCenter.collider != null || hitLeft.collider != null || hitRight.collider != null;
this is for ground detection
so if you're sending a raycast straight up or down all you need to do is check the normals on the RaycastHits
if the normal is too far off from straight up/down, you can consider the slope of the ground to be too much
so you suppose I should focus on the hitcenter raycast?
I didn't say that
you can analyze all three if you want
you will need to decide how to reconcile the three certainly
also the character can jump off of sloped angles but sometimes ignores a jump
like the jump doesnt register
could that be related?
I have no idea without seeing your script
anyone know anything about issues regarding inconsistent numbers on a rigidbody2d?
this is the magnitude printed
the object is quite obviously moving a lot faster than 0.00000X
I'm assuming it does the collision check, removes the velocity and then prints it. And it's inconsistent because of the physics tick rate
it probably sneaks the print in between phyics checks sometimes but other times it doesn't
in this test the magnitude returned on collision was 4.921604E-08
This is the magnitude printed by what?
it's printed by the object itself
not really sure what you're asking
it's printed by the rigidbody on the object, once it collides with something
I'm asking to see your code
Rigidbodies don't print anything on their own
void OnCollisionEnter2D(Collision2D collision)
{
Debug.Log(Rb.velocity.magnitude);
That implies there were 6 collisions in your video
It's very possible
It's spinning quite a lot
Well how do we know which is which then
What makes you think the log is wrong or inconsistent somehow
because very similar tests produce vastly different values
the object will have the same force applied to it, from the same distance, with no drag
and sometimes it prints someting as low as 4.921604E-08
and other times it'll print like 5
Because it's spinning like crazy
It depends at what part of the spin it hits the wall
That will change the resulting velocity
I didn't think it would take the rotations into account since it's a 2D circle
also the rotations are on the object itself
not the rigidbody
rb has frozen z rotations
That's very confusing to me considering the object is clearly spinning rapidly
What's the difference between "the object itself" and the Rigidbody
the object's transform rotations are being modified
Well that's an awful idea
how do you figure that
You can't possibly expect physics to behave well when you're busy teleporting the rotation of the thing around
Never mix Rigidbody physics with direct Transform manipulation
I suppose
yeah you're right
forgot about that
that doesn't seem to be the issue though
I removed rotations of any kind
this is just the rigidbody moving with AddForce
Well that looks to be pretty consistently 0 now
I am quite confident it is because of the frequency of the physics tick
with my original rotations, using the transform
it's still "consistently 0"
even with the rotations, everything works exactly how I want it, if the other object has a rigidbody
Hi, I create a Bow mechanics and I want to when I throw an arrow, it will at first go straight at the beginning but after time, it's going down more and more and change the rotation from it. How can I do this ? Now I have just this but I don't know if I need to adjust the gravity scale of the RB or use AddTorque().
using UnityEngine;
public class ArrowCollider : MonoBehaviour
{
public float movementSpeedX;
public float movementSpeedY;
public float rotationRate;
public Rigidbody2D rb;
private void FixedUpdate()
{
rb.velocity = new Vector3(movementSpeedX, movementSpeedY, 0);
rb.AddTorque(rotationRate);
}
private void OnTriggerEnter2D(Collider2D collision)
{
Destroy(gameObject);
}
}
how would i get the collision data like shown here?
https://youtu.be/ILVUc_yV24g?si=q-JPxuCLjPPnLUge&t=486
Let’s talk about stairs, why they suck in games, and what can be done about that.
You wouldn’t think stairs are that hard for video games, until you see some of the bugs they can cause
Check out a live demo of the OpenKCC Project here - https://nickmaltbie.com/OpenKCC/
Chapters:
00:00 Getting High
01:18 What are Stairs?
02:33 Hiding the Problem...
Jitter animation applied on a trail renderer prefab, LEFT is build, right is editor
How to make them match?
There are several ways, but one interesting one is using AnimationCurve
Why don't my bullets go straight?
private void Fire()
{
Quaternion initialRotation = Quaternion.Euler(0, 0, 90);
Vector3 IniatialPosition = new Vector3(0f, 0f, 0f);
GameObject AmoInstance = Instantiate(AmoPrefab, ShootPoint.position+IniatialPosition, ShootPoint.rotation*initialRotation);
Rigidbody AmoRigidbody = AmoInstance.GetComponent<Rigidbody>();
if (AmoRigidbody != null)
{
AmoRigidbody.AddForce((ShootPoint.up)*ShootForce, ForceMode.Impulse);
}
}
Looks quite straight to me ignoring the gravity. What do you mean exactly?
like it's going a bit up , because if it was really straight I won't be able to see the bullet while aiming
Does the ShootPoint object point bit up then?
I found à solution ! the shoot point was a bone of my rig so I replace him by a empty and now it work perfectly ! thx for your help ! 😁
how can i make a ball bounce but with 0 rigidbody gravity ?
it doesnt bounce unless i increase gravity but i dont want the ball to have gravity
I just added a new animation and found that the bullets don't go straight at all.
I don't see how bouncing and gravity would be very related
bounciness 1 and gravity 0 it doesnt bounce
bouncinesss 1 a,d gravity 1 it bounces
idk too
Btw do you have the same field of view for the gun and the rest in case you are using a two camera setup to render the gun on top of the background?
Share more details
Why doesn't the two box collider touch? The object on top as an rigidbody and falls down.
Default contact offset in physics 2d settings
for now i'm only using one camera to render everything
is using a configurable joint at every point the body moves like elbow, neck, knee etc a good idea or a bad one
Depends on what you're doing. That's a pretty typical way to implement a ragdoll
I'd start by doing something like Debug.DrawRay(ShootPoint.position, ShootPoint.forward) to confirm the bullet actually starts at the right position and the direction is right
good idea !
why I see nothing when I shoot ? I juste replace what was in my fire void
private void Fire()
{
Quaternion initialRotation = Quaternion.Euler(0, 0, -90);
Vector3 IniatialPosition = new Vector3(0f, 0f, 0f);
GameObject AmoInstance = Instantiate(AmoPrefab, ShootPoint.position+IniatialPosition, ShootPoint.rotation*initialRotation);
Rigidbody AmoRigidbody = AmoInstance.GetComponent<Rigidbody>();
if (AmoRigidbody != null)
{
AmoRigidbody.AddForce((ShootPoint.up)*ShootForce, ForceMode.Impulse);
}
}
by what you send me , I doesn't have any error in the console but nothing is display in the scene when i shoot
private void Fire()
{
Debug.DrawRay(ShootPoint.position, ShootPoint.forward);
Debug.Log("fire");
}
Maybe it just flickers in and out so fast you/your monitor cannot pick up the ray. Try to give the ray some duration (one of the optional parameters of the DrawRay method) and see if that does anything
I make the Ray work and as you can see, if i'm aiming the botom of the tree, the ray doesn't go at all where i'm aiming and when the player is holding the weapon high, the ray didn't even start from the muzzle
I'm so dumb, I found what was the problem. Thx a lot for your help !😁
so I've used unity a decent chunk but haven't really messed with the physics stuff. I'm messing with a RA2 type game and need real physics axles on the motors. the axle would have other parts like wheels parented onto it and it would be rotated with AddTorque, so I need some type of link for the axle to stick to, I've tried hinge joints and configurable joints. but the hinge joints have WAY too much give, and the configurable joints I just couldn't get to not be jittery and broken (most likely due to my lack of experience with the component).
I ideally want a solid non glitchy stable joint, that still has configurable springiness to it. I think the configurable joint is the way to go but am unsure, any advice on a good way to move forward with this idea?
play mode screen shot for setup context.
the WheelPart is the next part on the chain, attached to the motors axle
Anyone know why this is happening?
Idk if it belongs here
some strange screen jittering
I also have lerping on almost everything so I don't think its the script
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
This is my camera script though
You are multiplying mouse input by deltaTime which is incorrect
That's a problem but not necessarily your only problem in your script
Also "lerping everything" is not a fix-all
Your euler angle manipulation is also pretty suspect
o okay will double check all that ty
Why doesn't it work?
I want a physics rig where an object has two configurable joints. One is connected to another rigidbody and the bodies are swapped. Another is connected to another rigidbody so that body follows it
But when I put two on the object, it freaks out
Hey guys, I've been developing a VR based Squash game and facing some issues in collision between the Racket and the tennis ball, I've tried to write the script for both of these dynamic objects but something is still felt missing, I am dropping both of the scripts below, kindly help..
can i get some advice on good settings for responsive HQ physics?
I tried just setting certain things really high
but my game objects are super jumpy, like they just get flung random directions. not far most of the time, but its still unusable
here is my current setup
what specific problems are you having with the default settings that you want to solve?
i want to make a realistic motor that has a RB on its axle and the hinge joints and others were just freaking out on default settings
this post is related but from before i learned you could change the physics settings
if you want to make machines you might want to look into ArticulationBodies
oh?
well the game is meant to be like robot arena 2. can those be self contained on each robot part?
like, a motor is a part you can place, then choose a wheel to put on it. so not one prefab
you can absolutely build a system like this
oh cool! ill look into it
i also gotta figure out wheel colliders, and how to make them dynamically on play
a wheel could be anywhere on the bot, but i know you cant spin the collider with the wheel, so i cant include the collider on the wheel prefab when the whole prefab gets spun
right now just using a physics material on the mesh for the wheel, that doesn't work well at all. and i expected that
this is 100% what i wanted, wow how did this not show up when i was on google

I need some help designing a VR stock for guns
H3VR does this well, and all of the objects are physics based
I just finished my boneworks style rig, have no idea how I can implement it
Basically I want for when the gun goes to where your shoulder might be IRL, for the gun to have an anchor point around that contact point
H3VR
I mean, the problem with your idea is that it would break the link between where your hand is, and the gun, no?
This... is not a problem?
Games have been doing it for years. It is the basis of physics based VR
the hands normally clip through items, or if they dont are VERY selective.
ide imagen emulating the shoulder would involve code that knows when a stock is in range with a small trigger, then smoothly guiding it where it needs to stay in front of the collider, without overpowering the players movement
Not in physics based games?
how can i make this rotate properly when trying to turn?
in that video im trying to turn and yet the robot doesn't rotate like ide expect it too.
the wheels on the left are spinning opposite to the right, like tank controls almost
wish i could use Havok as thats what RA2 ran on back in the day. but i aint a pro member of unity lol
for more context, here is a clip from RA2, thats the kind of wheel physics i want to get, just more refined thanks to modern game engines. you can put wheels on anything in the game, so its very daunting to me lol
the wheels are super responsive in that game. feels very clean. but still like your controlling a 700kg robot.
Actual physically spinning wheels don't really tend to work very well in PhysX.
You should try WheelColliders or adding forces to the rigidbody manually
that's what I've read, and experienced.
And that's part of the issue, I tried wheel colliders but they just don't work for what I want want or just make it break
I assume that the main direction to go in would be the second option which is what I've been trying to do
I guess using AddForceAtPosition on the wheel position would be a good start
This reminds me of a combat vehicle building game I started a few years ago... I should get back to it
this is how i was trying to use wheel colliders before. along with the result. strange rotation from the RB being locked on rotation aside, it just has super strange physics and doesnt even move
the wheel collider would need to be self contained in the wheel prefab, and that's why its mounted on a locked ball joint, but due to how you are expected to use unity physics, the RB doesn't use local rotation space and the wheels also rotate strange like you can see. but the whole wheel spins and wheel colliders don't like that from what ive seen and read
for sure just need to do a custom script like you said.
a articulation body based 3d Wheel collider would be great from unity though. shoot ide pay for a addon like that lol
I've got a physics problem that I don't know how to approach, and I love any insight.
We are modeling a Texas Star shooting target. It's basically a wheel with weights, and when a weight is removed, the wheel spins to account for the new center of gravity. I've never done anything like this, so I'm not sure how to join two rigid bodies together and account for their weights.
Any thoughts on this?
you could prob use articulation body's
i was pointed to them few days ago and they are super useful for mechanical physics objects
the base of the star would have a articulation body on it, prob marked as immovable.
the star would have a articulation body and be set up with a Revolute Articulation Joint Type.
than each target would have its own articulation body with a fixed joint
or well, thats how ide set it up
shoot i mean, if your bullets will be physics based you could even use the breaking force limit the fixed joints give (ide still code the impact logic though to be safe)
Thanks for the response. I haven't heard of these components before (which is why I asked here :)) thanks for giving me a lead!
the force from the impact would snap the joint
yea! same thing i felt lol
Texas Star targets are dope btw, so good stuff!
its not perfect yet, but thats something!
ty
oh, it seems most of all the movement force is from the ground to ground friction
i dont understand why its working now
huh, if anything my code makes it more bumpy
🥲
Hello! Just wanted to ask, what kind of physics do I need to implement for a claw from a clawmachine ? Do this feels advanced to you or can I start learning physics from this example ? Thankss
i couldn't get my code to work how i wanted so i thought about how i could use a wheel collider. it would need to generate them separately under its own hierarchy due to unity BS
but i must ask, why are my wheels slipping like this? i have a physics material on the ground with friction, along with having tried messing with the wheel settings, nothing makes it get grip
Guys, I'm trying to add friction to my edge collider 2d but it's not working at all, I used 2d physics, scripts but anything works, is there other method to try?
You'd have to show what you tried
thats the inspector of the ground, i'm trying the Physics material 2d
the ball has a physics material 2d too
ok and:
- What materials are they using (what are their settings)?
- What kind of interaction is happening here? Is the ball rolling? Sliding?
- What effect are you looking to achieve?
- What happens instead?
grass have Sprite renderer, Edge Collider 2D
ball have Sprite renderer, Circle Collider 2D and RigidBody2d
the ball is rolling infinitely
I want to add friction to the grass so the ball won't "slide"
you gave me a list of components, not the physics materials
but yeah when the ball is rolling, friction actually has very little effect
in real life rolling objects have "rolling resistance" coming from deformation of the object but that's not simulated in Unity
what is Physics materials? i'm new in Unity
you were just talking about physics materials right here??
oh, ok
Hello, I want to tie the character by the foot with a rope and let it interact with the impact, but the rope must remain taut as if it were tied underwater.
Every way I've tried with the joint supports hanging/tying from above.
I would appreciate if you can help me.
it doesnt bounce back
the rope must remain taut as if it were tied underwater.
What I'm imagining is like... a balloon tied on a rope
is that what you want?
yes exactly
Ok then you need to actually make an attempt to model somthing like that
you need:
- A buoyancy force upwards on the character at all times
- A more realistic rope than a cylinder
but the first part is the most important
You could use the ConstantForce component or just write your own simple script
the rope itself is not the thing that would make it "bounce back", it's the force of buoyancy
the rope is just stopping it from floating into the sky or too far away in general
Hi!
i understand, i give it a try.
thanks for idea mate
@timid dove
Hello again, i made a balloon like this,
but i stuck on which joint to add and joint settings.
do u have any idea?
does anyone know whats going on here?
Hi physicists! I have the following issue and not really sure how to resolve it.
Situation:
I have a bot that travels ("glides") across a water surface in world forward direction. The water track consists of individual segments of 100 units in length that are simply positioned in a straight line. So each water surface (water box collider) is 100 units long. The boat has a capsule collider that keeps it on the water surface.
Problem:
Somestimes, when the boat crosses from one water collider to the next one. Right at the intersecting point of those two, it will cause a "jump" of the boat catapulting a bit into the air and gravity brings it back.
What have I tried?
- I have played with the collider's
contactOffsetbut with no luck - I have assigned a physics material to the water surface and the boat collider with bounciness set to 0
- I have verified that all water surfaces/colliders are at the same height and align "perfectly"
Any idea how I can prevent this jump and keep the boat going as if it was one large box collider? Just using one box collider is not an option since the level will later on be composed of multiple segments, potentially generated at runtime.
Use one large collider for the water and you can dynamically reposition it as needed.
Is there really no other way? This is a racing game and the final race tracks will be much more convoluted than just a straight line.
You could try using plane mesh colliders instead of boxes, in case the jump is caused by hitting the sides of the box collider
i'm sure there are other ways but I think this is the best way
How do I draw raycasts to debug? I am trying to use PhysicsDebugDisplaySystem.Line() but nothing is drawing
Unsure if im using it wrong or not
I do have gizmos on so I don't understand
Debug.DrawLine or Gizmos.DrawLine
you can also just turn on the physics query visualizations in the physics debugger
Where's that exactly?
"DrawLine can only be called from the main thread"
Okay Debug does work, instead of gizmos
Unsure why PhysicsDebugDisplaySystem just doesn't want to work but whatever
I'm not sure where or how you even found that. Gizmos and Debug are the usual candidates.
That's probably some internal thing for the physics system
That's probably what the built in physics visualizer stuff uses
iirc in a thread on the forums
Theres an official example that uses Debug.DrawLine so I guess that's just right
unsure if these work with unity.physics but i'll keep it in mind
Yeah that's why I asked about this because the manual doesn't really talk about drawing raycasts
yeah i know that one
I see
(which doesn't have anything about rays, thus why i asked)
How do I check the contents in a collision world? I feel like im doing something wrong because it only has a single element in its list (dynamic body?) and i have no idea where the two cubes with physicsShape are
Asking since my casts arent hitting those cubes
I'm been searching on this server but I still don't understand
InvalidOperationException: The previously scheduled job Broadphase:PrepareStaticBodyDataJob writes to the UNKNOWN_OBJECT_TYPE PrepareStaticBodyDataJob.FiltersOut. You are trying to schedule a new job BulletJob:BulletPhysicsJob, which reads from the same UNKNOWN_OBJECT_TYPE (via BulletPhysicsJob.world.Broadphase.m_StaticTree.BodyFilters). To guarantee safety, you must include Broadphase:PrepareStaticBodyDataJob as a dependency of the newly scheduled job.
like how do i even access that, where is it
im new to unity and c#, and im trying to set up a laser for a game im making however its sorta broken and im not sure whats happening with it, the laser’s raycast midpoint is somehow set where the laser starts instead of the midpoint of the ray. i've done a ton of debugging and just cant seem to find the problem https://gdl.space/hejesuqofi.cpp
Is it true that if you perform custom Physics.IgnoreCollision logic against some colliders and at some point later if a collider was disabled (or it's game object), all those previously set IgnoreCollisions will be wiped and need to be call again?
no colliders or gameobjects are being disabled, im only removing and reapplying a "hazard" tag to the laser when it activates and deactivates
what channel would i go to for lag problems?
Use profiler to find out what's causing the lag and ask on the channel most relevant to the cause of the problem. Ask on #💻┃unity-talk if you have problem using the profiler
How to avoid the caracter being stuck to the wall like this
Add a jump or automatic step-up mechanic to your character controller. Basic physics are not designed to allow that kind of thing being fixed inherently.
no but like the player is Stuck to the wall instead of falling, I don't want the player to be able to climb this wall
Make colliders vertical, use a navmesh or some other kind of kinematic constraint on player movement
how can I make a collider that fit perfectly to this part of my caracter ? I tried with a mesh collider but it doesn't work
Hey folks! Quick question. Is there a way to have joints that collide but have 0 mass or inertia? I want to have rotating joints that do not phase through objects but also do not have inertia. Is this a thing that can be accomplished?
how do u make something like that? Where u can push rigidbodies like this
Make your character out of a Rigidbody and move it via the physics engine
Ok thx
Assuming it's a skinned mesh, you almost always want to use compound collider made out of capsule colliders and/or spheres/cubes. That way it might not be a perfect match but unitys mesh collider doesn't really work for dynamic meshes and even if you update the colliders mesh manually runtime, it might not perform well enough. For character meshes it's highly recommended to use compounds whenever possible
ok! if a bullet hits one of the colliders, is it possible to get information on which parent has the child where the collider is? for exemple here, if my bullet hit the collider on the bone.009.R, can the bullet acces to the name of the parent object for exemple here, get the name of "Player"
Yes, having access to the parents as well as the specific collider that was hit is one of the advantages of compounds (can be used for headshot/damage system), but generally relying on object names isn't a good practise. Instead you could use tags or potentially layers in some cases to distinguish objects from each other.
I want the name because my game is a multi player game, and when an instance of a new player is created, I rename this instance by the ID of this specific player/client
Might be fine then, I got no experience with multiplayer games so I'm not the right person to judge that. Btw. this is likely what you will find useful https://docs.unity3d.com/ScriptReference/Transform-root.html
Oh thx ! that what I was looking for
you could also recursively or iteratively call Transform.parent until the parent you want is reached or the .parent is null (top most parent) but .root should do in this case
oh ok ! for now .root should be enought but that always good to know !
the problem is that my capsule fall on the floor the moment i try to addforce. Im so stupid i can't remember how to solve this problem
nevermind, freezing rotations should be okay
When i spam left click (grab and release object) this is what happens (when i grab the object, the collisions between the player and the object are disabled viceversa when released). So how can i fix this bug? I can basically go in the sky with this bug.
lots of workarounds.
- you could delay re-enabling collision between the object and the player for a certain amount of time
- you could delay re-enabling collision between the object and the player until the object touches the ground
- you could delay re-enabling collision between the object and the player until you have verified through physics queries that the player is not overlapping the object.
- You could delay being able to pick the object back up (with similar restrictions as above)
hello gang
im trying to make the red thing hinge on the yellow thing using the green thing as the joint
will a hinge joint work?
Thank you so much, i'll try all the solutions
For best optimization of my physics in my MMO game, should I avoid using rigid body or can I use it?
you're going to need to do your research on physics + whatever networking framework you want to use
physics + networking is a complicated thing
it would be best to avoid force-simulated physics in a network game. You can use triggers and force-simulation for purely cosmetic client-side effects. Ideally everything should be kinematic and as much based on integers (not floats) as possible. Naturally doing everything with integers is also complicated extra work, but in any case, if its really important to be super accurate (no integration error), use integers.
Okay, I am already doing research on the networking and I have a solid grasp of what I need.
Well, it will put a large focus on nature and how it interacts. So gravity on the client side only has me worried, but I believe I partially understand what you are saying. I will look into how to use integers more for my project, since they sound quite good
when i try to grab a gameobject (it has to implement collider and rigidbody) i have a problem where basically there are gameobjects that its collider and rigidbody is all in one gameobject and gameobjects where the rigidbody is in the parent and the collider are the children.
for example a plate, where there is an empty object that has a rigidbody and its children that have colliders
and burgers where it has an empty object that has a rigidbody and a collider and a children for the mesh
private void TryGrabObj()
{
RaycastHit hit;
if (Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out hit, grabDistance))
{
print(hit.transform.name);
print(hit.collider.name);
IGrabbable grabbable = hit.collider.GetComponent<IGrabbable>();
if (grabbable == null) grabbable = hit.transform.GetComponent<IGrabbable>();
if (grabbable != null)
{
grabbedObject = hit.collider.gameObject;
grabbedRigidbody = grabbedObject.GetComponent<Rigidbody>();
grabbable.grabbed = true;
grabbedRigidbody.useGravity = false;
grabbedRigidbody.drag = 2;
Collider grabbedObjectColl = grabbedObject.transform.GetComponent<Collider>();
if (!excludedParents.Contains(grabbedObject.transform.parent))
{
Rigidbody[] rigidbodies = grabbedObject.transform.parent.GetComponentsInChildren<Rigidbody>();
foreach (Rigidbody rigidbody in rigidbodies)
{
rigidbody.velocity = Vector3.zero;
rigidbody.angularVelocity = Vector3.zero;
rigidbody.useGravity = false;
rigidbody.drag = 2;
}
Collider[] colliders = grabbedObject.transform.parent.GetComponentsInChildren<Collider>();
foreach (Collider coll in colliders)
{
Physics.IgnoreCollision(coll, playerCollider, true);
}
} else
{
Physics.IgnoreCollision(grabbedObjectColl, playerCollider, true);
}
}
}
}
This is what my code is doing, but for the plate it doesn't work because the collider doesn't have a component igrababble.
does anyone have an idea on how to make a floating object "stay in place", but still be movable a tiny bit
so like, if you had a floating rock, and there was a player constantly applying force, maybe the rock would only move a teensy tiny bit
then as soon as the player stops applying the force, the rock smoothly moves back in place
i tried using moveposition, but it's way too fast and clips through objects
adding force also makes it a little too "slippery"
add a force that pulls the rock to the home-position and reduce the player‘s force over distance away from home.
Anybody up for a challenge?
Do you know how i could addforce to get the object to a certain position, because whenever i try to add that, the rigidbodies always feel so slippery
you just put the "home" position wherever you want the object to be and modify the power and reduction-over-distance of the players move-force, tweak that until it feels right, note that this is basically a gravity simulation and gravity decays exponentially over distance.
if you don't like it how physics work/feel, you need to use a different (kinematic) solution.
is there a way to check if a collider is colliding without doing a whole script and make a public boolean variable putting it true if it's colliding and false if not?
doing a whole script and make a public boolean variable putting it true if it's colliding and false if not
whay
If you want to make your game do stuff, you write code, or you use code someone else wrote
To check for collisions you either use collision callbacks or direct physics queries
it's because when i want to do a functional thing i wanna use as less scripts as i can to optimize but nevermind i did a script with a boolean var
WIthout any specifics of what you're talking about it's really hard to say or make any recommendation
"less scripts as possible" is generally not a good optimization strategy.
i didn't know it, i thought that the less the scripts are the more optimized is the game
that's a very naive way of looking at things.
You can measure the performance of your game using the profiler.
counting scripts is not a good measure of performance
i'll do it, thx
guys im trying to make the red thing hinge on the green thing which is connected to the yellow thing
does a hinge joint work?
Has anyone ever done in-depth testing, when it comes to the performance of the various aspects of the physics system?
I'm currently working on a system in which I might end up using a Physics layer just for raycasts, and have everything in that layer be set to be a Mesh Collider, but I'm uncertain what the performance implications of having a ton of non-colliding mesh colliders in a scene would be.
The physics engine is designed to deal with exactly that situation. Performance will determined by the length of your raycasts relative to the density of objects with proximity to its path. If you do not move these mesh colliders you can have a lot of them.
So basically, having a lot of colliders doesn't have much of an inherent performance implication until they are actually used to do things?
yes
you can also optimize the method for broadphase collision evaluation relative to how your objects are distributed (mostly in one plane vs arbitrarily)
I tried to make ragdoll but it doesn't work and I don't know why, all the part that are gone far away are the part where I tried to make ragdoll by Adding A character joint, a rigidBody and a collider
Usually this happens from individual bits of your ragdoll colliding with each other
When they overlap to start with
oh so my colliders shouldn't overlap ?
also I don't know if it's a probleme, but for rig and animation simplicity the foot and the hands are not connected to the legs and the arms
So this is bad ?
I tried to remove overlapping collider but it's not working , moreover I don't know why the player Is doing that because is animator is still active
It's ok but the overlapping colliders shouldn't collide with each other
Pretty sure there's a setting on the joint for it
Ok , but why it's still not working even if at the start the colliders are not overlaping ?
im currently using unity's navmesh for smarter enemies in a 2d game, problem is whenever the player moves and the camera follows it the enemy with a navmesh agent starts jittering and shaking but when the player and the camera stops moving it seems to be fine
jittering means there's a mismatch between the cadence of the object moving and the camera updates
typically this comes from using RIgidbodies without interpolation or having code that breaks rigidbody interpolation
so how do i fix that, the object(ill assume is player) 's movement is set on fixed update and the camera follow on late update, and yes i have the player's rigidbody set to interpolate
show your movement code
ok
i changed it to update before and it did fix the problem but caused even worse ones(player movement became inconsistent and it just goes through colliders)
You are moving your object via the Transform
ye
this breaks.... pretty much everything
related to physics
you certainly aren't going to get working interpolation
you should be moving via the Rigidbody
ok
ill change that
it seemed pretty obvious but i just stuck with this type of movement in all my games xd
Get a reference to your Rigidbody and replace the Translate line with
rb.velocity = moveDelta * speed;``` (make a speed variable too)
all your games are broken 😉
i havent noticed it yet 💀
physics has always been a problem for me
seems to be working now ty
Why my trigger collider doesn't always detect when the bullet passes through the collider, but when I shoot on the player it always detect that the player has been hit.
the script that detect bullet fly-by :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FlyBy : MonoBehaviour
{
public string BulletTag = "Bullet";
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag(BulletTag))
{
Debug.LogWarning("Fly");
}
}
}
Hi all, does anyone know why a SpringJoint in Unity could be applying a force upwards?
I'm trying to make a grappling hook system, and it all worked until today for some reason. I know probably the damper and spring values must be related to this, however, I just can't seem to understand it.
Whenever the hook is set on the ground the player begins to float away from it as if given an upwards force
I've tried a variety of values for spring and damper, incluiding the ones from the script that's all over the internet with regards to this (Dani Dev's one https://github.com/DaniDevy/FPS_Movement_Rigidbody/blob/master/GrapplingGun.cs)
Triggers are not the most reliable for projectiles since they can easily tunnel through objects without ever intersecting them
Just curious, then would it be viable to have a raycast running every frame
The raycast could check between last frame’s position and this frame’s position
So how Can I do ?
That’s the most controllable way to do it
Can you define the "this"?
what are we looking at?
and why does it seem not possible to you?
its a circle object and it has a CircleCollider2d component attached to it. The 2 lines in console are showing transform.position values of both circle object and its component
components don't have different positions than their GameObject
they all have the same position, determined by the Transform component
so of course they will show the same position
oh
well
it seems that their position should be the same, however whenever a circle is moved, its CircleCollider2d stays in the same place
You would need to show the object hierarchy and which components are on which objects.
But presumably your renderer is a separate object or something
or the collider just has an offset set
btw the location where that gizmo is shown may be different from transform.position if you have your tool handle position set to "Center" rather than to "Pivot". This is a common source of confusion, and you should check that.
well I'm actually implementing a drag and drop here, and it seems that the location of both CircleCollider2d and a circle object is accurate
If you want more help please share this information, otherwise I'm working in the dark.
what sprite image are you using?
I'm basically just using a slightly modified version of a basic Circle sprite
modified how
can you show the sprite editor for it
oh i've just changed its pixels per unit value to be 1080 instead of given 256
seems fine to me..
thats what i said
but sadly it doesnt seem to work
ive tried to search that up on the net but it doesn't seem like anyone who got it was bothered enough to make a post about it
could this be related to the way Raycast in Physics2d works?
i'm using it to implement the dragging function as the circle is always located under some kind of UI, so the basic MonoBehaviour OnMouse___ functions dont seem to work properly
you should use the event system for all of this
There's a built in drag system
i've tried to do that but the circle object isnt a part of the UI so i'm not sure where to get the event trigger from
it works for non ui
oh
you just have to make sure you have:
- Either a script with IDragHandler/etc on it or An event trigger component with the drag events set up
- A Collider2D on the object
- A PhysicsRaycaster2D on the camera
- An EventSystem in the scene
alright then but how can i actually trigger the OnDrag method from the interface if a UI element is covering it?
what kind of ui elemenmt is it
does that ui element need to be interactable too?
in my code i've done it like this:
var mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Ray ray = new(mousePos, transform.forward);
RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction);
if(hit && hit.transform.gameObject == gameObject) {
holdingdown = true;
} else {
Debug.Log("missed me!");
}
}
if(Input.GetMouseButtonUp(0)) {
holdingdown = false;
positionInput.GetComponent<InputFieldManager>().ReAssignInputValue();
}
if(holdingdown) { //decided not to use Input.GetMouseButton(0) as theres no need for it.
// Debug.Log(Input.mouseScrollDelta.y);
var mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mousePos.z = transform.position.z;
transform.position = mousePos;
actionLineManager.changePosition(transform.position.x + ";" + transform.position.y);
}```
yes
So that's confusing
if you click on the UI element, which thing are you supposed to interact with? The UI or the thing behind it?
How can you tell?
what is this UI?
oh thats not what i meant, my bad
the object that is interactable is located beneath a editor menu UI, that is parented by multiple actually interactable UI elements
wont it be a problem if i make the parent object un-interactable towards its children?
For whatever thing you want to be able to click through in the UI you should just disable the "Raycast Target" on it
alright, got it
i'm not really sure what this means
to be fair i dont even know either now
since you've told me this
i think i understand it now, i'll try to make it work with that interface
thanks for the help, ive learned a lot
I have a very simple scene - a cube and a floor.
I want to control the cube through a script that changes its velocity (only x and z components).
It seems to work only when the cube's gravity is disabled, and the cube does not move when gravity is enabled. The mass is set to 1, and there is no drag. Also tried to reassign a Rigidbody component.
What can cause it?
I'm facing an issue where the pushing object is passing through other objects. I've set Fixed Time Step to 0.01, all objects have proper colliders, extrapolate is selected, Continuous Dynamic is selected, the player's mass is 50, and the bullets' mass is 1. Additionally, I have a script on the bullets that applies a force in the opposite direction when the pushing object hits them. I can't seem to solve the problem. If anyone can help, I'm open to your solutions.
I'm having some trouble with configurable joints. I've got a bucket and a handle. The handle is a configurable joint restricted to one axis, and moves perfectly fine. I can't figure out how I can move the parent rigidbody (the bucket itself) without leaving the handle behind
the handle motion works as intended, but the bucket rigidbody falls to the floor, leaving the child handle behind
I've tried putting a fixed joint on the bucket to no avail
it looks like articulation bodies would solve my problem, but they are incompatible with XR interactable objects... Any speculation as to how I can achieve a parent-child relationship with rigidbodies and joints?
is there any heiarchy or order to joints connected to one another? I know parent/child relationships between rigidbodies are seemingly ignored
Hey guys, I've got some doubts to ask.
I'm currently working on a car controller using hooke's law. I've got it all working well and good and i decided to add steering but the issue is that i have no idea on how to add steering using hooke's law, I've done it using wheel colliders but i'm not using them
this is what it looks like
Making a car controller from scratch will get even more complicated than that. You don't just have to control steering but also sideways drag too.
There are detailed posts discussing alternative systems to wheel colliders on forums, they should be now migrated and searchable on Unity Discussions boards.
But if you want to proceed with yours, you'll need a lot of custom control of directional forces and calculating amount of sideways drag
um ill try, thanks for the help
Is Unitys physics accurate enough to be able to simulate say an engine with pistons without clipping and breaking
you mean using constraints/joints/pivots/springs and the like?
its not really possible to simulate a piston sliding in a cylinder with any kind of realistic dimensions and tolerances
you can probably make a "goofy" simulation, and you can probably use constraints to make something that looks like a piston in a cylinder attached to a crankshaft. You would probably have trouble simulating a camshaft/cams based on the collision solver aswell
but i'd be very cautious with my expectations. It would probably be much easier to custom code that kind of thing
note that physx sometimes produces unpredictable nomerical glitches at triangle edges when mesh colliders are involved (this affects all queries into the simulation, including raycasts aswell as its internal solvers), so if your need any kind of accuracy in surface friction & shape you will probably not get there. The only way to mask these glitches is by making the simulation less precise.
You would not want to try to use the physics engine to actually simulate this. Make an animation and just play it at various speeds
You could simulate things like engine rpm/torque/power hands etc numerically but doing it fully as a physics sim is a no go
A combustion motor is a basically a whole bunch of fluid dynamics which is extremely complex
i see my concept was to make a sorta sandbox style game that focused around creating mechanisms i wouldnt implement actual fluid dynamics though
Yeah you can do all that just don't try to get PhysX to do fluid dynamics
so it will still be able to simulate fast moving pistons and stuff?
i mean source engine was able to do it but doesnt that use like an old version of havok how does that compare to unity
that actually looks really useful thanks
It's not clear what you're asking here.
Is this the current behavior or the desired behavior?
desired behavior
i want my rigidbody to slide to things like this
this is another game
You would get this behavior automatically if using any typical dynamic rigidbody movement
but why is my rigidbody sticking to walls when i walk to them and then try to go left and right like in the video
friction
if you want to remove friction
alright
thank you so much
what friction does unity put on colliders automatically if i don't put any?
The default physics material
If there is no Physic Material set, a collider uses the default surface settings. To adjust the project’s default settings, use the Physics Settings.
oh thx
Hi, I'm working on a 3D platformer with a rigidbody character controller. Going ok so far, but I'm having an issue when trying to move my character on moving platforms
Hello how can we throw obects ? I'm currently making an FPS and I want my player to be able to throw a grenad but I don't know how can I do, do I parent the grenade to the hand and when I want the player to release the grenade I unparent it ? do I instanciate the granade when it's suppose to leave the hand ?
You can do either of those things, sure
Basically any method you've seen to shoot a projectile, the same works for a grenade
since it is a projectile
Yes, but for my bullets, they just go straight out of the barrel. However, my grenade needs to be held in the hand and animated before being thrown
Same deal, just with an animation beforehand
use an animation event for releasing the grenade at the right part of the animation
when I release the grenade, should I apply force to it ?
you can apply a force or just set the velocity directly
whatever you want
ok !
I've done a bit more digging on this. I've added a Rigidbody to the moving platform, and set it to IsKinematic. This initially didn't seem to make any difference, but changing my character rb from Interpolate > None > Interpolate on Start has fixed the 'sliding off the platform' issue as the moving platform moves.
Force application to my character still doesn't work correctly when on the moving platform though. It is applying force, but massively reduced when it is in motion. I've checked rb velocities, and they're the same whether or not its parented to the moving platform. Moving the platform through DoTween
Now have the player able to walk on moving platforms while they are moving. The best solution to this so far seems to be overriding the DOTween update cycle to use Fixed. I am interpolating both the player and the platforms rigidbodies now, but am getting a small bit of jitter on the background gameobjects, only when the player is on a moving platform, and particularly noticeable when moving on the moving platform. Any ideas?
Any idea why that black coin in the bottom sticks to the bottom wall and slides across instead of bouncing off it?
I think it's due to the rotation
Is their a way to increase friction between 2 object, to avoid my grenade sliding like that on the ground ?
Physics material is indeed the correct way to add friction but it is very well possible that the end effect still looks almost identical because instead of sliding the object will start rolling on the surface which may not be what you want either. If that is the case, you should consider increasing the angular drag of the object so that it's rotation will decrease faster
it's true that I hadn't thought of this case, thx !
where is the "used by composite" button? i have a composite collider and i have physics 2d enabled so idk what else could be wrong
what's in the "Composite Operation" dropdown?
it works
is it something wrong with the other rigidbody?
an object with physics to collide with the tilemap
Ok why don't you show the inspectors of the two objects?
(the full things)
heres for the object with physics
looks like it doesn't have a collider
oh 💀
If you want your object to collide with things, it needs a collider.
it works now, thanks
does anyone know why does this happen?
What is "this"? The space between the character and the ground? I'm guessing the small green rectangle below the character is for ground check so it's placed too low
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
Does anyone know why my character flips back and forth in the x axis when he moves into a wall? Here is my flip code
// private void Flip()
{
if (isFacingRight && rb.velocity.x < 0f || !isFacingRight && rb.velocity.x > 0f)
{
Vector3 localScale = transform.localScale;
localScale.x *= -1;
transform.localScale = localScale;
isFacingRight = !isFacingRight;
Vector3 currentScale = bulletPanel.transform.localScale;
currentScale.x *= -1;
bulletPanel.transform.localScale = currentScale;
}
}
I'd also like to mention that the second portion of the code is for something else and doesnt relate to the player
well this isn't really a physics question but...
Debug.Log your conditions and the values of the variables etc and you will find out why
mb, I just assumed it was 🤷♂️
Where would I put that
Also I know it probably has to do with the velocity going back and forth between positive and negative and never being 0, but how can I 0 it or rewrite the code so that it doesnt do that?
where would you put what
the log?
Right before the code that's misbehaving
oh I meant the question, sorry for not clarifying
could you still answer this pls looool
has anyone seen this behavior before? I'm using RigidbodyConstraints.FreezePosition (as well as FreezeRotationX and Y) and for the gear's rigidbody so that it snaps into place when it collides with a trigger volume. Instead of freezing in place, its sliding down slowly for some reason. i can give more info on the scripts if needed but it may be something simpler than that
Showing code would be good
And the inspector for the Rigidbody with the constraints
well at least two problems
first:
gear_rb.constraints = RigidbodyConstraints.FreezePosition; // NOT WORKING - just isn't freezing position or rotation
gear_rb.constraints = RigidbodyConstraints.FreezeRotationX;
gear_rb.constraints = RigidbodyConstraints.FreezeRotationZ;```
this is wrong
ok sweet
you're overwriting the constraints
at the end of this you will only have FreezeRotationZ
to combine them you would do this:
gear_rb.constraints = RigidbodyConstraints.FreezePosition | RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationZ;```
The second thing is:
gear_rb.transform.SetPositionAndRotation(rb.transform.position, rb.transform.rotation);```
It's highly recommended not to touch the Transform of your Rigidbody
you could do this:
gear_rb.MovePosition(rb.position);
gear_rb.MoveRotation(rb.rotation);```
gotcha i had those commented out right above woops
right
best to stick to the physics world (rigidbodies) as much as possible
ok i have another question, the gear I want to use is made of multiple separate gear teeth (11 of them, each with their own rigidbody). I read online that you shouldn't parent rigidbodies to parents with a rigidbody which makes sense, but how else should i combine the teeth together to make a gear?
why does each tooth need a Rigidbody
i wanted the collider to be clean since convex was super inaccurate
that doesn't answer the Rigidbody question
That answers the Collider question
which wasn't asked 😉
oh bc i want them to interlock with other gears
but again
why a rigidbody for each
you can have one Rigidbody in the parent
and 11 children with colliders
it will all be considered one physics object
oh yeah oops i didnt even have what i said i did
i did before though should've checked
its still doing something odd but ill figure it out
when i try to transform the parent rb its actually transforming the first child rb
not sure why
when i try to transform the parent rb its actually transforming the first child rb
What do you mean?
with this line
Also I thought you didn't have child rbs
in my reply, that highlighted tooth is the same as this one
even though i dont have child rb
if the project is in urp3d but the gameobjects are spritebillboards, would it be best to use collider3d or 2d? I would think its 3d but I cannot get the OnCollisionEnter to work
Everything has collider/rigidbody
The physics and the rendering are completely unrelated
You just need to be consistent about which physics you use
Everything needs to be 2D or everything 3D
I might need a little help with this but I am trying to make a script that causes a Particle/Particle Projectile to trigger a Animator Parameter upon collision
im still stuck with my previous problem, i have a parent gameobject with a rigidbody and it has children with only colliders. all im tryna do is transform the parent's rigidbody (2nd pic) to match the position of the trigger volume (3rd pic). instead, it doesn't appear to be matching the transform of any one gameObject, but it does look like it has something to do with the first child/gear tooth (1st pic)
culprit may be in either of these funcs?
does it at least do something? move but to the wrong place?
i think it may simple be colliding with the gears? this is assuming the cube is the only onTrigger collider while the pin and gears are not. MovePosition would stop on a collision.
Are you just getting confused because your tool handle position is in Center mode instead of Pivot?
that would make sense ill check
it does thankfully, ill get back to u
Just out of curiosity: is there some partucular reason to use physics for the gear? If you have multiple gears that needs to rotate against each other as I assume, that's usually easier to do just by coding the rotations based on the gear ratios rather than simulating it with physics which may end up buggy and unstable especially if there's many interlocked gears involved in the simulation.
thats rlly useful thank u, its hard to know whats the best approach as a beginner
what i wanted to do was have an adjustable torque slider but if im having this many issues ill consider using rotation, not sure if theres some interesting variable to adjust with that though
I have multiple colliders on gameobject. In that game object is there a way to use OnTriggerEnter type of deal and get the source collider that triggered that event?
So if goA triggers against goB I can get the goB collider from the parameter in OnTriggerEnter, but how can I get the collider that triggered that event from goA?
Put the OnTriggerEnter script on separate objects with only one collider each and have it forward its own collider reference to a function on the root object.
im trying to find a way in unity 3D to penetrate one collider into another. Think about how when a sword would strike a wooden block the sword would become embedded in the wooden block. That's the goal. I'm going for right now. however I need to find out how to dislodge that sword afterwards, too.
Any ideas?
please @ or reply so I can get the notification
do you need it physics based or can it be an animation?
also is the wooden block colider static, or can it be non-static too? might be easier if it is
either way I'd make them not collide, only above a certain velocity perhaps, and handle it via code/animation
might be possible to make it as an animation
but the collision is part of the base game mechanics
you throw a knife, it gets stuck in a wall, and then you can throw it out of the wall into another one
unfortunately, the other colliders (walls) are not static, but kinematic rigidbodies
I tried making the blade a trigger at first and just stopping if it intersects, but then the blade could just get thrown further into the wall. Ideally it would not be able to penetrate any further into the wall
you might REALLY like to learn about Physics.IgnoreCollision(), which can make all collisions between two specific colliders be ignored, and you can toggle it at will
So when blade hits the wall, ignore that specific collision, move it at the current velocity a bit further along the direction it was going (so into the wall, so it's not just touching it with the tip of the blade) and leave it there. Make sure to call ignorecollision with the optional bool again, when returning the knife, to reenable the collision with the same wall in the future
this way you will retain full collisions on the knife and you will get the initial oncollisionenter call, but you can disable collisions with the wall afterwards and control the knife via code when it's stuck in the wall, and when it's returning
oh, great, thanks! Didn't know about this
I suppose the big thing to keep in mind is to keep my wall meshes almost all convex
Since I could see some issues with not exiting a collider properly with concave meshes
It could get stuck inside the object like this
But that's super helpful, thank you
seems like you're familiar, do you know if there's any finnicky stuff I should know about this?
I guess I'm wondering if I need to handle issues where it doesn't ignore the collision correctly on the frame the collision happens
or if it just works well
you might have to babysit it via code during collision, to sell it really sticking into the wall nicely
you might also need to babysit it during flying back towards the player, don't reenable the collision immediately, and do the leaving the actual wall part from code, reenable collision with that collider, and only then fling it with physics towards the player. You might still have to make sure it reaches the player with some sneaky non-physics, if you insist it flies with physics towards the player, otherwise it will just get stuck into something else possibly. Make it bouncy on the way back maybe? or something
just a few ideas
main thing is script the going into and out of the wall completely from code, to control how it works, and let physics only effect it while it's 100% outside of the wall
thank you so much! 🙂
brilliant
Yeah that was my plan B. Thought maybe I'd ask if there was a built-in way to do it. Thank you for your reply though.
if your speed and acceleration are both 10 are you making an agent that can only move at speed of 10?
i am talking about navmeshagent settings. maybe wrong place to ask
Hello. I'm making a 2d spider that uses its legs to walk. It uses 2d hinge joints. I know you shouldn't use transform.rotate with joints and rigid bodies, but it gives more precision than the chaos of using motor speeds with precise alignments. The weird thing is, it works well with the right side legs, but the left side legs, not so much. they seem to only rotate one way(not consistently). but I'm assuming its going out of the joint limits, hence the full rotation. I only manually rotate the transform of the "thigh" to align it to lock on to its next step target. The left legs freak out sometimes.
Vector2 footPosition = GetFootPosition();
Vector2 directionToTarget = (currentTarget - footPosition).normalized;
float aimRotation = 0f;
float targetAngle =
Mathf.Atan2(directionToTarget.y, directionToTarget.x) * Mathf.Rad2Deg;
float currentAngle = legSegment2.transform.eulerAngles.z;
float rotationSpeed = spiderController.rotationSpeed * Time.deltaTime; // Adjust the rotation speed as needed
float newAngle = Mathf.MoveTowardsAngle(currentAngle, targetAngle, rotationSpeed);
legSegment2.transform.rotation = Quaternion.Euler(0, 0, newAngle);
Is there a better alternative to hinge joints that offer more precise control?
Is there a reason you need to use the physics engine particularly here? A lot of people do this kind of thing with inverse Kinematics
because faking it isn't as fun
Well... in a sense, everything you do in a game is "faking it" but I take your point
lol. I understand now why no one makes games where things "realistically" move. So that's kind of my drive of for doing it this way. If its been done before I'd be curious. think there's an untapped market especially with machine learning for physics based characters
This kind of thing is way too expensive to make. It’s been tried to death. There is just no way with current mainstream hardware. And ML also has absurd upfront cost for training that will never be recouped. The only option is to find an algorithmic breakthrough that improves efficiency a million fold (ML is entirely brute force right now). Ubisoft is working on a hybrid approach (animation + physics). Demos/presentations on that are on YouTube.
Any idea why this is happening ?
i mean, i’m halfway there if there were a way to set my joint angles with precision
I have kind of a beginner question about the FixedUpdate() method. I've Googled a bunch, but I can't find an explanation for why running the physics on a separate, regular schedule from the framerate is advantageous.
Intuitively it seems very odd to me, since it seems like decoupling the physics calculations from the framterate would make the game behave differently at different framerates, opening the door for weird behaviour on very high or low framerates. What is the purpose of separating out physics calculations like that?
For example, if my game starts lagging and the framerate drops, shouldn't the schedule of physics calculations go down as well, to keep behaviour consistent with other mechanics in the game?
It guarantees that the simulation is the same each time
In fact it closes the door for varied behavior
in larger games you decouple most of your systems from the rendered frame update. It is neither neccessary nor beneficial to many systems to be coupled to a render update. Often much slower, sometimes much faster updates are required. Generally having a constant tick rate for a system makes it much easier to keep the simulation consistent without any crazy prediction/reconciliation handling.
In a system with inconsistent frame durations something as simple as constant acceleration will behave differently once you don't have a fixed framerate
its also not so much a different frame time, its more of a tick count, that happens to operate on a fixed interval relative to the render "thread"
there will always be 50 steps per simulated second. If the simulation can't keep up, it still gonna be 50 steps per simulated second (50 is an arbitrary setting).
I guess what I don't understand is, shouldn't the acceleration behave differently at lower framerates? If my game starts to slow down, but the physics calculations don't, doesn't that create a discrepancy? If non-physics calculations slow down but the car still accelerates at the same pace, won't this mess with consistency?
No of course not, you want the game to work the same no matter what the framerate is
It wouldn't do for a character to jump higher or lower due to framerate differences
What are the "non physics" calculations you're referring to that would happen differently and become inconsistent with the physics?
Note that most things operating on the render framerate will use deltaTime to adjust for the framerate differences, which is fine for interpolation and aesthetic purposes mostly but it's not consistent for simulation purposes.
How are they moving/being moved?
Hi, I was wondering if anyone would be able to give a short example of how one could have simple 2d gliding, similar to the paper airplane mechanic in Paper Mario Ten Thousand Year Door. I attached an example for anyone who hasn’t experienced this gem https://youtu.be/e3q4WR72IQ4?si=0xHfFc98hKpLAb0K
I am a paper astronaut.
Shouts go out to @guignome01 for smashing this record with a 739.
The Funny Links for those who want them:
I’d really appreciate any help. I’d assumed this wouldnt require a super complex script to work, since it seems pretty simple.
Ideally I would like to emulate the loss of speed when not pitched down, but make momentum last way longer so it’s much more smooth and doesn’t require constant bobbing.
The sphere collision object is being dropped from a height onto the box collider
So regular Rigidbody physics without a script? Can you show screenshots of your setup including inspectors of both objects?
Alright
My rigidbody {my box collider is a child mesh of it}
public void ImportCollada()
{
if(water != 0){
if(ch.height != 0){
ErrorText.text = "Reduce your height to 0";
} else {
// Load the Collada file from Resources folder
GameObject importedObject = Instantiate(Resources.Load<GameObject>("FGC2024Water"));
// Set the position based on spawnPosition
importedObject.transform.position = spawnPosition;
// Add Rigidbody component (if not already added)
Rigidbody importedRb = importedObject.GetComponent<Rigidbody>();
if (importedRb == null)
{
importedRb = importedObject.AddComponent<Rigidbody>();
}
// Ensure gravity is enabled (default behavior)
importedRb.useGravity = true;
importedRb.mass = 0.53f;
// Add Collider component (assuming you want a simple BoxCollider)
SphereCollider collider = importedObject.GetComponent<SphereCollider>();
if (collider == null)
{
collider = importedObject.AddComponent<SphereCollider>();
}
importMaximum edObject.tag = "Water";
Ball ballScript = importedObject.GetComponent<Ball>();
importedObject.transform.localScale = desiredScale;
water--;
}
}
}
mycode
Show the colliders
Is this intended (2022.3.41f1)? I'm trying to maintain the Rigidbody behaviour regardless of it's child colliders. For some reason it seems to behave differently when I enable the larger colliders, even though it has the same Inertia Tensor:
https://nyc3.digitaloceanspaces.com/teamparty/ShareX/2024/08/Unity_0eFySNcsYz.mp4
What about Center of Mass?
Doesn't work either
Changing the center of mass doesn't help to maintain the behaviour
It's almost as if changing to a larger collider is affecting the rigidbody in some mysterious way, even when I try to maintain Inertia Tensor/Rotation and Center of Mass. In the video, you can see even when disabling all colliders it maintains the same behaviour, but when I enable the larger colliders there's a small delay before it acts wonky (even though the inertia tensors are the same)
I'm using AddForce to move the ship, but the mass is also the same
I also get different inertia tensor values printed out in my script than what's shown in debug mode
m_InertiaTensor = m_Rigidbody.inertiaTensor;
m_InertiaTensorRotation = m_Rigidbody.inertiaTensorRotation;```
I keep trying in different channels, but anyone have an idea why my ragdoll's legs get pushed aside when I enable my ragdoll? (pics @ #🏃┃animation message)
Hey guys, Im working on a gravity gun-esque tool for a 3d physics-heavy game and I noticed that when a given object is "held" by the tool, there is visible jitter. Now, interpolation is the solution for these kinds of camera-tracking situations, however I havent really used it before and so I have some concerns. First of all, if I have hundreds of objects with interpolation turned on, can this introduce a noticeable performance overhead? Could this be avoided by only turning on interpolation for a given object when it is interacted with by the tool? Can interpolation cause problems if I have some outside force affecting the held object, like an explosion or another object bumping into it, etc, or is this handled by the physics system internally?
Yes you can just turn interpolation on when it starts moving but why not just start with it on for all such objects and see if it's a problem before you go about prematurely optimizing things
Also interpolation is purely visual and should not affect the physics simulation at all
yeah I agree about premature optimisation, but there was a line on the docs that made me think it over:
When interpolation or extrapolation is enabled, the physics system takes control of the Rigidbody’s transform. For this reason, you should follow any direct (non-physics) change to the transform with a Physics.SyncTransforms call. Otherwise, Unity ignores any transform change that does not originate from the physics system.
and basically it made me worried that it might complicate things down the line to have it on all the time, esp since Im working in a small team and some ppl may forget about this; then again Ive been working with it on today and so far it hasnt really been problematic so it can stay on x)
Well your team shouldn't generally be moving physics objects via the Transform anyway
That's usually a wrong thing to do
yeah thats fair, we're all newbies tho so mistakes happen and it takes time for ppl to learn xd
but its better for sure to do things the right way and then learn than just do them the first way that works lol
any suggestions for simulating physics on the bridge?
- do not trust unity's built-in joints, especially when it comes to combining a lot of them. This goes for any more complex physics-based behavior you would like to not break completely
- what I usually do to remedy the above is seperate the visual and physical functionality. In this case, perhaps make the actual bridge collider one static object (or a few bigger planes) rather than simulating each board. the visible boards can use some custom logic to partially react to the player but in a controlled manner, not impacting the player back
also, unless its like a key moment in your game, believe me 90% of players will just run across it, maybe look around a bit, and forget about it. Keep that in mind, no need to get it 100% correct right now
Has anyone run into the same issue? 🥹 I'm just trying to maintain rigidbody behaviour with addforces, regardless of the colliders
Are the colliders touching eachother?
Yep, but they're also intersecting each other in the original colliders that works fine
Oh well, I found a suggestion that tells me to use Spring Joint. I want to add details that affect gameplay, more than anything a bridge should be something dangerous if it is unstable to go across it.
not sure if this would be the place, but in the unity editor my player can't phase through the walls, but in my playable build the player can. anyone know how I can fix this?
I have a tilemap collider made, yet it just goes right through
Why is it that I need a very low-mass on my rigid body And I need a very high-speed applied to for my rigid body to move.
I am using rb.AddForce(Vector3.forward * 4000) and a mass of 0.5
Show the full code. One reason could be that that's meant for continuous force and if you apply it only once the total force will be much smaller
using UnityEngine.EventSystems;
public class Forward : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
public bool buttonheld = false;
public float speed = 60.0f;
private Rigidbody rb;
private CurrentBot cb;
private void Start()
{
// Get the CurrentBot component from the same GameObject
cb = FindObjectOfType<CurrentBot>();
if (cb == null)
{
Debug.LogError("CurrentBot component not found.");
return;
}
// Initialize the Rigidbody from the CurrentBot's players array
UpdateRigidbody();
}
private void Update()
{
// Reinitialize the Rigidbody if it gets updated
if (cb != null && rb != cb.players[cb.currentPlayer])
{
UpdateRigidbody();
}
if (buttonheld && rb != null)
{
// Apply force in the local forward direction
rb.AddForce(Vector3.forward * speed);
}
}
private void UpdateRigidbody()
{
if (cb != null && cb.players.Length > cb.currentPlayer)
{
rb = cb.players[cb.currentPlayer];
}
}
public void OnPointerDown(PointerEventData _)
{
buttonheld = true;
}
public void OnPointerUp(PointerEventData _)
{
buttonheld = false;
}
public void Move()
{
buttonheld = true;
}
public void Stop()
{
buttonheld = false;
}
}
speed here is 60.0f but in the inspector i set it to 4000
{And also another question, my spherecollider keeps going through my box collider so i changed it to a box collider but it still goes through, i debug.logged it and it detects it. The box collider is placed horizontally and the sphere collider is to drop on it}
You should only be applying forces in FixedUpdate not update
Wdym by you debug.logged it? What did you log exactly? Where did you put the log?
Oh ok ill do that
So what should my mass be then, along with the speed
Where??? This is "what" you logged, not the where.
Force and speed are not the same thing
"speed" is not a good descriptive name for the variable
And it depends on how quickly you want to accelerate and how often you plan to add the force
Oh mb basically a button spawns the ball, so there is a script I attached to the ball and I debug.logged it in that script
Oh ok
{
// Reinitialize the Rigidbody if it gets updated
if (cb != null && rb != cb.players[cb.currentPlayer])
{
UpdateRigidbody();
}
}
void FixedUpdate(){
if (buttonheld && rb != null)
{
// Apply force in the local forward direction
rb.AddForce(Vector3.forward * speed);
}
}
``` is this what was meant by adding a fixed update
But where in that script???
Start? Update??
using System.Collections.Generic;
using UnityEngine;
public class Ball : MonoBehaviour
{
public Rigidbody rb;
private CurrentBot cb;
public GameObject instantiatedPrefab;
private void Start()
{
// Get the CurrentBot component from the same GameObject
cb = FindObjectOfType<CurrentBot>();
if (cb == null)
{
Debug.LogError("CurrentBot component not found.");
return;
}
// Initialize the Rigidbody from the CurrentBot's players array
UpdateRigidbody();
}
void Update()
{
if (cb != null && rb != cb.players[cb.currentPlayer])
{
UpdateRigidbody();
}
}
private void UpdateRigidbody()
{
if (cb != null && cb.players.Length > cb.currentPlayer)
{
rb = cb.players[cb.currentPlayer];
}
}
void OnCollisionEnter(Collision collision){
Debug.Log(collision.gameObject.name);
}
}
in its own function
That's a very special function, would have been helpful to say it was OnCollisionEnter
If that is logging the collision is definitely happening, it won't go through
Is there a way or a specified setting which can help me fix this weird thingie with the water? When you're outside of it, its fine, same goes on the inside, but my issue is when you're entering it, you have this weird line which really is messing with me, anyway to fix this?
Oh my bad
but then it is
What does this have to do with physics?
Because it's water...? I'm not sure
Am I supposed to use #archived-hdrp? I just noticed it, apologies
#archived-shaders is probably the best place
i have a configurable joint on a wheelchair so that when it tilts backwards it doesnt tilt too much but if it turns around it flips by itself
is there a way to fix this?
maybe there is a better way of doing this and limiting the tilting i dont know
is there a way to make the mesh collider not just a massive dome and actually make it the shape of the island? I can't use terrain since I'm needing to use a material instead of a texture (Terrain doesn't support materials for some reason)
Uncheck "convex"
Terrains absolutely support materials BTW
it does?
Is anyone interested in helping me solve this problem
If so i can send the code responsible for the dragging behaviour
I don't even see a problem in that video. Please do provide the code and actual description of the problem so someone might be able to help
The problem is that an offset is created between the cursor position and the position of the object when the cursor is moved beyond the border and then back. I dont want the object to move backwards as its held until the cursor "catches up" with it.
All code goes in one of the code channels, there is no way to fix your specific problem without clipping your object through other objects.
Scratch that, I'm thinking of something
I have a basket on a moveable rigidbody and i have a ball that is to drop on the basket but the ball keeps falling through the basket
Hey, so im using this tree and my character with circle colliders, and for some reason, at some spots the character gets rendered behind the tree (like it has to be) and in some spots it gets rendered in front... i tried changing the layers,. but then the player would also be infont of the buttom mart (the wood part) which i dont want, does someone know how to fix this ? https://cdn.discordapp.com/attachments/763500535554375750/1273417548481822770/image.png?ex=66be8a02&is=66bd3882&hm=6a908ccc202e3ed114227bff4308112dec25ef7e56150fd624d2a32981243c58&
https://cdn.discordapp.com/attachments/763500535554375750/1273417548846600233/image.png?ex=66be8a02&is=66bd3882&hm=3e17eb93d131601bcdb1b18c7326a0736683b6a3a7835793a3639dc860e65449&
https://cdn.discordapp.com/attachments/763500535554375750/1273417549299712080/image.png?ex=66be8a02&is=66bd3882&hm=39320cf7b9c93be3318945f4aee37da237b7f3c4537c6eeca3a6c3cba6c2b11d&
Prob something to do with physics or coliders no clue where to put this
please help with this
Does the basket have a collider? Does the ball have a collider?
Rigidbodies act only according to their physics, but collisions are handled by colliders, often together with rigidbodies
Also could be a problem of dynamic non-convex mesh collider which the basket might be
or moving a basket outside of physics simulation
That too, too little information given about the set up
Yes
Basically the basket is made up of 5 meshes, and i spawn the ball with a button, the ball passes through the bottom of the basket even with a box collider attatched
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
If you want to continue going into this blindly, you need to learn to provide all the useful information for the question and learn how to debug.
No
ok ill start this thx
In this case. First of all create a thread, then post screenshots of your setup with components propertios involved. Then post all the scripts that move object you throw and the basket. (Then someone might figure out what you are doing wrong at this point, tutorial will save a lot of time for you though)
Oh ok thanks
Ramp issue
what would be the best way to make collisions for this type of art?
it has grass, which make player to stop , since it has collision as well
i am using polycollider 2d
Don't put the collider over the grass?
I am using polycollider 2d, it automatically puts collider over them and each time I have to edit it
You've created a thread already, why are you reposting here?
That's what you have to do, either that or you remove the grass and place them separately with no colliders
Oh ok
any way i can improve this?
are you moving the transform there?
yes but that's temporary
is there any problem with it though?
here is an updated one using rigidbody
forget the end part, thats just me messing with some values
yea but the airbone physics dont
i got this problem where the car just slowfalls when its in air, i've tried everything i know but i can really fix it
do you know how i can fix it?
reference
you are making car controller right?
remove theese 2
and dont make physics continuous
ya
did it fix the faling part?
yep
ok, good
again, thanks alot man
ey, is the unity 6 good enough for usuage finaly?
ok, i guess its finaly for me to upgrade from 2020 version to unity 6
but its still in beta, think of its actual release
sure is
anybody know how to use hinge joints with spline followers
im trying to attempt to make a train system but hinge part just flys around and just spazzes out
i am trying to achive something like this
suggestion
dont use physics engine to make a train
what would you recommend then?
if you want a stable simulation of a train, yo will need to use beerier curves and just follow the path of those curves
im currentley using a spline system with beizer curves that follow a path
i want the atual train bogies to move when the train turns
i want the train wheels to turn on the curves
do you have info of how the curve is rotated
no
sadly, i dont know how you could get a point on a bezier curve and its rotation, so i cant really help you here
you could shample the curve into points and find closes point and copy its rotation to the wheels
Any spline system will have an API to retrieve rotation and position information at any point along the spline..use that
As for specifics, that's depends on the details of your "spline system"
Hey folks, I'm trying to make a scale that measures the weights of different objects, and it consists of two objects. I want to make it so when Object A goes down, Object B goes up. All well and good so far, but now I can't get Object B to go back down, since it's too busy copying (and inverting) the position of Object A. How do I fix this?
Has anyone had any issues with box volume being solid when though they're on is trigger
I'm using unity 2022.3.40f
URP
for some reason the box is solid
even when excluding layers I still can't go pass
That's also the only thing I got apart from the Volume component which needs the box collider
also using VR if that makes a difference
You mentioned earlier that disabling the Volume component makes the trigger passable, is that really the case?
Not the gameobject I mean
It makes a big difference how your player character is checking for collision
It could be checking it against triggers
If I disable the Box Collider it became passable. If I disabled the object it became passable. If I disable just the volume component it's not passable... weird...
That's the first not weird thing I heard about this
When using Exclude Layers I mentioned to disable Trigger checkbox
At least that way it should become passable to collider checks that specifically look for triggers
I have a feeling your VR character controller requires a specific setup with collider components
yeah maybe. If I disable is trigger and exclude layers everything I still cannot go pass
on an unrelated note. Troubleshooting this helped me fix another problem of mine
is there anyone here who has a good understanding of the wheel collider friction? I'm attempting to create a vehicle with wheels that emulate tank treads, but the grip settings make no sense
i can send you a package for tank tracks
i'd appreciate that
send in private DM
Hello. I think this is the correct channel since I'm in trouble with triggers detection. I have a trigger with a script. This script has an OnTriggerEnter2D and it only detects a static collider when it collides partially the trigger.
The blue square is the trigger, and the white wall is a collider. The trigger would detect the collider.
The green square doesn't detect the collider.
The triggers configuration is in the photo.
I'm about to sleep so I would appreciate your help, it's nice to finish a day with a happy ending xd
Do you have your tilemap Collider in polygons mode or edge mode
Is there a way to simulate cloth physics with wind in 2D
Thanks, it was that
how might I make barrels like this stand upright?
I still want them to be able to roll if they're knocked over, but i don't want them to fall over in the way capsules do
you can make a custom collider (that can be a simple cylinder) inside of a 3D software like blender and then apply a mesh collider to your custom collider
Overlap box doesn't seem to be doing anything
Physics.OverlapBox(transform.TransformPoint(checkOffset), boxCheckSize / 2, boxCheckRotation, fireMask)
gives me no results, while a overlap sphere at the same position gives me multiple results
my bad, forgot to do something else in my code
hi! im new and used AddForce in my script to move my 2d character because it was super straight foward, but now the character has too much momentum and doesnt stop moving if you release the key. how do I prevent this?
Hey guy's, how can make realistic cabin suspension for the truck in unity?
I'm trying to make a physics based claw machine, but moving it is a bit janky, and picking up pieces work - but once the claw starts moving the pieces clip through it. Anyone have any suggestions to make it more stable?
The easiest fix is to directly modify rb.velocity instead of using AddForce
Do parents on a collider receive trigger events?
How are you moving it?
A parent joint is moved through this script
Yeah, your issue is that you are moving it via transform instead of the rigidbody
That will lead to incorrect physics, like clipping through objects
Thanks, completely overlooked that for some reason. Fixed it now
There's something weird that I really need to stop from happening in unity, it has to do with friction.
I don't know how to explain it. If a CircleCollider2D of radius 1 enters a gap of this exact size, it can't move. Same with any other collider that's touching two things on parallel or perpendicular sides at once. In my game the player is a ball, and it very often happens that in situations like the ones on the screenshots it's impossible to move.
I'm pretty sure what I'd need here is a sliding mechanic, where under friction, instead of being stopped by the pull to the object, movement is ignored on that axis or something.
Ideally this is something that you just download or check on and works globally on any rigidbody (or specific ones, yall get it)
So is there a doohickey like this in Unity as of right now?
||(it has nothing to do with the fact that I'm on a bridge, those were the closest spots to replicate the problem)||
sorry, could you elaborate?
If you want snappy movement, you can do something like rb.velocity = moveDirection instead of rb.AddForce(moveDirection)
And you can optionally add smoothing to the moveDirection with Vector3.SmoothDamp or Vector3.MoveTowards
thank you so much!
i did what you said, but she still will not stop moving once i release the key, and continues in whichever direction .. here is my code, do you see the issue? thank you for your help
Your if statement specifically makes it not change velocity if you arent pressing the horizontal keys
If you remove that then it will work
oh i understand! thank you!
do i have to replace it with something?
Nope
It might feel too snappy/jarring this way though
So you might want to implement some kind of smoothing, so it accelerates and/or decelerates over time
its giving me this error? im afraid i dont know how to solve that on my own😭
Oh I meant the whole if(_horizontalInput != 0)
oh! and itll still work without it just fine?
Well, it will remove the issue of it not stopping when you release the key
lemme test it!
it worked! there is now a new issue though🥹
man i suck at physics
If anyone has a while, ping me
im not sure what you want here, you could make the collider either smaller by a fraction or larger by a fraction
Making it smaller would break other mechanics. I need it to somehow ignore upwards collisions while on ground
maybe with a raycast shot down, half the radius + 0.1, then check if there's something above, and if there is, ignore that collider
but how do I ignore a collider
I need colliders to be on
what if there's a rocket coming from the sky, that would also get ignored
I think what I'm experiencing is a bug that causes recalculation. Can someone from Unity help me out on this?
ignore a collider in terms of collisions? if so you can just make the collider a trigger or just turn it off
how does Rigidbody.SetDensity(float density) work?
This is the description:
Sets the mass based on the attached colliders assuming a constant density.
This is useful to set the mass to a value which scales with the size of the colliders.
i dont understand the density parameter
like what is SetDensity(5)
it sets a mass of the rigidbody based on the mass of colliders and scales with them
This is useful to set the mass to a value which scales with the size of the colliders.
thanks
Why are the wheel colliders not colliding with the floor?
I have this kind of hierachy:
- GameObject "Skateboard" with Rigidbody
- 4 wheel collider gameobjects with Wheel Collider components
- skateboard mesh
- 4 wheel meshes- board mesh WITH box collider
The wheels are pointing down and rotation is set to (0,0,0):
here's the wheel collider component:
is there a way to grab the amount of friction an rigidbody is experiencing? im making this game and i want to add a particle when a rigidboy slides across the ground with friction.
if not i think i have an idea on how to find it using ray casts and angular velocity
I don’t think there is and even if there was, I don’t think it would help you since the amount of friction does not indicate the amount of slipping. I believe the angular velocity and the velocity of an sphere are enough to determine if it is slipping although it wouldn’t give a point of contact that you likely need for the particles. Maybe the easiest way would be simply checking the point velocity at the contact point on OnCollisionStay since it would indicate the velocity relative to the ground. If the ball does not slip at all, it shouldn’t have any velocity relative to the ground
yeah i think i found a way, simply subtracting the magnitude of the velocity with the magnitude of the angular velocity (clamped so i dont get negative values) worked pretty well
That's quite far from the right way though... Even if it may seem to look fine, it definitely doesn't work in all cases and for the right reasons
This is the auto-posing feature in Cascadeur (an AI-assisted animation software). How hard would it be to get something similar in Unity?
i.e., I wanna be able to move one bone and have the other bones adapt
is there anything maybe on the Asset Store? Do they cost a lot?
i need help with something, when i move my player character on the floor via setting the velocity value itself instead of adding forces, my character gets slightly dragged back when they stop moving, and i cant for the life of me figure out what it is
i think it's a collision thing but i've checked with the colliders and the player's rigidbody many times now and nothing i change makes it stop
its supposed to just completely stop, no input = no movement, but it gets slightly dragged back the opposite direction. no compiling errors too
i've tried constantly setting the rigidbody's velocity x and z to 0 through Update when grounded and with no input but it still happens (groundcheck is working fine as well)
i seem to have fixed it by not having a constant gravity pushing me downwards
Show your code
kinda looks cool tho
it's hard to notice, but it does push back the opposite direction when i stop moving, its annoying since when i'm airborne i have no friction, so if i stop then immediatly jump i go a lot further back
I actually have no idea tho
it may seem minor but i'm trying to make a very responsive movement that does exactly what you want, but i've fixed it by now
Hi!
I am using agent bots with a NavMesh system. I'm facing an issue where the bots can push me into a wall or, more specifically, push me into a collider when I walk close to them. Making the bots avoid pushing the player isn't a solution because if the player walks near them and slightly cuts the path, the player ends up colliding with the wall. How can I protect the player collider to ensure it never penetrates another collider?
this should go into #🤖┃ai-navigation but to simply anwser, a navmesh agent has a obstacle avoidence feature built into them, if that doesnt work. make your player a non walkable surface that cuts the navmesh around it out.
but best be answered in ai navigation
Thank you
This is a very simple one, but not sure if this is a bug with unity...
I use a capsule collider for the player, when i throw a bomb, the physics object intersects with the player when pointing upwards.
As a simple solution, i just want to ignore the collision between the bomb owner and the bomb object.
(frame number is part of the log). I use Physics.IgnoreCollison with player and bomb collider parameters, but a frame later this ignore doesn't seem to work and a OnCollisionEnter Monobehaviour happens.
i log the colliders that are being ignored, and i log the colliders that are part of the collision. they seem to match in the logs. i also log when a physics simulation update happens (which is in between, every frame)
It is a pretty funny bug, but not sure why the physics.ignoreCollision doesn't work. anyone here sees what is going wrong, is it a bug, or am i missing something?
this specific usecase is part of the docs page for this method
> https://docs.unity3d.com/ScriptReference/Physics.IgnoreCollision.html
"This is useful, say, for preventing projectiles from colliding with the object that fires them."
Are you sure it's indeed a collision and not some OverlapSphere(radius).ForEach(col => ApplyExplosiveDamage(col));?
Yes it is coming from a manual Physics.simulate call that happens the frame after i set the IgnoreCollision.
Somehow the ignore doesn't seem to work and a collision callback is fired between the two colliders
it'd be an interesting bug if Physics.Simulate(..) ignores collision ignoring
yet somehow it sounds unlikely :/
@flat finch I confirmed that this is the case!
kudos on this find and feeling kinda sorry if a workaround isn't immediate 😅
oh no.. i hoped i was doing something wrong and that it would be an easy fix 😂 I guess calculate the edge of the player capsule and spawn the projectile just outside of it
good news is if you report this now you might end up getting an update within a couple months :p
looks like there were some other bug reports about ignore collision that are fixed in recent Unity 6 versions. I'm on a fairly new version 6000.0.13. let's see if this new one gets fixed hopefully quick
@flat finch is unity 6 worth it in any way? I'm currently on 2022.3 (as of very recently)
Yes, having my game load immediately without the unity splash screen made that an easy decision for me 😅
Apart from this, i haven't encountered any bugs or issues so far
but that's the only advantage you've noticed? 😆
I guess so, + the new multiplayer play mode is handy. Besides that I don't really use any of the new features that 6 has 😛
I see 😄 thanks
Hey all, question about colliders. How do you properly add a collider to an Open Sprite Shape so that it automatically traces the shape? I already tried adding an edge collider - that perfectly traces the shape, BUT I can't rely on that because 2 edge colliders won't collide with each other and I may want multiple of these colliding.
So I've been trying a polygon collider. The problem is, every time I add one it adds a collider that only traces the center of the shape, then roughly connects itself together. So the collider is only about half the size it should be, and the bottom isn't traced at all. I've searched high and low, closest online answer was to use 2D SpriteShape package, but my Unity already has that.
Any suggestions?
i believe you can edit the polygon collider to make a custom shape
You can, but I'm trying to find a way to automatically make the collider match the shape in case I wanted to procedurally generate custom shapes
There's no automatic way to do it, but you could code it
Dang... no automatic way? That's unfortunate 🙁
Why does it work for closed shapes, but not for open ones?
Because it is based on the spline, so for a closed shape it has a, well, closed shape ready to go. For an open one iy would need to extrude the spline out and or get the outline of the actual texture.
Got you. I'm sure it'll make more sense if I dive more into splines. Thanks for the help!
Following up that it was because of the projectile object being disabled while setting the ignore.
This was reported in https://issuetracker-mig.prd.it.unity3d.com/issues/physics-dot-ignorecollision-method-does-not-work-when-used-on-a-disabled-gameobject
I just updated to the latest 6000.0.16f1 and the issue is fixed
Reproduction steps: 1. Open the attached "ReproProj" project 2. Open the "Assets/Scenes/SampleScene" scene 3. Enter the Play mode 4....
Nice! although in my tests (in Unity 2022) it didn't matter whether the object was enabled while setting the ignore.
Moving with Physics.Simulate() straight up ignored all ignores.
I'm trying to find a way to have kinematic collision between two rigidbodies. but keep their dynamic collisions with everything else.
Example: https://www.youtube.com/watch?v=zO_2MoBXeu4
Example of inter-character collision in Dark Souls. No character can push another, regardless of how many there is.
I've tried a dual collider approach where each player has a dynamic collider inside of a larger, kinematic collider. The kinematic collider only collides with the inner collider of other players.
The problem is that when they collide at velocity, the kinematic collider intersects the dynamic body at the time of collision, so the object that got hit still moves away
I tried seeing if there's a way to force kinematic/non-pushing collisions using the modifiable contacts API, but I wasn't able to make it work.
https://docs.unity3d.com/ScriptReference/Physics.ContactModifyEvent.html
Has anyone had success with using the modifiable contacts to force non-pushing collisions?
I was thinking that I could just push both bodies back in the same direction they came from, at the same distance that the penetration happened at. But you can't set the position during contact modification.
There is an asset that does this https://assetstore.unity.com/packages/tools/physics/betterphysics-244370
Oh this looks great, thanks!
woah, why isnt this built into unity by default already?
no idea!
Looking at destroying objects that are prefractured, does anyone have any good resources on this sort of thing?
In terms of needs, I'd want either entire chunks of the building to fall when unsupported (so the building falls as one when the bottom floor is broken, for example) or for individual pieces to break off when those ones are unsupported
It's a little pricey but Rayfire is like the gold standard for this kind of thing:
I've seen rayfire, and would consider it if I had the cash
This is for a multiplayer game too, though I likely wouldn't have issues with making syncing stuff for it
For multiplayer, if at all possible, it'd probably be best to keep this kind of thing client-side only
that's the thing - it'll affect gameplay so keeping demolition client side would have an adverse affect
If I can't get this figured out, then I might take an r6 style of demolition
why does the box push me off, and why does it push me off so weirdly (fixed)
Hm, I'm having a strange issue when using hingeJoint2d with flipped objects (rotated 180 in Y)
For normal objects it works fine but if I flip either the hingeJoint2D object itself or any child object it spazzes out and flickers. Even with no motor or limits. Is this a known bug, or am I doing something wrong?
For context on what I mean by "spazzing out" it looks like this.
Whereas if I simply undo the left-right flip it looks like this, which is what I expect.
maybe just flip/rotate the renderer not the Rigidbody/collider.
In this example it's just a white block but I actually want to flip a more complicated object, it has collision on it as well so I can't just flip the renderer
Flipping sub-objects causes the same effect. The collider disconnects from the rest of the object
does inverting the scale on the x axis work better?
Hm, it does
-1 scale works without messing with the hingejoint
The rotated object thing still kinda feels like a unity bug to me, but as long as I have a workaround I guess I'm good. Thanks for the help!
that is unfortunate to hear lol. Up until now I have been firmly on the "Rotate on the Y axis" train for flipping sprites. Now I learn that there are certain use cases where that doesn't work as well 😭
Ditto. Negative scale just feels wrong to me. And unlike scale in x/y, rotation in the Y axis isn't something I have to remember if I'm doing stuff that changes object sizes like buffs and whatnot
Having a bit of a weird issue. I have a third person character controller and terrain. Both interact well when the terrain is set to Default layer. I try to set it to Terrain layer to work with my minimap and the character falls through on scene start despite Terrain also being one of the layers to check for ground. I made no other changes besides the layer, and strangely it works if I change the layer during runtime.
What do you mean by "terrain also being one of the layers to check for ground"?
That doesn't sound relevant really
You should check your layer interaction matrix instead
Also your code may be a problem.
I haven't touched the collision matrix. Everything there is enabled, but I'm using a layer mask to do a ground check on the player:
- Check under Layer Overrides in the CharacterController
- Share your movement code.
I don't know what Layer Overrides does. Pretty sure it's set to nothing, but again, all the collisions worked properly when the terrain object was set to Default. I thought maybe there was some reason Terrain always had to be on default, but that seems to not be the case.
anyone know what would be causing my sprites to be changing colors?
Thanks, i had a hunch that could be it. any why though?
rotation.z would be affected by lighting? Changing the material to Sprite-Default fixed it
Animation can't reasonably interact with physics objects, right? Like if I animate a stick to rotate it won't naturally interact with a ball as if it was a bat
Because animation isn't "physics" movement?
There's a checkbox
To "animate physics"
And then it should do something approximating that