#⚛️┃physics
1 messages · Page 25 of 1
i mean its reason for existence is determinism, so in that regard its a yes, but only you can know what potentially 'weird' requirements you have. (i certainly haven't tried to find the limits of its determinism)
I think "yes" is the answer, but I'm not sure what a "half-yes" with respect to potentially weird requirements could look like. I'm skeptical that I can or can't rely on it at the moment, but I could be worried about nothing.
i just used blender to make a destructable wall prefab, why arent the mesh colliders colliding with anything? im fairly new to unity
have you looked at your console?
you should pretty much never have the console window hidden
there are important messages and errors there
what convex do in mesh collider?
creates a convex hull as the collider shape instead of using the actual mesh
To to prevent the chain from breaking ? Since i added mass to the Balls the chain fall's apart. How to i prevent that, but keeping the Mass on the rb.
The Picture above is the chain. the picture below is one of the two players.
And that my whole movement script
public class PlayerMovementSystem : MonoBehaviour
{
Rigidbody2D _rigidbody;
Vector2 _moveInput;
[SerializeField] private int speed;
private void Awake()
{
_rigidbody = GetComponent<Rigidbody2D>();
}
private void Update()
{
_rigidbody.AddForce(_moveInput* speed);
}
public void ReadMoveInput(InputAction.CallbackContext context)
{
_moveInput = context.ReadValue<Vector2>();
}
```` I also tried rb.velocity but it had the same result of breaking the chain
okay fixed it for now by using more damping
why does unity's physics cost skyrocket on instantiation, but falls off after a little while? For context, I'm testing out instantiating 1500 moving rigidbody objects at the same time at the start of the screenshot
My question is why the physics portion takes up so much during the initialization, is this part of Rigidbody's initialization?
My guess is that the rigidbodies fall asleep after a short while, no longer taking as much resources
You can see more info at the Physics module https://docs.unity3d.com/Manual/ProfilerPhysics.html
Thank you!
Hi! Im currently trying to make like a sideways wheel of fortune. I want to have a pointer that goes left or right incase it lands in between two pieces. However im not quite sure how to make this. Currently using a hinge with a rigidbody, but i feel like this is too buggy and wont work. Anyone have any advice on what to do?
For a brick breaker projectile (3d), not using full physics I’m just using the rigidbody as kinematic, as a trigger, with continuous speculative detection but I’m still occasionally having some penetrations on my enemies at higher speeds. Not at my pc to test but is it continuous dynamic I want?
This setup relies on penetrations
you will always have penetration
at any speed
triggers don't trigger until the objects are overlapping
When you want probably is to be using BoxCast in FixedUpdate to simulate the movement and detect the collisions before they happen
I mean it’s sometimes just straight going through enemies
yes you will get tunneling
the collision detection methods are meaningless for triggers
they don't apply at all
Ah
I recommend using BoxCast
Is that viable if the enemies can move in some cases?
what's an enemy?
Box collider. Or is there an example of what you’re suggesting?
Well brickbreaker doens't really have enemies
yeah they have blocks that don't move
It's still viable
are they moving quickly?
You could also just use a dynamic rigidbody for the ball and kinemetic bodies with MovePosition for the enemies and use OnCollisionEnter
It’s brick breaker mechanics but with enemies shooting back. Some are supposed to move a bit
Well, I was using collisions but I kept running into this problem where things were sort of nudging each other around. I didn’t want to use the true physics stuff, just the collision detection essentially
if the enemies are kinematic there will be no nudging
The projectiles are Y axis locked and only move on X/Z. The impact looks at the difference in position between the projectile and enemy and determine which direction to deflect it in. It’s curated (currently) in the OnTriggerEnter
and for the player balls you can just modify the exit position/velocity in OnCollisionEnter to get the perfect reflections etc you want
So for the most part it works fine 99% of the time but I found there’s occasional quirks
Like tunneling
Hm. Yeah I guess I’m just having to consider if I should do my own minimal “physics” system or what. I don’t really need it to do more than say “did the ball hit a boundary or enemy” and then redirect it in the opposite direction but same velocity
Of course there’s some mechanics I’m gonna add that can add some variance to the deflection angle but it’s not meant to use any true physics
You’re making me think I should just use casts here instead of the physics components
just doing the boxCast in FixedUpdate from the previous position to the current position should be fine
and casts are not a replacement for physics components. They don't work without colliders
Yeah that’s fine, I just mean using rigidbody at all
There’s also a quirk that the collision calculations are not consistent. Launching the projectile at the same position, angle, and velocity produces some very inconsistent paths
I think at a high level it’d be preferable if it’s consistent so players can reproduce results with good grasp of the mechanics
that's why I'm saying to use Vector3.Reflect
I am. I mean it seems like the collision points are not always the same
But yeah I’ll try some new approach
you mean with your current trigger setup?
Yeah because it's going to be overlapping to varying degrees
and it's not clear how you're actually handling getting the collision points
since OnTriggerEnter doesn't give you any
Yeah that tracks. It’s just a position comparison, and taking whichever axis has the largest difference in it. If it’s X it’ll pick a flat X normal, if it’s the Z it picks a flat Z normal
for the reflect. That part works fine it’s just not consistent due to the timing error of triggers as you said
I think with a box cast I can preemptively detect a collision and tell it to fire from that point on the next frame
Hey what’s the diff between sphere cast and box cast in this case? Is box cast more ideal to use for impacting box colliders? Or should I be using the cast type that matches the bullet’s collider?
It's the shape of the cast itself
Boxcast casts a box through the scene
SphereCast casts a sphere
It should match the bullet yes
Yeah got that part. Makes sense
I’m assuming I want to do the casts in fixedupdate
Wonder if I could just have it cast once, determine the point at which it’s due to collide and check in update when it hits or passes that position (usually x or z axis only). Probably have an event when an enemy dies or moves to recast all projectiles
Cuz otherwise the colliders wouldn’t move in most cases. Only an enemy dying would change the trajectory
Also anytime the angle, direction, or velocity changes do a cast update
You would do everything in FixedUpdate basically
You would cast every frame either from the current position to where it will go next FixedUpdate, or from the previous position to where it is now
The distance would be rb.velocity * Time.fixedDeltaTime
I "love" trying to add a dash to my rigidbody movement code
btw here is the code for the movement
my character's arm keeps staying in place while the rest of the body moves away
i checked freeze position x y on the dynamic RB2D
So I add targets to a dictionary via onTriggerEnter2D and remove them via onTriggerExit2D. I've observed that disabling the collider also triggers onTriggerExit2D on the line instantly,
// My targets are stored in _crosshairTargetPair, and are removed from them when onTriggerEXIT2D
_collider2D.enabled = false; // This triggers onTriggerExit2D
_crosshairTargetPair.Clear(); // on this line, all my targets are removed due to onTriggerExit2D
so I was wondering if disabling collider2D automatically calls onTriggerExit2D to all overlapping targets? Because if not I couldn't get an explanation as to why this removal would be instant!
I assumed it would trigger next frame like how animations only start playing on the next frame when you call
animator.Play(nameOfAnimation, 0f, 0f); // from what I've observed, the playing of said animation only starts the next frame
Is this correct?
I didn't think disabling the trigger called ontriggerexit
Unless that's a new behavior
I tested it and I thought it was the only explanation in my case
used the debugger and everything
I guess I'd have to test. I know it doesn't work that way in 3D
But it wouldn't be the first time there's a difference
surprising behaviour not going to lie
after you suggested it I searched and found this https://issuetracker.unity3d.com/issues/ontriggerexit2d-is-called-after-exiting-play-mode-when-trigger-colliders-overlap
How to reproduce: 1. Open the user’s attached “TriggerBug.zip” project 2. Open the "SampleScene" Scene (Assets > Scenes) 3. Enter...
and someone even commented the same thing as you did!
Oh nice
but they never got a response back from unity
Thanks!
Hello, can semeone help me ?
I am making a 2d game (platformer, gamerage), and the collision works very well in the editor, but when I build and Ran the projet some of the collisions dont work
hey is this channel only used for unity rigidbody physics and colliders or can i ask about my own physics calculation?
If it is for a unity project, feel free, definitely the best fitting channel
ok thanks!
i want to make a player controller and he does move, but dont think i calculate the velocity correctly.
Vector3 CurrentSpeed = new Vector3(rb.linearVelocityX, 0, 0);
Vector3 TargetSpeed = new Vector3(playerControls.Player.Move.ReadValue<Vector2>().x * Speed * 100, 0, 0);
rb.linearVelocityX = Vector3.Slerp(CurrentSpeed, TargetSpeed, GroundAcceleration).x * Time.deltaTime;```
this is the code i used for it.
One thing that I'm seeing immediately is that you are using Vector3s everywhere and only ever using the x axis. The code would be easier to read if it used floats in place of Vector3 and Mathf.Lerp instead of Slerp. When it comes to the code validity, I don't see anything immediately wrong there. One slight issue there is the way you are using lerp smoothing which isn't framerate independent when used in this way. If this is all done in fixedUpdate (as it should), that isn't too big of a problem unless you change the physics timestep. Whether you want this type of smoothing is also up to you, there's many ways to implement smoothing and they may end up feeling very different in the end
thanks i didnt know that! i put it in FixedUpdate now and also i gave my code to chatgpt to see if the formula was right. i did a lot wrong calculating it but this is the code i ended up with now:
public void Move()
{
float Speed;
if(playerControls.Player.Sprint.IsPressed())
Speed = RunningSpeed;
else if(playerControls.Player.Crouch.IsPressed())
Speed = CrouchSpeed;
else
Speed = WalkingSpeed;
Vector3 CurrentSpeed = new Vector3(rb.linearVelocityX, 0, 0);
Vector3 TargetSpeed = new Vector3(playerControls.Player.Move.ReadValue<Vector2>().x * Speed, 0, 0);
if(playerControls.Player.Move.IsPressed())
rb.linearVelocityX = Vector3.Lerp(CurrentSpeed, TargetSpeed, GroundAcceleration * Time.deltaTime).x;
else
{
rb.linearVelocityX = Vector3.Lerp(CurrentSpeed, TargetSpeed, GroundDeceleration * Time.deltaTime).x;
}
}```
thanks for helping!
Idk why but I just ended up trying to use the normal collision logic, somehow moving the projectile’s movement resolution to FixedUpdate and using MovePosition on RB and now it’s 100% consistent. Bullet travels the exact same path even with rapid speed and rapid collisions. Easier solve than I had hoped
Hello, can semeone help me ?
I am making a 2d game (platformer, gamerage), and the collision works very well in the editor, but when I build and Ran the projet some of the collisions dont work
Wdym by them not working?
You'd have to show details about your game such as how everything is set up and moving
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Okay, first my player got an rigidbody2D and a bloc collider2D, if you need to see the parameters, tell me), to continue, all of my tiles, got a 2D tilemap collider. On the unity editor, the collision work well, but when I build the game, some collision dont work animore.
here is the script of my player movement.
https://scriptbin.xyz/tefakavacu.cs
Use Scriptbin to share your code with others quickly and easily.
BoxCollider2D you mean?
And can you explain in more detail what you mean by collision not working?
What are you expecting to happen and what is happening instead?
yes
I expect that the tilemap whit a tilemap collider 2d block the player from passing it, but instead, the player can pass trought, but only when the game is build, not in the editor
Shouldn't be any difference with this code.
Is your collision detection set to continuous?
yes
my question didnt get answered
my character's arm is coming apart
it doesnt rotate when kinematic and when dynamic it comes apart from the body
where to start if i want to drag and drop 2D objects BUT: it needs to collide while being dragged. prevent from passing thru walls
if i used kinematic body I could have full control on one hand but would need to handle all collisions by my self i guess...
dynamic on other hand already deal with collisions but i have no idea how to prevent it from passing thru walls... i would need to have some max velocity ... i imagine it could work fine that way since it doesn't have to perfectly follow cursor but rather try to move towards it
You can use a dynamic body and control it with AddForce or by setting velocity.
I think that in 2D, MovePosition also respects collisions.
You probably want to set the Rigidbody's collision detection mode to Continuous too, to avoid clipping through things at high speeds.
The kinematic + custom collision detection is not a bad idea either, you could use physics queries (casts) to check for obstructions when moving. Rigidbody2D.Cast, for example
I've recently come to the conclusion that most hack and slash games seem to using kinematic rigidbodies, and was wondering if there was any truth to this guess?
almost all games that offer a great feel use a kinematic rigidbody. those that don't have spent an absurd amount of time coercing a force simulated rigidbody into submission (and probably would not do it again).
I previously had a hard time reconciling how kinematic rigidbodies would work with root motion, any thoughts?
thats a weird question, if anything a force simulated one would not work with root motion. Also root motion is one of those things that often don't work out in practice. Say if you have any kind of AI, rootmotion is a nightmare to get working. It also requires you to have an animation for anything your character can do and any kind of mismatch immediately looks janky.
Thanks for answering!
Does constant spawning and despawning trigger colliders cost a lot of performance? I'm working on pickups system and i wonder how i should approach it. If a collider doesn't have a rigidbody then it's automatically a static one, and static objects are expensive when moved (i guess spawning or despawning may also count as moving). Does adding a kinematic rigidbody by default to such constantly spawned objects make calculations less expensive in some way (since they are treated as dynamic)?
Use object pooling
Also use the profiler
whenever you have a question about performance, use the profiler
If instantiating would be the problem i can implement pooling. My question is more about how physics are calculated when a new static object gets enabled / instantiated.
This is related to VR, but this channel is likely to know.
What is the principle behind good object physics in VR games? Clearly, it is not what I'm doing now.
public class GrabInteractable : MonoBehaviour, IInteractable {
. . .
protected void Awake() {
if (grabSound.Guid.IsNull) { grabSound = EventReference.Find("event:/Foley"); }
if(!rb) { rb = root ? root.GetComponent<Rigidbody>() : GetComponent<Rigidbody>(); }
if (!grabPoint) { grabPoint = transform; }
if (!root) { root = transform; }
}
public virtual void OnHold() {
onHold?.Invoke();
Vector3 targetPosition = Hand.position;
Quaternion targetRotation = Hand.rotation;
if (!doSnapping) {
targetPosition += Hand.rotation * grabPoint.localPosition;
targetRotation *= Quaternion.Inverse(root.rotation) * grabPoint.rotation;
}
if (Interactor.other.held != null && Interactor.other.held is GrabInteractable s && s.transform.root == transform.root) {
Vector3 handsDirection = (s.Hand.position - Hand.position);
targetRotation = Quaternion.LookRotation(handsDirection, Vector3.up);
}
rb.linearVelocity = (targetPosition + transform.rotation * extraPos - grabPoint.position) / Time.fixedDeltaTime;
(targetRotation * Quaternion.Euler(extraRot) * Quaternion.Inverse(grabPoint.rotation)).ToAngleAxis(out float angle, out Vector3 axis);
rb.angularVelocity = angle * Mathf.Deg2Rad * axis.normalized / Time.fixedDeltaTime;
}
}```
The object jitters a lot when my player moves, and the collisions themselves aren't particularly good.
Basic question first, do you have interpolation enabled on the RB's?
A video of the issue would help
Also how's your hierarchy? Are the RB's children of anything?
Generally you don't want to make them children of a moving object
No parenting used, no.
the principle is that your hands are the only actual physical object in the game, and that is very awkward.
What do you mean? @timid dove
Also pretty sure angularVelocity is not in radians
So i don't think Mathf.Deg2Rad makes sense in there
It is radians per second
Yeh
First, the subtle disconnect between the hand and gun. The overall wobblyness
Second, that awful jitter when moving.
Here is basically the exact system I am trying to replicate
Many VR games nowdays have object physics, even if they're not overtly physics based games (A strong connection between the controller and object is needed, unlike say boneworks where a disconnect due to weight is normal)
So the object has to look kinematic, but can't be
When is OnHold called?
I see similiar "disconnect" in this second video too. I think you just need to tweak the forces/add some damping
That is absolutely minimal. Welcome, even. It provides some smoothing for the weapon.
What it doesn't do, is wobble.
Mine wobbles
So yeah you need to damp it
Adjust the forces so that it does not overshoot but is snappy
I'd move that into FixedUpdate, yeah
Could be yeah, or it could be a physics joint, hard to tell
Same outcome really
A joint might be worth trying out too. Configurable joint lets you configure everything that any joint type has
Expect lots of trial and error though
I doubt it's a physics joint
I played that game for a while. It doesn't freak out the way a physics joint does.
Hey guys I was looking at the photon fusion FPS sample, One weakness of mine is probably unity physics so I might as well write a question here, The player object has a rigidbody which is set to IsKinematic, and user can not walk through walls etc, if the collider is disabled, it falls through the ground. How can i replicate this sort of environment. Currently my user can walk through walls regardless of if isKinematic is set or not. And doesn't fall through the ground If collider is disabled. Would help answer a couple of questions for me. Because I thought is kinematic needs to be disabled to actually detect collision like not walk through things
as far as i remember and understand there is kinematic player controller or something akin. it handles manual ground check and stuff like that.
kinemtic rigid body is like unstapable object of infinite mass. you gain more controll but lose predefined physic simulation behaviour. it still can detect collisions but you have to handle them by your self.
also you dont apply force to it. just use MovePosition on rb. if u want to pass velocity than you need to do somethink like rb.MovePosition(rb.position + v * Time.fixedDeltaTime)
I'm trying to make a vehicle that has 3 rigidbodies, the wheel objects connect to the main body with a hinge joint. I set motorTorque in the front wheels, which id expect to move the entire vehicle, but instead it gets stuck in place and the front wheels look really jerky
Hmm, not sure if joints are designed to work nicely with wheel colliders, but I would hope so
First thing i was gonna suggest is to change the mass scale/connected mass scale, but it doesn't seem to be exposed in HingeJoint
ConfigurableJoint has it though (and a bunch of other stuff)
how do i make tank
Zero effort question
like this
How good are you at vector math?
thats what im suspecting, but if I was to do something like truck and trailer, both of those would use wheel colliders and presumably a hinge joint to attach them
Yeah that's the logical way of doing it, just pointing out that there might be some quirks about it
Any child/parent relations involved here?
nope, the 3 bodies share the same parent
And the parent doesn't have a rigidbody and isn't otherwise moving?
Just makin' sure
it doesnt, the parent only has the vehicle controller component
I have found setting the main bodies mass to 1, allows the whole thing to move, but all its wheels are very jittery
Might wanna crank up the solver and/or velocity iterations in the physics settings
And/or a lower fixed timestep
The default settings lean more towards performance than stability
These can be adjusted per-rigidbody too
The hinge might be too stiff in a sense, since it only rotates on 1 axis
Some leeway on the other axes could help, but that would probably require a ConfigurableJoint
I'll get the simulation settings to be higher quality, though im wondering if the way im doing it is just naive and there's a better way, especially as I think the joints+wheels is causing issues. I noticed that I can cause the wheels to stop colliding with the ground when the main body intersects with the wheels body
It's always an option to implement your own wheels instead of using the builtin ones
I feel like WheelCollider has some jank to it
(Or use an asset)
it does feel like it provides far too many features that I have no real need for
makes sense as its intended to be a physically accurate wheel, so things like sideways slipping cant be disabled, instead the best fix is to increase those properties to reduce the effect
im not fond of using very large or very tiny values to stop something from happening
I wouldn't know really, haven't used any
I know there are decent vehicle assets (edy's?) so maybe those have something for custom wheels
the idea of purchasing a wheel asset, only to find it doesnt work the way I'd need, makes me hesitant
I understand that
I'll see if I can see anything where somebody makes a truck+trailer that both use wheels and a hinge joint
mine isnt any different than a trailer with two trucks on either side
personally, I'd fake the effect (simulating tank treads will be a lot of headache). I'd just make a spline that follows the shape of the treads, then deform all the points on the underside of the spline to match the shape of the ground
we are in physics channel
i want it simulated
take a spline that matches the tread shape, the splines package has EvaluatePosition which you can use to follow the path of the spline. If you evenly spaced positions along the spline, you can select two that are next to each other ([i] and [i+1]), those two positions tells you the length of that piece of chain
in theory you could create a rigidbody for every piece of chain, give it a box collider that has the correct size for that length of chain. Then for every chain create a hinge joint that attaches that chain body, to the body of the next chain body
make sure that the last length of chain loops back to connecting to the first chain
bear in mind its just the first thing thats come to mind for this, having written a rope simulation in the past, it can become very unstable and janky unless you crank the solver substeps up
im also not really sure how well it'll work when you need both sets of treads to be a child of the tank body (which I assume would itself be a rigidbody). Then there's a matter of getting the treads to be moved forwards as you drive, that image shows them using a gear mechanism to physically move the treads around, which sounds like a gigantic headache to get it working
All this just to create debris when the tank dies is waay overkill
Yeah - I was about to link there
in that case, just use a non physics tread during gameplay, upon death, spawn like 200 individual treads
easy
I have a kinematic character controller, but physics based objects in VR. This causes a really bad jitter when moving. How do I reconcile that?
investigate whether any of the involved transforms are updated in FixedUpdate while others are updated in regular Update and whether that may give rise to positions jumping back and forth.
uh, yeah?
The rigidbody, and the charactercontroller
But I can't just put the CC into fixedupdate to match it, because movement at 50 hz looks pretty shit.
jitter looks worse... also you can decouple and smooth the camera into the regular Update. Just need to implement it correctly.
2D game: how to simulate a bungee like line? just a spring joint will not work since it needs to be build out of connected fragments so it can collide with environment. what i want to archive is: one end of line is anchored to specific point in world space. i can control other end. there is limited stretch distance it can archive and when i release it it should try to get back to its origin. it would be best if i could control how fast it return. fragments the, self are on layer that dont collide with object on their own layer but collide with everything else.
a bunch of small rigidbodies connected by spring joints
basically follow any tutorial for a rope or chain but replace the hinge joints with springs
tried that. tried many configurations but it usually went crazy very easily... but i guess its kinda on right track? just need to add some other joints for better constraints. yet its still hard to get it right... for now no luck yet
Might wanna try tweaking the Physics2D settings for better physics accuracy
Like these
What if I just made physics update at frame rate?
I wonder how H3VR does this. The character is kinematic, but objects are physical
Yet the camera, and weapon, is perfectly smooth
not possible.
physics needs a stable update delta
Well it's possible - just not recommended. Because using a non-fixed timestep for your physics means you will get inconsistent behavior
like different jump heights etc
potato potato
so i feel like i am almost there... i used both spring and distance joints... although i still have some issues. it brakes if any element have mass other than minimal (I can ignore for now since i dont think i will do anything mass related) and if anchored end is mid air (will often happen in game) it spins insanely after retraction even though spring dumping is at max.
Well... It is after all a double or triple or octuple pendulum
A mechanism famous for being chaotic
I read about implementing slowmotion bullets and someone wanted it to be smoother; it was suggested that he change the bullets' rigidbody to interpolate; I was wondering if is advised against changing the interpolation property on rigidbodies during runtime?
Will there be any problems by changing the interpolation property at runtime?
It's not a problem at all but I wonder why you don't just always interpolate them?
I read on the forums that interpolating everything would've caused performance issues (I know the old saying goes don't pre-optimize and always profile, but I was curious) especially since the object in question is a bullet
I have some major issue with my game. In the video clip below, the car is drifting around relatively well. But the issue is that the RPM isnt spinning wheels according. When the car spins out, you can see that throttle is applied (1) rpm is at 1000. and wheels spin slowly. I am not sure what to do. When dirfting the car is driving fast, but the rpm is not high and wheels arent spinning to fast either.
Isn't that just what cameras do when the framerate somewhat matches (a multiple of) the RPM?
At certain speeds it can look like it's spinning backwards, even
Or are you talking about something else?
is there a way to get a cloth object to detect collision from prefabs with capsule colliders?
I can't seem to get it working
does Unity not support prefab collision detection for cloths?
Wdym by prefabs here?
You need to manually set the capsule colliders for the Cloth component for it to collide with them
so, the cloth component has a list of objects like this right?
I dragged in a prefab with a capsule collider
but it doesn't detect it when I put an instance of the prefab onto the scene
Doesn't quite work like that
The prefab reference won't automatically turn into an instance reference when you instantiate the prefab
You'd need to set it with a script if you need to change it at runtime
I see, I'm assuming you can modify that colliders list right?
If the cloth is part of the same prefab though, then the reference will stay linked
alright thanks
hello, having a bit of trouble with this specific interpretation of physics. i need a capsule collider with a circle bottem. the problem from ONLY a capsul collider comes when chopping my tree.
2d colliders cannot work in 3d, what can emulate a circle in 3d? I can use a convex mesh collider on a cylinder gameobject, but that seems way more performance intensive no?
If you want a cylinder use a cylinder
use a cylinder convex mesh collider? Is there any way to "cheat" it for more performance gains?
i need to have the ability for it to roll, while not intersecting with the stump it hits as it's falling. so box collider doesnt really work for this interpretation If i'm asking a stupid question please lmk and ill figure it out myself.
What makes you think the cylinder is going to be a problem?
You're prematurely optimizing
i was taught during learning gamedev to almost never use mesh colliders. but your right, a single cylinder, only used during 1 "animation" wont have a impact on the game
Anybody know how to achieve this lol? How to calculate the force and angle needed to hit an object (the player) and go high enough to hit the max height line?
Kinda like a mortar, but I want the projectile to always go a certain height that I specify, no matter the angle or how close or far the player is.
well - first you take this:
https://math.stackexchange.com/questions/785375/calculate-initial-velocity-to-reach-height-y
to calculate the initial y velocity you want. Call it yVel
Then you plug that into the "Time of flight" formula: in the table here: https://www.sciencefacts.net/projectile-motion.html except instead of where it says v0 * sin(theta) you replace that with the initial y velocity from the first step. That will tell you how long the thing will be in the air. Let's call that timeInAir
Then since you know how long the flight will be, and you know how far your target is horizontally you can just use the basic distance = rate * time equation to calculate the initial x velocity you need. In this case we have the distance and the time, and we want the rate, so algebraically we turn that into:
r = d / t or in this case xVel = horizontalDistance / timeInAir
So then you have your initial horizontal and vertical velocities you need. From there you can just set that as your object's velocity directly:
rb.velocity = new Vector2(xVel, yVel);
I'll give it a go and let you know, thanks so much!
All of this assumes these objects start at the same height
if they don't there are some changes to make
what do you mean? because yea I believe they will be at different heights.
well then that adds two complications
one is that the time of flight formula needs to be adjusted because it's assuming coming back down tot he same height
two is that it's not clear how the "desired height" is defined anymore
is it a certain height above the shooter, or the target?
because those will be different
the desired height would be something like (ShooterPosition + "desired height" added to the Y position)
and the desired height should be able to be changed right?
wdym by it should be able to be changed?
Also there's a third complication as well - if the target height is above the desired height then it is not possible to hit the target at all.
these formulas should support any height?
this is intended
well how can this be fixed?
well it's going to become a quadratic formula, for one, and that formula is going to have two solutions
one as the projectile is rising, the second as it's falling
we want the one as it's falling of course
I did get this from ChatGPT but it looks correct to me
and again where it has v0 * sin(theta) we just plug in the initial y velocity again.
Okay sorry if I'm asking alot of questions lol but how do I convert these hieroglyphs into code lol?, especially the initial y vel one.
what do you mean by hieroglyphs
As I just explained you replace sin(θ) with the initial y velocity
Remember we got that from the first step here - based on your desired max height
Yea uhm, what is this? How do I turn this into code.
square root of 2 times g times y
It's not complex
and Y is the desired height?
is to me 🤷♂️
yes
you're overthinking it
you just plug the numbers into the appropriate syumbol in the formula
bit slow on this but I'm getting there... I think which equation am I supposed to do 1st 2nd or 3rd?
the second and third are actually the same technically - just "rearranged"
the third one will be easiest to translate to code
where it has the +/- sign it actually means you should do the entire calculation twice. Once with a + and once with a -
then compare those two results and take the larger one
since that will be the "descending" part of the arc, which is what we care about
okay cool
a couple more pointers (bro I've never done math like this before lol) the little 2 next to the "InitialYVel" means power? and what does the 2 infront of "gravity" mean, and why is "gravity" under the whole equation?
the little 2 is an exponent yes
it means the thing it's attached to is raised to the second power (aka multiplied to itself)
the 2 in front of the g means to just multiply by 2
the big line with g under it is division
okay, okay, you teaching me things lol
Just never learned this stuff man. Okay the questionnaire finale (hopefully) why is there no symbol after (2g) or "gravity * 2" and the parenthesis with initial height and final height?
a number next to parentheses just means to multiply that outside number with the result of the calculation in the parentheses
bascially any two symbols just next to each other means to multiply
and anything just next to parentheses means to multiply
in code this is just like 2 * g * (initialHeight - finalHeight)
so the whole thing inside the square root is like:
initalYVel * initialYVel + (2 * g * (initialHeight - finalHeight))
@timid dove Doesn't work, something I did wrong?
probably dividing by 0 in tehre somewhere
looking
also where are you actually asssigning the velocity
(looks like it's a V3?)
Ok yeah your parentheses are a bit off
For this part everything before / gravity needs to be inside another set of parentheses
(same for the second calculation)
oh also
your gravity being negative is a problem
it should be positive at least for the yVel calculation
not sure about the big one 🤔
probably positive for both
okay I'll give this a go (also I just set the velocity of a rigidbody in another script and it is a vector3, could be wrong but I dont think that matters given that rigidbody velocity is a vector3)
well it definitely matters yes
because we will need to do a final adjustment then to translate our horizontal velocity into the correct x/z values for the 3D velocity
also the distanceToTarget value is a little suspect as well
where is that coming from and how is it calculated?
the transform.position is the enemy and the target is the player
that's not going to work becasue we need only the horizontal distance
to get that you'd do:
Vector3 offset = target.transform.position - transform.position;
offset.y = 0;
float horizontalDistance = offset.magnitude;```
basically I'm just removing the vertical component here
yeah still not working, no errors but it just shoots up into the stratosphere, comes down but not down on the player.
- is your gravity actually set to 9.8? (that is the default but you might have chjanged it)
also what is projectilePosition? Is that assigned properly? It should be a Transform at the place where the projectile is fired from
changed gravity to what it was (it was set to 12) didnt do anything, and yes that is what projectilePosition is and it is assigned
I mean it should have done something not nothing
in fact that would make it go higher if anything
well it didnt make it go towards the player
Two other things I'll mention:
- Debug.Log what
desiredHeightis - if the height it's reaching is still wrong, try the calculation with
-gravityeverywhere in the giant equation
that part will be because of the horizontal direction stuff I mentioned above
here
which I presume you haven't done
because you probably don't know how
fixed the stratosphere problem: just had to remove the initial position
oh yeah that makes sense
why so hostile dayum, we all gotta learn man, but yeah how? Is it not just set xVel to the x and z value?
no that would go too far
You know pythagoreanm theorem? We have c and we need to get a and b:
but we actually don't need to worry about doing the math really
we can just do like:
Vector3 offset = target.transform.position - transform.position;
offset.y = 0;
Vector3 horizontalDirection = offset.normalized;
Vector3 horizontalVelocity = horizontalDirection * xVel;```
wher xVel is the x part of the vector you returned in your function above
So it's like...
Vector3 offset = target.transform.position - transform.position;
offset.y = 0;
Vector3 horizontalDirection = offset.normalized;
float horizontalDistance = offset.magnitude; // we had this already before to plug into the function to get the x velocity
Vector3 horizontalVelocity = horizontalDirection * xVel;
Vector3 finalVelocity = new Vector3(horizontalVelocity.x, yVel, horizontalVelocity.z);```
something along these lines
okay let me try and apply this to my stuff
so here's the code: it works but not enough, it goes in the direction of the player, but, it doesn't go nearly far enough, and also the z axis is flipped, I can just negate the z value ofcourse but it's just more info.
oops that last bit should be horizontalVelocity.z
yeah just noticed that lol
basically if this is all in the same function we don't need the twoDVelocity thing
we can just use xVel and yVel directly
adjusted my code above to simplify it
okay yeah, still only nudges the projectile in the direction of the player doesn't actually arc to the player.
I'm looking for the best resources or methods to master physics in Unity professionally. Any recommendations or guidance would be greatly appreciated
The manual
there is absolutely zero reason to simulate it, all the time you're going to spend trying to get it to work (going through your message history, youve been trying to do it for over a month), you could have easily dont fake physics for the treads
all im saying is its silly to intentionally give yourself work, for the sake of an effect that really has no need to be physically simulated. it means youre eating into valuable time that you could spend developing your game
someone in roblox showed me my mistake
i did spend 1 year working on this but atleast i learned so much
and im prob gonna fix it today
1 year to implement something like this, seems like a rabbit hole
its worth it
im making a vr game with a physics based rig, and people move using their hands. quest 2 users, and quest 2 users only, are having an issue with slipperiness, despite the hand colliders having the max amount of friction possible. could someone help me with this?
Probably a #🥽┃virtual-reality question really
hi im trying to predict networked physics in unity for client side prediction
im trying a method where on the server i move the player in and out of a seperate scene without and with physics
the problem is that i cant get grounded detection thats inside of OnCollisionStay to work
anyone have an idea why it doesnt work?
I've been messing around with joints (specifically spring joints) in Unity to see what kind of accessories I can get bouncing around on my mesh.
Right now I just have a rigid body in my game object hierarchy that the head joint from the armature I made in Blender is connected to via a spring joint.
Everything works all well and good... when my animator is off, but when I turn it on it seems like the animations moving the mesh take precedence. I tried making an avatar mask (and even tried turning off everything in it) but that doesn't work. Oddly, even with all the parts selected to red on the avatar mask there is still some slight movement to the model as if it's still being animated somewhat...
Any ideas on what might be going on here or how I can get the behavior I want?
The animator would have to be animating physics (which is a checkbox somewhere) to behave well with physical interactions
Do you mean this?
yes
If so that doesn't change the behavior. I tried messing with all the settings inside of the Animator already.
I even have the avatar mask applied in this case.
Also the things it is animating need to actually be kinematic Rigidbodies
to interact properly
Changing them to kinematic rbs makes it not work with the animator on or off.
what did you change to kinematic rbs exactly
I'm talking about whatever objects your accessories are attached to
not the accessories themselves (just want to make sure we're on the same page)
In that case it works whether the rigidbody is kinematic or not. Currently it's just the character's head bone that is connected to this rigidbody via a spring.
Hopefully this video makes some things clearer of what I am dealing with
The only way I can seem to get around it right now is using position & other constraints to make the bone follow a dumby that's connected to another object with a joint........
This isn't ideal, but it works. If anyone has any other suggestions lmk please
Anyone understand whats going on here?
I cant diagnose the weird stuttering issue
Context: Vtuber program using VSeeface tracking data, and UniVRM spring bone physics. This project has dozens of outfits this character can swap to. Its had far more in the past and i did a purge not too long ago, the amount of bones and process of weight painting in blender is the same process as usual. Its worked just fine doing the same thing for the past few years and lately new outfits freak out. Tried different spring bone settings and swapping from late to fixed update. Tried turning off a ton of other vrm components to see if it was being overloaded or something weird
Edit: not sure what changed between the two. But i usually just export FBX, i tried the "Better FBX Exporter" Addon.. and now its running fine (so far) with zero stutters. So i guess something with normal fbx export. Kind of wonder if smoothing weight paint too much caused too many bone influences that just caused issues. Better FBX export has an unlimited bone influence option default on
Is it a bad idea to up physics to 90 hz?
@shadow heath hi, for an strange reason this happens when i kill an enemy
the enemies are supossed to be porcelain-like beings that when killed "explode" (spawn a prefab of a emptyobject with all the shards containing a rigidbody and boxcollider) and the shards be pushed by the explosion the proyectile has, The issue is, why they still...slidding..like if the floor were buttery...
also something i noticed thanks for recording this video is that when the "bird" ran towards the player, the shards of the "soldier" flew away, why? Maybe its the proyectile's explosive force, but still
(ignore the sound, it may be loud)
The stuff sliding, do they have a rigidbody?
the shards, yes
the idea is that they get pushed by the proyectile when the enemy dies (a way for make the bullet impact better), but they doesnt stop in floor...they just go...and go
I’m thinking you can either disable the rigidbody on collision or also apply a friction physics material to them
Or you can set your shard colliders to ignore the player collider by using the layermasks
i dont get the last one
btw they already are
They are what?
and how i disable the rigidbody on collision?
ignoring the player
the player's layer is called Valeria
also ignore enemies and other shards
In OnCollisionEnter, use the rigidbody instance and call .enable = false on it or just Destroy()
and btw for the material what i have do modify, higher the friction?
Yes and apply them on the collider, not the rigidbody
ok, thx
my rigidbody wont freeze x and y
Would you like to elaborate?
so my 2 arms are connected by a hingejoint2d
and the RB2d is dynamic and is supposed to only rotate at its pivot
but the whole arm detaches and follows the main arm
even when i freeze x and y positions
should i use fixedjoint instead?
maybe hingejoint is too powerful
ah yep
that fixed it
hingejoint is just too OP
dammit now it's staying in place in world space
what am i doing wrong
Freezing XY of the player? Or the arm?
the arm
How does your hierarchy look like? Is the arm a child of the player?
yes and i tried making a parent for it too
That's what freezing XY positions should do 🤔 What are you expecting
It's not for attaching things to each other
i need it to move with the body
Just don't freeze it
if i dont then it detaches from its pivot
Show your fixed joint
If you need the arm to rotate though, then fixed joint is not the play
switching to fixedjoint fixed the issue
You'd have to show more of your setup. Hierarchy, what has what components etc.
is freeze positions supposed to keep the object in place relative to the world?
Because this fixedjoint should not make it stay put in world space, but connected to chainsaw instead
Yes
ok so how do i stop it from detaching from its pivot
And also be able to rotate?
yes
Hinge joint
i tried that
Then you did something wrong
It's impossible to help you if you be like this
Show the full setup that you tried
Also, are you moving/rotating any of the rigidbodies with transform? For example, transform.Translate/Rotate/position/rotation
yes
the chainsaw
transform.Rotate
oh nvm
chainsaw.GetComponent<Rigidbody2D>().MoveRotation(input);
wait why doesnt it stay put with hingejoint
i freezed the positions with hingejoint and it moves together
I'd start with trying angularVelocity instead of MoveRotation
There could be other issues in your setup or code but you haven't shown much
fixedjoint works good except it fixes the position of the arm
hingejoint acts stupid no matter what i try
Why are you even considering fixedjoint if you need it to rotate?
rotates correctly
You are being very cryptic
sorry i was laying down
got tired of sitting
it rotates with the chainsaw
the arm is supposed to hold onto the top of the chainsaw
i tried all the other joints
they dont fix my problem
only fixedjoint does
but it still has that one issue
it fixes the position of the arm in world space
Am I interpreting this correctly?
SimulationMode is a global setting and can't be applied differently to individual
PhysicsScene2Ds?
Oh wait I think I got it - only the primary physics scene can auto-simulate. Secondary scenes always need to be simulated manually.
Hi, we have ragdolls in our game whose rigid bodies are on a specific 'Ragdoll' layer. However what we would like is that our ragdoll colliders are able to collide with each other for the same entity (i.e. its left and right legs collide)... but we don't want separate ragdolls colliding with each other (because we don't want them piling up - so are happy if they intersect each other). How can we achieve that easily?
can somebody pls help me fix this
void FixedUpdate()
{
Velocity = rb.velocity;
Drag = Cdrag * (Velocity * Velocity) + (RollingR * Velocity);
moveDirection = PlayerControls.ReadValue<Vector2>();
rb.AddForce(new Vector2(Mathf.Sin(angle),Mathf.Cos(angle)));
angle -= moveDirection.x;
rb.MoveRotation(angle);
}
First you would have to explain what's wrong
idk i think its because the values from sin and cos are only from 0-1 and not from -1 to 1
Not what I asked.
Explain what you expect or want this code to do, and explain what it's doing instead
you can';t just drop a piece of code with no context and expect people to understand what it's about.
well its supposed to go forwards when pressing W
how do you define "forwards"? Up?
(and you can rotate it left/right with a/d)
what does rotate left/right mean?
What's the style of this game? Top-down?
yes
and what is it doing instead?
does it help to say that that is supposed to be a car?
hard to explain
well one problem I see is that MoveRotation expects an angle in degrees but Sin and Cosine expect an angle in radians
but you shouldn't need to use sin and cos at all here
ohhhhh
you can just do rb.AddRelativeForceY(1);
(and later replace 1 with a variable so you can modify it)
Yeah ik i used AddRelativeForce() before but it didnt quite work with my drag
That comment doesn't make any sense - since AddForce and AddRelative force do exactly the same thing other than accepting the parameter in a different coordinate system
AddForce/AddRelativeForce have one effect and one effect only - they modify the velocity.
having an issue with some movement on a planet can anyone help?
rb.AddRelativeForce(new Vector2(0,moveDirection.y * speed));
like this?
As I mentioned you can use AddRelativeForceY
rb.AddRelativeForceY(moveDirection.y * speed);
well first of all what error?
Second of all which version of Unity are you using?
AddRelativeForceY is only in Unity 6
2021.3
well yeah then you would have to do it this way
ok thx, do you know how i implement drag?
There's a built in drag you can use
if you don' want to use that then you just calculate the drag force and add it to the body
add it how?
as a seperate line? so
rb.AddRelativeForce(...);
rb.AddForce(Drag);
id say yeah as youre adding in the relative force to the player then the drag will slow them down
ye i didnt really realize you can do add force multiple times
Hey everyone. I've got a question. In my game I need to create a tiled map and I want to optimize it by combining tiles into a single complex mesh to minimize draw calls. But as I understand, that's not a good idea for the physics, performance-wise. I will be better off with a multiple simple colliders than a single complex one, right?
Add force as much as you like lol ofc it’ll make ur player shoot off somewhere lol
2d or 3d?
3d
How big is the game map and is it generated dynamically or static?
Dynamically, and pretty big (hundreds of thousands of tiles, I use minecraft-style chunk system to optimize)
Did you try good old instancing?
If chunks aren’t big and colliders are simple rectangles then it should be fine to combine them per chunk
But if you can just have pieces as separate objects that’d simplify things a lot
To be honest, i couldn't find how I can do that intentionally in Unity. I know how in Unreal but all I've found in unity is how to optimize draw calls through mesh combination.
But yeah, instancing would make things much simpler
I think just ticking GPU instancing in material properties should enable it
But I don’t remember for sure, because, might only be for static objects
Found it. Graphics.RenderMeshInstanced. Interesting.
That’s for manually drawing it with code
You also lose culling unless you implement is yourself
Oh. That's a shame. On the other hand, I will be implementing chunk-based culling to turn off complex simulations in far away points of the map, so...
can anyone help me with my movement system, experiencing some weird behaviour at one of the poles of my sphere when the player walks near it
The way these channels work is you post the details of the issue you’re experiencing with screenshots and code as required. If necessary, explain what the expected outcome is. Then if someone can help, they will.
Hi guys! Wasn't sure to ask in HDRP or here because this question relates to the HDRP water system.
Does anyone know of an approach to mimic the usage of raycasts onto the water surface? Ideally I'd use raycasts but the water doesn't have a collider. I'm aware I can fake it with an object at the same height as the water but that won't help when there are large waves on the water surface. I need to be able to accurately pinpoint where the player is aiming on the water, accounting for large amounts of waves and swell
You would sample the wave the same way the shader does
Which means looking at how the shader works
Hmm I'm not sure about the underlying shader. There's an API to sample the water height at a given point which I've used for buoyancy but I think that can only sample straight down onto the water surface?
That sounds perfect, no?
It's only for going straight down onto the water, I want to do it at an angle like if I'm shooting at water for example and want to make splash effects. I suppose I can manually check lots of points along the path until one of them is at water height, just seems expensive
I'm trying to make this feature where the player can bind with a tile and move with it. Currently I'm doing it by 1.destroying the tile in the tilemap, 2.instantiate the prefab of the according tile, 3. connect it to the player using a fixed joint. Becasue I need its physics to impact the player's, but as you can see in the video, the connected tile will shake when the player jump and hit the ground(inertia I think). So I need an alternative way of doing this, I'm currently thinking of putting a composite collider on player, and instantiate the tile under player, and maybe the composite colldier will read both box colliders and combine them? But I also need the player tile and the new tile to have different tags, so say if the player tile touches lava it dies, but the attached tile won't trigger it. But I'm not sure how I can do that using composite collider
seems like it works if I just don't give the child object rigidbody 2D
having an issue with a movement system on a planet, so when the player gets to the south pole of the planet they get stuck on it and start moving in place and spinning, theyre fine on the north pole. it also sort of make the player walk around it even if you try to walk left or right. put my code here. if a recording of it is needed i can provide it as well.
Does anyone know how to use cloth physics? I can't seem to get things to work properly. Especially on these sleeves. They just constantly clip into themselves.
I've been using this to move my vehicle forwards, and previously I havent had gravity enabled on the body and the vehicle moved around no problem
float _currentThrottle => Input.GetAxis("Vertical");
void FixedUpdate()
{
Vector3 force = transform.forward * _currentThrottle;
force *= _speed * Time.fixedDeltaTime;
_rb.AddForce(force, ForceMode.Acceleration);
}```Now that I've enabled gravity, nothing I do can make it move. Even if I scale _speed up to a really high value, the position barely changes. Is there something that I'm missing?
dont multiply by deltaTime, it's already accounted for
even without that, theres no effect
I assume your vehicle is a rigidbody and such? What's the mass of it and what is the gravity factor? How much force did you try applying?
You can also try changing it's PhysicsMaterial, it might be as simple as you are not overcoming friction
its got mostly default settings
no phyiscs materials either, I did try making one with 0 friction to test out and that had no change
_speed is 5
oh! I just increased speed and it seems to have more of an effect now I'm not scaling by time
Yeah you shouldn't have to use too large values since ForceMode.Acceleration ignores mass
all my movement feels very strange now theres gravity, I guess I've been too used to the fact that my vehicle was never actually touching the floor
thanks for the help though!
why can't i move bones in unity? i have bone visualizer btw, i'm trying to clothe a character
when i try to move a bone it just doesn't move for no reason at all
how do i make dynamic bodies not apply force on others, like kinematic but can collide
This free asset lets you do "selective kinematics" https://assetstore.unity.com/packages/tools/physics/betterphysics-selective-kinematics-244370?srsltid=AfmBOoqTzxCLZwM-GFCo9VuWAuwNGtvk3uaGziIkdEdXDICjhKx6G9cC
(Full disclosure I am the author)
I've encountered something strange where the top speed of my vehicle never gets reached.
if(_currentSpeed > MaxSpeed)
{
rb.linearVelocity = rb.linearVelocity.normalized * MaxSpeed;
}
float force = Mathf.Abs(accelerationInput * accelaration);
rb.AddForce(transform.forward * force, ForceMode.Force);```
when `MaxSpeed=20, Acceleration=10` the highest speed the rigidbody gets too is about 12.5. It's only when I set Accel to be very high, does the max speed get reached.
I would expect acceleration to only impact how long it takes to reach the top speed, so a small acceleration would take a long time to get there. But it seems like acceleration actually determines what speed it can reach
ForceMode.Acceleration also does the same thing
I think ForceMode.Acceleration is more appropriate since it isn't divided by the mass
What are the values of accelerationInput and acecleration?
And does your rigidbody have drag/linear damping?
accelerationInput is 1 as its a Vertical input, acecleration is 10. I should fix the typo for acceleration
0 lineardamp, 40 angular
Apparently i can't type it either
Those seem kinda arbitrary, not really related to the max speed
Also friction can slow you down
well the input has to be 1, so it can actually apply force when the key is pressed, and I can increase acceleration to let the car reach the top speed faster (early game its going to take a while to get to the max speed)
its got a physics material with 0 friction
And friction combine is set to Minimum, or the ground/other object also has zero friction?
oh wait, the ground doesnt have that material!
ill see if a small acceleration value gets there
it reaches the top speed!
should if(_currentSpeed > MaxSpeed) come before or after the add force?
it doesnt appear to have any impact, but itd be good to have it in the right order regardless
AFAIK addforce doesn't modify the velocity until the next frame
Other than that I'm not sure, you'd have to try
Maybe someone like praetor knows
having an issue with a movement system on a planet, so when the player gets to the south pole of the planet they get stuck on it and start moving in place and spinning, theyre fine on the north pole. it also sort of make the player walk around it even if you try to walk left or right. put my code here. if a recording of it is needed i can provide it as well.
Is it better to use a large mix of primitive and mesh colliders, or is it worthwhile to merge them together as much as possible?
More simple colliders is usually better than fewer complex colliders
is this only rigidbody 3d ?
Yes
dang
im on 2d rn im fucked then
why doesnt my ragdoll stick to my mesh
Does the ragdoll control the mesh bones?
how do i check
Well, how do you have it setup? The whole point of a ragdoll setup is to have it control the rig.
I have done it how like every single youtube tutorial does it
I got it working before but cant seem to now idk what i did diffrently before
Do you have the rigidbodies and other stuff attached to bones under the Groin object?
Can you share some screenshots? Whole window screenshots with the hierarchy visible and one of the bones with rb selected?
The mesh sticks to the bones, if it doesn't follow the ragdoll, then it's not affecting the bones in any way.
Ok. Is the model flagged as static by any chance?
nope
Or the bones.
nope
makes zero sense if it was a the bones cause the ragdoll works as i said its just not the mesh
What happens to the mesh when the ragdoll moves?
It seems like the mesh is not bound to the rig at all. How did you create the model?
Does it move via animations?
made it in maya
did the bones there n skinned it
no jsut suppose to fall
and have used this exact thing before and it has worked
well, then the skinning part didn't work.
Take a screenshot of the model/mesh object inspector
Why is it a mesh renderer?
idk dont ask me lol
It needs to be a skinned mesh renderer
You made it
This might indicate that you either didn't create it correctly in Maya or didn't import it correctly in unity.
so is it a maya thing
ah right
thanks idk what i can do from here but ig ill ask my tutor
When i go in the negative y axis (down) it randomly snaps to -5000 velocity and goes faster than it should. Console prints out in RPM, Velocity, Power Format.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class CarController : MonoBehaviour
{
public float speed;
public InputAction PlayerControls;
Vector2 moveDirection;
public Rigidbody2D rb;
float angle = 0;
Vector2 Velocity;
Vector2 Drag; //resistance
public float Cdrag;
public float RollingR; //how much friction there is between rubber and the ground
public AnimationCurve Curve;
public float PowerMultiplier;
float RPM;
int MaxRPM = 6500;
// Start is called before the first frame update
private void OnEnable()
{
PlayerControls.Enable();
}
private void OnDisable()
{
PlayerControls.Disable();
}
Vector2 AddTorque()
{
if (moveDirection.y > 0)
{
RPM += moveDirection.y * 2;
}else if (moveDirection.y < 0)
{
RPM += moveDirection.y * -1 * 2;
}
else
{
RPM -= 3;
}
if (RPM < 0)
{
RPM = 0;
}
if (RPM > MaxRPM)
{
RPM -= 500;
}
Vector2 Vector = new Vector2(0, Curve.Evaluate(RPM) * moveDirection.y * PowerMultiplier);
Debug.Log(RPM.ToString() + " " + Velocity.ToString() + " " + Curve.Evaluate(RPM).ToString());
return Vector;
}
void FixedUpdate()
{
Velocity = rb.velocity;
Drag = Cdrag * (Velocity * Velocity) + (RollingR * Velocity);
moveDirection = PlayerControls.ReadValue<Vector2>();
rb.AddRelativeForce(AddTorque());//(new Vector2(Mathf.Sin(angle),Mathf.Cos(angle)));
rb.AddForce(-Drag);
angle -= moveDirection.x;
rb.MoveRotation(angle);
}
}
pls help
nailed it down to this line
rb.AddForce(-Drag);
but i dont know why and if i can fix it
well presumably your drag calculation is wrong
shouldn't you be taking the magnitude of the velocity
and squaring that?
you're doing a piecewise vector multiplication, which isn't right
ye i think too but idk im not that experienced with unity and maths like that so i just used the rb default drag
Back again with this crappy hovering system. Anyways I'm trying to snap the player above the ground it hits at ALL TIMES. This works but I feel like I might be doing it in the wrong order or something
The issue is that velocity accumulates, so MovePosition is trying to drag it up but velocity is trying to drag it down causing this horrible jitter until drag takes care of the built up speed on the Y axis. How should I go about doing this?
moving a Rigidbody vua the Transform is always going to cause horrible jittering
never move it via the Transform
Also it seems really weird to be manually moving the Rigidbody above the ground. Why are you doing that instead of just letting the natural collision of the body with the ground keep it there?
what are you trying to accomplish here?
I'm trying a movement method where you float the capsule above the ground to account for stairs, slopes etc, you get a lot more control
Ideally you would do this by manipulating the velocity or using a spring
But a spring based approach has an issue that I don't really know how to deal with but I should probably mention it here. It's a bit more of a math issue
for stairs why not just use a ramp-shaped collider?
And if you want to float it, you should be doing so via Rigidbody methods
Pretty much any time you touch the Transform of a Rigidbody, bad stuff is going to happen
Put it this way
private float Spring(float from, float to, float strength, float damper, float velocity) => (to - from) * strength - (velocity * damper);
If I did
playerBody.AddForce(Vector3.up * Spring(playerBody.position.y, targetHeight, standingStrength, standingDamper, playerBody.linearVelocity.y));
It would work but having any damper would cause a sort of lag back look
If I move up a slope, the damper will create some weird drag effect and pull me into the slope. If I move down a slope it makes me hover up instead because it's subtracting the velocity
It breaks interpolation too btw
Great lmao
There's no reason to do it anyway
you could always just be doing rb.position = instead of transform.position
if you really need to teleport
I'm not using transform.position should've clarified sorry
playerBody is a rigidbody
oh yeah - you can't mix MovePosition with forces either
Double great
BUMP
i still can't move bones in unity, they are stuck
I currently am having a few problems with my entities bouncing as they walk across a mesh at higher speeds with for example PhysicsVelocity.Linear.x =2; I am using DOTS , and these are mesh colliders built over a 16x16 tile chunk. I rly dont understand why this is so bouncy, when its a perfectly smooth mesh there?
Capsule collider over box seems to lessen it but its still verry visisble.
And moving over box colliders does not have this affect at all.
Moving just the transform with no velocity force but still having physics fixes the bouncing and is perfectly smooth.
I'm having an issue with rigidbodies where their horizontal momentum slows down when on a downwards moving platform. I first noticed it with my character controller but it seems to be a generic issue with all rigidbodies I use. I think I've isolated the issue down to the no friction physics material I'm using. When I set the friction to use the maximum value instead of the minimum, it reverses the problem so that the object only slows down while the platform is rising
I'm incredibly confused as to why this is happening
Are you using drag?
No but I ended up fixing it
I needed to change the collision mode to Continuous Speculative
This is for a FPS platforming controller. I want to add external forces like Rocket Jumping into the game. However, my Speed Difference system cancels out all external forces. Are there any other ways I can maintain tight turning speeds without compromising external forces?
https://scriptbin.xyz/jesikemime.cs (Only the Run and Apply Friction are really relevant for this question)
Use Scriptbin to share your code with others quickly and easily.
I also want to be able to conserve momentum to some extent and make it a key mechanic of the game
Sort of like TF2 Soldier
Is there a way to make little attached pieces like this stay attached while also letting the cloth as a whole have a decent amount of movement? If it's all ubound then it just falls but if it's bound then it just disconnects from everything else.
It's like a little ribbon
Hi
This might contact points if each tile is a small cube. There should be a demo in the physics samples to modify the simulation to reduce the effect, havok has an option to weld them. It kinda looks intentional in this case though, like a little bounce to his step
Hey all,
How much would be a difference if I have 10 objects with this mesh collider vs 10 Objects which are made of combination of primitive colliders ?
I know using primitive colliders is better than mesh colliders but I want to know first what is the difference in low numbers (Not 6k objects) ? And What is the difference if I use 100 primitive colliders on one object vs 1 mesh collider with low number of vertices like the screenshot ?
Can’t be answered that simply, depends a lot on what you do with the colliders. You can have thousands of mesh colliders if they are static and only ever interact with a couple of things and notice no difference.
As you might notice, it is a collider for a cabin. So interaction with it is just a collision between a player to prevent passing through.
Issues come up if you have many colliders close together and raycasts/collisions/overlaps that need to consider them all.
Makes no practical difference then. If the shape is easy enough to convert to primitives do it, but generally its too much of a complication in workflow.
I see, thanks. Even they don't impact much because of extra vertices they add to the game ?
if you have objects like trees, with loads of meaningless detail for collisions and 100s of instances of that object, do use primitives
i would look at the shape detail and how relevant that exact shape is to the player experience and decide based on that, i would say your particular example is fine as is
Thanks for the reply : ) i think the best corse of action for me is to just smoothly move the transform and not use force, i have alot of mesh colliders so increasing anything would cost frames. It works well its super smooth and when i detect falling i simply apply force at the start to simulate some momentum : )
Oh and its not a box around each tile but it is a line for each tile with an exposed face so yeh i guess its where they contact
Hello, i overwrite RB rotation, and I have rigidbody rotation constrained completely in the RB component. However this breaks the vertical position, by adding vertical shaking/teleporting/warping when falling via gravity.
I dont understand why thats the case considering im overwriting the rotation - not the position, and considering i have constrained RB rotation in component.
flatCameraRotation = Quaternion.Euler(0f, cameraInput, 0f);
transform.rotation = rigidbody.rotation = flatCameraRotation;
And finally, the reason i overwite RB rotation, is because otherwise RB rotation shakes/overshoots when i rotate the player's transform.
(Which, again, i thought wouldnt ever happen if i have RB's rotation constrained)
Anyone knows whats going on here?
Constraining the rotation doesn't do anything here
It's only about rotation caused by "natural" motion. Rotation from angular velocity
Since you're directly writing the rotation in code it doesn't come into play at all
You should never be modifying the Transform for a Rigidbody directly
hello everyone
is there a way to smoothen player movement when using Cinemachine FreeLook camera?
Interpolation helped first but broke most of the game (can't move player with transform)
How were you implementing the smoothing?
I wanna see scripts
there shouldn't be any need to smoothen it, it should be smooth already. If it's not you've done something to break it.
i simply turned on Interpolation in player's Rigidbody component
How can i improve the collision detection
https://www.youtube.com/watch?v=oLHP7GK2JYc&t=7s
the car phases through the player instead of crashing
The PassingCar collider is a trigger which literally means "no collisions"
you'll also have to use Rigidbody methods to move the car instead of changing transform position
i use a ontrigger enter on the car to get the "Collision"
the moving car doesn't have a rb tho
It should have if you want reliable collisions
Moving the transform teleports it around so it can easily skip over player
it is a child of the road, it behaves funky, any way to mimic normal child behaviour
Hey guys - Is there any obvious reason this isn't moving my character?
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
movement = new Vector3(moveHorizontal, 0f, moveVertical).normalized * moveSpeed;
// Moving the player
rb.AddForce(movement, ForceMode.Acceleration);
if (rb.linearVelocity.magnitude > maxSpeed)
{
rb.linearVelocity = rb.linearVelocity.normalized * maxSpeed;
}
I know it must be something silly, but it isn't jumping out at me
maxSpeed 0? You are not setting moveHorizontal? moveSpeed 0? Gravity causing too much friction so you need more moveSpeed?
Nope, max speed is defaulted to 5, but I've tried upping it. I updated the code snippet to show the horizontal and vertical for you. I printed that out and it's returning things fine to what I can tell. Move speed is above 0 as well. Let me check the friction though
put moveSpeed to 5000 and you'll see if its friction or not
It was the move speed being too slow! Thanks for the help 🙂
Hey everyone! I have a rigidbody that is using addtorque to face towards the direction the camera's facing, but whenever the player turns around, the object does a quick full 360 roll on the Z axis, then seems to be normal again. How would you go about preventing this?
You'll have to show the code, but best guess is that you're calculating the required torque from Euler angles
rb.AddTorque(torque * rotAccuracy);
rb.AddTorque(transform.forward * rotAccuracy * (weaponTargetTransform.rotation.z - transform.rotation.z));```
I'm using the cross method mainly for the x and y rotation and noticed it kinda affects the Z so I gave it its own torque yet the issue just persists
weaponTargetTransform.rotation.z - transform.rotation.z
😬 😬 😬 😬 😬 😬 😬 😬
Transform.rotation is a quaternion, not a set of euler angles - this calculation is not going to give you anything useful.
Also, Vector3.Cross can't be used with vectors that represent rotations. If one rotation is (1, 0, 0) and the other is (359, 0, 0) the real difference is only 2 degrees but the calculation counts it as a difference of 358 degrees
Yep cross product is for direction vectors not euler angles
Well actually you're using the cross product correctly here imo
since you are passing in direction vectors
I'm not exactly sure if that will give you the torque you want though... 🤔
I think what you want is basically
Quaternion diff = Quaternion.FromToRotation(rb.rotation * Vector3.forward, weaponTargetTransform.forward);
Vector3 torqueEulers = diff.eulerAngles;```
or even:
Quaternion diff = weaponTargetTransform.rotation * Quaternion.Inverse(rb.rotation);
Vector3 torqueEulers = diff.eulerAngles;```
Rotation glitches out insanely with either of those snippets
what if you scale the torque down?
the weapon target transform is not a child of the rigidbody is it?
Nope
Anyone have any ideas/tips for how to fix or help tunnelling problems with unity terrain? There used to be a terrain thickness variable, but I see that is no longer a thing. So far the solutions I've see are to change timestep for fixedtime (don't think this is a good idea), and changing the rigidbody collision detection mode to continuous.
Another thing I thought about was maybe extracting the terrain mesh, manually making it thicker, and then use mesh collider on it. But not sure how that would work out performance wise and is a really annoying workflow.
Just for context, there are a lot of rigidbodies since player and enemies are all active ragdolls, so I would like to avoid setting rigidbody to continuous, since that would probably be pretty taxing to do on that many rigidbodies.
Anyone had this happen: whole physics system just stopped working out of the blue... Rays are not being hit, gravity is not working. Any ideas as what I could have changed?
Did you mess with some physics settings
For example layer matrix
Ah disabled autosimulation, that'll do it
I have no recollection of even touching it
is this supposed to be None?
I can only choose PhysX
Physx is the only sdk there is unless you have unity pro I think
hmmm, something is broke here, I select it, upon restarting it's unselected
Okay, it seems to work now, for some reason I must have unselected it
Thx for the support
Found it out & got it working 👍
I'm on 2020.3 and I'm trying to remove positional constraints from HingeJoint2D. useConnectedAnchor exists on 2023 and above, but I can't update sadly.
Is there any way?
Ping if you reply by the way
when I turn dirrection of my character, he does a little hop and for a moment looses contact with the ground. it only hapens on a tilemap (I checked the colisions)
the problems are the small hops not the jumps
any ideas what could cause this?
btf I am really new and not good at this
Are you using a composite collider for your tilemap collider? I think the problem is you aren't
- add CompositeCollider2D to the tilemap object
- set the "composite operation" field on the tilemap Collider to "Merge"
How to make dancing Ragdoll. Do you guys any reference of anything to achieve dancing rag doll result
like animation and the rag doll together.
This isn't a physics question, but just press F
Is there a way to set an angle on a hinge joint in an instant?
as I know that to get to a specific angle over time springs/motors can be used
Search for "active ragdoll", thats what it is called. Usually you'd have an animated invisible character and then a physical character that tries to follow the animated character's movements with joints.
You probably wont find too much info if you search for "dancing" ragdolls specifically
surely all you need to do is to rotate the body itself to be the angle you want it
all a hinge joint does is restrict the freedom of rotation, I dont think it has any way to control the actual angle of the bodies
Might also need to move the rigidbody, in case its pivot is not in the same position as the joint's anchor
It is possible to make it go to a specific angle with a spring, as that has a „target position” in which I can input an angle
Thought there was an option to do that in code outside of the spring, as I use those hinge joints for levers that work with physics, so was hoping for a good way to set an initial angle on a lever like that
afaik, a spring force just applies torque in a certain direction
Yea, it does just add force to try moving the spring towards a particular angle over time
I was mainly asking if there is a way to rotate it to a particular angle in an instant via code
Probably just rb.MoveRotation (or rb.rotation if you don't want interpolation)
Or rb.Move if the pivot is offset
joints themselves cant, it would be nice if they could
ah dangit, that's a bit annoying
I guess I'll stay with my current solution of "set a spring to a target angle when a scene loads to get it to a particular position"
Can't what?
cant set an instant new angle on an attached body
like HingeJoint.SetAngle(0f) which would reset the hinge back to a rotation of 0
hi I got this wheel connected with a configurable joint the rectangle, how do I make, the wheel rotates but without the rectangle following like this, just stays "static"
hey, i have made a rope using verlet integration(followed yt tutorial) . I want to have the rope behave like a rigidbody2D, but i cant use the component itself cus it will cause the verlet script to malfunction. Any ideas on how i can achieve this?
In what way do you want it to behave like a Rigidbody?
If you want physical simulation you wouldn't use verlet integration. They are two different techniques entirely. Pick one or the other
There is absolutely no way to simulate physics on the rope?
I have made the rope physics, but it doesn't get affected by other rigidbody2ds
Like I can only move the rope thru the input assigned via script and no other way
please?
Of course there is. You just wouldn't be using verlet integration then
You would redo it as a chain of Rigidbodies connected via joints
Hinge joints?
You could also use verlet integration to pose some kinematic rigidbodies but it wouldn't be affected by other objects that way
Alright thx
Can u tell where the joint is connected from the wheel to the rectangle
I'm not sure I can help u with this man I'm sorry
The reason the rectangle is acting like that is because of the way the joint is connecting the 2 objects
Is the rectangle joined to the centre of the wheel?
Or is it connected to the outer part of the wheel
Try the centre
you're a genius
Is that sarcasm? Or did it work
@stuck bay Dead serious
it's not moving cause my bad coding, but it spins
Heyy nicee
That's progress
Now I think what shud do the trick is give the ground some and wheel some friction
Or u can try adding force to it when u give input
So that it moves
The best solution will be to use friction
But before that do it same for the backwheel
I'll try, thank you
feel like this would fit into physics, I'm trying to have a rigidbody lever kind of thing (column shifter). Is this fathomable to do in Unity, and would it be possible to include those red arrow forces so if the player lets go of the lever between the actual detents it will automatically go to the nearest one?
i'm not sure if levers can work on multiple axis like that with different "home" points
perhaps some kind of joystick/slider system with colliders to constrain it, then read the position to see if it's in the little detents?
Hmm, I haven't done anything like this with physics before. I suppose blocking out the walls would work but I feel like this approach would be a bit janky, and with some tweaking needed to avoid the lever getting stuck on corners.
On the note of forces I must admit I have only seen Wind being used once but never touched any other things like that so maybe someone else needs to chip in for that 😅
But I can see how I would achieve it with code by implementing a node graph to represent each path the lever can move along.
I would make these paths have two options - One-way (towards a home position) or a two-way (arrows pointing opposite direction).
If the lever is currently on a one-way path it should slide that direction. If the lever is on a two-way path it will choose direction based on which half of the path it's already on and continue sliding that way. - Unless the player is currently grabbing the lever, then it would just move in the direction best aligned with the players cursor/stick.
The code approach here would be much quicker to update if you add new layouts with different number of branches or directions etc.
Gotcha. I'm not familiar with node graphs, is that similar to the material node graphs but just for physics and physical related things?
I just mean this type of "graph" - it's a mathematical tool originally, for describing connections (edges) and junctions (nodes).
They are easy to implement in Unity for a simple case like this.
So any edge = a path the lever is allowed to follow.
Node = a spot where the lever may change direction, depending on player's direction input
I put together some quick code to show how a a node graph can be coded:
https://paste.mod.gg/tqqfvxmovhkz/0
A tool for sharing your source code with the world!
Ohhh gotcha tysm
so the nodes are physical points in the world and the edges are just the paths between them
Yep
And you can do some code to restrict a lever to follow an edge
If you have a 3D model to show the channels the lever can move inside you just have to align the nodes with the corners of the channels, and the edges will naturally line up.
Downside is it's harder to set up non-linear edges
Would aligning the nodes take place in the actual scene? or would I have to find each coordinate relative to the shifter grid
then put those into the script
So you would:
- Place some Empty objects in the scene and attach the Node script to each of them, and then move those empties around.
a) Select each Node and drag in other nodes that it should connect to
b) You don't have to do that both ways for the same edge - it's simpler if you only add an edge once, i.e. on it's starting node. - Add an Empty with the Graph script. This could for example be the parent object of the nodes just to keep things tidy.
- Add all the nodes to the Graph's node list so it's aware of them
How you align the empties with your shifter grid is up to you
Here's an example
Sweet thank you very much, I'll start playing around with it
and that empty with the graph script would have the lever attached to it?
Also assume I'd parent the shifter grid to those node position emptys
That's up to you. The graph script will just have the information you need.
You would still need some code to:
- Initialize the lever on the closest node when game starts
- If player drags it in a direction - decide which of the nodes best aligns with that direction (a vector dot product may help you here)
- If the lever is dragged onto another node, repeat the direction switching.
- While the lever is dragged along an edge, constantly check if the direction is valid in case the players cursor stops along the middle of an edge
- If the lever is let go on an edge, check if the edge is one way or two-way and determine which node it should slide towards.
- If the lever is let go on a node, check if there's a one-way edge away from that node.
And some things like that. This is generally just a little bit of "loop over a list of edges, find relevant one" and "lerp position along edge" which are frequent code topics, but I'd understand if it was a bit tricky to apply that to this new graph thing.
A little bit of vector math to compare where the player input points and compare that to the direction of edges
tytyty
I added a few updates to show the gizmo lines from my screenshots and also a safe-guard to make sure the "oneWay" list on each node is the same number of values as the "neighbors".
https://paste.mod.gg/bfhegpwcfttn/0
A tool for sharing your source code with the world!
In this case I only needed to set up "neighbors" for the central node since it's connected to all the others
And the resulting graph would look like this once it's "Generated"
struggling to find resources on how to make a tennis ball curve while in flight or after a bounce with rigidbody physics (example, a slice serve or top spin/back spin)
does anyone have suggestions on how to either use the Magnus Effect (not an expert on this and cant find any "template scripts" online that achieve this so far) or "cheat" the effect?
I dont want to use the bezier curve system because then bounces will be a pain
Hi Im wondering what would be the best way to create pinball style rails that a rigidbody ball could move through? (not my art btw just for reference)
but as @sharp rock said, a frictionless physics material is a good place to start. I am usless for physics, so that is the last you'll hear from me on the subject
I tried making a really rough tube with probuilder to see if the ball would move through it, but it looses a lot of speed and gets stuck even with 0 friction. I had maybe 24 sides on the cylinder
I think i might try to make a quick rail mockup in blender to see if itll work better with the actual shape and higher geometry
but what im really curious is that can I create these rail shapes easily using splines or something?
If it's intended that the ball can't fall off, then have it follow a set path, taking into account the entry speed. No real need for simulating it at all
To be fully honest, I wouldn't. Discrete physics isn't really a great way to do such precise simulation with really tight route. What is it that you are trying to accomplish in the bigger picture (what kind of game, what is this simulation used in the game)? Is there a way you could do your own simulation by just moving the ball along the spline?
(Use the Splines package)
Even if more advanced simulation is required, doing it by code on the path data sounds much more reliable solution than using the built-in physics engine which doesn't seem very optimal for this kind of simulation. Using the built-in physics is likely possible too but doesnt't seem optimal
Anyways giving any more specific ideas would require knowing more about the exact simulation you are looking for (derailing possibility? jumps? conservation of momentum, angular momentum, potential energy? requirement to simulate rotation? friction? rolling resistance? so on)
Thanks for answers, its probably best I go with the splines after some thought
my game is basically minigolf inside a pinball machine, so definitely need some custom code
Sounds like custom spline based solution would be sufficient then
one thing im a bit puzzled about is that lets say I have a path for the rails that goes up and then comes down or a loop de loop, so you need some speed to do the full path. how can i have the ball move along the spline taking into account gravity and friction?
since i assume when i make the ball follow the spline it ignores gravity etc, is that right?
You need to code the physics yourself but if you for example do it by directly transferring all of the potential energy to a kinetic energy, it should be quite easy really
You will need to write some code to simulate the concepts of momentum and gravity
It's not that complicated tbh
Especially if you think of it in terms of kinetic vs potential energy involving the y axis position
Accurately simulating the friction sounds very complicated if you are going to take the rotation of the ball into account but some simple rolling resistance isn't too bad (something like -constant * velocity)
For the potential energy part, I would just record the height change between the last frame and use that and the formulas for potential and kinetic energy to calculate the delta in velocity
have to be honest im a bit lost when you start talking about potential and kinetic energy. like i remember some stuff from school like kinetic energy is the energy of motion and potential is energy that could be realized based on the position of things. but like how it applies to this im not sure
probably a terrible explanation from me but shows how little i remember haha
I can walk you through my solution if you like
Yea if you dont mind, btw i see youre finnish, idk if were allowed to talk it here or strictly english
in practice basically just something like:
float heightDifference = heightThisFrame - heightLastFrame;
velocityMagnitude += heightDifference * someConstant;```
and then you move at velocityMagnitude along the spline
Haven't derived the formula yet but wouldn't the square in kinetic energy formula make the relation between height change and velocity non linear?
possibly. I would start with this and adjust later.
it could very well be cs velocityMagnitude += heightDifference * heightDifference * someConstant;
I owuld just see how they each feel
Also sorry for coopting the thread situation
does physics.bakemesh ignore baking options for non convex meshes? i want it to bake with MeshColliderCookingOptions.WeldColocatedVertices but it doesnt seem to do anything unless i turn on convex for the collider
anyone know how to fix this problem? whenever i walk or jump into a wall the object just starts freaking out but when i freeze position X it just glitches through the wall
you need to fix your movement code
this is what happens when you move a Rigidbody directly via the Transform
ignore the rotation i disabled it but the problem of him being able to cling onto a wall is still there
why do my crates do this funky thing when too many of them pile up on the conveyor belt heading into the wall
i found that by increasing the
mass, it took more crates to cause this issue, but i cant keep inceeasing the mass forever
what do i do to fix it
start moving via the RIgidbody instead of the Transform
ok
it worked thx
My player has a rigidbody and the camera is not parented to it so I'm taking baby steps. in the picture how can I that line of code to fixed update? I keep getting an error also should I rotate the whole player or just the rigidbody?
is this how you rotate the rigid body? rb.MoveRotation(Vector3.up * mouseX);
if so im getting a error on mouseX
it says this
I thought I was getting it from float mouseX = Input.GetAxis("Mouse X")
Made a few changes is this how you do it?
From a syntax perspective yes but this code won't work as you want as is
the issue is that Update runs at a different candence to FixedUpdate so if you do it this way you will lose frames of mouse input or get them double counted
the right way to do this is to accumulate the mouse delta in Update and consume it in FixedUpdate
something like this:
float mouseX;
void Update() {
// accumulate mouose input here
mouseX += Input.GetAxis("Mouse X") * sensitivity;
}
void FixedUpdate() {
// consume the accumulated input here
Quaternion rotationToAdd = Quaternion.Euler(0, mouseX, 0);
// we're consuming all the accumulated input so let's zero out the variable
mouseX = 0;
Quaternion newRotation = rb.rotation * rotationToAdd;
rb.MoveRotation(newRotation);
}```
Like this? also just to clarify will this completely get rid of the stutters?
yes and yes assumung you set your Rigidbody to Interpolate
and also assuming you don't have any other code that breaks Rigidbody interpolation
it's possible you have code in your movement script that also is problematic but I haven't seen that script
I haven't made the movement script yet. I just wanted to get the camera look script out of the way
thanks for the help ❤
I'll do the rest myself 👍
should I update/rotate the camera up down left right in Late Update?
Hi, I have a problem where my NPCs are moving jittery (as in the provided videos), and I don't know what's causing it. My first thought would be that me setting the transform manually is clashing with the physics system, but I wouldn't know which physics could be interacting with it, because the gameobject has no rigidbody
You would have to show your code for how it and the camera are moving
After some more testing, I noticed that it wasn't just happening on the NPCs, but on everything, even static objects. It's hard to notice in the video, but if you look at the edge of the sphere, it jitters as the camera moves. Would it then be something in my camera or render pipeline settings?
As for how the camera moves, I am simply using the XR plugin's "XR Origing (XR Rig)" prefab, and haven't changed anything besides the camera's far and near clipping planes
Again you need to show your code for how you're moving the objects
It's almost certainly an issue with how you're moving the objects
Or some settings on your XR stuff
Are you using Cinemachine?
If I do it this way, will it look the same as with the verlet method? Rn I have the segment lengths set to 0.25f .. Or do u think it will be a chain of 'blocks'?.. I chose the verlet method because I thought it is visually more accurate but maybe both are same?
Also, if I continue using verlet method, can I not do collisions using raycasting instead of using colliders? I'm thinking a raycast from the normals of each segment to check if distance between hit and origin of raycast is too less and register that as a hit?
no it won't look the same as verlet. It will be "blocks". You might do something extra visually to smooth it out, such as using the rigidbody positions or orientations as knots in a bezier curve for example.
can I not do collisions using raycasting instead of using colliders?
Raycasting requires colliders.
at least, Physics.Raycast does
does anyone have an idea as to why this barrel floats when i hit play
ok ive narrowed it down, it acts normally when i remove the network rigidbody, transform, and object from it, but i do need those
at least i think i need those
It needs colliders on both bodies? Cuz I have colliders for the ground and environment.. Just not the rope
If you want it to collide with things it needs a collider
#archived-networking not a physics issue then.
This could be the wrong place but I am new to 3d rendering and unsure what could be causing this. How come when I hit play and move the position of the object other axis move when I am not telling them to? Here is a video showing what I mean. I am only changing the X axis but yet the Y axis is changing as well?
I would assume that this component has something to do with it
So thats the thing.. My script is just this
{
void SetValue(string value)
{
if (float.TryParse(value, out float newPosition))
{
Vector3 beforePosition = transform.position;
transform.position = new Vector3(
newPosition,
transform.position.y,
transform.position.z);
// Debug.Log($"Y {beforePosition.y} -> {transform.position.y}");
}
}
}```
I actually posted in the code-beginner channel as well because it seems when I edit just one axis other ones get changed as well.
That's not the same script that's on the object
Yes it is, I just changed the name
So it's still happening if you remove the component?
No, good point. It is the script that is causing it I just dont really get how. in the script I am only telling it to change one axis and keep the rest the same..
Show the full script
The code you showed does nothing by itself
You should also know that the position you see in the inspector is transform.localPosition, not transform.position
Ah, maybe that is the problem then. Is there any way to show the world position instead of local position? Also, the script is being called by another script that is just sending a value like 4500
This script just takes the value, converts it to a float and then sets the position of the object its attached to
SetValue is private that's why I assumed there's more to the script. You can't call that from outside without reflection or something
The transform component can't show the world position, no
Some ways to draw it yourself:
A: Draw it in the game view with IMGUI: void OnGUI() { GUILayout.Label("World Pos: " + transform.position); }
B: Make a separate Vector3 variable for it and just look at it in the inspector
C: Make a custom editor
D: Debug.Log it and look at the console
@silver moss thanks for the help. My problems were coming from using the world position instead of the local position
is there a way to raycast a generic Collider? I wanna Physics.Raycast without knowing anything about what type of collider the Collider is. I know of Sweeptest with a rigidbody, but seems inperformant if im trying to just check whether anythings inside my collider at specific frame.
i can do 2 different loops, oncolliderstay and onfixedupdate, setting bool-true/false, but i dont want mechanic to rely on order of function operation
You never need to know what kind of collider it is to use Raycast
i meant like overlapshpere, overlapcube
ways to use the colliders entire collider to raycast against other objects in scene.
i could do 6 seperate raycasts and collider.containspoint if theres a hit i guess?
why not use OnTrigger/CollisionEnter and Exit?
with the way unity creates a ragdoll, where the hand rbody is a child of the arm rbody, and so on. Does that make it impossible to have something like the hand being kinematic to be fixed in place (use case for a climbing game where the hands can pull the character upwards)
i dont need any data held by these objects at any time other then when "placing" them, as their buildable objects. just dont like causing stuff to run unneedly i guess.
oh, and also, this object can spawn inside another object.
For a placement preview I would use direct physics queries yeah. The placement area should just be a simple box or sphere generally
it's not that hard to write a switch statement and do the OverlapBox/Sphere code for both
it's really the best way i think
You don't even actually need a collider
yeah, i dont even need the spawned objects to have a collider. the problem is a bit of the difference between a mesh's bounds and a mesh. i want the player to be able to place based on the "mesh's" hitbox, rather then a primitive collider. but i may be asking too much of the game.
at least for performance reasons, no reason to overcomplicate things
I think that's probably more accuracy than you need
One option is to hav ea few "placement dummy" box colliders on the prefab and use those to do a few OverlapBox calls in a decent approximation of the actual shape
