#⚛️┃physics
1 messages · Page 27 of 1
its supposed to detect the ground in front of AI and stop him if he's going to fall. just waiting for my project to compile to show relevant scs
debug ray properly working, collider has right tag, and i checked, layers are set to collide w each other
But you haven't actually said what's going wrong
Also, the layers collision setting is irrelevant for raycast
oh right sorry, just never collides with the ground
What does it collide with? Have you done any logging? How do you know it isn't hitting the ground?
it never sets off the if statement, i am just double checking now that it isnt colliding with itself, i tested earlier and it wasnt
So why don't you add a log that prints the object that it actually is colliding with?
I will note that your code doesn't seem to be taking into account the possibility that nothing is being hit and will throw an error in that case
Are you seeing errors in the console?
just logged it, it was colliding with itself🤦♂️
what is the best solution for this? simply offset it or make the collider another layer?
or something else?
Use a layer mask on the Raycast
ok cool thanks so much 🙂
so how do i make things not fall through the ground
No tutorials are working and i don't know why
Give them and the ground the appropriate physics components and make sure everything is moving via the physics engine
I have literally no idea what any of that means
no matter what i do it just wont work
Probably related to you not knowing what anything is.
Anyway your description of the problem isn't really giving anyone any clues to help you
ill write down everything i've tried
You would need to share with us exactly what you tried, how you set everything up, then we can point out what's wrong
ok
well i've tried turning off is trigger on both colliders for the terrain and capsule colliders, i've tried giving the terrain rigid body, the capsule rigid body, setting the colision to continuous on both, giving the terrain a box collider, giving the capsule a box collider, coding my own collision (it wouldn't even start after that) and thats about it
- Yes the colliders need to all NOT be triggers
- Please share screenshots of the inspectors for your "capsule" and the terrain
I just have a capsule with this code for movement, but the jumping doesn't work anyways because it can't touch the ground to begin with
using Microsoft.Win32.SafeHandles;
using System;
using UnityEngine;
using UnityEngine.InputSystem;
public class MovementScriptBaseCharacter : MonoBehaviour {
public float movementspeed = 5f;
CharacterController controller;
float gravity = -3f;
float velocity;
[SerializeField] float gravityMultiplier;
public float velocityMultiplier;
public float jumpPower = 5f;
PlayerInput playerInput;
InputAction moveInput;
InputAction jumpInput;
static bool IsDown(InputAction action) => action.phase == InputActionPhase.Performed;
void Start() {
controller = GetComponent<CharacterController>();
playerInput = GetComponent<PlayerInput>();
moveInput = playerInput.actions.FindAction("Move");
jumpInput = playerInput.actions.FindAction("Jump");
}
void Update() {
CharacterMovement();
}
void CharacterMovement() {
Vector2 direction = moveInput.ReadValue<Vector2>();
transform.position += new Vector3(direction.x, velocity, direction.y) * movementspeed * Time.deltaTime;
if (controller.isGrounded) {
velocity = -1f;
} else {
velocity += gravity * gravityMultiplier * Time.deltaTime;
}
if (velocity == -1f && IsDown(jumpInput)) {
velocity = jumpPower;
}
}
}
oh
thats much longer than i thought
Your code is moving the object directly via the Transform
Yeah
wait then what do i move it with then
Use the Rigidbody
But i can't change the rigid body's gravity
Or a CharacterController
Hold up but i thought the transform position WAS the character controller?
Physics gravity can be controlled from the physics settings or in your code
CharacterController is a specific component by that name
Well i do have a character controller set up so ill try to do it
Maybe you do but your code isn't using it
Your code is directly changing transform.position
can i just replace transform.position with controller.Move
That depends on if everything else is set up properly
Well i have the character controller set up so ill see if it works
yeah it cant assign move cause its a method group or something, idk what that means so ill just try to put the gravity in a whole different code block i guess
That means you tried to call a function without the ()
Move is a function you can't do Move = something
You have to call it
Like myCC.Move(location);
i guess but now an issue is that the direction takes too many arguments so it doesn't work
Well naturally you have to give it the correct arguments
I can't specifically use my velocity because the direction is from a 2d vector and whenever i try to use a 3d vector it gets mad at me for not assigning up and down
It should just be the whole expression you were "+=" ing before
and i don't want people to be able to just float up or down
You seem to just be struggling with the basic C# syntax of this
well im not exactly focusing since i'm still trying to code in the middle of this conversation to fix it
which luckily enough i finally found a fix for it
i didn't know you could just delete up and down on the 3d vector action so now i dont get a barrage of error messages probably and my movement is actually working now
Yeah I didn't know i had to use the controller for physics 😭
but yeah thanks for telling me about the thing with transform.position, i'll probably only use that if i have to add teleporting or something.
Does anyone know why it keeps making the reload sound when I'm not even touching the gun?? I'll guess I need to change it back to a physics joint?
There is nothing in that code that refer to a reload sound and when freeFloating is false, localDifference will always be equal to 0. I don't know what this code actually do
How to create damping between two object using code?
The reload sound is trigger by another triggercollider/script when the gun slide is pulled back. Visually it stays in place but the gun keeps reloading/triggering the sound.
You should take a look at this (it explains the update order) : https://docs.unity3d.com/6000.1/Documentation/Manual/execution-order.html . What you are doing with the code is setting the position of the transform during the Update, but the trigger actually triggers just after the physic simulation and before the Update, so the Rigidbody might move during the physic update and trigger the reload but you wouldn't see this since when the frame update, you set the position. What you should actually do is lock its local position with physics so it never touches the trigger when you don't want it to
You can probably lock the rigidbody by disabling it when needed and setting its "local" velocity to 0. But I don't know, I never tested it before
Thanks for the tip, I used IsKinematic and it worked.
I'm trying to use Spring Joints to create a some sort of lining for my fishing rod - but they are too springy/bouncy. What values I should set for it to behave properly? Or using Spring Joints in such way is incorrect?
What does "lining" mean for a fishing rod?
It's like a very thin rope, in a way
Oh a line
It really depends on exactly how this fishing mechanic is supposed to work
I'd say the vast majority of the time trying to make it physically realistic is a bad idea
Honestly, it's mostly for visual sake and all
It's not about it being realistic: I just don't want the points to bounce up & down, but still react with physics
(i.e. when the player cast his fishing rod and the lining/rope flies forward in the sky, until the end hits the water)
I would definitely not do this with a bunch of rigidbodies and joints
Any suggestions for an alternative?
verlet integration, trailrenderer, bezier curves
Ello, just wanted to get confirmation on a problem ive been having. My game has the ability to place objects on the ground, and checks to see if anything is colliding with it (ground included, because i will have slopes in the game). I have the buildings placed such so that they are "touching" / edge colliding with ground. Is the solution here to multiply the y size by like .99 when doing boxcasts? Or is there a better solution to handling edge touching of different items. (PS: I want the boxcast to see if theres any part of the ground above where its placed) so just want to ignore "edge" cases for now, can implement better logic if i want to be able to place on a slope
If you want to have the buildings aligned perfectly, you could use a grid-based system with snapping. Otherwise, the .99 scale trick on the OverlapBox call is good IMO.
Ahh gotcha, i do have a grid system, but the grid is more of a helper for the player, rather then dictating where items can be placed. thank you for the reponse
How much of an issue is it if my player is at a y position of -5.960464e-08 when it loads in and falls using a player capsule and rigidbody?
Why would that be an issue?
Im unsure if it will affect certain calculations 🤷♂️ . This is my first unity project
What do yoou mean
what kind of calculations and how would they be "affected"?
Idk ground checks, uneven surfaces
thats the thing I dont know if it would affect any
what about them?
its jsut a general question
Are you aware the number you wrote, written out as a full decimal is:
-0.00000005960464
yes
I mean I don't know for sure, because I'm having trouble understanding what kind of issue you think it would be causing
if you are trying to compare that number to be PRECISELY 0, for example, then yes that would be an issue
i mean if you wanna use it for a collider size or a transform scale, then it would also be a issue
you got to give what context you think it might be an issue in, because things depend on other things. If it was ALWAYS an issue, unity wouldnt have the ability to store / use that float
Anyone know why its giving an error?
You can mouse over errors to see what they are
Or look in the console window
Tessellation doesn't affect raycasts, right?
Meaning, a ray will hit the original terrain mesh before tessellation
shader displacements in general never get send back to CPU and therefore have no effect on collisions
My player ship seems to be rotating to the Z axis when colliding with an object despite me having already froze all points of rotation
Show your code
https://pastebin.com/MuEM7Xbu Certainly. This is the code that controls movement
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.
I purposefully set the object the player is colliding with low mass so it doesn’t affect its rotation that much
rb.freezeRotation = false; at the end of the ApplyRotation function unsets all those constraints
Yep - it's like Nitku says. You're turning those constraints off in your code
you're also rotating the Rigidbody directly via its Transform, which is a bad idea
Ah silly me! My reasoning for making it false was that I suspected it would eliminated the rotation of the X and Y which are needed to even move certain directions in game
Thank you!
I see. Any more efficient alternatives?
it's not a matter of efficiency
Rigidbody constraints don't apply when manipulating the transform directly
what is the best way to add collision to large environment models? like a winding ravine path or cave system
I would generally consider mesh colliders for their ease of use, for detailed meshes it can have an impact on performance so using separate more simplified mesh for the collider may be appropriate. If you have different LOD levels for the mesh, you can use less detailed mesh from there or make a new one (modelling tools often have tools to simplify existing meshes so you don't have to do that by hand)
my meshes arent very complex(psx style game) so i thought to use mesh colliders too but i seem to have misjudged how they worked
it kind of just tried to encapsulate the entire path in a collider which didnt work too well
do i have to split up the mesh into pieces that can work with the mesh collider or did i do something terribly wrong?
I'm not sure what you mean though make sure the collider is set to non-convex
is it common to have problems with tilemap colliders? i have a basic 2d platformer set up and the ennemies or players sometimes get hitched on what i can only assume is a tiny bit of collider sticking out
It's common when you neglect to use a CompositeCollider2D
thanks ill look into it
I am porting a game currently to consoles and we failed lotcheck on Switch due to some random crashes. Now after some testing I noticed the memory is increasing every couple of seconds although nothing seems to happen in the scene. And I noticed that when the game was paused it stopped allocating memory. I spent the whole day to figure out what the issue might be looking at logs, profiler/memory profiler to no avail until I started to conquer and divide in the scene and started to delete gameobjects one by one to see if it makes a difference. and it came down to Physics2D.
Some gameobjects that just had physics components attached were the reason for it. The Physics2d section in the profiler confirmed it, the “Physics2D used memory” count was increasing every frame as long as the game was not paused. I looked at the gameobjects with the components and nothing really was fishy about them except one thing: some of those had multiple colliders, meaning 1 gameobject had like 4 boxcolliders or/and two hinge joints etc
Is this the reason? I myself wouldnt setup GOs like this butgot this project from a publisher and thinking that Unity should be able to handle multiple comps like this, no?
Having multiple colliders on one object is not unusual or unsupported or anything
I know, that’s why I am wondering what actually the reason is that Unity allocates memory every frame without releasing it at some point
anyone have good experience with active ragdolls?
Calling GC.Collect manually also does not help.
I wonder if it’s some setting on any of the physics components leading to this, it feels like an engine bug
need help bros
i am trying to make active ragdolls playable and controllable from player input, i bought an asset pack with some prebuilt scripts because my scripts were too rigid and too confusing for me i hate quaternions and shit. Anyone who can help, it would be much appreciated.
my dms are open or ping if anyone has advice
my player just keep falling through the game i made a tile area and added tile collider and all and put rigdbody and capsule collider its a 2d game but my character keeps falling
can anyone guide how can i fix this
Rate this game on a scale of 1 to 10
Hi, can someone please help me with my tank controls/collision? :') I don’t know how to stop my tank from behaving like this when it hits a wall, and I’m not sure what to look into. Does anyone have an idea of what I should research to fix this problem?
That kind of thing usually happens when modifying the transform directly but you'd have to show the movement code
Do you use a Rigidbody on the tank?
Here is it. I used MovePosition since I read somewhere that it was probably better than just translate
// Handles tank movement and rotation
protected void HandleMovement()
{
float delta = Time.fixedDeltaTime;
// Move the tank forward/backward based on input
Vector3 movement = m_rigidbody.position + transform.forward * m_inputs.GetForwardInput() * m_tankMovementSpeed * delta;
m_rigidbody.MovePosition(movement);
// Rotate the tank based on input
float rotationAmount = m_tankRotationSpeed * m_inputs.GetRotationInput() * delta;
Quaternion rotation = Quaternion.Euler(0f, rotationAmount, 0f);
m_rigidbody.MoveRotation(m_rigidbody.rotation * rotation);
}
yep the second screen are the tank components
Have you tried using AddForce instead of MovePosition? I use this for Rigidbody2D, but use MoveRotation as you do.
I also had to adjust the 2D physics parameters to never get stuck in walls, but there are less parameters in 3D to play with... Just to give you some input of what maybe to look at.
I'll try with add force then !
AddForce() solved the problem ! but AddTorque() causes a new one :')
is it possible to pass an array of colliders into the Physics.Raycast function in order to ignore them?
can't use layers to do this btw
no, only a layermask
darn, well I appreciate it anyhow
You can always look at the documentation if you're unsure about the parameters of a method:
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Physics.Raycast.html
Hi ! I followed a tutorial on YT to create a blender character then export and create a ragdoll. But every time some of the spine parts looks like they stay at the original place they "spawned". Also the head "hitbox" is like 20 times too big.. On blender nothing looks glitchy in pose mode. Do someone has issued a similar thing ? thank you !
oh and I don't have a "head" or "def head" ? .. 🧐
Ok so i did not generate rig and it worked !
I may have missed something, but atm my problem is solved
This is expected
If you check the docs it mentions it only works on convex mesh colliders
https://docs.unity3d.com/ScriptReference/Physics.ClosestPoint.html
Over the past week, I’ve been working on mapping Unity’s terrain heightfield onto a PhysX scene. I initially pulled my data directly from the TerrainData API:
var data = terrain.terrainData;
int tileRes = data.heightmapResolution;
var heights = data.GetHeights(0, 0, tileRes, tileRes);
Despite using GetHeights (and also trying the underlying heightmapTexture), I observed discrepancies of up to 0.5 units on sloped areas. Only after implementing a custom exporter—one that raycasts every point in world space and reconstructs the heightmap from those samples—did the PhysX collider match Unity’s terrain precisely (sub 0.01). Unfortunately, that raycast-based approach is quite slow.
Is there something I’m missing in how Unity processes its heightmaps for collision? Beyond the known bilinear interpolation applied by SampleHeight, does Unity perform any special treatment when generating the heightfield collider? The terrain itself was created using Unity’s built-in Terrain Tools rather than imported height data. I’m also curious how others have handled server-authoritative movement: did you rely on GetHeights/heightmapTexture, or did you employ an alternative method to generate a PhysX-compatible heightfield?
I observed discrepancies of up to 0.5 units on sloped areas.
Well yeah GetHeights only gives you the heights at integer "pixel" coordinates. Everything in between those coordinates is interpolated
You can use https://docs.unity3d.com/6000.1/Documentation/ScriptReference/TerrainData.GetInterpolatedHeight.html or https://docs.unity3d.com/6000.1/Documentation/ScriptReference/TerrainData.GetInterpolatedHeights.html for the interpolated heights of course.
Unity can't feed physx interpolated heights though, it takes a heightmap which is going to be per pixel heights.
I'm not comparing height samples, I'm comparing collision positions.
If I take the heightmap unity is supposedly using, and import it into the same physx version, I would expect a raycast to collide at the same heights
Unless unity is like overwriting the raycast with its interpolated height when it detects a terrain collision?
it absolutely uses interpolated height for raycasts
it uses interpolated height for all physics interactions
otherwise the terrain would be minecraft shaped
Well yeah because physx does that
This would be unity applying something after
We are not talking visuals here
Unity may apply something after I'm not sure, but physx itself interpolates the height
Or else physx would be minecraft shaped
GetHeight(
GetInterpolatedHeight(
Appear to use direct sampling from the heightmap
But physics interactions are not the same, they do not rely on this,
There are two seperate things going on with terrain, there is direct sampling, and then there is actual physics collisions handled by physx. Physx is not mapping a blocky terrain even though you feed it in direct points. The whole reason unity needs the interpolated height method is because its sampling from the heightmap
I don't feel like I fully understand your issue
afaik Unity directly uses the PhysX terrain for everything
and doesn't do any additional processing or interpolation
I observed discrepancies of up to 0.5 units on sloped areas.
Can you elaborate more on this? How and where did you observe this?
Yeah and that's what I also thought, physx doesn't actually let you do anything besides change mesh cooking params and setting tesselation on certain points
If you dump the heightmap, in any of the various ways unity provides. Then create a physx scene, and create a height field at the same origin, size ect. Slopes will be off by 0.5+
And when I say slopes are off, I mean I'm picking a point, say 0, 0 and I'm doing a raycast from above. Unity might report collision at 427.3145, but on a physx scene with the same (or atleast I assume as the same) parameters, I might get 427.125
Doesn't seem to be a contact offset as its not consistant at all
My guess is you're doing something wrong somewhere in the translation process
perhaps Unity and Physx use a different coordinate/ordering system for example
like Unity starts top left and Physx starts bottom left, something like that
Yeah that was one of my inital theories but if that were the case the whole terrain would be off not just slopes
and dumping my own heightmap at a 1:2 scale via raycasts actually got me sub 0.01 precision to unities reported raycast collisions
But it just doesn't make sense why I would need to do that
Also I'd like it to be within floating point errors 😂 0.01 is kind of high
Help.... i excluded the layers in the collider and rigibody and it is still affacting the player capsule collider.... making the movement slow and weird
but simply removing them causing not being able to get the tail physics i want
what should i do?
(ignore the tail go through floor bug, i kinda went to project settings and in physics settings i disabled tail layer collision to everything to tail layer, will fix after)
Not sure if this belongs here or in Animation tbh, but I'm using a IK Chain constraint to drive a bone chain, but I would like bones in the chain to interact with some world objects (like wall/objects that move etc), is it possible to add colliders to the bones and have them 'pushed' out of the way by said objects?
i know its possible as i saw someone on reddit do it to push the gun in their hand back when up against a wall to prevent clipping
no idea how they did it though
i tried finding the thread but wasn't able to
Where are my terrain and physx experts?
Are you by chance making incorrect assumptions in how to map between a world coordinate to a terrain heightmap pixel to your other scene position?
Got one question about constant force vs gravity
My player has a rigidbody, and I use a script that makes them float above ground using force, with the legs using IK to touch the ground
Leftmost pic is when gravity is enabled
Second pic is with gravity disabled, but with constant force of -9.81 applied, which should be equal to gravity amount
Am I not understanding something about how constant force works?
I'm uh... sucky at physics... but could it be mass-related? Like, maybe you need to multiply the force by the mass of the object for it to be the same?
The mass matters as pulni said
It would only be equivalent to gravity if the object's mass was 1
Ahh, that explains it
Thank you
Aah okay. Thanks anyway dude 🙂
Hmm not sure I'm exactly following what you are asking here.
I'm placing them at the same origin, with the same sizing.
I have a unit test of about 70 points dumbed via raycast from unity, all flat terrain match, slopes are off by a hair (and more if using unities provided textures/heights). I have tried shifting the terrain in the x, and z origin by increments (0.1, -0.1) to see if it was off by a set amount, this yielded results indicating my placement was correct, as then flat spots that did match unity, no longer do as the terrain has shifted.
it is a complex terrain, and with 70 points tested, any sort of positioning/coordinate errors would show in a different way than slight slop height differences as flat areas return with no issue. The height differences actually go up depending on the magnititude of the slope. A cliff will return differences that are way larger than an area with a slight incline. The slight incline might be 0.001 off, but the cliff (if using unities provided heights) might be off up to 0.6
I have a stupid question. Can you slap an ortographic camera in a 3d scene and use rigidbody2d, vector2, etc to get the peformance benefits of 2d?
Ofcource you can. It is perfectly possible to have movement 2D and visual 3D.
@pulsar canopy
There's only one type of scene. The only difference between 2d and 3d is the camera and that you typically use sprites in 2d and models in 3d
I mean, will you get performance benefits out of the ortographic camera? I'm sure calculations in 2d and rigidbody 2 are faster, though
You can try toggling the camera between ortographic and perspective and seeing if it has any effect on the fps. I doubt it does
I don't think so, what you chose to show is what is shown.
What I'm getting at is, a true 2d is always more performant, other things being equal?
the fact that the camera is orthographic really isn't going to change the performance of rendering.
it will still be rendering the same objects with the same shaders etc
orthographic is not "true 2d"
it's just a camera projection that doesn't have perspective effects
you're still rendering a 3D object
for example, pixels on a heightmap define vertex positions. lets assume a 100m terrain and 1025px heightmap -> 1025 vertex positions but 1024 intervals. Pixel 0 of a 100m terrain is at 0 and pixel 1025 at position 100, if you however, for some reason, forget that last pixel, or map 1024 to 100, in your other scene, you would get slight offsets on sloped terrains, but not on flat ones for the same world coordinate.
Right. So true 2d is always more performant, other things being equal?
What does "true 2d" mean?
I mean just using sprites
it's really comparing apples and oranges
It's like... "what's more performant, an airplane or a car?"
Why
or maybe "a car or a boat?"
Because it's lacking context
you can render a plain old Quad mesh with a MeshRenderer vs a sprite on a SpriteRenderer in a scene alone
pretty sure the Quad would be faster
And that's "3D"
They are different tools for doing different things.
Yes, but I'm talking about a real 3d scene with 3d models vs a 2d scene...it's always more perforrmant, regardless of the canera perspective if the objects are 2d rather than 3d?
That's still kind of a nonsensical question because it depends on the sprites and models, and if you're planning to switch from 3D models to sprites only because it's "more performant" then that's just silly
but yes in general rendering one sprite is probably usually more performant than rendering one 3d model
It's a curiosity thing, more than anything
I'm considering doing a 2d game and I don't know how to draw and am much more familiar with everything in 3d
Therefore the answer is probably irrelevant as I'd choose to do it 3d cause it's the better choice for me
But I like knowing things
no
Ah yeah I see what you are saying.
I’ve double checked my spacing logic and it already accounts for the (resolution - 1) intervals
w.sampleDX = meta.Size.X / float64(resX-1)
w.sampleDZ = meta.Size.Z / float64(resZ-1)
And the caveat there I suppose is very high res sprites vs low poly models with colors instead of textures
Yea I get that part
i thought that i have disabled gravity, but for some reason there is a resistance when i move my character down?
what should i do to fix this?
code, based on a tutorial video
but why?
because it does not belong into Physics, you are not using any physics there
check the unity docs Charachtercontroller.Move you will see that too
oh wait you also have arigidbody there
oh ok
this wont work well together., you either use the cc or rb but not both
cc is character controller?
ah never mind i see it now..
so leave the code inside FixedUpdate, the freaking script name confused me totally.
so revert this change?
yeah please. what you had prevoiusly was totally fine i thought we are using a cc but totally forgot that 2d doesnt have one and the script name confused me.
wait
i might have done a mistake
hold on
yep
i forgot that crouch is down
so when i press down, not only it goes down, but it also slows the player down
im sorry
will do, thank you
Why is my model falling so slowly?
do you have any code?
try a rigidbody reset
it goes upward now and at the same speed
like its ascending instead of descending
Oh I had an animator object and it was affecting it mb
glad you fixed it
i have an issue:
sometimes the overlap detection does not fire when player and enemy collides
im not sure whether i am doing this wrong, or that there is something that i miss
OverlapBoxAll will only detect things inside the overlapbox but the enemy isn't going to be inside it because the overlapbox is exactly the same size as the player's collider and the enemy bounces off the player
If you want to detect the collision then just use OnCollisionEnter2D
collision/collider is for when the object bounce / touch, while overlap is when objects pass through each other
am i correct?
Maybe the object is just really large so it appears to fall slowly relative to the default gravity setting
Ive resolved the issue but I appreciate your help
hey yall, what is the best way to implement distance based knockback where no objects can cause the knock object to slow down and instead give way to the knockobject ? Im using rb.moveposition() to get my knock back my game object, however when it collides with another object, it will slow down, stop and not reach the distance its supposed to be knocked to. Turning on Kinematic body types will cause phasing issues so its a no go.
in this clip, the blue ray represents where the enemy actually ends up and the yellow ray represents where its supposed to end up. In the beginning when the enemy doesnt have another enemy standing behind it the blue & yellow ray aligns however when it starts to collide with another guy then he falls short of the knock distance
How can i set the zero of articulated revolute joint?
If the joint is in x axis and if i rotate the joint in that axis, the zero position doesnt change.
i use a tilemap collider on my grid map, i get stuck in nothing, same for enemies, cuz its "uneven" for some stupid reason.
i use a composite collider, some raycast fail because they are cast inside the ground, bu dont detect it cuz the composite collider is not filled. additionally, it doesnt work well with A* pathfinding graphs, need much more tweaking and such.
what am i supposed to do?
Use a CompositeCollider2D and use polygon mode
Is there any good videos online anyone would recommend for physics? (Vector3, Quaternions)
Vector3 and Quaternions are not directly physics concepts
more like, just spatial reasoning
Oh yeah I guess so
watch the end of the video to understand. Sudden jolts of force send fixed joints into panic which causes contraptions to "blow up". The playerbase HATES this instability and i wanna fix it. How?
Would a config joint with all params locked help?
tough crowd
implemented a new "soft weld" system that just makes a config joint with really high drives
works pretty well
are there any better alternatives? i want to keep using fixed joints but i dont want these explosions to keep happening when people are trying to make stuff
I have a problem with the car. When I open the game, it flies. I also added a Collider Wheel and things are fine, but after 3 or 4 seconds, the car flies.
what
what car are you talking about
why is there no plane collider? it's like the box collider but more efficient because there's only one face
For one, PhysX which unity uses by default doesn't really have support for them. The only plane collider PhysX knows is a plane that extends infinitely (like mathematical planes do) and can only be used for static objects. It's an interesting question why unity haven't decided to make support for that but I suppose that wouldn't be super useful for most anyways.
Box colliders are super efficient, you don't usually have to worry about that. The performance of a collider isn't really defined by it's faces (but rather many complicated factors), sphere colliders are often the most efficient collider shape even though they have 0 or infinite faces depending how you define it (they are mathematically super simple to model by using their center and radius and hence the performance). The AABB of a proper plane and a thin box would be very similar so there wouldn't be huge difference from there either.
Why there are no plane colliders that are bounded to an rectangle and can be dynamic then (e.g. useful for playing cards)? Apart from the previously stated lack of support by PhysX, it would be very unoptimal shape to simulate in a discrete simulation potentially causing a ton of tunneling issues especially when they interact with one another. You can see these issues in action if you create very thin box colliders and stack them on top of one another. The little I know about physics simulations, I don't think these issues are easily fixable for tailored plane colliders either.
Is there some specific concern that you have with the box collider and what would a plane collider fix in your case? You can always leave unity a feature request if you feel like it, but given that one hasn't been implemented to this date, it would be unlikely to happen in the near future unless they either update or change physics engines altogether (don't know how this is handled in other engines or never PhysX versions)
I have a car character locked on the Y axis for positions, and Z and X axes for rotation. It works great on its own.
But when I add a snow plow to it, it’s like it resists turning all of a sudden. The player and plow have no collision between them enabled. Can’t do trigger on the plow as it must push snow around.
The rigidbody is on the character prefab. Both the character and plow have their own collider on separate child objects. The plow is part of the character prefab.
I apply force by doing addforce. I already tried setting the center of mass in code, but that didn’t work.
Any ideas? For some reaso, when I changed some parameters, now the character rotates on the X and Z axes even though it is frozen. Still with the slow turning that is weird as if the plow interferes…
I need help, I can’t grab any objects that were supposed to be grabbable, what is going on?
Hi, I have a rigidbody and capsule collider with free y axis rotation. On slopes there is no issue going up or down but when moving along the slope at a level height the character controller slides without friction and the experiences a frequent jitter in y axis rotation. Anyone know why this may be?
You'd have to show your code
And the Rigidbody inspector
📃 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.
public void OnLook(InputAction.CallbackContext ctx) {
Vector2 delta = lookSensitivity * ctx.ReadValue<Vector2>();
targetEuler += new Vector3(-delta.y, delta.x, 0f);
targetEuler.x = Mathf.Clamp(targetEuler.x, xEulerMin, xEulerMax);
}
i've heard that mesh colliders are terrible so i was hoping there would be some alternative for level geometry that is static, and rectangle-shaped surfaces could use a plane collider instead i suppose. everybody keeps saying to put box colliders on everything but that is just insane, what is one supposed to do then?
Couldn't you use flat-ish box collider for a rectangular mesh? Who told you mesh colliders are terrible? They are generally bit worse sure, but often times the collision shape doesn't even matter due to how the broad phase/AABB check eliminates most of the potential collision pairs. Generally you should use the primitive colliders (box, sphere, capsule) whenever they give reasonable approximation of the shape. Using mesh colliders is totally fine in most cases though. For a super detailed mesh, I would consider a lower LOD level for the mesh collider, you often don't need nearly all the triangles to get good enough physics precision
If you could specify what kind of objects/meshes you a trying to get colliders in (what shapes? how many? dynamic or static? used for what? etc.), it would make it much easier to give any specific suggestions.
well i saw some reddit posts like https://www.reddit.com/r/Unity3D/comments/11cd0tf/mesh_collider_uses_up_too_much_performance/ and https://www.reddit.com/r/Unity3D/comments/ctw21o/a_question_regarding_when_to_use_mesh_colliders/ and it seems most people are saying that you should manually place box colliders for everything but it would take ages wouldnt it?? for example an enviroment like this image: (its not mine but its an example of stuff i want)
i cant imagine how people expect me to make box colliders for this scene
but also even a house like this would take ages to manually place box colliders
I wouldn't read too much into those posts, seems to be mostly people that "have heard" from somewhere. Both the original posters didn't find any issues with mesh colliders themselves, just that they were worried. This kind of scene I would make out of combination of collider types. If the terrain system was used, a terrain collider for the terrain would be quite obvious choice. The boulders I would either make out of primitives or use convex mesh collider (potentially for lower LOD mesh). With the poles and the trees even simple capsules could be sufficient. For the railing for example I would use a simple mesh collider (again with simplified mesh if needed)
More like couple minutes if you only need collisions with character controllers. If you needed the collider to be exactly the shape of the mesh for something like precise bullet decal positioning, I would just use mesh collider, that seems to be very low poly mesh anyways so I wouldn't be too worried.
but if i want bullets to collide properly and with precise decal positions then isnt the only way to make everything into mesh colliders in this entire scene? including the trees and poles and boulders. and would that still be fine for performance?
In fully developed scenes they can have a pretty notable impact on scene start times though
not something to worry about too much in advance however
I was just typing a message about that. The performance isn't generally the issue for low poly mesh colliders, but they can introduce other issues regarding loading times and memory consumption from what I have heard
though that can be mitigated by spreading them out across frames i think
its their initialization off of Awake() that can creep up at scale
Other than placing a ton of primitives, yes. I would start from the easier solution of mesh colliders, profiling in your own scene is the only way to find out what the cost is
The reason for those loading time problems I believe is that PhysX builds some clever spatial partitioning structures for each static mesh collider which makes them very fast to look up (good runtime performance). I don't know if it is possible to force those preparations to happen beforehand (during building for example)
hmm that is interesting, i wonder why it doesnt do that already. i also know that unity also has havok physics as an option, i wonder if that would be a lot better with mesh colliders?
Anyone?
Adding colliders changes the moment of inertia of the object
because it changes the shape of the object
Is there an easy way to account for this? I really wanna make my snow plow...
you can manually set the inertia tensor to whatever you want
You can also disable the automatic intertia tensor checkbox
Amazing, that was it!! Thanks
Dynamic Rope
jiggly asf lol nice work
Hi everyone! I have a very basic humanoid rig that I'm working with that uses configurable joints and some custom torque code that rotates the joints to the desired angles using a simplified idea of muscles.
The issue is that when the joints have reached their angular limits, any additional torque onto the limb will cause the rig to have "god forces". An example is that the rig could spin on the ground when at maximum angular limit and continues to extend the legs. The desired behavior is similar to what we have in real life - if you extend your leg while it's at its limit, it won't extend any more even though you're trying to. Again what happens in my simulation is that it produces unrealistic forces that will spin the rig around.
So far I have tried limiting the torque that can be added when the joint is at its angular limit, which sort of works but something is telling me this is a workaround that will give me more headaches in the future.
Does anyone know of anyone or game that has implemented rotating Articulationbody wheels?
Actual rotating collider, I've reached out to a few devs that may have done it but they had all given up on actual rotation and just had visual rotation
I've done all sorts of experiments to see if it was possible but rolling friction just seems to get in the way
figured it out, was a simple code toggle
Does anyone know how to transfer rotation between two bodies with configurable joint in unity? I am making a simple ball joint that will also transfer rotation
I have a physics based game in zero-gravity and currently when I shoot a bullet at a floating box (both have rigidbodies) the box moves a bit from the impact, this is normal behaviour ofc. But why doesn't the box start rotating when shot away from the centre of mass? Like when I shoot near the top of the box it only moves, but doesn't start rotating around it's centre of mass.
very begginer stuff(just came back to unity and I don't remember a lot):
Why is the object floating a little bit above the collider(colliders fall until they touch)
the floor is made out of tiles with colliders btw
it's very inconsistent too
the floor collider just randomly got bigger when I wasn't looking, but it still floats above that collider
It's the Default Contact Offset in your physics 2D settings
I'm trying to use animations from mixamo, but the two character I applied the animations to are not the animations I saw on the site.
Sounds like a topic for #🏃┃animation.
Does anyone know??
You'd have to show the inspectors of both objects. But if the box moves only a bit instead of gaining permament velocity there's some dampening mechanism that might dampen the rotation as well
Yes it's only a small force, is there a way to turn off that dampening?
the rigidbody has linear and angular damping properties
There's no way to know what it is without knowing your setup, you'll have to show the inspector and any relevant code
Yea sorry I thought I already tried turning off the angular damping, somehow that didn't work last time. But set it to 0 and now it works. Weird. Thanks for the help tho!
Bruh what now it doesn't work again?!
I'll make some screenshots 1sec
did you change it in playmode? those changes dont save
I'm in playmode rn with 0 and it doesn't rotate, I'll send some pics
Yeah now it doesn't rotate anymore, so weird
Every time I try to record it on video it rotates wtf...
Ok got it on video now
Looks like the object you're shooting at has a mass 1000 times that of the bullet. Unless the bullet is moving extremely fast, it's going to barely affect the thing
1 sec ill send the video
This time it did work
This time not working
It's so weird, one time it works, other time it doesn't
I sent some videos, maybe you know what it happening?
that's a bit weird, assuming nothing changed between
Yeah I changed nothing
Bruh I caught it working and not working in a single take... wtf...
I mean - you manually edited the damping and the position of the object between.
That surely messes with some things
it probably doesn't happen if you don't do that?
Ill try again later. I only set it to 1 and back to 0 to stop it from rotating.
Ok this is really weird. @timid dove @inner thistle @dull jungle
Just to be sure I made a test build. I put the boxes in a row left to each other and set the Angular Damping different for each of them. From left to right it goes from 0 to 0.6.
I shot all of the boxes and reloaded the scene a couple times, each time the results were different. Also some strange results, sometimes the box with 0 damping didn't rotate but a box with more damping did.
The last video shows it the best with very inconsistent results.
how fast is your bullet, what collision detection method are you using?
See this image for settings. Boxes are Discrete, bullet continuous dynamic.
(bulletForce = 1)
I would assume that the only rotational force you get is if the box has friction with the ground it is placed on based on what we see here, can you create a physics material with 0 friction? (and minimum as calc method)
The boxes are floating midair in zero gravity, they are not touching anything until they reach the wall.
This last video shows it the best with very inconsistent results.
Box collider
Bullet has sphere collider
are you deleting the bullet immediately on impact?
It gets disabled immediately yes (pooled)
can you try leaving it active, just to fool around?
Ok 1 sec
It's still weird
What is the mass of your bullet?
0.01
try raising it
ok
Yeah it seems more consistent now
I'll try playing with the values a bit
Ok I think the problem is the speed of the bullet
I increased the mass and it looked normal. But because of the mass increase the bullet went slower, so I increased the force to bring it to the old speed again and now it doesn't work again, even with the higher mass.
Thank you I didn't see that tab I was looking for it.
do you have some kind of logic on the bullets when they collide?
or in general
Yes, but I put return on a tag so it wouldn't destroy them on the boxes. But I think it's the speed
So I guess no spinny boxes in my game for now :(
I think this is just a weird unity thingy. But weird how it does give linear velocity, you would expect it to get no velocity at all right?
you can also manually get the impact point and apply a force by code
make the bullet a trigger instead and handle the collision force yourself
Not sure if it's correct chanel to ask but how can i make unity not cutting edges on textures with missing/fully transparent pixels? It's causing random player jumps while moving on flat platform. I've tried to use same tilemap with default square sprite and everything was fine so i'm sure the problem here
You can set a custom physics shape for any sprite in the sprite editor
Found it, thank you
hey guys, ive been having this issue, im trying to make a ragdoll after a hitscan attack on unity, the animations where fine but the character cant get up, i tried using the animations to get him up, i tried to change from rigidbody and collider to character controller nothing, the ragdoll itself works fine but it cant get up
also i made a code to disable the collider for a second after it stays on, which is my theory of why it doesnt get up, but it still didnt disable it, am i missing something?
btw i need that collider to trigger the ragdoll, but its also not allowing me to get my character up
I am making characters on ship
my character and ship are both rigidbody component
characters should be able to move freely on ship
how exactly i can resolve movement on top of ship?
You keep saying "get the character up", what's exactly are you doing to try to do that?
Anyone see the AVBD physics simulation paper? It looks like a more stable physics system that could be used for general physics sims or smaller particle sims like cloth physics
oh yeah i saw that, it looks interesting. from the example i saw, it still has issues with clipping at high speeds. but it's much better at handling ropes and chains.
why is the pillar not falling down? gravity isnt affecting it, any ideas?
is your game paused or Time Scale set to 0?
Is your physics simulation mode set to auto/FixedUpdate?
If your physics engine set to use PhysX?
Is there an invisible collider underneath it?
this was the cause
There ya go - simulation mode
Anyone done moving platforms for an FPS game? Bonus points if it uses or works with the Unity Starter Assets FPS asset
Kinematic character controller is the way to go
(free on asset store)
What if I want to use the Starter Asset one that is not kinematic?
I appreciate that that might be easier but Id like to solve it for both/all use cases too
sorry for the late answer, there is an animation to get the character up, and there is a script to try to make him upright however it doesnt work, you see when he gets hit he goes into ragdoll mode, then fallen animation and then get up animation, but he stays sideways
Starter asset uses a character controller which behaves kinematic as well
Is there any generally accepted way to calculate forces required for a desired velocity on an articulationbody that's part of a hierarchy? I can go off combined mass but that does not factor in anything related to joints
Why Rigidbody.angularVelocity won't exceeds 5.041452?
private void FixedUpdate()
{
Rigidbody rb = cube.GetComponent<Rigidbody>();
rb.angularVelocity += new Vector3(1f, 1f, 1f);
Debug.Log(rb.angularVelocity.x + "," + rb.angularVelocity.y + "," + rb.angularVelocity.z);
}
angular velocity is limited by physics settings
the default is something like 7 rotations per second
in project settings?
yes
alright thanks
what happens when a bouncy object hits another bouncy object?
double the bounciness?
Does anyone know why this is happening idk how to fix it
your 3D model is oriented incorrectly
the direction your object is moving is the forward direction of your object
If you switch to the Move tool and switch the tool handle rotation to "Local" (not Global) you will see:
Blue == forward
Green == up
Red == right
To fix this you need to reorient that "root" child object so that it is facing the forward direction of the parent object.
I fixed it, but new problem now. it flys but not well and its super wonky when it comes to its physics, if i pitch up it turns for a bit but then starts spinning
convincing realistic airplane physics are not going to be simple
yeah prob the worst problem rn is that i got my jet flying but when i turn and my plane is facing the new direction it is still moving in the old direction so like sideways basically instead of moving forward... and idk how to fix it cause ive tried quite a bit of stuff
Real quick question. Is there a method where you can make all 3D objects parented under a empty, follow the same rigidbody as if it was 1 object
That sideways movement is called sideslip which is totally normal in all aircrafts when rotated via the rudder (control surface at the tail that directly changes the yaw). The sideslip angle (angle between the plane axis and the relative wind) then causes drag on the tail and the fuselage that causes lateral acceleration that then minimizes the sideslip. You can search for yourself how the lateral force caused by sideslip could be simulated.
Worth noting is that planes rarely turn (not sharply at least) purely by using the rudder. Much easier way to turn is usually to roll the plane and pull up to turn. It depends a lot on the type of game and level of realism you are going for but many arcade type flying games don't simulate rudder at all because the roll and the pitch are enough control to fly the plane anywhere. Real planes don't usually use rudder to turn, it is mostly useful for correcting for yaw in case of engine failure or turn for example.
Wouldn't you just add rigidbody to that empty object?
hey is there a way to make a reliable collision detection using Physics.ComputePenatration ?
technically not a physics question, so im sorry if this is the wrong place for this
been using KCC for my character controller, which is great, but I've been having this problem where my character 'sticks' to things when they jump over/next to them, which sort of 'cancels' the jump and doesn't feel great (player expectation if you press jump is to get the full height, not to randomly stop halfway through the jump).
I tested with the KCC example and it doesn't have this issue. If I make the capsule collider on my character much wider it does fix the issue, but making the example collider smaller doesn't cause it in the KCC example scene, so I don't think it's that. (my thinking was that the character's long and spindly collider might be causing this but that doesn't seem to be the case.)
I don't really know what I could have done that changes this, since I haven't changed the kcc motor code at all, and my character's motor settings are largely unchanged from the default...
this post is kind of a hail mary since I'm not really sure what to do, any help would be appreciated 
sorry to ask, but do you really need the kinematics
Hey all! I need to somehow make a realistic aerodynamic physics system working… I would buy an asset but most of them are tailored to airplanes and I’m working with rockets and I’m worried that they won’t work for what I need specifically
Edit: holy moly what a run on sentence. Hopefully it’s still readable
yes? haha
I'm not about to remake my entire character controller to fix 1 issue 😭
I'm having my own grid in Unity, yet I'd like to combine it with 2D physics. Is my best bet using a composite collider? Some physics libraries seem to have custom colliders where you could implement collisions between other shapes and the grid, but I can't make one in Unity right?
Well, or polygon colliders I guess. Not sure which one is faster.
The thing is checking against the grid would be waaay cheaper.
What do you mean by combining a grid with 2d physics exactly?
Using normal 2D colliders and rigidbodies and the grid is basically the terrain that you collide with. It's also edited at runtime cause it's a sandbox game. So I have chunk and those chunks need collisions for each solid tile. Kinda like a tilemap. The thing is having a composite collider with 1000s of box colliders, one for each tile, sounds super expensive.
So why not use a tilemap?
Cause I use texture arrays for the type of cell. I also want greedy meshing to improve performance. I think a tilemap is also just a composite collider per chunk using each tiles collider.
Also a tilemap renders a cell no matter if there's something in it or not. I have layers that only add a quad to the mesh if there's e.g. a plant in it or so. Overall I get drastically better performance with my own mesher.
Cause I use texture arrays for the type of cell
So does the tilemap? Or something similar at least
I also want greedy meshing to improve performance
Tilemap performance is very good, I'm sure they're doing something like this under the hood.
I think a tilemap is also just a composite collider per chunk using each tiles collider.
Not sure what you mean by this
kind of sounds like you're reimplementing tilemap
Please don't derail my actual question or my question gets burried. 😦
Anyway you can always make your own PolygonCollider2D
I don't feel I'm derailing anything here
depending on how your game actually works you can certainly do your own grid checks instead of using the physics engine
It's ok if you feel like that. You are free to do what you want. It's just not what I asked.
Alright I'll bow out then 👋
What am I supposed to see when I enable Show Contacts and Show All Contacts in the physics debugger? nothing seems to change.
Make sure gizmos are enabled too
I assume I might be the millionth person asking this, but is there a way to prevent dynamic rigidbodies from 'pushing' each other, as if one had high mass?
There's an asset that lets you do that https://assetstore.unity.com/packages/tools/physics/betterphysics-selective-kinematics-244370?srsltid=AfmBOorRmWsuF_72PeThzuSkXD_n12cLck3vKmLy1nfIO4cjeXGuOxHQ
ok so i've got this basic ship set up where it'll rotate based on the mouse position, but whenever i do so the boxcollider2d attached to it has this really weird behaviour
the actual script and collider are attached to a child object of the sprite
Show how the hierarchy is set up and which objects have which components
And how everything is positioned/scaled etc
Which object has the collider? Which object is rotating? Which object has the Renderer?
Showing the inspectors of all these objects would be nice
These second two screenshots are useless
Again I want to know which objects have which components
Screenshots of the full inspectors for the several objects would be helpful
But the first screenshot at least has a pretty telling issue
It's scaled non uniformly
Ideally the root object is not scaled at all, or is only scaled uniformly on all axes.
The renderers and colliders should be on leaf objects (objects with no children's), and then they can be freely scaled.
Hello - I am making a first person character controller with a dash. My issue is that if you dash towards the ground, you get launched into the air, which I don't want to happen. Instead, dashing towards the floor should just stop your movement once you hit the floor.
I have tried adding a physics material with bounciness = 0, and that did not work. Anyone got any other solutions I could use? I was thinking perhaps I could lock the players motion to the plane of the dash, but rigidbody constraints only work on the coordinate axis.
Thanks, but is it also applicable to 2D too? I might be able to just modify its source code to make it work 2D, but just in case if there's 2D version for it, or an easy way to switch it to 2D mode
if someone can explain this please
i have projectiles that will be shot from enemies
player also shoots projectils
both projectile colliders are set as trigger, because some of them, i want to go through enemies
others will destruct on first trigger
my player, has 2 colliders, 1 as trigger, and one normal collider with rigidBody to not allow player to move through obstacles
i have also pickup items, that have only 1 trigger colliders
when player goes to pick them up, it detects trigger twice, because player has 2 colliders even though only 1 set as trigger
this is starting to confuse me a bit and idk what's a good approach here
or if what im doing is correct
Is it possible for the ocean in the hdrp water surface system to make waves colliders? so when player jumps into them it triggers he jumped into water and starts swimming .? or any other idea how to do trigger that he jumped under that water surface (im new to unity so if i speak nonsense i apologize)
i tried many things like box colliders but the game has waves that are above the box collider and it looks weird
(after 6h of thinking i got it)
Not for 2d unfortunately
Aww 😢
Still thanks for answering
are soft body proxies plausable?
like instead of simulating my characters mesh, can I sim a low poly version of specific body parts and bind the verticies of my character to follow it?
asking for a friend totally not about to do anything weird
Sounds like you're just describing a ragdoll, which of course are possible and common
Hey all, I'm trying to make a orbital trajectory predictor (think a very simple KSP), and I figured the best way to do it was a simplified physics scene in the background, plotting the positions, and reading it back to the main scene. It's generally accurate, but quickly diverges with some really odd behavior on certain orbits, especially elliptical ones. Any advice on how to debug this, or has anyone seen something like this?
I'm running PhysicsScene2D.Simulate(step) with step being the same as the physics engine timestep (0.02 default). I'm manually calling my gravity functions for each object before moving on to the next timestep. I've also tried predicting it with a RK4 integrator that doesn't use the physics engine, and that gets similar results that are generally accurate but then freak out on certain frames.
showing code would be a good start
Ah, thought I attached it, my bad.
!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.
A tool for sharing your source code with the world!
Hello everyone!
i have these two RBs connected by the configurable constraint
they are siblings, not in a parent<>child relationship
I'm trying to manipulate the driver on the constraint so that the cube will move to the center point
this works but i also want it to apply enough force that it can lift the heavy car to do so!
the car mass is 1500 and the cube is 150
right now it doesn't seem able to do this, even at very very high spring rates
so it'll wiggle, but it's unable to exert force on the other body through this spring i suppose
how could I achieve this?
i downgraded from unity 6 to 2022.3 and uh
how does this even happen
ill show the physics settings in a bit
Show also the rigidbody settings maybe. I don't remember what it was exactly but I remember somebody had a problem earlier where the serialized per rigidbody values didn't translate between versions (especially starting from unity 6)
wdym?
Inspector of the object in question
this happens with most objects, though i might have fixed it idk ill check later
I THINK this comes under #⚛️┃physics but if I'm wrong, LMK.
I've got a basic auto runner script which lets you jump right now. It handles custom gravity as well. Right now when you jump, there is a very small window where you are still colliding with the ground so you can input another jump and it functionally double jumps. This is not intentional. My fix for my other projects is to check if the velocity is upwards before adding the grounded state to the character. However, this doesn't work when the player is moving up slopes because there is an inherent upward velocity of the normal force. I tried to isolate it using Vector3.Project but it didn't work and left me with non zero values when I wasn't inputting a jump. I'm not sure what's wrong, can any of you wizards help me out? I've got a PhysicsMaterial with 0 Friction on the player
This is what I tried:
Vector2 SlopeTangent = new Vector2(GroundNormal.y, -GroundNormal.x).normalized;
Vector2 SlopeVelocity = (Vector2)Vector3.Project(RB.linearVelocity, SlopeTangent);
Vector2 NonSlopeVelocity = RB.linearVelocity - SlopeVelocity;
Make sure you're only moving your Rigidbody via the Rigidbody
just tune your grounded check to be tighter
how are you checking if you're grounded currently?
I can attach the script it is fairly small and self explanatory
I'm using a Collider Cast
I've tuned the Grounding Check so it is literally as tight as can be with the method I'm using at least
In my scene, I have a game object that consists of an outer circle, an inner circle, and a dot (neutron) at the center. I originally wanted 2 main things to happen: For the dot to get movement input to move around the inner circle, as well as follow the main game object of this whole construction (the outer circle is the parent). I made the inner circle a child of the outer circle since it just needs to follow it, but the neutron is where my problem started. At first it was dynamic and I've tried combining addForce and linearVelocity to try and make something work, but the physics ended up fighting each other and it looked jittery and unstable. I think my best approach is to simply make the neutron kinematic since it doesn't really need any sort of dynamic physics (apart from collision which can happen with kinematic objects anyway, and it only collides with the also kinematic inner circle), but when I make the neutron a child of the outer circle - It changes the position in a circular manner because of the rotation of the outerCircle. I've tried handling it in LateUpdate to maybe get it to stop, but it just ended up causing more problems. I might be looking at it from a wrong angle but in general - I can't seem to find a way for the neutron to both have stable movement input while also constantly following the position of the overall game object (I can't use transform.position, since it didn't go well with physics).
Does anyone have any ideas or directions I can go in?
!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.
a powerful website for storing and sharing text and code snippets. completely free and open source.
fellas, if any of yall understand this, i would be eternally grateful. as shown in video, my bullet is not bouncing how i'd expect it to on these colliders--it should just bounce off once and follow the tracer--or so I thought. Does anyone know why this is occuring?
it feels like the force almostt isn't being redirected properly
Um... How to fix this?
Either:
- fix the hierarchy and position the wheels properly
- fix whatever code you're using to position/pose the wheel objects when the car is in action
Can you tell me what I should do, please?
I just did?
bump on this if anyone has any ideas
have a frictionless physics object but it's moving pretty weirdly
not how you'd expect
heres another video where you can see it's only on less sharp bounces
For this kind of game I think I would probably precompute the path with Raycasts and then animate the object along the path rather than hoping Rigidbody will behave predictably
It looks to me like you are already doing step 1
thats a good idea i hadn't thought of that. agreed too, because the bouncing is a major part of the game
the tracer does that, yeah
just out of my own curiosity do you know why that is even happening?
never seen it before
Unity 6. I need help fixing this, or figuring out why it's happening. This capsule, bounces up and down on a mesh collider floor, it's got a frictionless physics material. This ALSO happens on my player which also has a capsule collider, it's driving me mad lol!
It only happens on edges btw.
Try marking it have friction
Does anyone know why my bullets suddenly speed up and speed down?
I’m currently using an impulse add force method for them
Not without seeing your code
Presumably a bug in your code
This is the main code for setting up the instance
The code that calls this passes in a velocity
The issue is probably with that
I’ve tried to put the rigidbody to sleep and waking it up again but the same result still occurs
Not sure how that's relevant to what I mentioned
Wait so what does it mean
It means you're passing in a faster velocity sometimes
We should look at the code that calls this function
Try modifying velocity, not linearVelocity
Isn’t velocity deprecated
The function below is the one that applies the stats
In Unity 6, yes. If you are using Unity 6, I think linear is the correct usage
So again this velocity is coming from some higher up function
We need to keep going until we see how it's being set in the first place
I’m not on my pc rn so I don’t have the specific function but I’ll get on in a bit
Alright I'll probably be on a boat by then. Just make sure you're not doing something like multiplying the velocity by deltaTime
I suspect you are compounding velocty. Does the speed increase every respawn?
Damn
No
It’s a for loop which uses a referenced array of scriptable objects holding the stats of the bullets
Also using coroutines for cooldowns
The way you're using a coroutine there is also a little problematic because WaitForSeconds is not a precise thing. You're not going to have even bullet patterns especially when the framerate is fluctuating. That's a separate problem to solve though
heres the code for the attack pattern
pivot must be at the center of the 3d wheel.
I made a bullet penetrating raycast algorithm that works basically like this
while(traveled < maxdist and penetrateddistance < maxpenetrationdistance)
if not inside something
raycast in direction by maxdist - traveled
move current position in direction by stepsize
set current collider to hit collider
if didnt hit, break
else
raycast backward from current position
thickness is the distance from entry to exit hit
if we run out of penetration distnace, we mark this penetration as not going all the way through
if we hit something, add a penetration to the list with appropriate values
otherwise, move current position in direction by stepsize and continue
and when i shoot a raycast to test penetration, it works just fine. it detects entry and exit points, however sometimes it erroneously creates thousands of points when hitting a certain thing, any advice on soemthing better than this would be good thanks, this algorithm kinda feels janky. anyway when doing this it never generally MISSES a wall entirely. i added this script to my bullet though, which kinda moves its position by its velocity and then casts one of these rays from last to current, but somehow it seems to randomly miss walls, going straight through. if i do normal raycast, these walls are not ignored and the bullet hits them just fine, but JUST for this it breaks, seemingly randomly, although i noticed it more when it hits at a shallow angle. any ideas why???
heres a demonstration, the gizmo with lines and circles is my test ray that clearly detects everything just fine, the particle system is wehre the bullet hit
Hello! I am making a 2.5D platformer (2D sprites, 3D environments) in Unity. I am using a state machine for the movement. I am having some problems with physics, my jumps are too small, but when I try to enter a somersault state (like in Metroid), in which is activated when the player is jumping while moving, the player is launched across the test stage as if it were teleporting, sometimes ignoring the physical barriers I put up. I have used forces and I have not directly manipulated the velocity. There are times when my character trips over like one slight pixel on the ground that I put together with cubes. I have noticed after debugging, when I try to move the character, it doesn’t move after that fact. I checked the debug logs and every time my character trips, there is no buildup in the velocity. My UpdateState method is tied to fixed update for physics. Before I share my scripts, Are there any physics based functions I should avoid?
For tripping over a slight pixel that should be fixed with composite colliders
is there a way to get collision points without a rigidbody ?
Raycasts?
Otherwise - custom physics engine
What's the use case?
i am creating a custom car physics .its almost done just the collision is remaining
how exactly
yeah
Have you checked the docs?
That would be a good place to start
Check out other physics queries too
Such as the other shape casts, and overlapXxx
Though only the casts will give actual points
i want the points for collison response
for raycast i will need to check i all directions and i cant find anything related
Wdym in all directions
for collision detection i would have to cast rays in all direction to check any collision .right?
Why not just in the direction the object is moving?
Also don't forget about BoxCast or SphereCast
What if the obj collides sideways
Like another car colliding
What does "collides sideways" mean?
Anyway why are you trying to reinvent the wheel here?
That other car would detect the collision since it's moving that direction
If u mean the custom physics, then for optimization and full control
if the trigger is deactivated then reactivated with the collider still inside, does ontriggerenter be called upon reactivation?
answer: yes but only if the other collider has a rigidbody 😡
🙁
It seems unlikely to me you will improve on the performance of Physx.
What should we be looking at here?
umm no idea. Had to fix it myself. Lil boxes can now fit on the back of the truck, but no collision with the back of the truck (they fall off)
edit: fixed 7 hours ago (aroung 7:3X PM. It's 2:12 AM now)
Hi all, I just posted in #🌐┃web but it turns out to be an issue in a Windows build too, so it must be something editor -> build general issue. My vehicle prototype uses only Rigidbody and WheelColliders and runs and seems to ouput sensible values for the various forces (torque, rpm, slip). However, when I build and run independent of editor the forces are massively different such that the vehicle does not have enough torque to even move (my calculations are giving <10 motorTorque on the WheelCollider, rather than 500+), rpms look similar at a glance, but wheel slip is much higher. Everything is run within FixedUpdate, except for updating wheel position/rotation from GetWorldPose and the HUD (run in Update). Are there specific player/build settings I should look at to identify the difference in physics calculations?
it does seem to be framerate dependent as changing vsync in editor also breaks behaviour.... will check further
heh, ok so it was the wheels in Update being the problem and running the editor in vsync
anyway to stop the jittering when the character reaches desired speed?
im just stopping the AddForce when it reaches the speed
Unfortunately this isn't really sufficient to maintain a perfect speed limit because Addforce doesn't affect the velocity until after the simulation step runs. Essentially your velocity measurement is one frame behind
For the correct way to handle this, you could check out the source code of my asset which has a speed limit feature.
Basically you need to look at the AccumulatedForce on the body and cancel it out after clamping
` switch (limit.Directionality) {
case Directionality.Omnidirectional:
Vector3 clampedVelocity = Vector3.ClampMagnitude(expectedNewVelocity, limit.ScalarLimit);
// We're hard clamping so remove all accumulated force
_rb.AddForce(-accumulatedNewtons);
_rb.SetLinearVelocity(clampedVelocity);
break;`
does this hard cap the speed? becuz i want the character to be able to gain speed above the running max speed
setting the speed to clampedVelocity
That code is for a hard cap yes
My asset also handles "soft" caps which allow the object to go faster than the limit if it gets hit by another object for example
but not with AddForce
You could consider just downloading the asset (it's free on the Unity asset store) and seeing if it meets your needs
It's not clear to me from your description exactly what you are trying to accomplish
i think im just gonna go along with the jitter
its nothing major i think
probably
hopefully
Thank you!
` if (moveDirection != Vector3.zero && !crouchSlide.isCrouching && !Strafing && !crouchSlide.isSliding && isGrounded)
{
float maxmaxSpeed = maxSpeed + 1f;
if (speedometer.XZspeed < maxSpeed)
{
rb.AddForce(moveDirection, ForceMode.Force);
Debug.Log("Adding Speed");
}
if (speedometer.XZspeed >= maxSpeed && speedometer.XZspeed < maxmaxSpeed &&!_jumpBuffered)
{
rb.linearVelocity = moveDirection.normalized * maxSpeed;
Debug.Log("Speed Max locked");
if (angle > StrafeMaxAngle && angle < StrafeMaxAngle2)
{
rb.linearVelocity = moveDirection.normalized * maxSpeed / StrafeReduction;
}
}`
this part of the script is behaving differently if i recompile the script mid testing
the jitter is removed if i recompile for some reason
why would that be?
Recompiling during play can cause all sorts of issues, it doesn't mean anything by itself. It's usually better to switch it off and set it to only compile when the game is stopped
i want it to not jitter and recompiling is the way to fix it seems like
probably a script execution order issue or something .
Recompiling isn't a fix, it's a temporary bandaid that hides the issue.
This isn't an efficient way of finding the issue, you can't really know what the actual difference is between fresh compilation and compiling during play. Debug it "normally" with a debugger or log messages
Also is it really a problem if the max speed fluctuates a little? It doesn't seem to cause any issues visually
its not a big problem yeah but it just irks me a little
also if i add the speed meter to the finished product
seing it jitter like that would be really weird
It probably always rounds up to exactly 13 if you round it to one decimal point
Apologies for the repost, but I thought I might have some more luck in the Physics channel. I want the player object to stick to a mesh as it curves. Currently I'm adding rigidbody force to the object and rotating as it goes, but when the player is upside down it breaks and starts floating freely. Any ideas how I could achieve this?
Like in mario kart when the map does a loop-de-loop, the car is still driving as if the ground is it's directional force, that's what I want to achieve
float maxmaxSpeed = maxSpeed + 1f; float minmaxSpeed = maxSpeed - 1f; if (speedometer.XZspeed >= minmaxSpeed && !_jumpBuffered && speedometer.XZspeed < maxmaxSpeed) { rb.linearVelocity = moveDirection.normalized * maxSpeed; if (angle > StrafeMaxAngle && angle < StrafeMaxAngle2) { rb.linearVelocity = moveDirection.normalized * maxSpeed / StrafeReduction; } } else if (speedometer.XZspeed < maxSpeed) { rb.AddForce(moveDirection, ForceMode.Force); Debug.Log("Adding Speed"); }
fixed the jittering with this script but rb.linearVelocity is getting set 0.21 lower than specified
why would it be 0.21 lower?
rb.linearVelocity = moveDirection.normalized * maxSpeed;
if i set the max speed 10 it gives me 9.79
do you have any drag on the Rigidbody?
also known as "linear damping"
no
is the object touching any other objects?
Such as the ground?
Also which branch of code is running here exactly?
Is it the if or the else if?
and where does this speedometer.XZspeed come from?
touching ground yes
Vector3(rb.linearVelocity.x, 0, rb.linearVelocity.z).magnitude
its the if
shouldnt rb.linearVelocity set the velocity to watever this is regardless of external circumstances?
yeah it is the friction
Yes, after which the friction will take effect during the simulation phase
got it thanks
...generally you use joints/hinges to have multiple rigidbodies be part of one system.
how do I make the player (that has character controller component) to be able to push the enemy but without the enemy being able to push the player (but can push the other enemies)?
2d or 3d
3d
Not with CC but with rigidbodies you could use a selective kinematics asset like this https://assetstore.unity.com/packages/tools/physics/betterphysics-selective-kinematics-244370?srsltid=AfmBOoqmthNV5Rbe7qqA_tKh7AmtikBK_r6qerjZv3UuJcTqfqz825Ng
thanks, I'll try that
could play around with making kinematic objects that follow the player, while only interacting with specific layers using a layermask.
program the object to disable itself without input and so on.
Does anyone know of any Rigidbody replacements which produce similar physics which is deterministic?
"deterministic" is pretty vague. Physx is already determinstic on the same hardware. Can you be more clear about what your exact requirements are?
For networking purposes RBs are not ideal as the results are non-deterministic, not all my users will be using the same hardware so can’t really rely on rbs. Just wondering if anyone has made a script which makes an object physical without the use of RBs?
Plenty of games use networked rigidbodies with server authority and client prediction and are fine. It's pretty rare to have a significant desync based on hardware precision and on those rare occasions it can be handled relatively gracefully with rollbacks and resimulation techniques.
"a script which makes an object physical without the use of RBs" - you're describing essentially a custom physics engine here. And yes, plenty of other physics engines are used in unity networking contexts including:
- Havok
- photon fusion physics
The networking unity discord seems to somewhat disagree with you, floating point precision between different hardware will cause discrepancy's between client & server but i guess if its infrequent enough it shouldnt matter much.
I wouldn't be able to use any other engine as im using NGO and which isnt compatible with the whole DOTS ECS stuff
Hey boys.
I trying to make a roulette wheel, which i have created in blender. To accommodate the complex geometry im using Mesh collider without Convex and a rigid body. This partially works, if the wheel isnt turning. But i've created a script to rotate the inner wheel on the Y axis. This results in the sphere clipping through the model. Any bright people that has some ideas how I would fix it.?
This is won't work with concave colliders.
Any moving object is going to need to consist of solely primitive or convex colliders if you want proper collisions
- Rebuild the collider from primitives and convex meshes
- Make sure the object is rotating via MoveRotation in FixedUpdate or angular velocity
Actually MoveRotation similarly to MovePosition isn't any better than setting rb.rotation for non-kinematic bodies (apart from interpolation which doesn't affect physics). Angular velocity and addTorque should be preferred to avoid tunneling issues
One thing to try though would be to set the rigidbody to kinematic and then rotate via MoveRotation which in that case would be slightly better than teleporting the rotation
Yes I was suggesting MoveRotation for a kinematic body
Which cannot use angular velocity
ah right. What I'm wondering now is whether they would be able to use the concave mesh collider with the kinematic + MoveRotation though?
No
The collisions won't work
Good to know
Now that I tried, mine seems to work totally reasonably in Unity 6 at least
Compared to Rigidbody.rotation at least, it is much much better
Don't know how recommended that is but it looks fine and there are no error or anything
I am writing a custom suspension implementation. I have noticed a difference between RaycastNonAlloc and Raycast. I think it's probably working correctly but my code requires an adjustment if i want to use NonAlloc.
Raycast Implementation
_isGrounded = Physics.Raycast(_position, -transform.up, out _hitResult, _suspensionLength + _wheelRadius, Physics.AllLayers, QueryTriggerInteraction.Ignore);
_previousSuspensionLength = _currentSuspensionLength;
_currentSuspensionLength = _isGrounded ? _hitResult.distance - _wheelRadius : _suspensionLength;
_load = ((_suspensionLength - _currentSuspensionLength) * _suspensionSpringRate) + (((_previousSuspensionLength - _currentSuspensionLength) / Time.fixedDeltaTime) * _suspensionDamperRate);
_load = _load > 0.0f ? _load : 0.0f;
_rigidbody.AddForceAtPosition(_hitResult.normal * _load, _position);
RaycastNonAlloc implementation
_isGrounded = 1 >= Physics.RaycastNonAlloc(_position, -transform.up, _hit, _suspensionLength + _wheelRadius, Physics.AllLayers, QueryTriggerInteraction.Ignore);
// Left out to save characters
_currentSuspensionLength = _isGrounded ? _hit[0].distance - _wheelRadius : _suspensionLength;
// Left out to save characters
// Left out to save characters
_rigidbody.AddForceAtPosition(_hit[0].normal * _load, _position);
The difference is that when i drag my car object into the ground and the suspension generates an opposite force the suspension seems stuck in the car itself.
Is it possible raycast non alloc does not account for colliders onto the same object? the collider is in a parent object
I am trying to debug it, but i can't quite deduct the difference
Wdym by "same object" here exactly?
Raycast doesn't have any sense of an object from which the ray "originates". It's a static method.
Your code looks incorrect to me though. That 1 >= Raycast condition seems backwards.
That seems to be saying you're grounded only if the Raycast doesn't return any hits.
The wheel script is on a child object of the object with the rigidbody and box collider. The raycast if i remember correctly ignores colliders it starts in unless some specific object. I think you are right about the comparator it should be 1 <= hits
Maybe that’s the issue, when i can i will check
In my mind the most straightforward way to write it is if (hits > 0)
It was the expression that was wrong, i tested it now with 1 <= Physics.RaycastNonAlloc() and that works.
What difference 👀
It’s already solved, i thought maybe i needed to do some extra code but it was the 1 >= that needed to be <=
Sure, but what difference between Raycast and RaycastNonAlloc are you talking about?
I thought there was a difference but it was just that line wrong on my end.
Im having the issue where cubes can be held inside walls and its kinda jittery. I know why but i dont know how to fix it. whis is my current code and im jsut pushing an object to a point
public void UpdateTransform(Transform Target)
{
rb.transform.rotation = Target.parent.parent.rotation;
Vector3 previousPos = rb.position;
rb.MovePosition(Vector3.Lerp(rb.position, Target.position, Time.deltaTime * atractiveForce));
Vector3 delta = rb.position - previousPos;
rb.linearVelocity = new Vector3(delta.x, 0, delta.z);
}
You can't be doing both MovePosition and setting the velocity
you should pick only one - and that one should be setting the velocity because MovePosition does not respect collisions
you should also not be rotating the object via its Transform
you should basically never touch the Transform of a Rigidbody if you want it to behave realistically
how do i lerp with setting velocity?
Just lerp the target position
basically replace MovePosition with just calculating a position to go to
Vector3 previousPos = rb.position;
Vector3 targetPos = Vector3.Lerp(rb.position, Target.position, Time.deltaTime * atractiveForce);
Vector3 delta = targetPos - previousPos;
rb.linearVelocity = new Vector3(delta.x, 0, delta.z);```
it seems to be moving slwoly regardless of atractiveForce
this:
Vector3 delta = targetPos - previousPos;
needs to be:
Vector3 delta = (targetPos - previousPos) / Time.fixedDeltaTime;
that works. Should i turn off the cubes gravity when held so it can be well held?
Well - it seemed like you were purposely excluding the y axis from the holding behavior
is that not on purpose?
If it's not then you want to simplify like:
Vector3 previousPos = rb.position;
Vector3 targetPos = Vector3.Lerp(rb.position, Target.position, Time.deltaTime * atractiveForce);
Vector3 delta = targetPos - previousPos;
rb.linearVelocity = delta / Time.fixedDeltaTime;```
ah it wasnt. ill add it
what should i do so the face of the cube faces the player?
that was the intent around the idea of changing rotation transform
a similar thing you did with velocity, but for angular velocity
get a target rotation (the player's rotation probably), then calculate the rotation difference (Quaternion.Inverse is useful for this), then set the angular velocity similarly
how do i do the last part of delta/time.fixedDeltaTime?
Quaternion previousRot = rb.rotation;
Quaternion.Inverse(previousRot);
Quaternion targetRot = Quaternion.Lerp(rb.rotation, Target.rotation, Time.deltaTime * atractiveForce);
Quaternion deltaRot = targetRot * previousRot;
rb.angularVelocity = deltaRot / Time.fixedDeltaTime;
my code is this
You're not doing anything with the inverse line
It should be delta = target * Inverse(previous)
what about the last line?
Quaternion previousRot = rb.rotation;
Quaternion targetRot = Quaternion.Lerp(rb.rotation, Target.rotation, Time.deltaTime * atractiveForce);
Quaternion deltaRot = targetRot * Quaternion.Inverse(previousRot);
rb.rotation = deltaRot / Time.fixedDeltaTime;
code looks like this and the last line says i cant do devision with quatieron to flaot
- Angular velocity, not rotation
- Convert it to euler angles
Can anyone help me with joints? I have it working correctly when the rock has a low mass (video 1). The plane moves around the rock until the hinge joints reach their angle limit, after which the rock is pulled by the ship. However, when I increase the mass + damping on the rock (video 2), instead of the plane's velocity being stopped because it can't pull the rock, the hinge ignores its limits and also comes off. Essentially, I want a stronger hinge. Does anyone know what the problem is and how I can fix it? I've been debugging this for hours 😭
what code are you using to move these objects?
The ship is the only thing with code. This is the only code that matters:
Vector2 direction = new Vector2(Mathf.Cos(transform.eulerAngles.z * Mathf.Deg2Rad),
Mathf.Sin(transform.eulerAngles.z * Mathf.Deg2Rad));
rb.AddForce(direction * moveSpeed, ForceMode2D.Force);```
Is there a better way to format code?
!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.
though there's nothing wrong with what you did
other than you should put ```cs so it gets color coded
Vector2 direction = new Vector2(Mathf.Cos(transform.eulerAngles.z * Mathf.Deg2Rad),
Mathf.Sin(transform.eulerAngles.z * Mathf.Deg2Rad))```
Instead of this couldn't you just do `transform.right` btw?
Have you tried changing the settings on the hinge joint?
Given 10 or 20 bodies, is it possible to predict their positions in 1 year?
Like I want to predict orbits for my planets and later even spaceships. How is that possible? The planets don't realy interact with my spaceships, only with other planets. Same with my spaceships, they only interact with planets, not other spaceships
My idea I have currently is to just simulate it until that time. But that is kinda difficult, because I want to predict it 10-20 years in the future, and making that lag free is not realy possible, especially with low end CPUs
Use a second physics scene and simulate.
But yes it's going to be computationally restricted.
If this is for orbital mechanics you would use orbital mechanics equations instead to predict the position
It's for a map screen and maneuver nodes like seen in Kerbal Space Program
I gathered as much yeah
a note KSP does use rails for planets at times so you can still speed up without issues
Hm yeah. My current system is pretty dynamic, because even the sun is changing it's position due to the 1 planet orbiting it
I'm afraid of landing rockets on planets because they're always gonna move lol
Im trying to make a box share the same rotation as the player but it seems to not be doing anything
Quaternion previousRot = rb.rotation;
Quaternion targetRot = Quaternion.Lerp(rb.rotation, Target.rotation, Time.deltaTime * atractiveForce);
Quaternion deltaRot = targetRot * Quaternion.Inverse(previousRot);
deltaRot = Quaternion.Euler(deltaRot.x, deltaRot.y, deltaRot.z);
rb.angularVelocity = new Vector3 (deltaRot.x / Time.fixedDeltaTime, deltaRot.y / Time.fixedDeltaTime, deltaRot.z / Time.fixedDeltaTime);
Why don't you just
vector3 player_rotation = player.transform.rotation;
obj.transform.rotation = player_rotation;
i was told not to
and i also like lerping
yeah alr idk lol
i just strugalling a lot with rotation based stuff in genral
I remember when I started with unity 2 years ago... It was a horror so I immeadiatly stopped just because of rotation
ive been using unity for a few years but never programing to the extent i am now
Ah flip, I'll have to code my own line renderer
Absolute Noob here. I am trying to add a wheel collider to a wheel but the wheel collider is running "against the tyres grain" if that makes sense, along the incorrect axis. I found the wheel as a free asset. Hopefully an easy fix?
put the visual components on a different object
First thing's first. Press the ` key and make sure the "Tool Settings" overlay is visible in your scene view:
Actually I see it in the bottom right of your scene view in your screenshot
You need to set that to "Pivot" and "Local"
Then you are actually looking at the object's real position and orientation
Wheel Colliders are always aligned with the object's forward direction, which is the blue arrow (once you're in local mode)
As not jordan said, a good way to fix this is to move the MeshRenderer to a separate GameObject which can be a sibling of the wheel collider in the hierarchy
But I still haven’t fixed this
That starts out well but everything after the first line it's just nonsense
Try something like this:
Quaternion deltaRot = Target.rotation * Quaternion.Inverse(rb.rotation);
deltaRot.ToAngleAxis(out float angle, out Vector3 axis);
if (angle > 180f)
{
angle -= 360f;
}
if (Mathf.Abs(angle) > 0.01f)
{
rb.angularVelocity = angle * Mathf.Deg2Rad * speed * axis.normalized;
}
else
{
rb.angularVelocity = Vector3.zero;
}
Yeah quaternions elude me very much
Quaternion's x, y and z (and w) components don't have anything to do with Euler angles so you can't treat them as such
how can i make it so the cube dosent tilt up and down with the player looking?
what i tried didnt work
Normally I’d just change all angels but the one I wanted to stay and make it 0 and while it kinda worked it didnt fully
Usually there's a player model or object that has the correct rotation that the movement code uses so change Target to point to that instead
Okay it’s a little late for me so I’ll try tomorrow
Thanks for the help. Luckily I do already have a point like that to use
mesh collider doesnt take the shape of the mesh
i require assistance idk why its doing this
what setings do you have on the MeshCollider?
do you intend for it to be convex?
yeah unless theres another way to make a collider for a hollow shape
Convex is the opposite of hollow
you will not be able to run inside it if it's convex
oh alr
It sounds like you want it to be concave, which means you should uncheck that box
omg thank you
those collider lines werent showing up when i had convex off so i thought it just want doing anything
but now it works
thank you again
so how can i restrict player speed to 1: allow stuff like launch pads to work but also 2: prevent the player from launching themselves on accidental steep slops created by cubes and 3: still have falling not be painfully slow
That is because when convex is turned off it just uses the existing mesh.
I have a 3D game that uses vertical and horizontal knockback. It basically sets the linearVelocity of the rigidbody of the victim to the knockback Vector3.
But i have a problem where if a move has both positive horizontal and vertical knockback, but the victim is very close to a wall, what should happen is the character should go up and not horizontal. But instead what happens is all the momentum dies and the character falls right away.
How can i get the character to go up when there's a wall very close to the character and both horizontal and vertical forces are being applied?
nvm i figured it out using physics materials and messing with the friction
i'm not sure if it's applying the full vertical force, but at the very least it's pushing the character up
if someone has another solution please lmk
i mean physically that's going to be the most realistic result.
any other solution would just be trying to recreate that interaction
through code, right?
My player position start at 0.5 for Y, but once i add a Rigidbody 2D, it changes the position to 0.51f, why ?
It doesn't look nice, the player seems to be levitating instead of being grounded
Found a fix by adding an Y offset on the tilemapCollider but still curious to know why this happens
In physics 2d settings there's a thing called "default contact offset"
this is a necessary part of the physics engine which results in a small offset between colliding objects
alright thank you, so this offset is mandatory i guess, and we need other offset to fix this ?
You will most likely find that in your game at full resolution such an offset will not be noticeable to the player anyway. But yes you can offset the sprite to compensate
I see, maybe i'm focusing too much on details
Can anyone help me with this. I have no friction, i am setting the angular/velocity from the platform. The platform and player have no friction, no drag, and no mass. However, it appears there is still some inertia? Centripical force? IDK
Both are rigidbodies and usint Unity 2022.3 basic physics.
Same behaviour no matter the interpolate, kinematic, and constraints. I have tried constraining rotation on both, I have tried boosting past the velocity difference (overshooting) and it still happens!
rb.velocity = getPlatform.rb.GetPointVelocity(rb.position);
Please don't recommend fixed joints etc. or move position unless you have some magic solution to remove jittering involved in both methods.
Don't know what jittering you mean. MovePosition/Rotation + kinematic rigidbody is often the way to go for moving platforms. It is up to the character controller to handle that correctly (using the point velocity might not be sufficient since that makes the object slowly drift outwards)
I'm gathering its the point velocity now, thank you.
The jittering for moveposition when on top of a physics platform looks like motion blur at a high frame rate. no motion blur on
Do you mean switching the player to kinematic at least when on physics platform?
No I mean the platform should be kinematic and moved via the Move methods, is that what you do already?
When you configure everything correctly you will not get jittering
This might visualize the point. In the image the platform is moving in circular path but if we take the point velocities at each point (the vectors) and move towards that velocity, in discrete simulation, we will inevitably divert from the actual path of the platform. I wouldn't know for sure but this could be one of the problems you have. One way to minimize this would be to predict the next position of the platform and derive the required velocity from there
I see. Yes the platform is kinematic in the video. Getting current linear velocity is the problem. Any pointers for making MovePosition look smooth?
So what you are moving with MovePosition and what jitters? Do you have interpolation enabled for the jittering object?
The platform is interpolating to be smooth, same as the player. But adding the platform velocity to the player body pos in MovePostion makes it motion blur
I don't know what "motion blur" would look in this case but If you want to keep the player non kinematic during the ride, you should probably consider moving it directly via velocity
MovePosition/Rotation are mostly useful for kinematic bodies
the point of moving platforms is to inherit their velocity to solve puzzles yeah
but moveposition does seem to give it velocity
For kinematic bodies it surely does but if I remember correctly, it just teleports the body for non-kinematic, I could be wrong though
yes yes, you are right, i was mistaken
I don't know if you will see it in a compressed video:
So that would probably not count for the interpolation. Is settings the velocity of the player directly an option?
the player jitters. continuous, interpolated, all that jaz. yes, i set the velocity and it behaves exactly as adding the difference.
it would be nice to know the velocity is being updated on pllatform before player but i don't know enought about unity physics
rb.velocity = getPlatform.rb.GetPointVelocity(rb.position);
So was there an issue besides the drifting with this approach?
no, exactly the same as a velocity += difference
so i prefer the latter because other objects can interact and pass velocity additions
don't know what difference refers to here but if there is no jittering, you should probably go for it. Avoiding the drifting should be "as easy as" not using GetPointVelocity and figuring out the correct velocity yourself
I suppose I could just pass the motion to the player when the platform moves as a velocity change. oh the differnce is say, the player could not be knocked off the platform by hazard if its setting its velocity to platform.
I think I know what to do, thanks so much Aleksi for confirming what it is.
Np. feel free to ask if you have any questions later on
Hello, I'm making a brawler-type game where each player is driven through active ragdolls. The way I have it setup is using configurable joints and making the target pose for each joint the joint of a reference animation. (Shown in blue). The ragdoll also has a force on the head pulling it upwards and a force keeping the hips straight up. Movement is done by adding force to the hips. ** I'm having trouble making the ragdoll more stable and making controlling the camera not so wobbly. Also maybe not having the ragdoll's feet dragging on the floor when it walks. Any tips?**
I highly suggest driving motion from the feet and going up. I'm not sure why you'd put all that work into the character and not have a 3rd person camera but you'll always wobble with the camera attached to the head like that. If I was you, I would be moving the hands, feet and head manually and the rest follow. Might need to have a lot of dynamic configuration though.
It might be you end up with a hybrid of ragdoll and IK rig
by moving the limbs manually do you mean by adding forces to them or using IK? do you think that i should push the feet forward and make the rest of the body align with the feet? also the model is off mixamo lmao
How would you guys simulate a suspension-less wheel? Like in Garry's Mod the ones you can place on objects with the tool gun.
Maybe just decrease the friction on the wheel object a bunch, and then make the model rotate proportional to the parent object's velocity? Or is there a better way?
how do I make it so the player cannot phase through object?
the character is using rigidbody and for the object is box collider
Does the character have a collider and are the colliders 3d
Is the movement done with forces or velocity?
it's moveposition I believe
rb.MovePosition(rb.position + moveDirection * movementSpeed * Time.deltaTime);
you're referring to this right?
do I need to change it to either those two? does using moveposition ignore the object's collider
It might cause that if the colliders are very thin
I thought of that too, but it does the same thing when running towards bench and the throne which has a thick box collider
Im wanting to fix an issue with my cubes where no matter the mass of the cube, it can push any other object. What would be the best way to fix it? my current code for it is this:
Vector3 previousPos = rb.position;
Vector3 targetPos = Vector3.Lerp(rb.position, Target.position, Time.deltaTime * atractiveForce);
Vector3 delta = targetPos - previousPos;
rb.linearVelocity = delta / Time.fixedDeltaTime;
how do you want it to behave exactly?
preferably+ how pushing an object into another would in real life. It may move a little depending on the mass but not to this extent
I have a simple problem but I dont have an easy fix
lets say I have some rigidbody thats moving with some mass. I have a “wall” object that the rigidbody needs to collide with, but instead of hitting it and stopping, it should break through.
the wall cannot be a trigger, it has to be a solid object
I just don’t want it to stop the momentum of some objects
i also want to limit changes to layering and the wall itself
im also not in unity 6 im in 2021
any simple fix? i feel like this should be possible
the “walls” have rigidbody set to kinematic
Like this?
ou
I have breakable objects I want the player to collide with, but bosses to just break through
Ohh okay I get it now
Is there a way to do what I want?
I would have 2 colliders on separate physics layers, one collider is trigger on a layer that only interacts with the player, and the other non trigger that collides with everything else it should appear solid to
I think it works pretty well, because it's never meant to be solid to the player, so it feels like an appropriate use of layers
other option is maybe to have an animation of the player breaking it, and applying physics after the collision
its annoying to need two colliders
such is life with unitys physics
trying to wrangle a realistic physics sim into working for a game
In my 2d game I have a bunch of zones that deal damage over time. I use OnTriggerStay2D for it to deal damage to the player.
When the player stands perfectly still while inside the zone, OnTriggerStay2D no longer gets called, and it resumes immediately after the player moves.
I want OnTriggerStay2D to be called every cycle the colliders overlap, is there an easy way to do this?
I do it in update
track the overlapped objects by OnTriggerEnter2D and OnTriggerExit2D
I found that to be a bit unsafe especially with coroutines, because things can be destroyed after Enter and before Exit
or fixedupdate rather
I do think disabling an object inside of a trigger will not call OnTriggerExit2D which… I think its really dumb
I'm pretty sure if the zone spawns on top of player, OnTriggerEnter isn't called either, so there needs to be a manual check in Awake
yeah I could probably do it your way, just have to be safe with some checks, I was hoping there's some setting to just force it to call OnTriggerStay
that makes sense, thanks
You could even make it its own component just to track objects in a trigger
how do I fix this ;(_ _
the character uses rigidbody (3D) with moveposition for movement and the object all uses box collider
Maybe this can help you: https://discussions.unity.com/t/why-does-rigidbody-moveposition-ignore-collisions/876471/3
Show your Rigidbody inspector
thanks, I'll check it
and can you show the inspector of one of the objects that you are trying to collide with?
(also the capsule collider here)
can you turn on gizmos in your scene view so we can see the outlines of the colliders? Your box collider is both tiny and very high up according to those settings
so we should make sure they're actually in the position we expect
it is there, also it doesn't phase like if it were have no collider at all. it kind of let you phase if you run continuously, and if you stop it pushes you away
I can take record another video if you want
when I import the 3d object it was very small so I upscale it hha
aghh I've been trying to fix this problem for over 2 days rn, if anyone know the solution please I'd be very happy
Moveposition is the issue, change it to forces or velocities instead, because moveposition can go inside colliders no problem
This sounds like when you're moving it pierces through and when you let go physics does its job and pushes you out the collider so it makes sense to make sure you're moving correctly
Have you tried fixing the scale already? It's possible that a massively scaled down collider works wonky even though the final size looks correct in the scene. If you can't fix the model you can add a parent to it, scale the model and add a non-scaled collider to the parent
Or at least test if it works with just the default non-scaled cube with a collider, to confirm it's those particular objects at fault and not something else
oh my you're right, it did worked thanks!! although I do like the mvoement of the moveposition better
I thought of that too, but I've tried remaking the room with smaller scale and it did not work. but thank you nonetheless
how do i add force that only affects the direction of movement and doesnt add any speed
Change the velocity directly. rb.linearVelocity = direction * rb.linearVelocity.magnitude
but then its gonna be pretty annoyin to make the turn natural
leftRightDirection = Vector3.Cross(rb.linearVelocity, Vector3.up).normalized;
i tried this but
this doesnt seem to be taking vertical movement into consideration
if im applying force to the true left right of the direction im going in then i think it should work
how do I manually apply gravity to a kinematic player with moveposition movement, I've tried various way but it doesn't work. lot of times it just overrides the movement
if you're using MovePosition you are completely in control of the motion of the object
so you'll need to simulate gravity and everything else yourself
The basic idea is to keep track of the velocity, or at least the vertical (y axis) velocity, and accelerate it each physics frame.
yea I just learned about it, thanks
I was able to make it work tho
So, I am currently writing a fluid simulation based on this video
https://www.youtube.com/watch?v=rSKMYc1CQHE
Let's try to convince a bunch of particles to behave (at least somewhat) like water.
Written in C# and HLSL, and running inside the Unity engine.
Support my work (and get early access to new videos and source code) on Patreon or Nebula
Source code:
...
And I did most of the things that were in here (I just have yet to move it to a compute shader and I haven't implemented ability to interact with the fluid via mouse)
But I'd like to know if anyone here could have any idea how could I modify it so it could interact with other gameobjects
Hello, i made a code that has 2 states between a normal animated player, and a ragdoll player, the problem is this chest collider wont fall correctly and will stay upright all the time which causes alot of issues, is there any fixes to this ?
Is there really no one here who could point me in the right direction with this?
It's not the kind of topic that could be summarized in a useful way. Google for "fluid simulation algorithm with obstacles" and try to adapt them to your use case