#⚛️┃physics
1 messages · Page 59 of 1
Eric Fakos, lead developer of Proton Quantus
lol
Just one thing: I'm not lead. fholm is
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(0, 0, -Input.acceleration.z * 90), 0.2f);
This will rotate the character... you are also interpolating here, which should already smooth a bit...
I assume you are running from FixedUpdate, right?
So no need to consider Time.DeltaTime
so there's an error
that 0.2f
you should read from Time.DeltaTime * a confirgurable interpolation
Because unity's update will NOT work constantly at 50Hz like that 0.2 assumes
that's why
The reason it is smooth is because you are interpolating A LOT
You are taking almost 1 full second to rotate it...
Maybe you want it to react faster, etc... It's all doable, but you need to got your code right
Regarding Joints. I have a fixed joint on camera, and it connects to a rigidbody (to simulate dragging). Works great. One issue is now that I want to set the object's "depth" (near or far from camara) and to do that I need to modify the joint's connected anchor. However, I am getting some weird readings. I understand it's perhaps due to the anchor's orientation following a different convention than the global orientation? If this is so, how would I go about converting that over and reading it in relation to world position?
Here is my debug code:
Debug.Log($"Connected Anchor: <b>{Mount.connectedAnchor}</b> | Cam Pos: <b>{Camera.main.transform.position}</b> | From Camera: <b>{Mount.connectedAnchor + Camera.main.transform.position}</b>");
And the result:
Connected Anchor: (0.9, -9.7, -6.5) | Cam Pos: (0.0, 7.0, -6.7) | From Camera: (0.9, -2.7, -13.2)
And the actual position of the connected rb (in world coords): (0.15, 0.743, 3.05)
Please help 🙂
Yo can i have help setting up foot ik on 2d character
i have used hinge joints for the ragdoll
hey guys
I just found a script on youtube where it converts my polygon collider to an edge collider (making the collider shape hollow)
Is there anyway to save what the script does so that when I stop playing the game the changes made in the game are permanent?
Is there a way to copy the points data of the polygon 2d component and paste it in the edfe collider component in the unity editor?
Whew this took a while to figure out, but I did, I can now set the object depth (while dragging it) with any joint by only modifying the connected anchor point. Works awesome 🙂 If anyone else had issue with this, let me know.
I figured it out
On runtime, you can copy the updated component
And then paste that component in the editor
Whats best practice for retrieving a smooth velocity from a ridgitbody?
Is this normal for a rigid body that is not moving? https://im6.ezgif.com/tmp/ezgif-6-bbb196b4acf5.gif
use SmoothDamp
I have this unwanted behavior, was wondering if anyone else had this issue? I am using a Joint (doesn't matter which one, this applies to all of them). My script adjusts the connectedAnchor point so that the connectedBody moves in relation to this joint. Now this works perfectly if the host joint is either in motion or is rotating. However, if the host joint gameObject is NOT moving or rotating and the script is adjusting the connectedAnchor, the connectedAnchor actually updates and moves (verified by OnDrawGizmos), but the connectedBody doesn't move and won't update it's movement UNTIL the host joint gameObject moves or rotates, to which then the joint updates the connectedBody correctly. If this is confusing a requires a visual demonstration, let me know I will make one.
As a dirty workaround, I just have the host joint object transform backwards by 0.001 to make use the update occurs correctly. If anyone can suggest something more cleaner. I'm all ears 🙂
For Ragdoll, is there a way to bake transforms of a ragdoll to use as static? e.g. running a ragdoll simulation in editor and freezing transforms for runtime?
@north egret How would I use that to pull a clean velocity from the ridgit body?
@karmic yoke i dont know what you are doing but from the question you are asking, it soulnds like youre doing things weirdly
why dont you tell us why you need this "clean" velocity in the first place?
Im making a 3 omniwheel platform in Unity. I want it to move north east by powering some motors. With side friction completely turned off, all directions except North East and North West, work fine. Now im testing it with adjusting several variables, but no matter what I do... the result is the same. Anyone having a good explanation of what the variables exactly do? When I look it up online, everyone says something different.
The picture below shows the traveled path starting from the center. It always starts correctly, but at a specific point is basically starts rotating another direction.
Anyone have a good understanding of what preprocessing does for joints?
I have simple a cuboid, with 2 raycast wheel collider at start and end center of shorter edge. Which acts like suspension of bike. Now what is the best way to balance it? Moving C.O.M or adding torque to balance?
var targetRotation = Quaternion.LookRotation(targetpos - transform.position, Vector3.up);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * rotationSpeed);
rb.AddForce(transform.forward * Thrust);```
I'm using this to control a ridged body to a target position But it keeps over shooting its target by a decent amount. Does anyone have an example of a pid controller to make it a little more accurate?
@karmic yoke
Vector3 pos;
Vector3 velocity;
Vector3 targetPos;
void Update(){
Vector3 delta = targetPos - pos;
Vector3 pForce = delta * pMultiplier * deltaTime;
Vector3 dForce = -velocity * dMultiplier * deltaTime;
velocity += pForce + dForce;
pos += velocity * deltaTime;
}
position pd
read and edit velocity from rigidbody, read position from transform or rb.position
and dont use pos+= . . . line in the end
this example just makes its own physics in plain c# you know
@karmic yoke you should also clamp force before applying it
so that character doesnt apply impossible forces when either distance is too big or velocity is too big
Hi, I'm trying to do player movement using transform.Translate but currently when the player tries to run against a wall he sort of glitches in and out of the wall. I would like to prevent that by just moving the player to the side. I tried using hitInfo.normal to compute that vector but that doesn't seem to work for cubes not aligned to 90 degrees to the player (the normal vector is weird). Any ideas how I can compute the green line?
@opaque vine
green = Vector3.ProjectOnPlane(red, surfaceNormal)
Woah thats easy! Thanks a lot !!
np
Oh neat, I never knew that was a thing
do the ctrl+space now and then
I mean, still means I have to think that Vector3 has that 😂
Yeah I really wasnt expecting that
and I feel like its a weird place to put that function
Vector3 math is just in Vector3 static functions
You also got Vector3.Lerp in there
And you also have Color.Lerp for colors
I guess
Hey, I think it fits here: How do I get the position where a particle collides with an object? I'm using OnParticleCollide.
Can anyone please help? should I use pid with one of those?
PID maybe, also did you try with a spring joint ?
I'll check spring joint, should I use PID with moving center of mass or with torque to balance?
I am planning to use it with network, so avoiding default unity wheel collider, my ray cast wheel is very similar to the concept in this video. Have no idea how spring joint would work with networking
Multiple ways of doing it, depending on the accuracy you need:
- have your server authoritative for physics (calculations done server side only) then sync transforms (pos & rot) on the client
- have the server send relevant variables to the clients so they can apply their own physics (spoiler: unity Physics are not deterministic so only works for simple games where collisions are not the main focus of gameplay)
- implement your own physics system, not relying on Unity's one
Hello. (I am not sure where do I post this)
I am learning DOTs and one of the problem I have is my Entity (sphere) sinking in even though I I applied the Collison filter correctly. Not sure what is causing that.
SweepTest does not seems to work, when you are already "in" that object even by a tiny tiny bit. So if you run against a wall with high speed you glitch into the wall. Is there any workout besides adding extra range to the sweeptest?
Increase simulation steps maybe? Would probs put a heavier load on the computation though
Fish must consume ball
@stuck bay if you actually use physics in way that bike can rotate in that axis then PID would be most common way to solve that, yes
you could use ML to train to correct it too I suppose
i have a capsule collider and rigidbody attached to my player, and when a enemy projectile with a sphere collider/rigidbody hits the player, sometimes the player just goes flying up into the air with a high velocity? anyone know how to troubleshoot
@obsidian whale how do you move the player/enemy projectile?
enemy projectile is just flying through the air from its initial AddForce the enemy gives it (arc parabola), and the player is standing completely still ontop of a moving vehicle when it happens
How is it standing on it? Is it parented?
no, it is just standing ontop. the force of gravity pulling the player down onto the surface of the car is what allows the player to stay perfectly still ontop
the player and car are two seperate gameobjects, and the car is moving using wheelcollider torque
hmmm
might be because of lag..?
try artificially reducing fps and see if that occurs more often.
i increased solver velocity iterations to 32 (from 1) and it hasnt happened since, but ill keeptesting a bit 🤷♂️
that might have a huge impact on performance.
Did you try setting collision detection on your object rbs to continuous dynamic?
What would be the best way to add some noise to to a projectile traveling to a target. below is what I have for a missile. rb.velocity = transform.forward * Thrust; var targetRotation = Quaternion.LookRotation(targetObject.transform.position - transform.position); rb.MoveRotation(Quaternion.RotateTowards(transform.rotation, targetRotation, rotationSpeed));
i have a question, why wont OnTriggerEnter2D() owrk even if i have a 2d trigger?
Do you also have something that enters the trigger?😁
Do you have a rigidbody xd
Hey guys, I don't use complex / realistic physics in unity much but in the case of a floating airship eg. blimp - in 3d not 2d (with player able to walk around while in motion)
Would the right approach be to give the base object an accurate level of mass, and have sufficient constant upward force (eg. at 6 points for stability) to keep it afloat?
Would I need multiple base objects instead of one (connected by joints?) with accurate mass to give better stability?
Are there any tutorials that go over general more complex physics use cases and best practices? (Not just tutorial on how to use spring joint for example)
Cheeers 🙂
blimp huh
sounds like you'd want a center of mass
and a center of lift
@random leaf
you should be able to change center of mass through the scripts
for center of lift, you somehow would need to figure out center of volume
and add upwards force depending on the volume every frame
that sounds like a good approach
QUESTION:
I am working with a hinge joint on a moving object. The hinge joint is child of that moving object and the joint moves that parent object by moving the hinge joint as a lever. Now i see that moving the parent object without rotation works just fine. But when i try to rotate the parent object, the hinge joint/lever gets unwanted movement. I thought parenting would fix that? Is there some special "Connected anchor" setup for this?
TLDR: A hinge joint setup that represents a lever rotating in x axis has false intput when rotating the whole joint along y or z axis. x axis is fine though. Why?
Crappy models to simplify the idea:
Say this is my airship, how would I have all the parts taken into account for buoyancy in the air, how would I keep my upward forces balanced (ie. able to tip slightly but not immediately tip down like a helicopter), all collision objects considered when bumping into other objects, but again so that a collision (esp. at slow speed) wouldn't send it careening off slowly towards the ground?
I know these are complex questions but I'm struggling to figure out what I need to google even to figure out the answers
Thanks for any help / suggestions 🙂
@random leaf How about u connect the top and bottom with chains/ropes implemented with maybe hinge joints. Then give the top a RB with constant up forces just like gravity but up
then apply RB force movement to the bottom part and the chains and top part should follow accordingly
it will be quite hard to stabalize it for floating because rising force and gravity must cancel each other perfectly.
or apply force movement depending on where you want to have your driving thruster/propeller
i guessed the bottom part cause of the propeller like thing in the back
Oh okay, thanks you so much!
I'll try ML as well
Yeah it's pretty simplified really, I'll see what I can figure out 🙂
Found this which was a great help for stability
2D Code
Error:
Simply, I am making a multiplayer game in 2D. Currently using BoxCollider2D. I want the player to be able to collide with walls, and ECT. When two players collide, as in one running into one. The player that got pushed is vibrating, or getting pushed away from the other player. This only happens in the client side that pushed the character and not the server. I know this is mainly because the player position can only be changed within the player itself through my code. But instead of doing anything with this, I would just like to ignore collision on players. I tried using the Physics2D and disabling the layer that uses the Player to stop colliding. It did not help.
What sort of joint setup would you use for a spinning propeller? One that spins up from 0, but also with no forces upon it will spin back down to 0?
The propeller doesn't need to have any impact on the rest of the physics, more of a visual thing but I was hoping to leverage the angular drag to get it to spin itself down
ah figured it out
configurable joint
For My Proble:
It seems that my Prefab didn't change it's layer. And I just checked it to make sure. I found a fix to it Lol.
Got some airshipping going on 🙂
@random leaf
1- center of lift is higher than center of mass
2- make upwards force from center of lift
3- make downwards force from center off mass
4- make sure you have some angular drag on these or it will oscillate
and thats it, your airship will be stable
What's a simple formula for steering? To not overshoot a homing target?
I'm only doing a velocity += dirToTarget * speed * deltatime, and it's overshooting
I'm supposed to do like, dir + something based on current velocity or something..
I have a problem guys, OnTriggerEnter() doesn't get called if it happens outside the camera's view.
What are u trying to get trigger?
Maybe something moved by Animator?
That's exactly what I'm trying to do
It doesn't register when the player hits an enemy or enemy hits the player.
If you're wondering how the enemy is outside the camera view in that case, it's because it's a multiplayer game
And everything is done through host, and when the host isn't watching, client's hits doesn't count
I've tested it in offline mode too by blocking the camera, so I'm sure it's not a networking issue
U gotta set the animator to AlwaysAnimate
Alright
So yeah about my homing formula
This is i guess some rocket science
Vector3 dir = target - p.position;
dir = dir.normalized;
dir *= homingSpeed; // speed towards target
dir -= p.velocity; // the "balance" force
p.velocity += dir * Time.fixedDeltaTime;
p.velocity = Vector3.ClampMagnitude(p.velocity, homingSpeed);
But this still overshoots
My use case is, the particles explodes outwards, but overtime they're "steered" towards the target position. So it looks like a missile bursting outwards first then straight to the target
If the target is too close, or the burst outwards is too strong, then it'll overshoot. So i guess the "speed towards target" part also needs to be balanced, or even reversed, depending on some factor. I just dont know what this factor is..
just curious what everyone’s process is for creating accurate and inexpensive colliders in Unity? I’m trying to import a friend’s 3d art and apply a rididbody but every method i’ve used to create colliders is inaccurate or too expensive on physics. i’ve tried techies collider creator and a couple of other paid and non paid assets for collider creators but nothing is working smoothly.
Guys. When an object falls and collides with my another object, the object which was at rest, squishes a little. How can I prevent it?
it is 2D btw
How would you implement a controllable character able to walk around on a moving "vehicle" with semi-complex mesh?
Needs to be physics based to gel with the physics of the moving thing & be able to navigate it
Parenting to the physics object is definitely important for the local physics but I'm still getting issues with sliding
is jobified/burst physx casting possible?
@random leaf Could parhaps duplicate the vehicle physics components in a static environment and have the character simulate physics there
You'd make a capsule with rigidbody for player
Duplicate vehicle physics mesh
Put them in a different layer
And attach the oncollision callbacks and stuff
And then do some matrix transformations to transform the transform of that capsule in that envoronment in to your visual character
ahh interesting idea
hey guys
i wanna ask before going to buy Magica cloth being on sale, is there any hope that unity cloth 2020 will be as good as Magica cloth or Obi cloth ? any roadmap for it ?
Is it a good idea to pool many rigidbody colliders?
I'm thinking around 1000 on average. Pooling means setting it in/active often, which i hear is a perf hit
What should i do instead for pool? Just "teleport" them out of the map when not in use?
Hi, I'm having a problem setting up collision detection on custom mesh which is 10k triangles.
All I want to do is to get what points from my custom mesh are currently inside a box collider , then I will deform them to be outside of box
I'm trying to achieve something like it:
https://i.stack.imgur.com/kQfRv.gif
But I'm having a problem if there should be two rigid bodies or just one? And they shouldn't move (IsKinematic = true, which also disables detecton? 😛 )
@gilded sparrow maybe consider using DOTS for the collisions?
Cant.. and 1000 is still alright
Alright - pooling is usually trading memory for performance.
Or maybe something more hacky - run a force sleep script on rigibodies not in use. That would save the collision checks.
That could work too
I still need to teleport it tho right? Bcoz after they're forced sleep, they can still be sleeping in the middle of the road and have cars crashing on them (just an analogy)
Good question. I would try it out without teleporting first (guessing you are hiding the mesh) - if it works and is performant no reason to move them around.
anyone this?
trying to make a fully physics based tank tread, here's my current progress
any tips to make the simulation more stable?
I've tried increase physics simulation iterations with no real difference
quick math problem, how do i make player not be able to go over speed limit (but also not slow down when pressing the key in direction of velocity) but also slow down when pressing in the other direction or change direction when pressing the key to go to the side
(i am using addforce)
So this is builds off of @quiet ivy's question but slightly better explained:
So I'm developing a first person game, and I want to make realistic player movement. To move the player, all I have to do is call one line of code AddForce(), in which I pass in a value that acts as the amount of force being applied. The problem with this is that if I add a constant amount of force, then the player takes a really long time to accelerate and it moves really fast, so what I have to do is change how much force is being applied based on the velocity of the player and the friction and gravity but I don't know exactly how to calculate that. Is there maybe a function that I can use that takes some variables about the player's velocity, drag, etc. and determine how much force should be applied to the player?
i got most of the walking fine
even keeping the velocity of the object i am standing on
but in the air it just feels not right
i want to have slight control in air
What's your drag set to Foxyz?
0
good lol
the problem is
when i am jumping off a moving object
and holding w for example
in the direction im moving
it slows me down
and i don't want that
if i set forcemode.force then it's gonna go over the limit
So what you do is you add the moving object's velocity to your velocity
basically
it works wonders but as i said i want little air control and so i wouldn't get slowed down while pressing the key in the direction im flying to
but still being able to slow down if i press in the opposite direction
from what i've got it's just a vector math problem but it doesn't seem that i can figure that out by myself
ping when answering me cause i'm going sleep
I have a weird issue, basically i try to stomp on enemies in my 2d platformers but sometimes the stomping function happens far away from said enemy when i'm above them
I need some help :/
for some reason if I enable any line that has references to velocity.x or z I can no longer fall.
basically all im doing is taking my rotation dividing it by the absolute value of itself to get its direction.
IEnumerator rebound ()
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
float absRotationx = Mathf.Abs(Rotationx);
float absRotationz = Mathf.Abs(Rotationz);
velocity.x += Rotationx / absRotationx * 50;
//velocity.z += Rotationz / absRotationz * 50;
yield return new WaitForSeconds (0.1f);
//velocity.x -= Rotationx / absRotationx * 50;
//velocity.z -= Rotationz / absRotationz * 50;
I just tested it again I cant move vertically at all
You might be misinterpreting the value out of context when calling for it. Consider making the velocity call points individually (though may take longer) instead of calling a variable (in this case, rotation or velocity). If you have difficulty reaching out to the rotation or velocity reference, there is most likely a problem of how your variable was stored. Good luck @dusty verge
hmm alright, thanks
I'm up again and ready to negotiate
This line of code is supposed to output the rotation of the y axis but it gives me a decimal between 1 and 0 instead of the actual angle of rotation listed in the inspector is there a way I could get the rotation listed in the inspector using C
Rotation = FPP.transform.rotation.y;
fixed it had to use eulerAngles
hey guys, I'm trying to use Articulation Bodies to make a robot arm's tool follow a target. I want the movement of the end of the robot arm to naturally adjust the position of all the other joints, but I'm struggling to get the robot to move at all. Here's a pic of the types of motions I want to simulate and how I've set up my joints (they're indicated in light blue) -
lastly, this is my current hierarchy for the robot. The "tool" is the smallest attachment at the end of the robot. This hierarchy makes the components move naturally when the component below them is moved or rotated, but for Articulation Bodies to work, I understand the "tool" component needs to be the parent?
I never used articulation bodies (i would just go the IK route) but isn't this force limit to high ? Maybe that's what is preventing motion ??
hey, thanks for the response! I tried several lower force limit values, but nothing changed :/ I believe there's something wrong with the hierarchy or the joint configurations I made, but I can't figure out what. If I try to move the end of the arm, the entire robot just vibrates rapidly but doesn't move
Just to make sure, can you try zero as values for Force Limit AND Damping ?
Otherwise I'll let answer someone who already worked with that
hey, thanks again! I tried to zero both values and I can move the joints now, but I can't push/pull the tool joint and cause the entire robot arm to move in response. I assume I need to use inverse kinematics in combination with articulation bodies to get that sort of movement?
To clarify what my goal is, I'm making a HoloLens 2 application where the user can pull a robot arm with hand gestures in whatever positions they wish for validation purposes. I want to be able to drag the end of the robot arm and have the rest of the arm respond realistically to that motion.
I'm doing a physics2d.overlaparea
how would I get a count of how many colliders are in contact
Collider2D[] collider2Ds = new Collider2D[2];
ContactFilter2D contactFilter2D = new ContactFilter2D();
cast.OverlapCollider(contactFilter2D.NoFilter(), collider2Ds);```
This was my attempt after reading the scripting API but it doesn't work
Nice ! Yeah IK purpose is exactly what you describe. Have a look at the "Animation Rigging" package, they have a simple 2 bones solver easy to implement. It should even bé enough on its own, but I'm not sure why you're using Articulation body so maybe you still need it. And also I dont know how they would behave together as I never used it
thanks for the pointers! I wanted to use articulation bodies to get access to real simulation physics with target velocity, joint friction etc. to make the robot behave like in real life, especially when it's following a target. I'm not sure how realistic the behavior will be with IK but I will give it a shot!
It just solves position on n-1 bone. But no joint friction, so presumably lower than your expectations. Happy coding !
Hya! I'm working on a Glider Plane in my game. It uses a rigidbody and edits to the rigidbody.velocity to move.
When I add a collider though the rigidbody / object behaves completely different then without; Direction changes, the object moves way faster, etc
Why is that, am I using a wrong approach?
Ive tried using a standard 3D Cube with the same script, also getting weird results
What specifically changes when I add a collider?
I'm using the same Velocity vars
Oh and if I disable the Box Collider of the cube, it flies just fine too
Anyone any idea what Im doing wrong?
maybe the center of mass?
@outer bone try setting rigidbody.centerOfMass to what it is when you just have one collider. I also know that just having larger colliders can affect the behavior of rigibodies, so you may need to adjust your force amounts
i believe you can only change the COM in code btw
I wasnt using Force, instead calculation velocity (which im thinking of getting rid now again :P)
Im unsure what exactly caused the behaviour, but I re-coded the scripts and rebuild the gameObjects and it works well now
I did find some articles / posts saying things change since you add a center of Mass that that could have had something to do with it
others recommended setting the inertiaTensor
but that is Definately above my paygrade 😛 Im glad I got it working now, controlling in-air collisions with physics materials, works pretty well!
HI im just wondering
The ParticleSystem's Collision module said it uses the Physics world. Is there a way to make use of this kinda of "physics" object, say without using the particle system?
I mean, i can handle 30k particles total with the Collision module, but i definitely can't do 30k rigidbody + collider gameobjects
How can i fix this?
@stuck bay set the collision detection to continuous
i did
Oh dang
no i was asking if they need to have it also
Try it
I have a player with CapsuleCollider and RigidBody.
He is walking on a floor with a Box Collider.
Floor's BoxCollider has a physics material with very high friction.
Yet, player's movement is not slowed at all (just as if there was no friction). Does anyone have an idea what I'm doing wrong?
ok
Copy and paste?
no still doesn't work
@ruby frigate let me see a screenshot of your physics material
@stuck bay I'm sorry but I dont think unity has the capability to handle collisions that well
Wait 4 years for havok and dots to come out of alpha lol
its top down, i see games that have top down collisions?
how do they do that
But, from what I can tell from the video, you're forcing the object into another
@tough path
Sadly didn't change the problem.
It seems the friction does work, but stops at some point.
So the player slows down quickly, but will then keep moving forever, at maybe 20% of original speed (instead of slowing down to 0 due to friction)
Is addforce not working with the friction settings in PhysicsMaterial?
No not what I meant
So I assume you're doing add force on fixed update and you're adding it based on Input.GetAxis for player input, right?
Doing it with Input.GetAxis, but in Update() and multiplying by DeltaTime.
Okay well first of all
Do it in fixed update
You should always do physics related stuff in fixed update
Second of all, how physics works is if you add the same amount of force over a period of time, you don't stop accelerating (unless there's friction involved)
So what you have to do is somehow calculate how much force you should add based on the player's velocity
I've been trying to figure out how to do that and I've had a hard time
I'm gonna email my physics teacher tomorrow lol
But shouldn't the friction slow down the player? I apply force while pressing W. Then I stop pressing -> shouldn't the friction force be applied until the player eventually stops
It is slowing down the player
But in this case, friction is a constant
So the same effect I was talking about would still happen, but it would just happen slower (based on how much friction you have)
Well there definately is something wrong with my setup.
Because no matter how you look at it, this behaviour is weirds:
- pressing w for 3 seconds speeds player up to max speed.
- releasing w
- player speed quickly is decreased from 100% to about 20%
- then player keeps moving forever at 20% of max speed
Yeah unity doesn't handle physics very well
I've said this before and ill say it again: just wait four years for havok and dots to come out of alpha testing then you'll be set lol
Simple enough, right?
Ok now it seems to work, but removing all PhysicsMaterials, setting the friction directly in the player's collider, and setting friction to 10 -_-
I'm trying to use the GraphicRaycaster to see if my click hits any UI button, however I can't seem to restrict the layers that can be hit. .My buttons have a specific layer (UIButton) but my raycasts are also hitting all the other UI elements (which I don't want to detect).
Is something wrong with my GraphicRaycaster settings ? I tried with "All" and "None", no luck
Does anyone know if ConfigurableJoint has a limit for Angular Y&Z limits? I cannot seem to set any value below 3 (aside from 0). Angular X Limit can be set to anything though 🤷♂️
sticking one more question in here because I'm not sure how to go about this or what to look up
(2/3 through calc 3)
i'm revamping my grappling hook system and it doesn't use any rigidbodies, where in this problem (a,b,c) is my position and (d,e,f) is my projected position
i've been directing player velocity directly from (a,b,c) to (d,e,f), and while it works, it's causing some odd bouncing issues because of approximations
the sphere is mapped by x^2 + y^2 + z^2 = grappleLength
first you need to define a function for that particular curve
in parametric format as such:
fx(t) = ...
fy(t) = ...
fz(t) = ...
where fx is x position, fy is y position, fz is z positon
at given "t"
and then, you take the time derivatives of each component and obtain:
f'x(t), f'y(t), f'z(t)
and then, these are your x,y,z components of your swing vector (for your time derivative "t")
@umbral vector
But you shouldn't be needing any of that calculus to move an object in a curve like that
Vector3.Slerp is for exactly these situations
I'm still really new to unity, I was going to use the unit directional derivative to direct the player's velocity to the sphere's surface
oh my god
never used slerp before but it looks like exactly what I needed
thank you ❤️
no probs
@umbral vector
you have a third param in lerp and slerp, thats the "t" of the curve
@umbral vector But this is also probably not the best way
Wanna hear how i'd do it?
absolutely, i've gotten no guidance on the best way to do it so far
1- apply external forces or gravity
2-look at all the forces applied last frame, update velocity
3-remove velocity component on rope direction
4-update position from the velocity
5-translate the player in rope direction so distance between rope pivot and player doesnt change
@umbral vector
This will give you a stick instead of a rope tho
But it can easily be made like rope
the way I'm doing it now goes like this, and it only applies when the player is outside or on the grapple hook's length:
- find where player is expected to be from current velocity
- draw a line from the hook to the expected location
- clamp the line to the grapple hook length
- find direction from current location to clamped expected location
- direct player velocity in expected that direction
i had teleports but ended up removing them
there's two problems with this approach though
the player will move in circles at the bottom because gravity is always pulling the player down, then that force gets turned into sideways movement
as of changing some things in my code the player is constantly gaining velocity
as in every swing they'll go a bit higher
multiply velocity with 0.95f every frame to make air resistance
that's what i've been using so far
that doesnt sound good
whats with the expected position and stuff
expected position is where the player will be next frame
a vector is made between the hook and that expected position, then clamped to the rope's length
you should be thinking about what velocity should be only
and position should figure out itself
and afterwards, you just translate the pos a little bit to maintain rope length
it's only used to determine what direction the player will move in
there's no teleportation with these scripts, the expected location is just a value
i see okay
translateDirection will need to make use of slerp
right now it just uses homemade lerp
translate direction shouldn't be necessary
you dont have gravity?
you dont have force/acceleration
Hello
you should be doing velocity += gravity
oops, the player doesn't feel gravity on frames when being redirected right now
one moment
so it turns out the player was having gravity applied on rope physics frames, just after the redirecting happened, definitely the wrong place
however i also found the increasing velocity problem
this dumb peice of code that was going to make the bottom of the swing a magnet which one of my friends suggested i try to stop the perpetual circular movement at the bottom
thats just gravity
and that shouldn't stop the circular motion, air friction should
bottom is a fixed point?
and thats not gravity?
thats a magnet then as you said
and that wont stop the swing neither
basically it would pull the player towards the bottom of the sphere
it will just make it swing faster
actively pull them that is
this was another idea i had for a solution to the circling problem
it didn't work at all, unless i messed up the code
you seem to be making it complicated, why dont you think it over
1- apply external forces or gravity
2-look at all the forces applied last frame, update velocity
3-remove velocity component on rope direction
4-update position from the velocity
5-translate the player in rope direction so distance between rope pivot and player doesnt change
thank you for helping me out 
i think i need to take a look at all the stuff that unity can do on its own with vectors too
give me your code and i see if i can do it how about that
some spoonfeeding for you
there's a few different objects at play but i'll send it
just send me your latest piece
also my movement is totally messed up
thats a fatass script

using UnityEngine;
public class Swingalang : MonoBehaviour
{
public Vector3 ropePivot;
float ropeLen;
Vector3 velocity;
Vector3 forcesApplied;
void Start(){
ropeLen = (ropePivot - transform.position).magnitude;
}
void FixedUpdate(){
// add external forces
forcesApplied += Vector3.down * 9.8f * 0.02f;
// forces get added to velocity every frame
velocity += forcesApplied;
// change velocity so the component on ropedir is always zero
Vector3 velocityOnRopeDir = Vector3.Project(velocity, (ropePivot - transform.position));
velocity -= velocityOnRopeDir;
// add velocity to position every frame
Vector3 newPos = transform.position + velocity;
// change position so that rope length stays the same, you already did this part didn't you?
Vector3 dir = (newPos - ropePivot).normalized;
newPos = dir * ropeLen;
transform.position = newPos;
// these forces are already applied, we want to reset this variable
forcesApplied = Vector3.zero;
// air friction
velocity *= 0.96f;
}
}
@umbral vector
make a new scene, put this script on a empty game object
give object position -10,0,0
and hit play
i did that, then forgot to add the script
add the script?
it's not moving still, i'm gonna check if i might have messed up something
i did not test this code
i am on ubuntu now and i dont have unity
make sure fixedupdate runs
put a print in there
make sure there are no errors in unity console
so you understand the code?
honestly i don't at all
lemme add some comments then
what does project do in this situation?
projects a vector on a direction
i used that to get the velocity components on rope direction
using UnityEngine;
public class Swingalang : MonoBehaviour
{
public Vector3 ropePivot;
float ropeLen;
Vector3 velocity;
Vector3 forcesApplied;
void Start(){
ropeLen = (ropePivot - transform.position).magnitude;
}
void FixedUpdate(){
// add external forces
forcesApplied += Vector3.down * 9.8f * 0.02f;
// forces get added to velocity every frame
velocity += forcesApplied;
// change velocity so the component on ropedir is always zero
Vector3 velocityOnRopeDir = Vector3.Project(velocity, (ropePivot - transform.position));
velocity -= velocityOnRopeDir;
// add velocity to position every frame
Vector3 newPos = transform.position + velocity;
// change position so that rope length stays the same, you already did this part didn't you?
Vector3 dir = (newPos - ropePivot).normalized;
newPos = dir * ropeLen;
transform.position = newPos;
// these forces are already applied, we want to reset this variable
forcesApplied = Vector3.zero;
// air friction
velocity *= 0.96f;
}
}
@umbral vector
thank you for sending all this, but i still can't understand how your code "Vector3 velocityOnRopeDir = Vector3.Project(velocity, (ropePivot - transform.position))" works
it's way simpler than everything i created though
You understand Vector3.Project?
@umbral vector
You could do the same with dot operation
a1 = Vector3.Project(a,b)
i don't understand projection, especially in the context of this code :(
i thought i did and i was very wrong
i can tell sort of what it's doing with visuals online
we are just trying make sure that velocity doesn't try to extend/contract the rope
we are trying to keep the velocity on swing direction thats the purpose
you probably got confused trying to do the same thing
this is how i do it
so velocity is being projected onto the player's position, right?
velocity is projected on this
(ropePivot - transform.position)
which is rope direction
which is "b" in the image
velocity is "a"
i'm hitting a brick wall here, i still don't understand
wouldn't velocityOnRopeDir be 0 in this situation?
exactly
but we apply gravity on that force you know
if you dont do that operation im doing, your velocity wont look like this
look at how i update velocity
it does not know about rope until that part of code
velocity += gravity
this is what happens to velocity
think of this as
"rope tension"
a force in rope direction
that's exactly what i'm missing from my code
velocity can be is blue by default
what i do is
blue - green
so velocity will become red
.
or in other words, i figure out green
and apply its reverse as force
you could say thats rope tension force
where is the magnitude of that force coming from?
the rope tension force, sorry
if you pull against rope
with some force
that makes tension
rope will pull back in opposite direction
physicswise
that works with forces
in physics
but i did that with velocity
i'm actively trying to figure it out, sorry if it doesn't seem like i'm making any progress
thats not how physics works, thats not how highschool physics questions are solved an all
i know you've given me all the information needed to understand it
i just need to think about it longer, i'm sorry for making you wait
tension is at a maximum at the bottom and top of the loop
it's 0 at the middle
main entry point is:
rope velocity cant have a magnitude in "green" direction
and we somehow need to eliminate it
start there
dont think about tension
i just don't understand what vector3.project is doing at all
i'm seeing some light, one moment
it's finding the distance gravity goes away from the pivot point
blue is not gravity
its what gravity did to velocity if there wasnt any rope
you are getting close i think
gravity is always going to make velocity go more downwards, isn't it?
wouldn't blue always just go down?
sorry, i worded myself wrongly
and right now, we are discussing what the rope does on the velocity
blue is a constant downwards direction, right?
no
if you want to go, i've kept you here for an hour and a half already
you've given me everything i'd need to figure this problem out on my own
i just don't want to keep you here, i really thank you for all the help you've given me
allright i'll go after i explain this
1- lets say blue was your velocity right, no rope or anything
2- and then you shoot grapple and there is rope
3- at that moment, green is calculated and subtracted from velocity(blue)
4- and your new velocity is red
blue is velocity directly after gravity is applied to it then?
assume there is no gravity for this example
i can't thank you enough for the help, i'm going to review everything you've said until i understand what's going on
@umbral vector if you solved some of these questions back in the day, you should find it familiar
it took me an hour and a shower but i get what's going on here
i stuck myself in a thought box and couldn't get out of it
thanks again, rewriting the grappling hook!
hey i have multiple cars with a mesh collider in the same spot. and i dont want them to fly around because they collide with each other. How can i make them ignore each other? i added a check in my OnCollisionEnter function but this does not prevent it
the meshcollider is attached to one of the car's childs
and this happend right now
@fossil merlin set them to a same specific layer and then set in Project Settings-Physics that the 2 layers dont collide
solved it ty
Hey peeps. Does anyone know why my rigidbody is clipping through changes in a surface's geometry sometimes?
I've set it to speculative continuous, as that's what I'd expect from it. It's non-kinematic. I have three colliders attached to my player. I affect it in code using rb.velocity = velocity. However, I also tried using rb.AddForce(), but that hasn't helped the issue at all. I used to use a character controller, and no clipping occurred, but now it seems to be fairly common
The documentation also highlights the problem of clipping on gaps
but then mentions no solution whatsoever
I hate to badmouth the Unity team, but are rigidbodies just totally broken? Everywhere I look online it's nothing but complaints and bug reports
So, what's the deal with wheel colliders and its problem about not moving in a straight line? "Car" keeps turning left or right (depending on speed and settings) on its own. I've found a lot of pages on unity forum about that but no correct solution, most of the posts were made 5+ years ago and said that it is just a unity version bug. But it is still a thing in 2020 unity! Any ideas?
Not enough info on your problem...
@limpid quartz changing collider meshes and rigidbody interaction is probably not something physics engine is expecting
you could always do a raycast from character, downwards direction
see where it hits, reposition the character
and make sure this happens after the terrain/mesh edit
i have just a cylinder with multiple bones, how can i make it soft? like a rope, or a snake
with joints and rigidbody?
When using the wheel colliders and moving forwards, it starts to steer left or right by itself when accelerating
Still not enough. What's your setup in the scene? The hierarchy of the objects involving the wheel colliders? Wheel colliders inspector values? The vehicle GO and it's inspector? Your code?
is it possible to simulate acceleration on a character controller I'm trying to figure out how to make a smooth transition from a quick push off of a wall from my character to slowly decelerating from air friction but I can only find examples with rigid bodies.
Would it not be fairly normal to assume that most games would at some point have two bounding boxes attached together though?
Such as tiles?
You want tile collision?
Or a seam, such as a door in a wall? It seems like this is an incredibly basic piece of functionality that's present in almost all video games
Tile collision or being able to handle a new surface along an object if possible 🙂
you want a door, and thats about it then
when you close the door, you are making a new tile collider there
and that glitches the character if a character was in the doorway
@limpid quartz am i understanding correctly?
if thats the case, you can either:
-prevent door from closing when the tile is occupied with a character
-or use a very thin collider for the door so it very easily pushes out the character
asking for number 1:
could the ball's grounded code be detecting two objects and add two times more force?
if you did a raycastall in ball's movement code you might've done that mistake
Yeah, that's the thing. It's fairly complex movement code that I have at the moment
It's a FPS game with momentum, wall jumping, sliding, etc
The player uses a rigidbody, 3 separate colliders for torso, feet and upper body, and I also fire raycasts out in 4 horizontal directions and also downwards
.
for number 2, i dont see a very nice way to handle that
you could look at velocity, cast a ray from that direction, reposition the object depending on where it hits, as i said before
I already do that, and it seems to change direction most of the time
it would only change position
but every now and again I'll just fall through the floor and out of the scene 😭
you got any transform position sets going on other than this?
on rigidbodies i mean
Nope, I only use rigidbody.velocity = velocity, with velocity being set before this based on some raycasts, states, button presses, etc
I assumed it was because of the high speed and was a bullet-through-paper problem, but enabling speculative continuous doesn't seem to help at all 😦
The actual position is never manually set, just the velocity - and I would expect the actual rigidbody to handle collisions detection and resolution itself in the background
before:
rigidbody.velocity = velocity
after:
Vector3 deltaV = velocity - rigidbody.velocity;
deltaV = Vector3.ClampMagnitude(deltaV, 10);
rigidbody.velocity = rigidbody.velocity + deltaV;
You can limit how much the velocity can change in frame with this
If you that change
This is pretty much moving with force but your control is as good as velocity control
Best of both worlds
Thanks dude! I get what you're saying
But I already clamp my velocity 😦 The player wants to be able to move quite quickly, as you use ramps and drops to gain momentum for jumps. You can also ground pound downwards onto a slope to gain movement speed
So I don't think it's even happening because velocity is too high
this is not clamping max velocity,
this is clamping max acceleration
i think you got the wrong idea, this is not what you think
I must have
See, I was under the impression that as long as I never manually touch transform.position, the physics system will handle collision resolution in the background
yea but you are manually touching the terrain technically
Are you saying that you think I'm accelerating into the geometry despite my velocity being capped?
So in the next cycle I'm adding a load to my velocity again when already touching the geometry?
Could that override the physics system in the background?
Ahhhhhh
It's hard to debug or use example code, as the movement system I have is quite complex. I used to just use a charactercontroller, and it worked fine and never clipped. After switching to a rb, this has been a problem
i just think you should try to limit the change in velocity as i said,
not too sure this will fix %100 of the issues you have
But I'd like to use a rb, as it seems to make more sense in the game's context, as it's heavily based on physics and movement
Thank you so much for your time dude!
I'll see if that's causing the problem. I'm at my wit's end trying to think of solutions at this point
you could also find ways to control the terrain change
so that terrain doesnt change in way that clips the character
or move away the character whenever terrain is transformed
The terrain doesn't change in real time though
It's just static geometry
and pretty blocky geometry, too
looks like terrain changes when in contact with ball
Mostly cubes, with the odd 45 degree inclines
Sorry! That was probably just my diagram not being very good 😂
That's just the player falling downwards onto a low poly slope
I'm gonna try and screen cap what's happening and get in on youtube. Some video footage might help
"when geometry surface changes"
then you mean the slope in there
hmm
thats a different case then
and my explainations are irrevelant
but limiting velocity change could still help
That's also probably much more complex haha
Yeah, this is just static geometry, but I'll obviously be changing direction as the surface normal changes along the gemotry
are you changing the collision mesh or not
Exactly. And I only ever change velocity - never direction touch transform.position
Nope
The mesh isn't changing, I just meant that the player is touching different parts of it was he falls down
okay got it
The low poly slope has a few surfaces on it, and on the player touching the next section of the ramp, with a different surface normal, he can clip through
it should be fine, you shouldn't be having these issues
velocity control should've been fine as well
maybe velocity is too high
It's melting my brain
maybe you are setting velocity too high
i think you should limit the velocity change like in that example code i told you
other than that, i dont know what might be the issue
The player needs to move at extreme speeds though. I also limit velocity once it hits a certain threshold. It doesn't feel like I'm moving so fast that I should clip though
I'll screen record and send a video through soon my dude
@limpid quartz i am not talking about limiting velocity
i mean limiting acceleration
you should try the acceleration limit
i have spoken
how would i go about making a 2d ragdoll move with a moving platform? the platform is using a kinematic rigidbody2d and its being moved with .MovePosition. it's using a physicsmaterial2d with max friction and 0 bounciness. the ragdoll seems to stick for a bit if it was going in the same direction as the platform when it lands on it, but then slides off when the platform changes direction. i've also tried parenting the ragdoll to the platform, which didn't seem to do anything.
you probably want to have velocity on the platform, move it with forces as well just like you do with ragdoll
@pastel scaffold
Thats number 1
number 2 is
You have a piece of code that slows the character right?
velocity *= 0.9f?
what do you have
rigidbody friction?
what is it?
you need relative friction to the platform which the character is standing
@pastel scaffold
Heyy, so i have a little thing, i've been trying for 2 days to get the orbit for a planet around a sun. I've watch a dozen tutorials on youtube but i cant figure it out. Could someone help me ?
new Vector3(sin(time * angularSpeed), cos(time * angularSpeed), 0) * radius
@slender wagon
seen this before?
No i havent wow
Do i have to search that on yt?
this is just a piece of psuedo code for a rotating* vector
So a rotation vector is a direction that needs to be have AddForce ?
Well i'm trying to do it with gravity
you wanna apply gravity forces then
@slender wagon but you know, the real solar system is not stable
your system will most likely eject planets
I know, but at least all planets have an orbit
until there are only two planets left
Mine just crash into the sun
i mean at start
give some velocity to planets in the begining
yea
so they have some velocity to maintain the orbit
But how do i figure out how much velocity they need?
Haha i just want it to rotate the sun
or you use that equation
gravity = centripetal force
you know distance, you know mass1 and mass2
you know know gravity constant
you need to figure out velocity in centripetal force equation
Im looking at it on wikipedia
Uhm well i think i'll need to figure that out
But what you mean with gravity constant?
@slender wagon this is very similar to a common highschool physics question type
in that equation you have a constant
its that constant
@viral ginkgo sorry for late response. ill try using velocity, but i dont understand what you mean by code that slows the character
what prevents the ragdoll character from endlessly sliding after you stop pressing buttons?
@pastel scaffold
friction
physicsmaterial2d on feet
uhhh not really ill double check
if the feet arent dragging behind when you walk, then you probably arent animating limbs with force and thats not a %100 active ragdoll
no, they dont drag, i have sort of an animation thing going on that rotates the rigidbody of legs using rigidbody2d.MoveRotation
@pastel scaffold then its not an active ragdoll you are doing
and animations wont react to external forces
an active ragdoll would be one that only uses velocity?
https://www.youtube.com/watch?v=phrudWsx9Gg
This is what my active ragdoll looks like
@pastel scaffold
limbs are moved with force or torque
np
How do i calculate the range between two masses?
you can access gameobject position via transform.position
@slender wagon if i were you, i'd make a new gameobject that has references of all planets in the scene
and i'd do a double for loop on that list if you know what i mean
Ahh yeah, but how could i get the distance between the two>
(planets[i].transform.position - planets[j].transform.position).magnitude
@slender wagon
given that i,j are iterators
and planets[i] is a list that contains all planets
Ah okay thanks
@viral ginkgo I've kinda fixed it, the planets go around the center. But is it possible to make a projectile tractory ?
you'd need to define these in a function:
velocity, position
whatever your do with planets, you'd do the same with velocity and position
iterate many times, record position each time or every 10 times or so
you'll have your trajectory
Alright i'll first try to get the velocity and position
these are not the velocity, position of your object
you make your own simple physics
I feel kinda dumb haha
just to simulate one tragectory
or you could make a seperate physics scene and simulate the same object multiple times per frame, to render that trajectory
you'll be able to do PhysicsScene.Simulate
and advance time in that scene without breaking your main scene
thats the idea
Aha so if i get this right
Im making a new scene
Where everything is the same as the main scene
not a new scene, it wont do it
you need to have a seperate physics scene
if you make a new scene, it wont make a new physics scene and physics simulation will be shared
and you want be able advance time on a particular object without breaking your main scene
@slender wagon This is overkill anyway
I just explained that so you know your options
I'd just make new vectors position,velocity
do the same logic you do on your planets on them
but 100 times
This sounds really complicated haha
You could define your own orbit physics
And not use rigidbodies
For your current orbit system as well
Im using rigidbodies to orbit the sun
Its not much different then what your are doing now anyways
addforce would be velocity += myForce/mass (given that F = ma and "a" is velocity change)
well you need a little physics/math in gamedev
better understand what you are doing
so if i use rb.velocity += myFoce/mass then it will be the same as rb.AddForce(x, y, z)
Cause tbh i kinda need to make the tractory, cause it wont really work without
using physics:
rb.AddForce(myForce0);
rb.AddForce(myForce1);
rb.AddForce(myForce2);
same thing but no physics:
Vector3 position;
Vector3 velocity;
float mass;
Vector3 myForceSum;
myForceSum += myForce0;
myForceSum += myForce1;
myForceSum += myForce2;
velocity += myForceSum/mass;
position += velocity;
myForceSum = Vector3.zero;
@slender wagon
rb.AddForce(myForce0);
rb.AddForce(myForce1);
rb.AddForce(myForce2);
Why do you have this 3 times?
this is an example to show how to add multiple forces
just wanna show how you'd add some force
Ah okay, imma try to make a PsyicsScene
physics scene is more difficult as i said, but you'll be able to predict collisions
Anyone know how I can truly lock a config joints axis?
Setting locked does the trick except the object still moves
like it'll spring back into place eventhough I have it on locked?
I'm trying to achieve stabbing so I need the Z axis limited while X/Y are locked and unmovable in any direction other than Z
Expected behaviour
It's configured in local space, so the Z axis is in the direction of the stabbing, all other axis are locked.
I've shown only what is relivent to the stabbing functionality, angular related things aren't required atm.
Figured it out
Turns out the connected mass scale was at 1, allowing basically anything to move it, adjusting the values makes it immovable in any direction other than the desired one.
Anyone here have experience with dynamic bone and colliding with rigidbodies and what not?
Hey 👋
How do I change the distance between my camera and a target without modifying the camera angle?
I could get the camera to zoom in/out but when I do the LookAt it changes the camera angle when reaching certain distances
Hello, is it allowed to ask questions here?
ah idk i'll just ask. I have a Problem with collision well i think i have a problem with my brain but right now i can't figure out why my collisions don't want to work.
So i got colliders and all set up and they work but it looks kinda scuffed and when i set the player speed to fast it just doesn't give a shit about my "collision". Maybe someone can help? I got a Video that shows what i mean.
this here.
maybe it's my movement script after all?
@tacit dawn did you try setting the rigidbody's collision to continuous? Also, what are you using to move the player?
Are you talking about field of view when you say camera angle?
Hey all, I'm having a problem related to switching from Animator -> Ragdoll. Here's a link to my forum post: https://forum.unity.com/threads/animator-rigidbody-pulse-on-change.1013335/ I appreciate the support.
Hey! No... By angle I mean the pitch. I have some references for doing this but I don't know how to translate the code to Unity. But to me it seems they take the player position and subtract by the camera position and move the camera in a straight line without using the LookAt
Here's the reference https://www.github.com/open-ragnarok/open-ragnarok/tree/master/roengine%2Fcamera.cc
Could replicate the code by taking a closer look at the reference.. Thanks anyways!
@stuck bay Thats what i made for PlayerControls. i'll post a picture about my settings for the Player collider and stuff
{
public float playerBaseSpeed = 5.0f;
private float playerSpeed;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
// playerSpeed manipulation starts here
playerSpeed = playerBaseSpeed;
// TODO: make this settable in a menu
bool inputSprint = Input.GetKey(KeyCode.LeftShift);
bool inputSneak = Input.GetKey(KeyCode.LeftControl);
playerSpeed = inputSprint ? playerSpeed + 3.0f : playerSpeed;
playerSpeed = inputSneak ? playerSpeed - 3.0f : playerSpeed;
// movement starts here
float inputX = Input.GetAxis("Horizontal");
float inputY = Input.GetAxis("Vertical");
Vector3 move = new Vector3(inputX, inputY, 0);
transform.position += move * playerSpeed * Time.deltaTime;
}
}```
@stuck bay this are my settings, so i think the Problem here is that it still can move into that direction after hitting a wall it just hits the wall again until it breaks through the wall.
I have currently a problem, that my golf ball is sometimes bouncing of flat platforms (paths). Rigidbody settings are also be seen in the video
(Fixed by changing "default contact offset" to 0.00001)
Here again with a wheel collider problem. When I'm adding torque to the vehicle, it starts moving sideways for some reason and I can't find a fix for it. Can anyone help?
I have a super weird problem..
My homing projectile uses rb.MovePosition (also tried rigidbody.position)
It "homes" fine except when the target moves, in which it just stops
Doing Debug.Log(rigidbody.IsSleeping() + " : " + tr.position + " - " + newPos + " mag: " + dir.magnitude);
Ohmygod figured it out
Was doing this:
transform.LookAt(lastDestination);
Apparently rb.position or Moveposition doesnt like it if transform is modified right after. Flipping this around fixes it
Wow ok
Actually there's another problem
The above case is fixed, but if the target's moving when the projectile is spawned, then it'll also never start moving
Maybe im not getting something here..
Ok i gotta also do rigidbody.rotation..
Hey everyone :)
Working on a VR game and was wondering if anyone knew how to make the player rig be physics based, similar to Boneworks. I currently have it setup for physics based hands, but I am able to walk through things, and things like climbing wouldn't work at all. I would assume some form of inverse IK would be required for things like climbing, to make sure to pull the main body along instead of the hands going to never land alone. For the body, and mainly the camera, I have no idea how it would work.
So how would one go about rigging up a player in order to allow physics based interaction with the world vs simply phasing through everything?
I've been using Unity for education and something is messing with the physics. In the program when the player hits an object the object is supposed to go flying, however it is not registering the collision on the first hit and thus requires multiple before it goes flying. I am unsure if this is better here or in #archived-code-general
Share your code.
I am updating my rigidbody velocity in every FixedUpdate like this:
if (rigidbody.velocity == Vector3.zero && newVelocity == Vector3.zero) { return; } rigidbody.velocity = newVelocity;
The if statement is to prevent unnecessary 0 assignments when it's already on 0.
This still causes the rigidbody to have increasing velocity which is causing the transform to move.
There is no other code that does something with the rigidbody. When I disable this code, the rigidbody is not moving at all.
Anybody know why and how I can solve this?
I usually don't mess with directly with velocity to avoid strange results. I prefer to apply forces.
Does newVelocity sometimes get reset ?
otherwise you're always moving yeah
Also you cant' be sure about zero equality because floating point precision, but that's another topic
newVelocity is by default Vector3.Zero untill I receive a MQTT message. Im not receiving any messages at the moment, which means that newVelocity is still on zero and not being reset.
I thought it had to do something with the floating point precision
That's why I changed to my own compare function which works like this:
But it's still moving. Really strange
ok your compare function is ok
Back to the topic so you expect no velocity at all, though you see your rb moving
It's a on a flat ground ? which shape ?
it's on a plane currently
rotations are 0
I think i've just found the problem
Thanks to your question 🙂
The mesh collider convex didnt work as planned
isn't it just falling because gravity maybe ?
oh ok good
so not a flat ground, eh ? 🙂
It's making it unbalanced, which causes the physics engine to add velocity
It is flat ground
Just the object moving on it is not flat haha
oh ok, great you figured it out
Thank you for your help!
Just replaced the mesh collider by a box collider. Problem seems to exist. It's standing still for a few seconds and after that it starts adding a velocity of 2.
Seems like the world center of mass drops down from 6.1 to 5.4 and then it al goes wrong.
The velocities seem to change from -6 to +6 every time. Like it's teleporting?
can you show screenshot of the scene ?
Physically, he's not moving anymore since the mesh collider got replaced by a box collider. The rigidbody velocity is just acting really strange.
Honestly I dont even know if that's to be expected or not, I never look at that. I guess you'll see if that's getting in the way when you try moving ?
Okay this time I really solved it
Yeah it was getting in the way. Every velocity update of X and bigger im sending a message back
The problem was the FixedUpdate.
Changing it to Update made it behave correctly
Uhm... I'd rather mess with Physics in fixedUpdate
I dont see how you compute newVelocity, but let's say you replace it with rb.velocity = new Vector3(0, 0, 1); does the movement still have jittering effects ?
newVelocity is a global variable in the script. With a method like setVelocity (Vector3 velocity) I set this variable. This function is only called through my MQTT Adapter script. So simply: Receiving a message over MQTT containing new velocity value. call the setVelocity method with the new velocity value parameter. Set rigidbody's velocity to this new value
Just did what you said @supple sparrow and it results in the same jitter effect, just a little bit less because it's also moving now
Man, I dont know. Is there a Physics Material on the gameobject ? Is the gameobject slightly above ground when spawned ?
I have it slightly above ground. There is no physics material on the gameobject only on the ground
with bounce 0 and both frictions 0.6 (default)
@sweet flicker if you ignore teh values going all over the place, does it behaves like expected or movement is messy ?
Lots and lots of tutorials on the net, youtube, ...
pick one that looks cool to you
@supple sparrow It is moving like expected but with a little jittering. It moves slightly up in decimals on the Z Axis. And even less down on the X axis. Thats my only worry atm. Even when it's idle it has this jitter.
can you easily make a gif or video about the jittering when idle ?
alright, and does it help if you set collision detection to continuous ?
As you can see, it's falling down really slowly. After hitting the ground. It starts adding velocity and changing the z axis
actually in the scene your object isn't really moving.
The simulation goes crazy but it's not troublesome ?
It's moving the Z axis a little bit up in decimals, but you can't really see it with the human eye. It's a simulation of a real robot, overtime this minimal change in the Z axis can cause a difference that's why I wanted to get rid of it. But it seems that we cant?
I guess velocity applied is not enough to make it move but enough to update values
I'd say you'll see if problem persist when you begin moving
Yeah again just minimal, I will leave this unsolved and will just accept this
Thank you for your time!
No problem, happy coding
is there a way to make fixed joint actually fixed? i tried searching everywhere and none of them works for me
@fleet iron what are you making with fixed joint?
If you have a rigidbody in parent
and have multiple childs with colliders attached(no rb in childs), that will be a single rigidbody, including all those colliders
but then if i delete a object the other objects in it will get deleted
and its hard to make that placeable
How do you apply a torque to an object so it aligns with a vector?
I'm currently doing ship.GetComponent<Rigidbody>().AddTorque(Quaternion.FromToRotation(ship.transform.forward, dir).eulerAngles);
where dir is the given vector
@fleet iron
.
hierarchy:
g.o with rigidbody
g.o with collider
g.o with collider
g.o with collider
g.o with collider
g.o with collider
.
you can delete any child
.
@soft sparrow
Vector3 target = my target normalized direction vector
Vector3 current = ship.transform.forward;
Vector3 torque = Vector3.Cross(target, current);
// i may have mistaken the sign, one of these two should do it
rb.AddTorque(torque)
rb.AddTorque(-torque)
rb.angularVelocity *= 0.9f;
I'll try it out thanks :)
How does a physics engine know if two bodies overlap?
I assume bounding box check is done first, in the octree grids that contain the two objects.
After engine knows these two objects bounding boxes overlap, what happens next?
I wanna know how a simple cube collides with a complex, concave terrain mesh
it does "solver iterations"
it goes over every potential collision and if it finds one, it calculates the new transform.
It does this for as many times as you specify in the physics settings or until no collision is detected
depending on the type of objects the detection can be really easy or really tricky and there are loads of different ways to do it
circle is easiest, you only need a radius.
box is second easiest
polygon/mesh is a lot more difficult
if at all possible you should reduce your collision geometry to circles and boxes 👍
Hmm i see, i plan on using smooth voxels, i wonder if there are volumetric collision checking methods, or people just convert to convex mesh pieces and do these types of things
Hopefully I'm in the right channel for this, sorry if it's incorrect! I'm trying to find a reliable way to have my character slide down a slope if it collides with it mid air. So far, I have it working properly but only if I'm facing the object/terrain nearly perfectly with transform.forward. If I jump onto the slope so I'm perpendicular to it, I just continue sliding forward. How can I get the the vector that I'm using for my controller.Move to be the in the opposite direction of the angled surface that I'm colliding with?
is there any benchmarked or anecdotal best practices regarding to which degree a mesh collider should be split up into sub sections? In my own experience on a slightly older project (also mobile), I noticed some benefits to splitting up some big ones, but I never really exactly tried to find the line.
@viral ginkgo About the earlier code you posted, it seems to oscillate a lot, how would I go about counteracting the oscillation?
Nevermind, I'm stupid and forgot to add the last line
Not sure I figure your setup. Can't you just minus the vector ?
Or go down - Vector.up and let your collision glide you along the slope ?
Or are you looking for the tangent ?
I would compute the forward vector with the normal of the collision point (using the dot product) to find the facing direction
and projection on the surface
but depends on your implementation and if you're using custom or Unity components
@drifting quartz It's poorly explained, tell me if you need further help
Whats the difference between lerping and simply moving based on Time.deltaTime?
lerp = linear interpolation = inferring data between two known points.
i have no idea what you mean by simply moving based on Time.deltaTime
I feel like if you move an object at a certain speed and multiply it by Time.deltaTime you would get a linear movement as well
it would only be as linear as your framerate
Wouldnt linear interpolation be the same way?
Because it only calculates a new value every frame?
for lerping you need two points. Moving by lerp is choosing a new point at a fixed rate and using Update to move from the previous point to this point.
you can achieve the same effect with both, but you start to lean more towards lerp the more physics the rest of your game uses (because physics runs at a fixed rate)
So in general, the fixedupdate loop should be used for physics CALCULATIONS but not the actual movements? FixedUpdate should set the target and update should lerp towards the target?
yeah. fixed update = make the decisions
update = the stuff in between
also collect input in update
Ah - my confusion was I saw a lot of people putting the .Move(delta) in the FixedUpdate
which I guess is inproper?
the whole charactercontroller makes things confusing
A lot less confusing than making a character controller out of a rigidbody though
not if you understand the update loops. imo charactercontroller is just a way of getting it done without needing to understand
Well my understanding is the character controller's move function basically handles movement, collisions, and slidealongwall
character control is not a trivial thing and deserves a lot of attention in games.
I know - I'm coming from Unreal Engine where I was studying the character movement component that is like 30k lines of code
But I had a lot of issues with UE4's debugging process
using delta time in your calculation is a way to decouple it from the framerate but the easy mistake to make there is not multiplying it by another constant as well.
My movement code works pretty well - I'm mostly having trouble getting a smooth camera. Wasn't using lerping but it still seemed fairly smooth. Will have trouble when I add impulses in the future though
https://textuploader.com/1enak
private void ApplyInputToVelocity()
{
Vector2 velocity2D = new Vector2(m_Velocity.x, m_Velocity.z);
...
if your camera needs to follow something, make it a child of that object. if it moves smoothly so does the cam.
if you also need to reposition the camera then move it's local position at the same time as it's parent's world position
looks like you covered all the bases in that code 👍
It's a first person camera but for whatever reason when I use the mouse as the input it is really stuttery but if I use up/down/left/right on the keyboard or a controller it's really smooth. Something to do with the mouse taking in deltapixels vs the keyboard being 0 or 1 i guess
Also check cinemachine cameras, they can do a lot for you
This is the stuttering I'm getting
https://streamable.com/21s6pl
Starting to wonder if maybe that's just how mouse movements are (not smooth) and games just smooth it out artificially for you?
Lerp translations and Slerp rotations for smoothy-smoothy
One other thing I don't understand about the FixedUpdate - if I multiply my acceleration by deltaTime it shouldn't matter whether deltaTime is fixed or not. I should be moving at a constant speed regardless of my framerate. Are we sure fixedupdate isn't more for performance reasons than this whole "fixed rate" thing?
I know UE4 does not have a FixedUpdate loop - just the regular update loop which may be because it is designed to be run on PC/Console more than Unity
also from my understanding, fixedupdate does not actually have a fixed real deltatime - that's impossible
fixedDeltaTime will return the frame rate of the physics simulation
Right, which from what I understand will not always be .02, it will be as close to .02 as it can get
(assuming you're using .02 as default)
yeah I guess the engine will at least try its best
Update() depends on your hardware max capabilities
So, other than performance reasons, what exactly is the benefit of using FixedUpdate(). If your code is written correctly, you'll adjust for time.deltaTime regardless of which code block its in
Or is it just that Unity doens't run its physics calculations on Update() strictly for performance reasons which would make sense
but why then does the documentation talk about how its frame rate independent which doesn't seem to be true
If you work with a rigidbody, you should update relevant code in FixedUpdate
I'm using charactercontroller
If you move yourself the transform, go ahead in Update()
but still do it as a factor of Time.deltaTime
oh you mean character controller from Unity ?
Don't even remember if it uses rigidbody or not :p
Right - it's just contrary to what I'm seeing on forums everywhere which might be because everyone seems to use rigidbody's for their character controller which si weird
From what I understand the character controller has its own implementation of collision detection - it doesn't really simulate physics it just has a function that checks for collision when you try to move and responds accordingly
Gravity and momentum for instance are not implemented which makes sense for a character controller since you dont want your player to bounce off objects (unless you do, but then you probably want to code it yourself so you have more control)
note that you can have both, let's say compute movement vector from input/gamepad in Update(), but applying the vector on rigidbody only when FixedUpdate()
Every controller ends up different
Yea - I'm just of the mind that you should not use rigidbody at all for your player character. Maybe in some games but if you were making like a 3D FPS game or something it doesn't seem to be the way to go
yeah sure in this case a simple capsule is enough 🙂
As I said, I do come from UE4 and the whole rigidbody based character controller is really strange to me
Maybe people just keep the first think they found and tried and that worked
How do Agents react to physics in UE4 ?
Well for non-character objects its mostly the same. But almost no one enables physics on their character controllers, they use capsule based movement controls and code the physics
Its not that Unity and UE4 are capable of doing different things, it's that the community in UE4 would consider rigidbody controllers to be really weird and people here at Unity seem to think capsule controllers are weird
The whole rigidbody thing was weird for me too at the beginning
It is definitely not the most common among AAA titles from what I see.
Things actually got a lot smoother after I moved everything to Update() and removed all my fixedupdate code. I'm thinking you just shouldn't use fixedupdate if you're making character controllers for pc/console - if you really need to slow it down it's probably better to write your own code to make your movements trigger every fraction of a second rather than change the default .02 value for physics updates.
I'm still having a problem with the mouse giving me clunky movement but this only occurs with a mouse and not the controller which makes me think there's something weird going on with the inputs
Well FixedUpdate is still useful. Gives you constant interval between simulation steps. So for everything related to the physics it's where you want to be.
for your mouse movement feel free to share a glimpse of code, people here will help if htey can
I think the reason we use FixedUpdate when we're calculating movements for rigidbodies is because the rigidbody physics code all executes inside fixedupdate. In the context of character controller (no rigidbody), there is no physics calculations being performed in either the fixedupdate or update. So you don't need to worry about your code being in sync with the physics calculation code
CameraPhysics.cs
{
if (m_FirstPerson)
{
Vector3 euler = m_Camera.transform.localRotation.eulerAngles;
euler.x -= m_InputTheta * m_1stCameraSpeed * Time.deltaTime;
// If our rotation is above '0'/'360' (same thing), decrease by 360f to make negative version
if (euler.x > 180f)
euler.x = Mathf.Clamp(euler.x -= 360f, m_1stMinThetaAngle, m_1stMaxThetaAngle);
else
euler.x = Mathf.Clamp(euler.x, m_1stMinThetaAngle, m_1stMaxThetaAngle);
euler.y += m_InputPhi * m_1stCameraSpeed * Time.deltaTime;
m_Camera.transform.localRotation = Quaternion.Euler(euler);
}
else // if third person...
{
}
ClearInputs();```
InputFunctions.cs
{
m_CameraPhysics.RotateCamera(m_CameraInput.y, m_CameraInput.x);```
``` void OnLook(InputValue value)
{
float phi = value.Get<Vector2>().x;
float theta = value.Get<Vector2>().y;
m_CameraInput = new Vector2(phi, theta);
}```
Alright another Unity trick
If your camera follows your player, you can put it in LateUpdate(), so you can be sure it's executed after player movement
That makes sense
This can be the source of jittering, or maybe not 🙂
Didnt fix the issue on my cameraphysics, thinking about whether it would actually make any difference if I did that in my inputfunctions as well (I wouldnt think so)
What I find really bizzare is this is only happening with my mouse. It does not happen with a controller of if I bind it to up/down/left/right on the keyboard
how do you read your input theta and phi
void OnLook(InputValue value)
{
float phi = value.Get<Vector2>().x;
float theta = value.Get<Vector2>().y;
m_CameraInput = new Vector2(phi, theta);
}
this should be broadcast when it detects new values for Mouse<Delta>. I am unsure of whether it only checks for new inputs once a frame but I would think so
It uses the input system package
forgot this code block
Cameraphysics.cs
{
m_InputTheta += theta;
m_InputPhi += phi;
}
Oh it's the new InputSystem package ? Didnt use it yet. I'm still on the Input.GetAxis way
Maybe someone else here will be able to answer, or try #🖱️┃input-system
Yea I was there first but then I thought I may have had a physics problem so I came here but now I'm thinking it is actually an input-system problem
Yup
Hey Guys so I have a ragdoll script which turns my player into a ragdoll when I press U, but when the player is moving and I press U he just stops and falls down instead of tripping is there, does anyone know how I can fix this?
@dim kiln you probably wanna set the rigidbodies of ragdoll limbs
this code has nothing on ragdoll limbs
@supple sparrow Thank you! Your reply made sense, I ended up doing what you had suggested with calculating the angel of the impacting surface and then creating a new heading based off of that and I have it working now. 😄
Great :)
i dont know if its right doing right here
Hello guys, i have some problem with trajectory prediction.
Well, i need to predict/calculate perfect velocity for ball to hit exact on target.
So math is pretty basic, trivial physics equations. So It works perfect with Fixed timestep tending to zero, but with 0.02 there is very noticeable imprecision.
Well, although equations are good, and trajectory renders excellent, when i play simulations the actual trajectory differs a little, but with longshot, this imprecisions caused by fixed timestep stacks giving in result projectile missing target.
My question is, do you have any idea, how to take the physics timestep into account in my equations?
I found similar post in google with screenshot that show my problem so i am going to copy paste it here.
Small Unity physics riddle...at least for me:
Why does this do what I expect (rotate the player around the Y-axis):
player.Rigidbody.AddTorque(player.transform.up * speed)
But this does not rotate the player around his forward axis, but instead just
moves him to the left or right:
player.Rigidbody.AddTorque(player.transform.forward * speed)
Also tried it with AddRelativeToque but same effect.
Hey guys, I have some issues with some box rigid bodies stacked like bricks when the scene starts. They push eachother at the start and become very unstable. I already tried tweaking the physics material which didn't help. Now I'm trying to get them to sleep when they instantiate but it seems like forces are being applied anyway. Does anyone know what I'm doing wrong?
I'm assuming it should not be done in Start?
Did you try increasing simulation steps in the settings ?
Also, do you compute the equation on Update() or FixedUpdate() ?
@supple sparrow Hey, thanks for interest. Do u mean Maximum Allowed Timestep?
Its physics so FixedUpdate
Ok, I would try to do the calculations on Update() though, and use FixedUpdate() only to apply the results
Edit > Project Settings to mess with interval
The thing is, I dont kinda understand what do u mean by equations compute.
I use some basic mah to calculate initial velocity, and then i just set rigidbody.velocity and it differs from expectations
how to take the physics timestep into account in my equations?
You meanTime.fixedDeltaTime?
and when fixedTimestep is like 0.0001
It matches expected trajectory, but when its standard 0.02 it fidders like on picture
differs*
I mean I would do the math in Update() and apply velocity to rigidbody in FixedUpdate()
thats what i am doing
Alright then go to Edit > Project Settings, you can reduce time steps interval
you might get a performance hit though
Yea. thats the thing. and this is mobile game + trajectory simulation iterations would fly to the sky
so i must stick to 0.02 but take it to account somewhere, but dunno how
Time.fixedDeltaTime ?
yup. this must stay on 0.02
can you show equation for the parabola ?
sure
this calculates launch velocity
and parabola points are gatheres from PhysicsScene simulation
here
So when you hardcode physics.Simulate( withAVeryLittleNumber ) it works as expected ?
Yea Exactly
But gives poor performance ?
Also true
Maybe Physics.Simulate is not suited for mobile ? Real question here, I don't know the answer
hmm, suited or not (well it works fine on Redmi 8) in editor problem is the same
So i maybe better question would be :
How to bypass imprecision of FixedTimeStep grater than InfiniteSmallNumber
Becouse in real life it would probably be infinite small number or 0 and equations relates to reality 🙂
Do you sync the simulation with the framerate like the official example ?
https://docs.unity3d.com/ScriptReference/Physics.Simulate.html
No but thats not the point, as whole simulation gets done within one framerate
(or on call, yea there is coroutine to optimize it a bit and get drawing effect, but still its not about replacing physics, but simulating it on call)
Then I have no idea. Would have to spend the time to try it myself.