#⚛️┃physics
1 messages · Page 23 of 1
Looks like you have some other script or code resetting velocity to zero
Most likely your movement script
There is nothing setting it to 0. The only script manipulating velocity in any way is by addForce(direction*speed, forceMode.acceleration)
And the velocity is not 0 unless I'm standing still ever
And I'm printing this while moving around and I can see in the rigid body that velocity is rather high
The logs seem to disagree.
Well.
YOU WERE RIGHT :---)
Im sorry but i was hell bent on the thought of the physics handling itself messing up
well
great to know now
thank you so much for ur patience
public Vector3 customGravity;
void FixedUpdate() {
rb.AddForce(customGravity, ForceMode.Acceleration);
}```
You can either let this be additive or turn off normal gravity to replace normal gravity entirely
Actually this looks like your movement code is causing an issue
You are likely setting your character's vertical velocity to 0 in FixedUpdate. The fix is to stop doing that.
I added a force, not set the velocitu
Based on the way your character is moving it seems like you're doing something fishy
You don't have a parabolic motion curve going on
I did use Impulse, not force
Your gravity appears linear, which indicates an issue with your code
Why don't you just show the code?
The force mode wouldn't cause this
I am not on my computer, but I'll type if.
rb.AddForce(Vector3.up * jumpForce, forcemode);
//forcemode is set to Forcemode.Impulse in the editor.
Note that I modified rhe drag
The drag is the problem
Set drag to 0 and the gravity will be fixed
How do I make the player's movement smoother?
Like, not slippery
That's a really vague question
But also without addint too my friction
I'll just tinker around eith 0 drag and see what I want done
Use higher acceleration forces and enforce a maximum speed limit
That will make it snappier
Does anyone know how to fix this problem? When the ball hits the player, they get pushed back. I want it so that the player is static and the ball doesn't have influence over the player via force.
use a kinematic character controller instead of a dynamic Rigidbody
How do I do that?
Would that mean I have to reprogram all my movement?
https://pastebin.com/RKGn31wR got an issue with ice physics in my project, especially on slopes. sometimes i slip and sometimes it's inconsistent.
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.
How can I prevent this?I know I can make weapons trigger but I want them to collide.
for colliders to collide within the physics system, at least one has to have a dynamic rigidbody
I meant that stutter effect
that happens when those weapons get between the hinge joints
Does anyone know how to fix this problem, I have given my chicken object a Pickupable layer and the chicken should directly transform to handtransform, why is the chicken not in the hand but in another position?
Code?
using UnityEngine;
public class ObjectPickupDrop : MonoBehaviour
{
public Transform handTransform;
private GameObject heldObject;
[SerializeField] private float pickupRange = 2f;
[SerializeField] private LayerMask pickupLayer;
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
if (heldObject == null)
{
TryPickupObject();
}
else
{
DropObject();
}
}
}
void TryPickupObject()
{
Ray ray = new Ray(Camera.main.transform.position, Camera.main.transform.forward);
if (Physics.Raycast(ray, out RaycastHit hit, pickupRange, pickupLayer))
{
if (hit.collider != null)
{
PickupObject(hit.collider.gameObject);
}
}
}
void PickupObject(GameObject obj)
{
heldObject = obj;
Rigidbody rb = heldObject.GetComponent<Rigidbody>();
if (rb != null)
{
rb.isKinematic = true;
}
heldObject.transform.SetParent(handTransform);
heldObject.transform.localPosition = Vector3.zero;
heldObject.transform.localRotation = Quaternion.identity;
}
void DropObject()
{
Rigidbody rb = heldObject.GetComponent<Rigidbody>();
if (rb != null)
{
rb.isKinematic = false;
}
heldObject.transform.SetParent(null);
heldObject = null;
}
void OnDrawGizmos()
{
if (handTransform != null)
{
Gizmos.color = Color.green;
Gizmos.DrawSphere(handTransform.position, 0.1f);
}
}
}
Hey there, has anyone made a rigidbody character controller for very large entities and can share some best practices? I am wondering whether I should use rigidbodies at all, or use them with the kinematic option.
Looking into options to simulate 3D in 2D in a kinda-top-down ~45° camera angle.
The characters can move on the ground but then also jump:
Right now I have gravity set to 0, 0 in project settings for 2D.
I see a few ways to do it.
First:
- Set the gravity vector to 0,-9.81 in project settings.
- Normally, all the characters and moving objects have gravity scale of 0.
- When the jump starts, set gravity scale to 1, launch character up, remember the position when the character jumps, then on each update in the jumping state check if character's position is the same or lower than the starting position. If it is lower, then switch back to the moving state and set the gravity scale to 0.
Second:
- Set the gravity vector to 0,-9.81 in project settings.
- Add colliders under each character that always follow them and only interact with that specific character. This probably means a lot of collision layers.
Third:
Switch to 3D physics.
I wonder if I should go 3D physics with 2D graphics here
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
It's likely a scaling issue
KITTY GAME
I've seen how varying time steps for Physics.Simulate() can cause some weird break down in the simulation (e.g. objects at rest suddenly bouncing around), but it got me curious- why is that?
Having a fixed time step is just simply better for physics stability
Having continually varying delta time will give you inconsistent calculations.
It's easy to show that. 30 physics tickrate vs 60 physics tickrate will give you a different feel for the same vehicle controller, for instance. The calculations are simply not going to be the same, due to numerical errors, etc.
So, by having a non-fixed tickrate, you take this inconsistency into a whole different level.
I'm experimenting this weird issue (each plank has a collider and a rigidbody and the planks on the middle has fixed joints to hold them meanwhile a force it's not applied
Sorry it's not clear exactly what your issue is
I will say that the Rigidbody should probably be on the root object of that Pallet prefab, not a child.
but each plank should be independent
What is a "plank"? I only see "Pallet"s here
the planks are vibrating
parts of the pallet
you need a root rigidbody \
and to have the children be rigidbodies connected to the root with joints
but it's not really clear why you need this complicated setup
What are you trying to achieve with this?
this is a video that I recorded a few time ago, but now with the new (and bigger) terrain I get this issue
as you can see each part of the pallet is independent when it "breaks"
I would just have a single Rigidbody and a single collider here, until it breaks. When it breaks, you swap in the separate pieces.
It will behave (and perform) much better
I moved the pallets to 0,0,0 and now there is no vibration, I think that the issue is caused by the coordinates, does the physics system have issues with big numbers in coordinates?
pretty much every system has problems when you get too far away from the origin
Best practice is to stay within ~1-2k units from the origin.
well, then probably that was the cause, I was on 5k, ?, 3k...
Is it ok if I use transform.rotate for a kinematic rigidbody? Said rb is a sphere collider and I'm wondering if there are any repurcussions to doing this
@humble plaza you probably need to clamp the movement of your character to the hit distance such that your character will still move that last bit and not simply stop when there is any hit within max raycast distance
Essentially the same as rb.rotation. I'd rather use the rb one but that doesn't do great job respecting physics either. For kinematic bodies though there exists rb.MoveRotation which modifies the .angularVelocity making interactions with other dynamic bodies much more accurate. The .Move... methods + kinematic body are usually preferred for moving and rotating obstacles that don't need to be dynamic
How much of an issue is collision mesh complexity with performance?
Maybe that question is pretty worthless without context...
depends on so, so many things
Yeah... I hate to go down the route of prototyping it and it not work, but perhaps that's my only option.
So, I have a Rigidbody-based character controller that @thin dew is doing almost everything to develop.
But I'm running into a problem.
When I jump the player into a wall, the player sticks to the wall until the player is no longer holding in that direction.
Is anybody here?
can anyone help me, I'm trying to recreate ridge racer 4 in Unity, I have a ground with box collider and rigidbody, but for some reason the car is falling through the map. I don't know what should I do? The root CAR object has a rigidbody and a car controller script, the gameobject child BODY has a mesh collider with mesh renderer and then there are wheels with wheel collider.
am I missing a lore here on this simple car controller?
Ridge racer definitely doesn't use a traditional physics engine so I would say you're probably on the wrong track entirely.
The way the cars hug the track it's almost definitely spline-based with custom physics.
No, I meant to say, how should I stop the car model falling through the mesh instead of standing on the mesh.
Isn't "standing on the mesh" and "stop falling through the mesh" the same thing?
I'm so sorry, I meant, how can I make the car to stop falling through the mesh. Forget the first part "standing on the mesh"
It will not fall through if there's an appropriate Collider
i Have a box collider on both the car and the ground!
gameobject child BODY has a mesh collider
Is the mesh collider marked as convex or no?
show the inspector for the ground and the car
I'll show in few hours because its snowing outside and I want to eat snow XDXDXD
How to set up the collider for a mesh that deforms?
While technically possible to emulate such a thing at great cost (soft body physics). Unity only supports rigidbody physics.
It's possible to fake soft body physics by using physics joints on the bones of a skinned mesh
I want to create Shield System like this, then how to impl this? (2d physics)
This is the inspector of root object Ground
This is the inspector of the root object SportsCar
and for some reason, when I hit BeginPlay, the car just warps through the ground, I don't know what's wrong?
nevermind, the tickbox in the ground's box collider "is trigger" was on. that's why the car was going through it.
you can do multiple raycasts
simplest way
How to make a rigid body on child object use parent game object position as a base?
So let's say we start with 2 game objects: parent and child. Child's local position is (0, 0, 0), then I start moving the parent game object, the child follows and keeps the local position of (0, 0, 0). Then let's say I do ChildRigidbody2D.linearVelocity = Vector2.Up * 10 and now the child rigid body moves up.
But then as I move the parent game object, I'd like child rigid body move with it, too, but also move in its' local space.
I tried joints: relative joint, but it hardcodes the relative position and I can't launch the child body with addForce or linearVelocity.
Basically this behavior:
Simulate physics to carry rigidbodies on moving objects. Very fast and optimal.
But without the additional structure of objects. I guess, I'll have to manually translate the child's position based on parent velocity on this update in the late update
Hello, I am making a simulation game, in 2D, top-down, where each tile in the tilemap is 1x1 meters.
Now I wonder, the velocity of Rigidbody2D, is it in m/s? Or other units?
unity uses m/s for velocities, m for units, mostly s for time, m/s^2 for acceleration, N for forces etc.
SI in other words
Thank you :)
hi! not a unity specific problem, but i want to find out the acceleration produced by an engine of a given power.
I tried using both the power force and power kinetic energy and i am getting different results :( and i have no idea which one is correct :(
F = ma is the basic equation
You'll need force in terms of newtons and mass in terms of kilograms
I mean that i have power in terms watts, and want to get the force generated
I know P = F v is a thing but its kinda weird
Do you want to calculate how much acceleration will come from how much RPM an engine produces?
I guess... although how do i find the rpm? Lol
This whole area is really infamiliar to me
Actually if you already know your speed, you can calculate acceleration off of that and calculate RPM off of that as well so basing it off of RPM is pointless.
If you go from 0 to 60 MPH in 3 seconds, you can do
(60 - 0) / 3 = 20 MPH per second or 1/180 mile every second (if you want a fraction)
sorry I wasn't responding quicker, I just did a ton of formulas just to now remember you could do this 😅
Wait but im trying to calculate the acceleration to apply it to the object?
I only have access to the currect speed generally
ah
I feel like i am missing something crucial haha
you could convert RPM to RCF (relative centrifugal force) which is a measurement of acceleration which you could use as acceleration
RCF = (RPM)^2 * 1.118 * 10^-5 * R(Radius of Wheel)
you could multiply or divide RCF to get a lower value of acceleration if needed
sample problem if you had an RPM of 2500 and a wheel radius of 11
RCF = (2500)^2 * 1.118 * 10^-5 * 11
RCF = 768.625
//Optional
Finalforce = 768.625 * 0.1
Finalforce = 76.8625
Hmmm? Wait i thought acceleration would depend on torque not rpm?
Its all so confusing
you can use RPM to calculate Relative centrifugal force which is a type of acceleration
That calculation above should be all you need if you know RPM
The problem is that "power" doesn't directly convert to force (which is what you need to actually know to calculate acceleration), as there are lots of other factors involved, at least in the real world
We don't even know what kind of motor this is
Is it a rocket? Electric motor? Internal combustion engine?
What's the full context here?
I'm going off of it is a Piston engine of some sort
but converting RPM to RCF should be okay
Doesn't this depend on a lot of factors like the mass of the wheel, its radius, its moment of intertia, etc?
From what I'm looking at all you need to know is the wheel radius and RPMs
Doesn't the engine displacement matter too?
RCF = (RPM)^2 × 1.118 × 10^-5 × r this is the formula I found 🤷♂️
But thats for centrifugal force tho
Isnt that just the force which makes the body rotate around a center point?
yeah that makes sense
sure, but it is still the acceleration of the wheel, which you can use for newtons 2nd law to get a Force I would presume.
you could probably convert it to newtons if you want
Also I would think you need this rotational force because you are trying to apply this acceleration to the object, so the object's velocity is 0 so you cannot do really any acceleration calculations with 0 velocity
due to how division and multiplication works
Okay, so in my game, the zombies im using are currently turned into a ragdoll on death, but does anyone know if there is a way to destroy the limbs, (example: if i shoot the body enough, the body is deleted, and the limbs are remaining, no longer restrained by the ragdoll skeleton)? - i cant really find anything online doing this exactly...
Wait I think I just found the perfect formula which gives you a linear speed that could be converted to newtons
RPM = 2000 or 33.3 Hz (Need to know this)
Radius = 30cm wheel (convert to meters which is 30/100 which outputs 0.30)
F = Hz or Frequency
W = Angular Velocity
V = Linear Velocity
W = 2pi * F
W = 209.23 Rad/s
V = W * R
V = 209.23 * 0.30 = 62.769 m/s
Then
F = M * A
F = 40kg * 62.769 = 2510.76 newtons
Visually you would need the limbs to be rendered by a separate MeshRenderer and destroy, disable, or detach them.
If you're using a SkinnedMeshRenderer, it's not straightforward.
you turn Angular velocity into Linear Velocity, by multiplying W with the Radius in meters. then just do F = MA.
but that would be the entire calculation to get what you want
62.769 is the Acceleration and I just converted it into newtons for use in unity
I'm planning to make voxel game (block game that look like minecraft). How is unity engine performance at handling tens of millions of static (unchanging) box collider? Should i write my own physics or use unity physics? And if i write my own physics, then how do i make my custom physics work together with unity physics?
My first concern with that much box collider is memory consumption
Using tens of millions of box colliders will not work at all
how do i make my custom physics work together with unity physics?
You wouldn't, generally.
You would pick one or the other
I believe most people who do minecraft-style games in Unity build dynamic meshes for chunks and use a single MeshCollider for a whole chunk
Ehh? Isn't mesh collider very laggy?
That's a meaningless overgeneralized statement. No.
Hmm there is 1 million block per minecraft chunk (256 height limit), are you sure it is not laggy?
Minecraft does not use individual colliders for each block
nor does it really use any off the shelf physics engine
But yeah pretty sure, I've seen lots of people make "minecraft in unity"
and they've all used MeshCollider in my experience
note that the collider should be simplified to the greatest degree. For example a completely solid chunk would only have a collider with 8 vertices
(i.e. a single large cube)
Hmm interesting
Looks like i need to find tutorial to make minecraft physics on unity
Thanks
Yeah
but yeah - procedural mesh generation is the name of the game
The worst case scenario would be the case where every block is not touching each other, which would easily cause hundreds of thousand of box collider
well it's still one mesh collider, but yes probably, something like that.
And how do i handle that worst case scenario
Don't worry about it until it's actually a problem
See if it actually causes issues.
I suspect it won't.
It is a problem tho, in minecraft multiplayer there is troller who modify chunk to make it laggy for other player, so i need to make sure in that worst case scenario the game won't be laggy
Yes, you should make sure it's not
but don't jump to the conclusion that it's a problem before you try it.
As you can see, the zombie model has details inside, I'm guessing its made for this reason, and each of the limbs use skinned mesh renderer, which i can disable with a simple limb health script, but the thing is that if i remove this mid section as in the screenshot, the whole body still sticks together.
Is the only way to get the result im looking for, removing the mesh renderer, deleting the joint, and making each part their own root parent?…
Why?..
Why what? What are you wanting or expecting to happen here?
I have marked isTrigger, but it still leads to collisions.
Here collision of my main object:
My guess is your movement script uses raycasts or capsule casts or something to detect obstacles
setting the collider as a trigger has no effect on that.
My question is if you don't want to collide with these cubes why do they have Colliders and Rigidbodies at all?
isTrigger implies that the object will simply have a collider, which you enter and something happens, but there will be no collision. Isn't that right?
Yes but that's talking about interactions with dynamic rigidbodies that are moving via normal means like velocity and forces
I don't think that's how your movement code works.
I can send my code
Go ahead
I'm already 90% sure about what I will see
I would love an answer to this question though:
My question is if you don't want to collide with these cubes why do they have Colliders and Rigidbodies at all?
an explanation of what components are on the player would also be helpful.
Objects or Hero?
on the cubes
some objects are needed, others are not...
I'm get component to set the "isTrigger" and that interaction with the object takes place.
Is there a language barrier here?
I don't understand what this sentence means
One second please...
Anyway it seems pretty obvious that this is your problem:
#⚛️┃physics message
I'm setting up a collider in Unity and enabling the isTrigger option. As for the Rigidbody, I want it to interact with other objects but not with the player character. I've even written some code for that
Understand?
How to resolve this problem?
Yes I understand.
The thing you should be doing is:
- Instead of disabling gravity, just remove the Rigidbodies or make them kinematic.
- Change your movement script to use a layer mask for its raycasts or capsulecasts that ignores the blocks
I have some suspicions about the layers because I have Post Processing set up
on capsule collider
Can I send my code of movement?
I've been waiting for it
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
yep like I said it's just manually handling collisions in this script with Physics.OverlapSphereNonAlloc
So, what should I do about it? 😄
Anyway you already have a way to exclude objects from it:
// Collision will not happen with these layers
// One of them has to be this controller's own layer
[SerializeField]
private LayerMask _excludedLayers = default;```
why don't you just use that
One second please...
Do you mean assigning a specific layer to a certain object?
I mean excluding the layer the blocks are on from your movement script with that field.
It worked! You are a very attentive person...
Now it remains to set up the interaction, but I'll probably do it tomorrow.
Thank you for your help!
One problem... When I am in the collider - the button does not appear
it checks by tag
If I set layer - button does not appear
If I set default layer - button apper
is it possible for layer A to affect layer B but not the other way around?
in 2D physics
Not really
they either affect each other or not
I actually made an asset for this for 3D but 2D doesn't have the appropriate APIs available to achieve something similar in the same way: https://assetstore.unity.com/packages/tools/physics/betterphysics-selective-kinematics-244370
You could make the objects in layer A kinematic, that would get you the effect you want, but it wouldn't allow e.g. layer C to affect layer A objects as though they are dynamic.
Could you describe the exact gameplay mechanic you are trying to achieve perhaps?
https://gyazo.com/d5d392513f0ef0c58b36d1e84dd1de72 I'm picking up a bunch of water particles out of a bigger mass and I temporarily changer the layer of the grabbed particles so that the other particles off the mass don't block them from getting picked up smoothly. However I would love for the other water particles to still detect the collision of the grabbed ones so that the water doesn't drop instantly when you grab some or that you can smash the grabbed ones into the mass.
I guess making them kinematic would work but it's a lot of work for the desired effect so not sure if I'll go for it
wheel colliders are very weird
Pretty sure this is #🏃┃animation question, i don't see anything physics related
Unless it's an active ragdoll or something
ill post it in there might be smited for crosspost
If you delete it from here it won't be considered crosspost
It can't collide*
Tags dont matter in collisions. Layers might matter.
Show the code you use to move the character and also the components of the character and the cube
Hey, very beginner here
I'm trying to add very basic gravity to my game.
Problem is, when I add basic Rigidbody gravity to a sphere (1), it goes flying off in the air (2)
I thought it was due to clipping but I can confirm it is not
The sphere is likely colliding with something, thus causing it to fly off
you say you can confirm it's not due to clipping
how are you confirming that?
You should add a script to the ball with OnCollisionEnter in it. It will tell you exactly which object(s) the ball is colliding with.
I checked every side of. The ball floats over every surface.
Could it be bouncing to hard ?
I'll try that thanks
Ok so it does collide when it falls. Show do I prevent it from bouncing so strongly?
Ah turns out I had messed the collision of the ground, so the ball was ejected to the top of it. Thanks !
Can somebody help with this issue? (I don't want my player to fly off of the slope and instead stick to it)
what scripts do you have for player movement
What do you mean? You want me to show you the movement code?
without code nobody can suggest you anything.
okay hold on
||
||
here's the important bits (the left is what i use to move the player and the right is how i get the slope vector)
what are you getting if you put rigidbody. AddForce(Vector3.down * downWardForce); in place of targetDir.y something like this.
I'll give it a go and let you know
Tried it and you can't set a float value to a vector3 value
edited it. remove targetDir.y = and add force like rb.AddForce(Vector3.down * downWardForce);
i mean the entire line and replace it.
Yeah I know I'm currently tryin it
rb.AddForce(Vector3.down * downWardForce * rb.mass,ForceMode.Force); you can try even this also.
this doesn't work because: Too little of a downward force doesn't fix the issue on harsher slopes and too big of a force causes the player to slide down the slope automatically.
Are there any good ways to learn about vectors in unity?? I’ve been trying to make an enemy AI and like when I see tutorials they’re doing normalized vectors or adding/subtracting vectors and I understand none of it. I really want to be able to understand it enough to work with it confidently
there are many other talented people here but they might require more details like how are you calculating slopeHit and where are you modifying exitingSlope etc.
There's an overview in the docs https://docs.unity3d.com/6000.0/Documentation/Manual/scripting-vectors.html
anyone know why the wheel collider wobbles like that?
the ground is pretty uneven, but i assume there is a way to make the wheels handle it?
Pehaps the wheel mesh is not correctly aligned to its axis?
I dont even think you can rotate a wheel collider even if you wanted (it will stay aligned with global y axis) so definitely seems more like issue on the mesh axis or the way you rotate it
i'm pretty sure vector is teached in high school? You can find high school text book that contain lesson about vector
I don’t remember the lesson i had 5 years ago 😭
And i def didn’t learn what “normalized” is
cm'on it is just high school lesson it won't be hard. You can just find free online learning website that teaches vector
My autocorrect arr
if you dont know what subtracting vector means, then you lack the basics to learn what normalized vector mean.
It’s a little different for programming, I know how to add or subtract a vector but I don’t know what use it has. I just read the document and learned it it wasn’t that hard
Vector in unity is just code implementation of vector in math
Awesum
Ah yeah it was an issue with the mesh in the end, model wasnt mine
Either way is there a way to make it more "stable"? As in driving better on uneven terrain
There are a lot of settings in the wheel collider and i dont know which does what
so does anyone have a fix for this....?
If you are going to write a custom car controller, which is pretty complex, you should know how to look at documentation
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/WheelCollider.html
You probably need to also add forces/torques to the rigidbody, or use a joint, to stabilize it
well yeah but it is a bit difficult understanding how exactly each attribute affects the end result
i guess trial and error plays into it too
Have y 'all run into a bug where Unity sets the physics SDK to "none" randomly? It's happened to me twice now
somebody can tell me why when i turn off kinematic the characters just spins and fly like crazy?
you mean when you turn it off?
Because when you turn off kinematic the object actually starts getting physically simulated
It looks like there's some internal interactions going on
the comment no?
is this a ragdoll?
yes
Probably all the pieces of the ragdoll are intersecting each other
and colliding
causing craziness
oh
that explains everything
actually i find a smart solution
unparent the player from the ragdoll when he dies
How would you guys go about being able to use physics to open this (or any) hatch with a top down player?
Do you really need it to use Physics?
Not necessarily
I would recommend writing a simple script to animate it opening and closing
and just calling that
Well, ok, so yeah I guess it does need to be physics 😄
Use a hinge joint
I need the player to physically grab onto it and then be able to drag it open by moving their body
We use a configurable joint to hinge it open, so that's all good. What I need is a decent solution for being able to attach the player's hand to the handle and have his movement be able to open it. Similar to like Human fall flat grabbing things and moving them
I tried a fixed joint on the body, but I use the mouse to determine look rotation, so it ended up flinging the player around
Using the mouse to determine look rotation seems unrelated to your problem
What you might have trouble with is how you are applying forces or moving objects with the mouse
Well the mouse is a problem when it's rotating my player's body, and that is what the fixed joint is on. Then it rotates to the right and wants to drag the hatch door to the right :/
Yeah maybe this, I'm kind of unsure..
yeah that's a problem if you're just moving the player's Transform directly
The typical way to do something like that is:
- When you click, spawn an invisible kinematic Rigidbody at the clicked position
- Each fixedupdate, move the invisble rigidbody with e.g. MovePosition, according to where the mouse is
that way it's all within the physics engine and behaves better
That's a good idea! I'm kind of doing the same thing now, except, there is no rigidbody, it's just a point between the hands (to put it simply). I will try that, thanks for the idea!
Wait, follow up question though. How would you attach the hatch's handle to that invisible point though?
Ok, that's what I thought, thanks 🙂
I am working on some golf ball physics. Since I have wind, loads of sphere spin, etc, unity physics doesn't feel like the right move. Does anyone disagree? ANyone got a link to a golf physsics paper or implementation I can read up on?
How can I rotate my rigidbody such that it respects collision? Torque doesn't do anything for me
Torque should work. Show your rigidbody settings and the code you tried
I am using playmaker so I don't know if you can read that.
I really should just rewrite the char controller in c#
I know there is also rb rotation and moverotation
in case this helps you,
but it doesn't rotate
Not really familiar with playmaker. Are XYZ supposed to be set to None?
I did look at this doc but it doesn't tell much https://hutonggames.fogbugz.com/default.asp?W317
And what does your rigidbody look like?
yes, you either map individual planes or all of them in the ''vector''
rb is kinematic if that's what you mean
you can see the vector live with the numbers below ''vector'' and ''mouse direction'' which means it works
Kinematic bodies don't react to forces or torque
so what should I use instead?
rigibody rotate or move rotate
I assume one of those at least works with kinematic
I don't know what those are but in C#, .rotation "teleports" the rotation and skips interpolation, while MoveRotation rotates and respects interpolation
Why is your rigidbody kinematic though? Are you doing custom collision checks?
the reason I'm using a rigidboy at all is because I had to switch away from character controller and scrap it
it's a diving game where my character is elongated, i.e. its collider capsule is supposed to face in the Z direction
but stupid character controller capsule can't do that
wait, I am stupid
I should uncheck kinematic
and just uncheck use gravity
d'oh
stupido
now torque works ofc
Most likely. You didn't give any good reason to keep it kinematic
Kinematic is for when you want to explicitly control the body without having forces and torques affect it
yeah yeah, I remembered
I just forgot
been a while since I worked with rigidbodies with my previous game
all good
thanks
Anyone got any experience with velocity matching a player to an object, In a multiplayer setting where player is controlled by client & Object is controlled by server?
so if I want to make a slippery stair that interacts with a collider and not the player should I have a setup like this?
This is the player collider
the stair colliders
What does "interacts with the collider and not the player" mean?
it makes a collider move which is set to the player
so if I run into it, it moves me around like on ice
That sounds like an interaction with the player
So I don't understand the original statement
Is it possible to have a one sided fixed joint? Where object As movement influences object Bs movement But object B has no influence over object Bs movement?
how do you guys get more accurate rb physics, my player controller slides and falls very slowly, just 2 examples but I've noticed a lot of other strange behavior
This is likely due to your code
im just adding an addforce method on the rb based on the 2d wasd vector, i dont see how it can be my code unless im not writing enough code
Then it should behave normally
Have I really hit the limits of the convex mesh colliders? When I turn on convex, for an already convex object (blender: Convex hull option) , it decimates it to a useless shape. Will I just have to make it not convex and take the performance hit?
having some issues relating to hinge joints - I'm giving them a target angle to move to via Joint Springs, but the joints snap the target position to 180 when they're above 180 or below 0
anyone know of a way to tell if a configurable joint has reached its angular limit?
Why are you using blender's convex hull?
Unity/PhysX already creates a convex mesh if you enable "convex" in the mesh collider
Or is it that the blender's convex hull mesh is alright but the "convex" option in mesh collider messes it up?
Do you mind sharing this 3D file so I can take a look?
How can I get or set the top speed of a rigidbody? I know that once LinearVelocity.magnitude can show the top speed once the object is at its speed limit, but I dont know how I'd calculate that ahead of time
The simplest way is to clamp the velocity with Vector3.ClampMagnitude
Idk what you mean with the "get" part though
You should be the one to determine the top speed
I just mean get as in "taking all the properties of the rigidbody, how can I calculate what the top speed would be"
I don't think there are any properties that would determine a top speed
Nothing stops you from setting the velocity to (99999, 0, 0)
(Except of course being kinematic or otherwise constrained)
You could probably calculate a resulting velocity from some forces or acceleration though
well, with Mass = 1, Linear Damp = 0.2, Angular Damp = 0.2 the magnitude reaches 5
then Mass = 0.5, Linear Damp = 0.2, Angular Damp = 0.2 the magnitude reaches 10
It's clear there is a relationship between the mass and the top speed
What I'm trying to do is determine the % the current speed is, to what the highest speed could be, so that I can do something like apply some artificial boost but only when the speed is between some range
It's clear there is a relationship between the mass and the top speed
No that's not how newtonian physics works
there is no limit to the max speed in newtonian physics other than those imposed by the limits of the software such as floating point representation precision.
The damping is definitely relevant but since there is no maximum force you can add, there's no maximum velocity.
If you imposed some constraint like "the maximum force is X per physics step", there's certainly a maximum speed you could reach with that limited maximum force per fixedupdate.
Basically:
Force adds to the velocity (how much it adds depends on the mass)
Linear Damping removes a certain percentage of the velocity each physics frame
And you reach your maximum speed when those two things become equal.
That requires you to know the formula behind how the damping is applied though. If it's the default Unity damping then you can look that up.
hi everyone, I'm turning to people who know unity well because at the moment I'm trying to learn this software
I just don't really understand the 2d collision system (I'm talking about wall-floor-ceiling collisions, not coin collisions) if I understood correctly there is:
rigibody2D which basically allows unity to take care of everything in terms of physics (you just have to type 3 lines of code) it uses collider2D
raycasts: one line to make it really simple
OnCollisionEnter2D:
and finally there are overlaps
here's everything I know (that I understood)
but so which one should be used for wall-floor collisions (apart from rigibody I don't think we have much control)
or there are other techniques that I don't know
thanks
but so which one should be used for wall-floor collisions
This is a really vague question
wdym by "used for collisions"?
what are you trying to do?
actually I wonder if that's all there is to do this type of collision with gravity, rebounds...
because I have the impression that with the rigibody we don't have total control over the variables of physics
i don't know if it's very clear
actually I wonder if that's all there is to do this type of collision with gravity, rebounds...
The physics engine gives you gravity, collisions, bouncing etc out of the box
you don't have to do anything
unless you want to customize it somehow
That's why I ask - "what are you trying to achieve"?
just practice seeing all the ways to do collisions in 2D to get an overview
Just got "Triggers on concave MeshColliders are not supported" ... is there a general way to fix my colliders? This is terrain for a golf course
Why would the terrain be a trigger?
make it not a trigger
Idea was to do manual physics during ball flight until it interacts with something, then switch to unity physics.
That doesn't do very good job explaining why the terrain would be a trigger though does it? I also don't see a reason not to just use unity's physics during flight and adding your own forces on top if you need features like curving path based on spin or more sophisticated air drag model (or do you do that already, I'm confused). It sounds like you are making the environment triggers because you don't want the ball to interact with it until the ball hits something, but that makes little sense since the ball won't interact with things it doesn't hit anyways. Triggers also sound terrible solution for capturing hits for a high speed ball since triggers don't respect the collision detection mode (continuous collisions) in any way so there's a chance the ball tunnels through geometry without any notice and even when you get a trigger hit, it won't give an accurate representation of where the ball should have naturally hit something (because the ball might already be way below the surface of the object)
I don't see what that has to do with the terrain being a trigger
why are there only like
three threads on the internet about wheels?
Im finding it hard tuning a vehicle's friction. If I move it any slower than crawling pace, it spins 720 degrees and then regains grip
unless the trick is to only drive on perfectly flat ground
yeah i can't seem to get the car to go faster than a few mph without spinning out with the stock wheel settings
Yes, the convex mesh from blender is just what I want but when I turn it to convex in unity we get the lower poly mesh that is too basic for collision. Unitys "convexing" is really poor and I can't find any parameters to adjust it
I tested with a similiar shape and the convex mesh looks fine
Your mesh might have some degenerate triangles
Okay I replicated your problem:
This happens when the mesh is very small. I did this by scaling it to 0.001 in blender and then to 1000 in unity
At 0.01 -> 100 it seems to be somewhere in between
This is probably due to some floating point precision limits. Could also be an optimization that PhysX/Unity does to small meshes
Is interpolating physics broken for you too? Every rigid object that I set to interpolation, interpolate, is acting weird. If the object does not interpolate it acts correct, but the FPS of the animation is bellow 50 I think
Works for me
Which version are you using?
6000.0.32f1
My guess is it's something in your scene or code
Like what?
If the code is exactlyt he same, but the only difference is the setting for interpolation?
For instance, when not interpolating, if you drop an object in a certain way, it will almost always drop the same way. While with interpolating, it will randomly bounce around more
It's less consistent and stable
I do not seek consistensy, but it's an example of how more chaotic it is
I will try 32f1 though
Oh wait, I am actually using it now heh
If that's true it's a bug you should report
interpolation is only supposed to be visual
it's not supposed to affect the physics
That's what I thought. I really don't think that's how it works.
The physics have had a lot of issues in version 6, thought hey fixed some of the previous issues.
I will wait a little to see if anyone else has this issue.
I mean, early versions of 6 had a lot more issues in physics
Ah, outstanding. I think I was playing with obj files that add in a 100x scale, if I recall, which would explain why it is failing for me. Not a great system to fail like that but at least I know some work with scale can solve it. Much appreciated!
Hey guys, hoping to get some help regarding ragdoll and fixed joints.
I've currently got a simple character controller and animations and I've created another character with ragdoll physics attached by a fixed joint to the palm of my player's hand. The Physics for this is incredibly janky and I'd love to be able to reduce that somehow.
Things I've done:
- Set all rigidbodies to Interpolate
- Set all rigidbodies collision detection to Continuous
- Set all character joints to Enable Preprocessing
- Given every rigidbody a physics material with dynamic friction and static friction reduced to 0.2
- Increased the Default Solver Iterations in the project settings. (I have tried a range of values, including the max of 255. The video shows a value of 16)
What can I possibly do here to make this less jank?
Hey, i'm new about this thing but i've created a building for VRC world. Everything was fine until i was created glass wall. Then beign troubles. I used for it Mesh Collider but that makes me stuck into it. I was searching about any solve but not found. Know someone, how to fix, please? Have some thick walls which are good but the thin stuckin me.
Is it possible that your colliders are intersecting? That could cause issues. If they are inside each other
Well, I suppose that's possible. The ragdoll will malfunction like that if the colliders overlap I assume. I understand I could use the ignore physics collisions on layers, however I do want this layer to collide with itself unfortunately, so would the solution be to simply reduce the size of all my rigid body colliders? (Even though by default they aren't overlapping, but still decrease the size to create a gap?)
Yea, it does not need to ignore it's own collider. I am saying if the colliders are too "fat", it will explode like that, because they cannot reach resting position, ebcause they will always pressue each other.
Give it at least a little space between each collider
Got it, thanks for the advice
Enable Collision might be of importance. Disabling preprocessing for the joints may help the stability of the simulation too
what is your opinion to the best Method to create a dash ability
Hi there
I am a beginner. I am trying to implement a plate balancing game
I have encountered something weird, which is although the ball do falls on my plate, but when I tilt the plate with my scripts written, the ball didn't roll, but remain in the air
using UnityEngine;
public class PlatformController : MonoBehaviour
{
public float tiltSpeed = 10f;
void Update()
{
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
Vector3 tilt = new Vector3(verticalInput, 0, -horizontalInput);
transform.Rotate(tilt * tiltSpeed * Time.deltaTime);
}
}
my scripts
what happened
or probably something goes with the collision setting?
my settings for the plate
my settings for the ball
Likely because you are using transform to rotate the plate, it will bypass physics pretty much
You should either:
A. Add a non-kinematic rigidbody to the plate and use torque or a joint to rotate it. The mesh collider should be marked convex. You can lock the rigidbody position in the constraints tab
B. Add a kinematic rigidbody to the plate and control its rotation with MoveRotation (collisions might be unreliable)
got it, let me update my codes
Hi, trying unity after godot.
Having pretty simple question. Why CharacterController.Move should be called in Update instead of FixedUpdate (Is it correct to call it PhysicsUpdate?)? My concern is wouldn't it cause to many physics engine calls if call it every frame?
No
It's designed to run in Update so that the movement is not jittery
Yeah, I don't think CC supports interpolation so it would not look smooth on high framerates (if it was moved on fixed update)
Exactly
you can implement interpolation yourself, it's extremally simple
You can but I'm not sure that's very beneficial for character controllers (over just moving in update)
for a single player game yea, not very important, but i still would do it so that the logic runs perfectly the same regardless of fps
The difference is likely not noticeable but I get the point, that would be totally reasonable although I likely wouldn't care enough to do that myself in any of my casual projects
can someone please help me? i wanna make a rope physic with spring joint but this is keep happening
Im not sure if this is the correct thread but it is related to physics so Im giving it a shot.
The bedside table has a mesh collider that is equal to its size, so when I drag and drop prefabs ontop of it gets in the right position, however I have a second child box collider that extrudes above the table, this is to prevent the player from jumping ontop of objects, this boxcollider only affects the player and nothing else in the physics tab, however it also block the placements of prefabs ontop of the table, so I cant drop and drag prefabs manually over the table anymore, instead they slide along the invisible box collider, is there any solution for this?
If the box is on a different layer, just hide that layer here in the top right of unity:
Hi, so i have this configurable joint sphere that is supposed to track the cameras local position using target position but there is a weird offset that i do not remember setting? I also send my code and more of the config joint
Oh yes perfect!! thanks 😄
In my train vehicle, I have it so you can freely drive it around via the users input, and I've added a new feature that allows the input direction to be locked (shown as the red line). As if the wheels have been attached to some rails, only moving in the rail direction and not to the side.
What I cant figure out is how I can constrain the position of the locked section, so it is unable to move to the side even when it has external forces pulling it in that direction. Right now I can enable the lock, but the train is still able to be pulled perpendicular to its locked heading
Better to use a spline library and handle physics manually than trying to use Rigidbody
eh, having the position effectively just be interpolated along a spline doesnt really sound that great
Why not?
You can easily simulate basic physics with that
F = ma
And have a velocity
one problem is the entire vehicle consists of multiple different bodies that are connected together
if I was to switch the wheel section from a rigidbody, over to the non-rb locked version, I'm not sure how I'd handle the other parts connecting to it and allow them to still apply forces to the locked portion
only other thing is if I worked with splines, I could implement a custom prismatic joint, because a joint like that would achieve the desired behaviour
Is that needed? What kind of game is this?
it would be, yeah. Its basically an action roguelike where you drive a train around to defeat enemies
I plan on having tracks that you can drive either end of the train onto, locking it on the track as there will be different mechanics that become available in that mode
or with both ends on 2 tracks, youd get multi-track drifting
off the tracks its like that video, full freedom of movement
but the side thats on the track gets fixed and effectively the other side would orbit around it
if it was possible to do something like the constraints here, but Freeze Relative Position X I could see that being ideal
I assume Unity does more stuff underneath with the constraint, rather than it essentially just being the same as body.linearVelocityX = 0;
Relative to what, though?
You'd effectively do that with a joint
relative to transform.right or maybe .up
freezing the X axis would use the worlds X direction like the black arrow. But the relative X direction should be the red arrow
heres a more accurate video showing what I'm after
then just imagine the same idea but if the rail was to curve rather than only be vertical
You could try Articulation bodies (which would mean 3D physics) but I really think you're looking at something spline based and custom
I'm not familiar with articulation bodies, but if they'd be able to achieve the sort of thing youd expect with rails like these objects, then they could be worth it
but if not, I suppose I'll have to implement a completely custom type of joint
conceptually, its not that complicated of a feature. But I'm sure implementing it is another story
for any sort of curve, its easy enough to find the location A on the curve thats closest to B
I wonder if it could be done by just giving an object at A that uses the typical spline/path following like most people do with train tracks, then attach B to it via something like a distance joint
this is my code for my player why the jump buffer dont work some help ??
https://paste.ofcode.org/XgwgmgkZeE9GG6RGWg94CH
What does "the jump buffer don't work" mean?
What are you expecting the code to do?
What is it doing instead?
What debugging steps have you taken to investigate?
Hey!
Maybe the wrong channel, but;
I'm trying to find an alternative to detecting environment interactions (Unity 2D). The use case is when players or enemies touch grass sprites they will trigger a tween animation. Right now the POC simply uses circle colliders and it is obviously not very performative, especially since our game is a horde-shooter with lots of enemies.
We really don't want to start implementing DOTS now.
Anyone got any idea how to work around this issue (outside not having any environment interactions)? Was thinking this might be common. Maybe some sort of shader, masking or camera layering.
Are you using tilemaps?
No, we use some wacky self-made solution
I'm actually not even the artist or the programmer on that, but i decided i wanted to start figuring out a solution
Tilemaps are almost certainly more performant than a solution that involves many individual SpriteRenderers, if that's what your solution does. And if you use a TIlemap you can just check nearby tiles to see if they are the interactable ones
We might make a sprite based collision technique to what you're alluding to, as in just subdividing our playable area into a grid.
As you can tell, we are really into making things more complicated for ourselves!
So I have a weird issue. I'm applying a impulse force up to make the player jump, but if the player is in motion horizontally the jump height is reduced.
I'm just doing(pseudo code)
Rb.addForce(vec3, impulse);
}```
Could be anything from:
- Other code modifying the vertical velocity
- vertical momentum gained in other ways such as running horizontally up a hill
SHowing us a video and the full movement script would help
As well as the inspector configuration of the player and which components it has
Alright I'll do it later sense I'm at work, ty tho
one other thing might be if you have linear drag
No drag, really it only wasd apples using addForce and rot with mouse vector, and a stair climbing that doesn't add a force but teleports based off of the stair height, but I'll prov8de the script later
My guess is you are clamping the whole velocity vector
Yeah if you're doing some kind of clamping/speed limit thing that'll do it. That falls under "some other code modifying the velocity"
Could it be because I'm setting a max velocity
yes absolutely
Sounds like your code is working as expected
I guess so, but how to I limit the players speed
Change your code that limits the velocity to only care about horizontal (x axis) velocity
I'm guessing I do that with if vel.x > Val, vel.x = val
Probably just
myRb2d.linearVelocityX = Mathf.Clamp(myRb2d.linearVelocityX, -maxSpeed, maxSpeed);```
this was fixed coz i forgot to add a a rigidbody to the component that time lol
i've done it before so many times that i forgot this time
circle based collision is just a matter of checking if the distance from A to B is less than the radius
once the distance from the enemy to the player, is less than the radius, you know the enemy has "collided" with the player
guys why is it when I add a Mesh Collider to my custom built Mesh polygon, it generates a square collider?
figured it out after 5 hours
Look at this sexy Mesh Collider. Basically, if you feed the Mesh Collider Vertices all on the same Z Pos. I think it returns a quad. BUT if you feed it a 3D array of Vertices, you get this beautiful artwork.
I've got my kinematic body attached via a hingejoint to a counterweight body. What I need is to be able to control the direction my kinematic body moves in, so it feels like its actually being influenced by the movement of the weight. The video shows what it's like without any influence
void SolveUnbalance()
{
Vector2 armDirection = (_counterweight.transform.position - _rb.transform.position).normalized;
// get the direction from the center to the counterweight
Vector2 perpendicular = Vector2.Perpendicular(transform.up);
// find the direction that is perpendicular to the direction the triangle faces
_unbalanceDirection = Vector2.Dot(armDirection, perpendicular) * perpendicular;
// aim from the triangle towards the side that the counterweight is
_unbalanceDirection = Vector2.Lerp(transform.up, _unbalanceDirection, Mathf.Abs(_unbalanceDirection.magnitude));
// not a great approach, but this will steer the direction towards the counterweight
// that way the more to the left or right the weight is, the more influence pulls it that way
}```This has been my attempt for it, and it only sort of works
Kinematic bodies aren't affected by forces
If you want that kinda thing make it not kinematic
I know, which is why I'm trying to solve it
https://en.wikipedia.org/wiki/Pendulum_(mechanics)#/media/File:Oscillating_pendulum.gif I figure its sort of similar to how pendulums behave
A pendulum is a body suspended from a fixed support such that it freely swings back and forth under the influence of gravity. When a pendulum is displaced sideways from its resting, equilibrium position, it is subject to a restoring force due to gravity that will accelerate it back towards the equilibrium position. When released, the restoring f...
huh, it embedded the wiki page not the gif itself
The clever way to do this I would say is to check the velocity of the counterweight each FixedUpdate and work backwards to figure out what force the joint must have applied to it to change its velocity from the previous frames velocity to the current.
Then apply Newton's second law:
Every force has an equal and opposite reaction force.
That opposite force is what needs to be applied to the main body
You could also just make it not kinematic and get that for free
I've been using a dynamic rigidbody, it's nice that this effect does come for free, but it's pretty tough to fine tune the bulk of my movement code
it's greatly improved now im using a kinematic, its just this pendulum type effect thats been the first hurdle. End of the day it is just some additional math to be solved to get what I need
What I'm having trouble visualising is what direction the counterweight would push the triangle. Would it be the angle perpendicular to the joint (green line), ie the same way the box would be rotating towards (red arrow)
Or would it actually be the acceleration direction like what the gif shows?
One a problem with finding the velocity of the counterweight is I have to subtract the triangles velocity, otherwise the counterweight might not be rotating, but it inherits the velocity of the triangle.
Vector2 currentCounterVelocity = _counterweight.linearVelocity - _rb.linearVelocity;
That becomes a problem the moment I apply the reaction force, because the next time it updates some value begins to accumulate and the forces "explode"
No no
this isn't what I meant.
Something like this:
Rigidbody2D counterweight;
Vector2 previousCounterweightVel;
void Start() {
previousCounterweightVel = counterweight.linearVelocity;
}
void FixedUpdate() {
Vector2 currentVel = counterweight.linearVelocity;
Vector2 differenceFromLastFrame = currentVel - previousCounterweightVel;
// Work backwards to calculate what force must have been applied to the counterweight
// How much did it accelerate?
Vector2 acceleration = differenceFromLastFrame / Time.fixedDeltaTime;
// To accelerate the counterweight that much we need to have applied a force proportional to its mass
Vector2 forceApplied = acceleration * counterweight.mass;
Vector2 equalAndOppositeForce = -forceApplied;
// Now apply equalAndOpppositeForce to your "main" body.
// The details of this are unclear to me since it's kinematic.
// But if it was a dynamic body it would be mainBody.AddForce(equalAndOppositeForce);
// store the velocity for next frame.
previousCounterweightVel = currentVel;
}```
I havent applied the force yet, but the yellow line is what equalAndOppositeForce gets calculated as. Does that seem right?
more or less, yes
_desiredForce = _facingDirection.normalized;
_desiredForce *= speed;
_rb.linearVelocity = _desiredForce;```The actual velocity for the triangle is pretty simple, though the [documentation](<https://docs.unity3d.com/6000.0/Documentation/ScriptReference/RigidbodyType2D.Kinematic.html>) has me wondering why you'd choose to deal with manually setting a position rather than setting the velocity to alter it
`This type of Rigidbody2D can be moved by setting its Rigidbody2D.velocity or Rigidbody2D.angularVelocity or by being repositioned explicitly.`
Sometimes you may wish to teleport it
ah, true
But yeah the ability to set velocity on kinematics in 2D is nice. 3D doesn't have that
3D uses PhysX doesnt it?
yes
I cant seem to apply the counterweights force, the moment I try and use it it quickly "explodes"
_desiredForce = _facingDirection.normalized;
_desiredForce -= _unbalanceDirection;
_desiredForce *= speed;
_rb.linearVelocity = _desiredForce;```
more or less like that
What happened to the force we calculated before?
which would point the blue vector towards the yellow to give it the white direction
and why is velocity being set directly to a force?
its named _unbalanceDirection
Force and velocity are not the same
poor naming choice on my part
it would be like:
_rb.linearVelocity += (_unbalanceDirection * Time.fixedDeltaTime / _rb.mass);```
not sure why the facing direction or speed should come into play
unless we're mixing up your existing movement code with this new stuff here
(also assuming this is in FixedUpdate)
private void FixedUpdate()
{
SolveDesiredRotation(MaxRotateRadian); // all this does is rotate the triangle to face the joystick/WASD input
_desiredDirection = _facingDirection.normalized; // forces can only be applied in the direction the body is facing
CalculateMomentum(); // handles the accel/deccel to build speed over time
_desiredDirection *= Momentum; //Momentum is multiplied against fixedDeltaTime
_desiredDirection *= 1f; // scale the speed
SolveUnbalance(); // the counterweight calculation to find _unbalanceDirection
_rb.linearVelocity = _desiredDirection;
}```Thats a more broad overview of the whole process
The way I'm thinking of it, there's the direction the triangle is moving towards that the player controls, but as the counterweight has it's own unbalanced force, I need to adjust the triangles velocity, so it combines both the players input and the velocity from the counterweight
is it more efficient to use overlapSphere or a bunch of raycasts
How many raycasts?
If it's like 10 raycasts, then I would expect OverlapSphere to be faster
Not really something we can answer
It would also depend on the size of the overlap/length of the raycasts - which affects how many objects the physics engine needs to check
What's the use case?
I have one big rigidbody cube, and above it, one small rigidbody cube, each with 0 rotation. I start the game, the small cube drops onto the big cube, but as it lands it rotates a little before settling. In theory, surely there should be no rotation, since they're both box colliders with no rotation, right?
If I set angular damping to 0, the box fully flips over on collision. How can this happen when a perfectly flat cube falls on another perfectly flat cube?
Is one of the boxes a child or another box? Or are they children of anything else?
That definitely sounds odd
Does it happen in an empty scene where you just add two cubes?
I just tested it in an empty scene and now I'm getting the behaviour I expected
So clearly something else in the scene in messing with it, even though the cubes are far away from everything else. Reenabling objects one by one to figure out the problem
well, not my project. i just saw this and thought it looked like a performance hazard
#💻┃code-beginner message
Hey, do anyone know why do my objects fall through a mesh collider? If an object touches the floor with a single face it just falls through. This doesn't work with other colliders. What should I do?
Mesh colliders are not supported for rigidbodies unless you mark it convex. You should have warnings/errors saying that in the console
i need a formula/calculation for calculating force of each thruster depending on center of mass
To achieve what?
non fliping
So you mean you want net zero torque
mostly, yes
oh, thanks
for a kinematic rigidbody2d, Im not quite sure the right way I should move it around. I could either calculate the velocity needed to be set as linearVelocity or I could calculate a position with the velocity and move the transform.position according to that
I also don't know if I need to calculate acceleration or not in order to find the correct velocity
If you want it to interact properly with other objects you will not use the Transform
You would use the Rigidbody2D
Once I set the linearVelocity and the angularVelocity of a body, like this:
rb.linearVelocity = rb.transform.up.normalized; // velocity always aims in the direction the body faces
rb.angularVelocity = GetInputDirection(); // the body will turn towards the joysticks direction```How would I find the "real" velocity (I'm not sure what to call it), as in what direction will the rigidbody move towards when you consider both the linear and angular velocity
Say in this, the point would travel along the dotted path over time
Hmm, it could be as simple ascs var rotatedVelocity = Quaternion.Euler(rb.angularVelocity * Mathf.Rad2Deg) * rb.linearVelocity;
Untested
Might need to account for angularDamping too
float newAngle = _inner.angularVelocity;
Quaternion rotatedVelocity = Quaternion.Euler(0f, 0f, newAngle);
Vector3 dir = rotatedVelocity * _inner.linearVelocity;
Debug.DrawLine(_inner.transform.position, _inner.transform.position + dir, Color.yellow);```The yellow line is aiming in the same direction that the joystick is, but I dont think it's actually showing the right direction.
In the image, even though the yellow line aims to the right, the next step of the simulation would actually have the red line match the white line as it only ever turns a small amount each step
I omitted * Mathf.Rad2Deg because I already use it when I set the value ofangularVelocity
I forgot to account for time in my example. How far ahead are you trying to predict? One fixedupdate?
float newAngle = _inner.angularVelocity * Time.fixedDeltaTime; seems like that was the missing part!
🤔 If you read from angularVelocity (radians) and use it in Quaternion.Euler (degrees), you need to convert
Yeah
Is _inner not a rigidbody?
it is
is there a way to create physics colliders in scene using unity's physics stuff without fully using dots? i want to create a static scene of colliders for boids to raycast in, don't really like using the gameobjects approach
It's not clear what your definition of "fully using dots" is, but you have to use DOTS to use Unity Physics
you can freely use GameObjects and Components for the rest of the game even when using DOTS for the Physics part
you'll just have to write a SystemBase system or two to glue things together
basically i have an array of meshes and im rendering them like this https://pastebin.com/Uai7UbPQ
because they are proc-generated i there for dont use gameobjects for it. but i still want to do raycasts so i wanted to also add an array of colliders but you have to instantiate gameobjects with regular colliders so i wondered if i can use unity's physics api and query an array of those colliders without using Systems and all that jazz
in simpler terms i just wanted to use a more pure math representation that i can query with a ray cast without all the bloat of using dots or gameobjects
I think you would need to pretty much import a separate physics library and directly use its API (or write your own) to avoid that overhead completely.
It's probably not worth the hassle
The DOTS stuff is pretty lightweight.
is it normal for layermasks to allow physics cast (line or circle for example) to still get other colliders whose layers aren't in the mask?
nevermind
has to do with argument ordering for the optional parameters causing my layer mask to be fed into the distance optional parameter
oh my bad wrong channel
Hi, guys. What is the best way do set colliders for the ground? I made ground in blender and it is just a curved plane. I add mesh collider and have problems with dropping objects on it. They just go through the ground sometimes as collision detection for planes is not good. What can i do? Do not want to duplicate box colliders under it as it would be a lot of work(
"collision detection for planes is not good" is something that I'm not aware of at least. Usually tunneling happens when fast moving objects without Continuous Collision Detection hit thin objects. Make sure that is enabled for you rigidbody, otherwise you will get tunneling effects no matter which collider type you use
So Collision Detection -> Continuous
The only problem with planes that I know of is just that they are infinitely thin so if the object gets over half way through within one physics frame, the physics system will force the object to the other side and not back to where it came from. When continuous collision detection is used, the physics system calculates continuous path for the object and stops it before it gets to tunnel through obstacles
If I didn't make myself clear on that, the Collision Detection mode should be set for the moving object, not for the ground (which doesn't likely need rigidbody at all)
yes, i tried continuous detection, still bad
Could you record a short video clip of the effect happening as well as the setup you have?
It's really hard to get the full picture of what's happening and what might be causing it from textual description alone
i dropped it 10 times before, was completley fine
What type of collider does the sword have?
mesh, convex. Bedore it was box but same effect
and it has continuous rigidbody right?
as you can see it hits the ground with the handle, but then goes below
i played a little bit with settings, now it discretre, but with other types its the same
i will test one more time
with continious
yep, same
its fine with box colliders or mesh convex, but i cant make the whole ground convex as it adds wrong collision surfaces
You shouldn't have to make it (the ground) convex anyway
and this is multiplayer, using photon. But it happens localy..
I have seen similar effect happening when small/thin colliders collide with large mesh colliders, I'm currently trying if I can replicate that
i thought maybe i was missing something obvious but looks like there is no common solution
The only difference is it only happened for me with very extreme values. I have not seen it happen in scene like this where the speeds are low and objects of reasonable size
Have you tried using the Physics Debug window to see if it reveals something of interest?
never tried..
when i make collider convex its fine, as it becomes to have thickness
It would also be good if you could place the objects on the scene in edit mode in a pose where the tunneling happens every time so it would be easier to see what is happening there frame by frame (in the physics debugger for example)
in the scene view i move the sword under ground and it falls. But if there is some thikness, it pushes the sword back on surface as i release mouse button
looks like thats how the physics worls, nut you said you have this isue only with big values
Which collider are you talking about?
That does not sound normal though. I'm unable to recreate the effect in unity 6 with reasonably sized objects
Yeah, something's off
@silver salmon Are you sure that the sword has no scripts or other components (like animator) that could be modifying its transform?
And it's not parented to another rigidbody or anything silly like that?
+What is the scale of the sword object in unity?
ground collider
after instantiating it is being attached to an empty parent SpawnedItems with coordinates 0,0,0. Scale is set to 0.8 right after instantiating
and there is no animator
@silver salmon Did you use the regular Continuous collision detection mode for the sword or something else. The only mode (other than discrete) where anything remotely similar happens is Continuous Speculative but even then it required really thin objects to occur
i tried all of it, and yes, the ground is a plane, so it is thin
no, not the ground, the falling object must be thin for it to happen for me
With Continuous I need to set the scale of the object on one axis to around 0.00002 in one axis for it to go through but at that scale range even floating point issues start to arise
not thin
maybe there is something else..
If some of the faces on the ground are inverted, this could also happen I assume, but you would have likely noticed that by now due to other issues wouldn't you?
The handle still colliding doesn't seem to suggest that either (would need to be very specific triangle that's flipped but in theory possible)
dont know, i think it will fall under ground every time but it happens only 1 of 10..
You could try to set up a test scene where this would happen automatically every time you press play so it would be easier to debug (wouldn't be 1 of 10)
yes, ok, will continue to investigate, thank you!
Just making sure -- The spring in this case will push the cart along the blue vector, not the red one, right? (ignoring the torque applied from the offset force)
The red vector force comes from the inclined plane not the spring.
Does anyone know why my player jerks so much when I move around?
private void Update()
{
moveDirection = transform.right * horizontalInput;
}
private void FixedUpdate()
{
// Apply horizontal movement
_rigidbody.AddForce(moveDirection * horizontalMovementSpeed, ForceMode.Force);
}
Try enabling interpolation on the rigidbody
So the cart would be pushed along the red vector? I thought the spring pushing would coerce an equal and opposite force from the ground regardless of the normal of the contact point?
the wheel would
It will, but the wheel is pushing against the slope and therefore the slope pushes the wheel along the normal with equal force. They are two different forces. If the other force didn't exist, even if you made the slope 89 degrees steep, the cart would not slow down at all and only be pushed upwards which if you think about it, wouldn't make much sense
Ah I suppose if I think of it like a bouncy ball it makes more sense that way. good point. Thank you!
In reality you would get something like this happening of course but I assume you are not simulating the spring in that dimension
No not quite. It's a kind of simple suspension system
Assuing the wheel is on some kind of piston that limits its movement to vertical
That's what I thought. Still you would get the red component pushing the wheel towards the normal, some of which will result to the spring contracting and some will change the velocity of the cart itself
If you ran into 89 degree wall, the spring would only minimally contract and the cart would most certainly stop or do a front flip over the obstacle
Oh, to be clear this example has all objects still at the initial stage
just a compressed spring
With any reasonable scenario with a car having a bumper in front, I'm not even sure you would need to account for that outside the spring contraction (the maximum angle between the car body and the slope would be minimal) but in theory it should happen that way
@snow surge With a monster truck for example, I could see a scenario where the spring force wouldn't be sufficient to resolve the collision (with some trucks even a straight wall could be hit wheels first). By the spring force logic alone the truck would be sent flying upwards while in reality that wouldn't be at all what would happen (it would just face plant the wall)
Hi, I am trying to create these awesome animation thingies using a Ragdoll (trust me this is more of a physics/transforms based question)
The main concept was for the ragdoll to have configurable joints with spring force (I think it is called Angular YZ drive etc), that would make it so that the character does not fall. Another mixamo:hip bone hierarchy at the same time would play it's own animation, and the configurable joints target rotation would be changed to that another mixamo:hip. This would enable for a more "physics based" motion.
I tried achieving this, using this tutorial: https://www.youtube.com/watch?v=iNLQCwCHEBM
However, Unity freaks out and does not accurately rotate the limb in the desired direction. I have no idea if I am missing something from the tutorial or just doing something really dumb. If you need more details, screenshots, etc. head over to my dms id really be grateful for the help!
Not sure if it really matters, but both of these do not face the same direction when all rotation axes are 0
So I'm trying to make a Sonic style game, but I'm having trouble getting loops to work.
Movement Script: https://pastebin.com/pHEWCfp0
Player Stat Script (Included because it has the gravity calculations): https://pastebin.com/BTsKfrGK
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.
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.
There are a lot of things wrong with the code. I don't have a specific thing to call out as "the reason" it's not working, but there's much to fix:
- both of your raycasts are hardcoding
Vector3.downas the direction to cast, rather than casting in whatever direction the player's feet are. transform.rotation = Quaternion.Euler(Vector2.up);makes very little sense. You are confusing direction vectors with euler angles here seemingly. This will set the player's rotation expressed in euler angles to (0, 1, 0). That's 1 degree of rotation on the y axis, and 0 on the other axes. If you just want to make the player upright that would be eithertransform.rotation = Quaternion.identityorQuaternion.Euler(0, 0, 0)transform.rotation = Quaternion.FromToRotation(Vector3.up, LoopHit.normal);also doesn't make sense, as thius is setting hte player's rotation to the _rotation that would go from the suyrface normal to the player's current rotation... it's kind of a misfire. What you want is actually the rotation where the surface normal is "up". That would be something like this:
Vector3 forward = transform.forward;
Vector3 projectedForward = Vector3.ProjectOnPlane(forward, LoopHit.normal);
Quaternion newRotation = Quaternion.LookRotation(projectedForward, LoopHit.normal);
transform.rotation = newRotation;```
4. your basic movement code: `RB.velocity = new Vector2(MoveVelocity.x, RB.velocity.y);` makes an assumption that your player is always standing upright, which obviously is not true when going through a loop.
Thanks for the response! I'll try to fix the stuff you pointed out, but I have a question about the code you gave me.
Isn't Vector3.ProjectOnPlane supposed to take 2 arguments and not just one?
yes that was an omission on my part, I fixed it.
Thank you
Anyone?
Do you still have your ragdoll bones parented to each other? They should not be
Make them "siblings"
Either with no parent or a parent that never moves
Also, make sure that no animation is affecting the ragdoll bones directly
Btw that tutorial is questionable. In the final result, the legs rotations are inverted. 🤦♂️
Active ragdolls are more complex than "joint.rotation = targetBone.rotation"
For me, this extension has been helpful for setting the target rotation correctly:
https://gist.github.com/mstevenson/7b85893e8caf5ca034e6
Make sure to read the comments
Okay let me look into it and lyk asap
Thanks!
I've been setting angularVelocity in a rigidbody2d to allow it to rotate how I like, but I've figured its probably better to start using AddTorque() and now that I am doing that, I cant seem to get any of my existing rotation code to produce the correct torque value.
The documentation says that in order to get a specific change in degrees that I should do (angularChangeInDegrees * Mathf.Deg2Rad) * body.inertia; . Which makes me think that is all it should take to use the code I have which already is producing the angular change I want in degrees
torque is analagous to force
angularVelocity is analagous to linear velocity
there is no such thing as an equivalence between the two, because they are apples and oranges
there is no such thing as a torque that results in a particluar angular change in degrees
torques produce velocity
and the velocity determines how quickly the orientation of the object changes
So all torques will eventually result in some number of degrees of change, but there's an additional variable in there - time
The sentence:
However, if you require a specific change in degrees, then you must first convert the torque value into radians by multiplying with Mathf.Deg2Rad then multiplying by the inertia.
Is poorly worded. What they meant is "degrees-per-second"
not degrees
And there's little reason to use AddTorque there instead of just setting the angular Velocity directly if your goal is to just reach a desired angular velocity
For my use all I care about is for it to do something akin to "rotate from the current angle to a target angle over a period of time"
I'd assumed AddTorque was a better way to do that as it might do a few extra things underneath that would make the angular velocity be set correctly rather than the value I'd find if I was to set it directly
it says it scales by inertia which I've never been doing, so I might have been accidentally setting the final value wrong
it seems like I've messed up the turning circle somehow 😅
"rotate from the current angle to a target angle over a period of time"
Definitely just set the angular velocity manually
You will go throlugh that whole torque calculation thing and your end result will just be the same exact thing as if you just set the angular velocity manually
The only effect that AddTorque has on the body is to change the angular velocity
What would the intended use be for the method?
if you don't have an intended target angular velocity and you just want to apply a certain amount of torque.
For example a game where you fly a spaceship and you can hold Q to fire your attitude control rockets
you would AddTorque in FixedUpdate while Q is held
ah, that makes sense
Hey, folks. I'm quite new to unity, so appopolgies if I come across a bit green. I've modelled a banana peel , and would like the peeled pieces to have almost ragdoll physics, but I can't seem to find any tools for ragdoll'ing that aren't specifically for humanoid characters. Any ideas? :)
I've had a search online, but everything seems to be for characters, rather than props.
The tool you are referring to is only to simplify the process of adding rigidbodies, colliders and joints to the bones of humanoid character. You can add and configure these components yourself to pretty much anything. Check documentation to find the best components for your use case. If you want, you can also create some kind of humanoid character ragdoll in order to check how all the joints are configured there.
Thank you! Figured it out in the end, is just a case of playing around with the values now :)
When I do set a target rotation, do I do it only for the bones that the ragdoll wizard setup with rigidbodies or do I start adding the script to every single bone
You set target rotation for each joint that you want to move
Got it.
I got this 2D homing fireball but when I apply the follow script it follows the player but the rotation is all wrong it's like the trail has a weight.
The trail is being dragged downwards
transform.right = direction; is all you need, not anything with the Cross products
So I only change linearVelocity and transform.Right and not angularVelocity?
Is there a good reason you would need the rotation to be physically simulated? Isn't it just a visual thing?
Not really, it is just a visual thing but that was the solution I found online since I'm not too good with physics calculations
Is this updated code the proposed solution?
Yes
Though it might break interpolation now that I think about it. Two solutions to that would be:
- use Atan2 on the direction vector to convert it to an angle and apply that to rb.rotation
- put the sprite on a child object and rotate the child only as here
I solved it by making the main sprite a circle and by seperating the trail to its own animation so it doesnt get affected. Thanks anyway :)
anyone have any idea how to implement tank movement (without actually simulating each part of the track with hinges)? I've tried using wheel colliders but I had some issues with that, now I'm just calculating the angular velocity of each track (left/right) but I'm having trouble applying that as a force to the tank. either there's too little friction and it slides once it starts moving, or it can't move at all.
Show your current code too
this is what I'm currently using to apply forces to the tank (had to use really big numbers to even get it to move)
float velocity = (treadLeft.treadSpeed + treadRight.treadSpeed) / 2f * 100000f;
float angularVelocity = (treadRight.treadSpeed - treadLeft.treadSpeed) / 0.5f * 100000f;
rigidbody.AddForce(transform.forward * velocity, ForceMode.Force);
rigidbody.AddTorque(Vector3.up * angularVelocity, ForceMode.Force);
should be transform.up *
Probably not a fix to your problem, but instead of torque you might want to try AddForceAtPosition for each side of the track
So turning right would be achieved by adding forward force on the left track and backwards force on the right track
That's sort of how tanks work right?
that's another one of the things I tried haha
didn't work too well either
I think it's mainly a problem with friction
since the tracks are just static colliders
Btw the reason you have to use large numbers like 100000f is probably because your tank has a large mass
And ForceMode.Force divides the force by mass
true
I had that open haha
Acceleration might be easier to work with here
Also, what do your colliders look like, specifically on the bottom that is in contact with the ground?
And the physics materials?
Might want to use low friction on the physics mat so you get better control over the velocity with forces
I've tried a bunch of combinations of static/dynamic but can't seem to get it right
Making your vehicle a "hover craft" is pretty common too: Don't have colliders for the wheels, just use physics queries (RayCast, SphereCast) to check the distance to ground and add force to hover above it
if the friction is too low, it'll slide when the tracks stop turning
This way the collisions don't interfere with your velocities
hmm, I could try this
thanks
Oh one more thing, try messing with rigidbody.centerOfMass
Maybe expose it as a variable for debug/dev purposes
hmm ok
what would be a good way to stop it from bouncing too much up and down with the "hovercraft" approach?
I guess I just have to write a full suspension system at this point
guess that would be fun too
Damping/not adding too much force when not necessary
yeah I'm trying to implement damping now
Seemingly simple question - how do you detect trigger-type collisions on fast projectiles?
I looked this up for a while and the solution often cited is to use Rigidbody2D.Cast. But when I tried that, I eventually discovered that only works on NON-TRIGGER types of colliders. That seems to defeat the whole point of that solution, as for non-trigger/solid colliders you can just use Continuous collision detection.
I know I can just set the projectile's collider type to non-trigger and set its layer overrides to exclude "Everything", but this feels like a weird solution and my gut is I'm doing something wrong here.
any advice?
how do you detect trigger-type collisions on fast projectiles?
can you clarify what you mean by this? what is the situation you're describing?
Suppose you have a bullet and you want it to deflect off another collider at an exact angle. Solid (non trigger) collider won't work for that, so better would be using the bullet's collider as a trigger, and when the bullet's OnTriggerEnter code fires, activate a change in the bullet's velocity to the angle you want.
That way it doesn't bounce off the other collider with any weirdness, because you can precisely control what it does.
I'd use a raycast and calculate the new angle from the hit normal
Huh, good to know. I'm surprised I kept seeing suggestions to use cast
I'll keep that in mind. Thanks!
Actually, what if it's not something small enough for a single hit point? Like what if it's a big sprite moving fast, like a ball or a car or something?
Or even a really cartoony, wide bullet?
SphereCast etc.
What if it's a complex shape like a vehicle?
Rigidbody.SweepTest
For 2D?
Exactly, Rigidbody2D.Cast is what I was trying to use before. But I found it only works with solid/non-trigger colliders. I'm trying to figure out how to use that for trigger-type colliders
Assuming it's a situation where you don't want it to be solid/non-trigger. Suppose a fast moving lightning beam or something
What is the purpose of the colliders at this point?
Calculating if the object hit something, taking into account the object's exact shape
You might be able to use Rigidbody2D.Cast/Collider2D.Cast and set the colliders to non-trigger temporarily, but that sounds like a hack
Yes, exactly. I found I can slightly less hack it by setting exlusions to Everything in the collider.
But still, a hack. Anyway around hacking this?
It seems like it should be straightforward
I was going to suggest using solid colliders but with collisions disabled via their layer, but seems like Rigidbody2D.Cast/Collider2D.Cast can't take a custom layermask parameter so i guess it wouldn't hit anything then
Can't think of a non-hacky solution right now. I'll let you know if something comes to mind
For now, I would probably just cast with solid colliders that are disabled normally and enabled only for the cast
I feel a lot better knowing I haven't overlooked something obvious then 🙂
Ok, I'll give that a try
Thanks
@silver moss So I did a full test and it mostly works? The cast works terrific for detecting the other sprite, and the red sprite never even vaguely clips through.
However, it looks a bit odd visually for the opposite reason. In a simple test here, I'm trying to make high-speed bouncing work, but WITHOUT actual bouncing, instead using code to reverse Y velocity when a hit from the cast is detected. I have the red sprite's collider set to solid (non trigger) and am keeping it that way for simplicity's sake now. There are no physics materials attached to either red nor green sprite.
But it doesn't look like it goes all the way down. How far down it goes even varies from bounce to bounce.
It looks like the framerate's been capped to 30, but the inconsistency looks even more pronounced on my 60ish hz display:
I coded the moving sprite's casting according to how I've seen recommended online mostly. The direction of the casting is determined by the normalized velocity, and the distance it casts is determined by the speed of the sprite * Time.fixedDeltaTime:
private void FixedUpdate()
{
float distance = rb.linearVelocity.magnitude * Time.fixedDeltaTime;
int numberOfCollisions;
numberOfCollisions = rb.Cast(rb.linearVelocity.normalized, hits, distance);
Debug.Log("number of collisions is " + numberOfCollisions);
if(numberOfCollisions > 0)
{
FastTriggerEnter();
}
}
private void FastTriggerEnter()
{
rb.linearVelocity = new Vector2(rb.linearVelocity.x, -rb.linearVelocity.y);
}
But it doesn't look like it goes all the way down.
This makes sense because you are casting from current pos to next pos, instead of previous pos to current pos
It never gets a chance to reach the collision point
Because you invert its velocity when it's "about to collide"
To me it would make more sense to cast from previous to current position. If hit, set position to the closest hit position and revert the velocity or whatever you want to do
What's the usecase here though?
Use case was I was trying to make a bubble that a circular player object could jump on, and when you jump on it it would perfectly invert your Y velocity so you could chain jumps together. At the same time, when the player bounced on the ground, it needed to set the player's exact bounce up speed, IF the Y velocity was too much. This is because you could let gravity drop the player, or press a key to slam down fast, and I wanted a controlled bounce if you were going down super fast.
I also remember having issues with bouncing on bubbles not being consistent 100% with the velocity of the bounce. Usually it was perfect, sometimes it was like a dead stop. I think I was trying to find a more consistent solution
Hi, might anyone know why my script isn't working as expected? I've made a trajectory predictor, by following the implementation in this forum:
https://gamedev.stackexchange.com/questions/71392/how-do-i-determine-a-good-path-for-2d-artillery-projectiles
As of now, the path that my object travels is slightly lower than the one indicated by the line renderer, so I believe that I've either miswrote the equations or there is some aspect of the physics system that I haven't taken into account. Here is my script:
https://scriptbin.xyz/norokoniba.cs
I know very little about unity's physics system, so I'd love an explanation as to what went wrong here
That's a great idea. Thanks!
Make sure to move it according to hit.distance, not hit.point
What would go wrong with hit.point?
If you move the object to hit.point, it will now partially clip into the collided object
You should just add cast direction * hit.distance to the position instead
This way you move it "until it hits"
So that the collider's edge ends up on the hit point
hello! Have a quick question here, i made my player characters collider bigger then the player, so it actually floats ABOVE the ground
i have a raycast checking if theres ground within 10m below my character
ray.GetPoint(distance) is ideal
but here, my character is UNDER the ground
ground is set at 0, and the pivot point of my transform is where the move component is
Make sure your tool handle position is set to Pivot not Center
The player should never be below the ground in the first place.
yeah, and its only underground in this specific area
If this y is negative then your ground is not at 0
Or it's not a flat plane or something
That's a map magic terrain
it is just a couple of Unity terrains behind the scene
Which is a heightmap basically
so just for clarification, its not to do with collider of player , but something to do with MagicMap, a 3rd party asset? If so i will figure things out myself
True that, I always forget it exists
Why doesnt the scale effect the raycast this is very weird
This is really realy weird
Btw i alsi tried collisions but only raycast is broken
what do you mean by that
can you explain what we're looking at?
What raycast is involved here?
not mapmagic necessarily just the height of the terrain
Would anyone mind helping me out😅?
i want to create rotation for my spaceships with add torque (physics are important, yes) and it's in space so there is no drag.
problem is idk how to make it not overshoot the rotation -> so it always adds the exact torque/deceleration counterforce to smoothly stop exactly at the target rotation (i am trying to do this for so long now i am losing my sanity again)
İ do a raycast to the layer of those 3 toruses however even if i change the scale of these objects it raycasts like the scale is 1
I'm not sure what you mean by it Raycasting like the scale is 1.
What are the details of the Raycast?
What results are you expecting from the Raycast?
What results are you seeing instead?
Nvrmind i fixed the issue
i'm doing some collision checks for a custom character controller using com.unity.physics, and i'm trying to use cast my character's capsule into the collision world to determine a maximum position that i can move to without penetrating other objects
the problem i'm running into is that ColliderCastHit.Fraction returns a fraction such that if i move by that fraction, the next CapsuleCast will consider the cast to hit at Fraction=0, leaving me stuck
i've checked the source and this seems to be a trivial consequence of how Unity.Physics.ColliderCastQueries.ConvexConvex is implemented, as it advances in discrete steps and outputs the first fraction where a collision is already happening
i can work around this by modifying the source to add a ColliderCastHit.LastFraction property which simply stores the last fraction at which a hit wasn't yet detected (a hit being detected by distance < 1e-3)
is there a better way to get a pre-penetrating fraction for collider casts? i'd prefer not to have to modify the package source if i can avoid it
Hey all, I am trying my hand at a 2d platformer and I'm trying to stop the player from being spiderman...
The player is a rigidbody2d set to dynamic, I figured out how to stop it from sticking to ceilings with a 'grounded' check, but what about walls? The solutions I see online are to use a frictionless material, but that results in sliding!
Just wondering if there are any common solutions to this problem, thanks!
ok I fixed it with a second box collider that goes around the main one but has no friction, still wondering if theres a neater method though
when I walk against a wall or anything that collides with the player, it starts to spin. How do I make it tight and not spin?
constrain the Rigidbody's rotation
how to make an object with HingeJoint to swing infinitely?
if this component can't do it then tell me please which speed rotates the object when the component is added and how to get/set it
anyone experienced with articulation bodies I have a question
do child articulation bodies of the parent articulation body ignore collision within itself?
in addition also, is it possible when a collider (with a rigidbody) imparts a force on another rigidbody, can one check for this collison and nullify the imparting force?
Hey everyone,
I'm trying to get my first-person character controller to move smoothly on a moving and rotating platform (like a ship) without making the player a child of the platform.
Right now, I’m using a raycast to detect if the player is standing on the platform (by checking a specific layer), and then I apply the platform’s movement and rotation delta to the player in LateUpdate().
What I’m Doing
-
Raycast Down from the player's feet to see if they are on a platform (using a tag or layer).
-
If they’re on a platform:
Store the platform’s position and rotation from the last frame.
In LateUpdate(), calculate how much the platform has moved and rotated.
Move the player by the same position delta and rotate their Y axis to match the platform.
- If the player jumps or steps off, the raycast no longer detects the platform, so they stop moving with it.
The Problem
It kinda works, but the player slides when the platform moves, especially when it turns only. Since I’m using a CharacterController, I’m applying movement using Move() instead of setting transform.position, but it still doesn’t feel right.
@rotund sentinel Don't do weird spacing pushing away other messages. It's also highly unreadable as a whole.
nice I'll look into this, are you able to answer my other question? #⚛️┃physics message
if not thats fine
I don't know anything about articulation bodies
noted, thanks for the assist anyhow
Spacing?? Can you explain what you mean by that?
lots of spaces inbetween your text
Does anybody know if it's possible to fully set the state of a rigidbody to a recorded state, including it's contacts? Obviously you can set it's position/rotation/velocity/angular velocity, but this leaves out any contacts it may have had which means it's state is not identical to the recorded state.
The only idea I've had so far that might accomplish this would be to actually record it's state 1 physics update prior to the desired state, set it's position/rotation/velocity/angular velocity to this state and then run PhysicsScene.Simulate() once. I believe this would cause it to then generate contacts, but I don't know if they'd be identical to what would've been generated originally. If anyone has any thoughts on solving this kind of problem I'd love to hear them.
I'm not sure I would agree about contacts being part of the state? What's the end goal here?
I want to be able to modify the impulses of the contacts generated for a particular rigidbody via Physics.ContactModifyEvent. However, for the particular modifications I want to make, I need to know what the impulse is going to be for each contact. From what I can tell, ContactModifyEvent occurs before the impulses are calculated as there isn't any way to get the impulse of each contact in ModifiableContactPair.
So, what I'm hoping is that if I were have a duplicate rigidbody in a separate physics scene that I apply the state of the original rigidbody to and then simulate one frame for, I will be able to record all the contacts generated for the duplicate rigidbody including the impulses for them. Then, when the original physics scene is simulated and I receive the ContactModifyEvent, I would be able to match up these modifiable contacts to the ones I recorded for the duplicate rigidbody and know what their impulses will be. I am hoping that if the position/rotation/velocity/angular velocity of the duplicate rigidbody are identical to the original, then the same contacts would be generated.
However it seems that if you set a rigidbody's position/rotation, even via MovePosition or MoveRotation, this affects how the contacts are generated, even if you set them to the position/rotation the rigidbody is already at.
You want angularVelocity if you want to set a rotational speed
How fast can a physical bullet object go in Unity before it starts to phase through other objects? I am somewhat reluctant to use raycasting for bullets
If you don't use continuous collision detection, the bullet can phase through a wall if it moves a greater distance than the thickness of the wall (+the radius of the bullet) in one physics step
So you want CCD at least if you go with rigidbodies
Alright, thanks
The effect is called "tunneling" FYI
CCD works at any speed or will it still break if speed still goes high enough? I copied the bullet speeds from muzzle velocities of real life guns and some of them fire their bullets at speeds just over a kilometer a second
Ah, thanks for letting me know
For such velocities a SphereCast or CapsuleCast may give you better results.
I do prefer casts for bullets that travel at realistic speeds
Raycast works for most cases, you only need spherecast/capsulecast if the bullet needs to have some volume
If you potentially have a lot of bullets active you can look into RaycastCommand. Way cheaper than having hundreds of CCD rigidbodies flying around
Thanks for the advice!
What is the best solution for making a character move on a moving & rotating platform without making it a child?
I've experienced issues with CharacterController not inheriting platform rotation properly, causing drift. Is there a way to fix this, or is Rigidbody the better option? Which one is the best approach for smooth movement and performance?
How would the logic work for handling this correctly?
With a rigidbody, when calculating the character's velocity each frame, you can add the platform's velocity to the character's final velocity before applying it
Have you looked into off the shelf solutions like https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131 ?
KCC has this problem solved pretty well
thanks (bruh i forgot to send)
I'm not sure how to describe the problem, but I'm having trouble figuring out how to get the movement to feel "tight". See how in the video after it completes a 90 degree turn, instead of moving in the new direction all the existing velocity pushes it sideways
Your object has momentum
that seems to be the entirety of your problem?
If you don't want momentum, you should be manually overwriting the velocity instead of adding forces.
alternatively - you need to apply much higher forces if you want to get faster acceleration.
I'm wary about changing the code to go from adding force to overwriting velocity, mostly as I'm not sure if that would be a significant change to the code I've already got
I think if I could increase the "friction" of it, that could help straighten it out once it makes the turn
yes another option is:
- applying higher forces overall
- applying forces that counteract your current sideways momentum
- limiting top speed either with another drag calculation or rb drag or straight up clamping
Basically some combination fo all this
but you just need to think of it in basic physics terms
to counteract any kind of velocity you don't want, you need a force
i made some swinging object and i don't understand how to get it's angle
i used transform.rotation.eulerAngles and for some reason it swings between 290 and ANOTHER 290 angle, why?
i mean it goes to from 290 to 270 than again increases to 290
what do you plan to do with the angle
basically using euler angles to do logic is always a bad idea
especially reading them back from a Transform
euler angles are pretty much cancer
how to get an angle that i can see in Transform component?
You can't get that one
it's visual only
and it's a bad idea
what is the END GOAL here?
There are better ways to do whatever it is
would it be the same principle as a helicopter rudder?
All newtonian physics works the same
f = ma
what you have here is torque which is for rotation which is really not that relevant here
because we're not concerned with angular velocity
to make the object swing infinitely by applying force when it reaches equilibrium point (i mean the point where it ends up when stops)
that was the answer to this question
You mean down
so it depends on the orientation of the thing but
presumably the rest point is at "0" rotation?
no
Can you show the object in scene view with its gizmos so we can see its orientation?
(with gizmo rotation in local mode)
ok so it's weirdly rotrated but if i'm reading this correctly you want to know when its forward direction (blue arrow with the move tool enabled) is facing down it seems?
So you can do something like:
float differenceFromDown = Vector3.Angle(transform.forward, Vector3.down);```
*it will face up in that position
it's hard for me to tell with the rotation tool selected
that's why i told you it
Then it'd be:
float differenceFromDown = Vector3.Angle(transform.forward, Vector3.up);```
And if you need a signed angle you can use Vector3.SignedAngle
Hmm, never consideret it, but it seems im forced to use it now. I may try to make my own one firstly
Thanks for the tip
i wrote this before
if (transform.rotation.eulerAngles.x < -90 && !speedsaved)
{
angVel = rb.angularVelocity;
speedsaved = true;
}```
how to use what you wrote here?