#⚛️┃physics

1 messages · Page 25 of 1

golden terrace
#

It's a big bite to chew, but it's probably ideal that I just test anyway.

bleak umbra
#

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)

golden terrace
onyx galleon
timid dove
#

you should pretty much never have the console window hidden

#

there are important messages and errors there

steel pulsar
#

what convex do in mesh collider?

timid dove
stuck bay
#

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
stuck bay
#

okay fixed it for now by using more damping

wide horizon
#

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?

silver moss
wide horizon
#

Thank you!

rain sparrow
#

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?

pure moat
#

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?

timid dove
#

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

pure moat
timid dove
#

yes you will get tunneling

#

the collision detection methods are meaningless for triggers

#

they don't apply at all

pure moat
#

Ah

timid dove
#

I recommend using BoxCast

pure moat
#

Is that viable if the enemies can move in some cases?

timid dove
#

what's an enemy?

pure moat
#

Box collider. Or is there an example of what you’re suggesting?

timid dove
#

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

pure moat
#

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

timid dove
pure moat
#

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

timid dove
#

and for the player balls you can just modify the exit position/velocity in OnCollisionEnter to get the perfect reflections etc you want

pure moat
#

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

timid dove
#

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

pure moat
#

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

timid dove
#

that's why I'm saying to use Vector3.Reflect

pure moat
#

I am. I mean it seems like the collision points are not always the same

#

But yeah I’ll try some new approach

timid dove
#

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

pure moat
#

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

pure moat
timid dove
#

Boxcast casts a box through the scene

#

SphereCast casts a sphere

#

It should match the bullet yes

pure moat
pure moat
#

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

timid dove
#

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

eager finch
white palm
#

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

wide horizon
#

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?

timid dove
#

Unless that's a new behavior

wide horizon
#

I tested it and I thought it was the only explanation in my case

#

used the debugger and everything

timid dove
#

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

wide horizon
timid dove
#

In 3D you don't get the callback at all

#

Not immediately, not next physics update

wide horizon
#

and someone even commented the same thing as you did!

timid dove
#

Oh nice

wide horizon
#

but they never got a response back from unity

wide horizon
warm flare
#

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

coral moat
#

hey is this channel only used for unity rigidbody physics and colliders or can i ask about my own physics calculation?

unique cave
coral moat
# unique cave 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.
unique cave
# coral moat ok thanks! i want to make a player controller and he does move, but dont think i...

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

coral moat
# unique cave One thing that I'm seeing immediately is that you are using Vector3s everywhere ...

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!
pure moat
# timid dove You would do everything in FixedUpdate basically

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

warm flare
#

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

timid dove
flint portalBOT
warm flare
# timid dove Wdym by them not working? You'd have to show details about your game such as ho...

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.

timid dove
#

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?

warm flare
warm flare
timid dove
#

Is your collision detection set to continuous?

white palm
#

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

oblique urchin
#

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

silver moss
#

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

wide horizon
#

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?

bleak umbra
wide horizon
bleak umbra
wooden wigeon
#

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)?

timid dove
#

Also use the profiler

#

whenever you have a question about performance, use the profiler

wooden wigeon
#

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.

tight dock
#

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.

silver moss
#

Basic question first, do you have interpolation enabled on the RB's?

tight dock
#

Set to interpolate

#

yes

silver moss
#

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

tight dock
#

No parenting used, no.

timid dove
#

the principle is that your hands are the only actual physical object in the game, and that is very awkward.

silver moss
#

What do you mean? @timid dove

timid dove
#

So i don't think Mathf.Deg2Rad makes sense in there

silver moss
#

It is radians per second

timid dove
#

oh

#

my bad

#

They're so annoyingly inconsistent with that

silver moss
#

Yeh

tight dock
#

Sorry for the wait

#

I tried a bunch of things that claude suggested

tight dock
#

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

silver moss
tight dock
#

What it doesn't do, is wobble.

#

Mine wobbles

tight dock
#

Should it be fixedupdate?

silver moss
#

Adjust the forces so that it does not overshoot but is snappy

silver moss
tight dock
#

You think that game just does what I'm doing but better?

#

The same way?

silver moss
#

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

tight dock
#

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.

harsh matrix
#

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

oblique urchin
#

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)

sage whale
#

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

silver moss
#

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)

short lava
#

how do i make tank

silver moss
#

Zero effort question

short lava
silver moss
#

How good are you at vector math?

sage whale
silver moss
#

Any child/parent relations involved here?

sage whale
#

nope, the 3 bodies share the same parent

silver moss
#

And the parent doesn't have a rigidbody and isn't otherwise moving?

#

Just makin' sure

sage whale
#

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

silver moss
#

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

silver moss
#

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

sage whale
#

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

silver moss
#

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)

sage whale
#

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

silver moss
#

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

sage whale
#

the idea of purchasing a wheel asset, only to find it doesnt work the way I'd need, makes me hesitant

silver moss
#

I understand that

sage whale
#

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

sage whale
# short lava like this

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

short lava
#

i want it simulated

sage whale
#

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

timid dove
#

All this just to create debris when the tank dies is waay overkill

sage whale
#

this is for debris???

timid dove
#

Yeah - I was about to link there

sage whale
#

in that case, just use a non physics tread during gameplay, upon death, spawn like 200 individual treads

#

easy

tight dock
#

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?

bleak umbra
tight dock
#

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.

bleak umbra
oblique urchin
#

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.

timid dove
#

basically follow any tutorial for a rope or chain but replace the hinge joints with springs

oblique urchin
#

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

silver moss
#

Like these

tight dock
#

I wonder how H3VR does this. The character is kinematic, but objects are physical

#

Yet the camera, and weapon, is perfectly smooth

bleak umbra
#

physics needs a stable update delta

timid dove
#

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

bleak umbra
#

potato potato

oblique urchin
#

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.

timid dove
#

Well... It is after all a double or triple or octuple pendulum

#

A mechanism famous for being chaotic

wide horizon
#

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?

timid dove
wide horizon
low blaze
#

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.

silver moss
#

At certain speeds it can look like it's spinning backwards, even

#

Or are you talking about something else?

tranquil bridge
#

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

tranquil bridge
#

does Unity not support prefab collision detection for cloths?

silver moss
#

You need to manually set the capsule colliders for the Cloth component for it to collide with them

tranquil bridge
#

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

silver moss
#

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

tranquil bridge
#

I see, I'm assuming you can modify that colliders list right?

silver moss
#

If the cloth is part of the same prefab though, then the reference will stay linked

tranquil bridge
#

alright thanks

worn mantle
#

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?

timid dove
worn mantle
#

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.

timid dove
#

You're prematurely optimizing

worn mantle
#

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

elder sedge
#

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.

timid dove
# elder sedge Kinda like a mortar, but I want the projectile to always go a certain height tha...

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);

elder sedge
timid dove
#

All of this assumes these objects start at the same height

#

if they don't there are some changes to make

elder sedge
timid dove
#

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

elder sedge
#

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?

timid dove
#

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.

elder sedge
timid dove
#

yes they can support any height

#

you just have to plug it in

timid dove
#

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.

elder sedge
#

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.

timid dove
#

what do you mean by hieroglyphs

#

As I just explained you replace sin(θ) with the initial y velocity

timid dove
elder sedge
timid dove
#

It's not complex

elder sedge
#

and Y is the desired height?

elder sedge
timid dove
timid dove
#

you just plug the numbers into the appropriate syumbol in the formula

elder sedge
timid dove
#

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

elder sedge
#

okay cool

elder sedge
timid dove
#

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

elder sedge
#

okay, okay, you teaching me things lol

timid dove
#

I'm curious how old are you?

#

These are things I learned back in grade school.

elder sedge
#

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?

timid dove
#

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))

elder sedge
#

@timid dove Doesn't work, something I did wrong?

timid dove
#

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

elder sedge
#

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)

timid dove
#

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?

elder sedge
#

the transform.position is the enemy and the target is the player

timid dove
#

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

elder sedge
timid dove
#

also what is projectilePosition? Is that assigned properly? It should be a Transform at the place where the projectile is fired from

elder sedge
timid dove
#

I mean it should have done something not nothing

#

in fact that would make it go higher if anything

elder sedge
#

well it didnt make it go towards the player

timid dove
#

Two other things I'll mention:

  1. Debug.Log what desiredHeight is
  2. if the height it's reaching is still wrong, try the calculation with -gravity everywhere in the giant equation
timid dove
timid dove
#

which I presume you haven't done

#

because you probably don't know how

elder sedge
#

fixed the stratosphere problem: just had to remove the initial position

timid dove
#

oh yeah that makes sense

elder sedge
timid dove
#

wasn't meaning to be hostile

#

idk im tired

timid dove
#

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

elder sedge
#

okay let me try and apply this to my stuff

elder sedge
timid dove
elder sedge
#

yeah just noticed that lol

timid dove
#

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

elder sedge
#

okay yeah, still only nudges the projectile in the direction of the player doesn't actually arc to the player.

normal oyster
#

I'm looking for the best resources or methods to master physics in Unity professionally. Any recommendations or guidance would be greatly appreciated

sage whale
# short lava

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

short lava
#

sthu

#

i learned alot

#

and i no longer need help

sage whale
#

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

short lava
#

i did spend 1 year working on this but atleast i learned so much

#

and im prob gonna fix it today

sage whale
#

1 year to implement something like this, seems like a rabbit hole

rotund pelican
#

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?

viscid granite
#

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?

robust holly
#

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?

timid dove
timid dove
#

yes

robust holly
#

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.

timid dove
#

Also the things it is animating need to actually be kinematic Rigidbodies

#

to interact properly

robust holly
timid dove
#

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)

robust holly
robust holly
#

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

grizzled topaz
#

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

tight dock
#

Is it a bad idea to up physics to 90 hz?

solemn eagle
#

@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)

shadow heath
solemn eagle
#

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

shadow heath
#

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

solemn eagle
#

i dont get the last one

btw they already are

shadow heath
#

They are what?

solemn eagle
solemn eagle
#

the player's layer is called Valeria

#

also ignore enemies and other shards

shadow heath
#

In OnCollisionEnter, use the rigidbody instance and call .enable = false on it or just Destroy()

solemn eagle
#

and btw for the material what i have do modify, higher the friction?

shadow heath
#

Yes and apply them on the collider, not the rigidbody

solemn eagle
#

ok, thx

white palm
#

my rigidbody wont freeze x and y

timid dove
white palm
#

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

white palm
#

freezing x and y positions makes my arm stay behind in world space

#

how do i fix this

silver moss
white palm
#

the arm

silver moss
#

How does your hierarchy look like? Is the arm a child of the player?

white palm
#

yes and i tried making a parent for it too

silver moss
#

It's not for attaching things to each other

white palm
#

i need it to move with the body

silver moss
#

Just don't freeze it

white palm
#

if i dont then it detaches from its pivot

silver moss
#

Show your fixed joint

#

If you need the arm to rotate though, then fixed joint is not the play

white palm
#

which joint then

silver moss
#

Go back to hinge I guess?

#

And fix whatever the issue was there

white palm
#

switching to fixedjoint fixed the issue

silver moss
#

And introduced another issue

#

Which is that it can't rotate

white palm
#

no it stays put

#

in world space

silver moss
#

You'd have to show more of your setup. Hierarchy, what has what components etc.

white palm
#

is freeze positions supposed to keep the object in place relative to the world?

silver moss
#

Because this fixedjoint should not make it stay put in world space, but connected to chainsaw instead

white palm
#

ok so how do i stop it from detaching from its pivot

silver moss
#

And also be able to rotate?

white palm
#

yes

silver moss
#

Hinge joint

white palm
#

i tried that

silver moss
#

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

white palm
#

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

silver moss
#

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

white palm
#

fixedjoint works good except it fixes the position of the arm

#

hingejoint acts stupid no matter what i try

silver moss
white palm
#

it does rotate

#

i told you fixedjoint fixes my problem

silver moss
#

It rotates with the parent or individually?

#

With parent i mean what its attached to

white palm
#

rotates correctly

silver moss
#

You are being very cryptic

white palm
#

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

timid dove
#

Oh wait I think I got it - only the primary physics scene can auto-simulate. Secondary scenes always need to be simulated manually.

mossy swan
#

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?

hollow fable
#

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);
    }
timid dove
hollow fable
#

idk i think its because the values from sin and cos are only from 0-1 and not from -1 to 1

timid dove
#

you can';t just drop a piece of code with no context and expect people to understand what it's about.

hollow fable
#

well its supposed to go forwards when pressing W

timid dove
#

how do you define "forwards"? Up?

hollow fable
#

(and you can rotate it left/right with a/d)

timid dove
#

what does rotate left/right mean?
What's the style of this game? Top-down?

hollow fable
#

yes

timid dove
hollow fable
hollow fable
timid dove
#

but you shouldn't need to use sin and cos at all here

timid dove
#

you can just do rb.AddRelativeForceY(1);

#

(and later replace 1 with a variable so you can modify it)

hollow fable
timid dove
#

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.

visual cloak
#

having an issue with some movement on a planet can anyone help?

hollow fable
timid dove
#

rb.AddRelativeForceY(moveDirection.y * speed);

hollow fable
#

gives an error

timid dove
#

well first of all what error?
Second of all which version of Unity are you using?

#

AddRelativeForceY is only in Unity 6

hollow fable
#

2021.3

timid dove
hollow fable
#

ok thx, do you know how i implement drag?

timid dove
#

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

timid dove
#

with AddForce

#

the only way to add forces

hollow fable
#

as a seperate line? so
rb.AddRelativeForce(...);
rb.AddForce(Drag);

visual cloak
hollow fable
#

ye i didnt really realize you can do add force multiple times

pseudo hornet
#

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?

visual cloak
pseudo hornet
hybrid umbra
pseudo hornet
hybrid umbra
#

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

pseudo hornet
#

But yeah, instancing would make things much simpler

hybrid umbra
#

But I don’t remember for sure, because, might only be for static objects

pseudo hornet
hybrid umbra
#

That’s for manually drawing it with code

#

You also lose culling unless you implement is yourself

pseudo hornet
#

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...

visual cloak
#

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

light gate
subtle canopy
#

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

timid dove
#

Which means looking at how the shader works

subtle canopy
#

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?

subtle canopy
#

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

misty crow
#

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

misty crow
visual cloak
#

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.

paper basalt
#

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.

sage whale
#

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?
sweet snow
sage whale
#

even without that, theres no effect

sweet snow
#

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

sage whale
#

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

sweet snow
#

Yeah you shouldn't have to use too large values since ForceMode.Acceleration ignores mass

sage whale
#

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!

split spruce
#

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

timber zephyr
#

how do i make dynamic bodies not apply force on others, like kinematic but can collide

timid dove
# timber zephyr how do i make dynamic bodies not apply force on others, like kinematic but can c...

Get the BetterPhysics - Selective Kinematics package from Sadness Monday Productions and speed up your game development process. Find this & other Physics options on the Unity Asset Store.

sage whale
#

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

silver moss
#

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?

sage whale
#

accelerationInput is 1 as its a Vertical input, acecleration is 10. I should fix the typo for acceleration

#

0 lineardamp, 40 angular

silver moss
#

Apparently i can't type it either

silver moss
#

Also friction can slow you down

sage whale
#

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)

sage whale
silver moss
#

And friction combine is set to Minimum, or the ground/other object also has zero friction?

sage whale
#

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

silver moss
#

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

visual cloak
#

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.

gray sentinel
#

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?

timid dove
timber zephyr
timid dove
timber zephyr
clear adder
#

why doesnt my ragdoll stick to my mesh

tender gulch
clear adder
#

how do i check

tender gulch
clear adder
#

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

tender gulch
clear adder
#

yeah

#

the whole ragdoll works the just the mesh wont stick to it

tender gulch
tender gulch
clear adder
tender gulch
clear adder
#

nope

tender gulch
#

Or the bones.

clear adder
#

nope

#

makes zero sense if it was a the bones cause the ragdoll works as i said its just not the mesh

tender gulch
#

What happens to the mesh when the ragdoll moves?

clear adder
#

cockall

tender gulch
#

It seems like the mesh is not bound to the rig at all. How did you create the model?

#

Does it move via animations?

clear adder
#

did the bones there n skinned it

clear adder
#

and have used this exact thing before and it has worked

tender gulch
#

well, then the skinning part didn't work.

#

Take a screenshot of the model/mesh object inspector

clear adder
tender gulch
#

Why is it a mesh renderer?

clear adder
#

idk dont ask me lol

tender gulch
#

It needs to be a skinned mesh renderer

tender gulch
#

This might indicate that you either didn't create it correctly in Maya or didn't import it correctly in unity.

clear adder
#

so is it a maya thing

clear adder
#

thanks idk what i can do from here but ig ill ask my tutor

hollow fable
#

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

hollow fable
#

nailed it down to this line
rb.AddForce(-Drag);
but i dont know why and if i can fix it

timid dove
#

shouldn't you be taking the magnitude of the velocity

#

and squaring that?

#

you're doing a piecewise vector multiplication, which isn't right

hollow fable
twin nebula
#

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?

timid dove
#

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?

twin nebula
#

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

timid dove
#

Pretty much any time you touch the Transform of a Rigidbody, bad stuff is going to happen

twin nebula
#

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

timid dove
#

It breaks interpolation too btw

twin nebula
#

Great lmao

timid dove
#

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

twin nebula
#

I'm not using transform.position should've clarified sorry

#

playerBody is a rigidbody

timid dove
#

oh yeah - you can't mix MovePosition with forces either

twin nebula
#

Double great

split spruce
#

i still can't move bones in unity, they are stuck

civic hill
#

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.

civic hill
#

Moving just the transform with no velocity force but still having physics fixes the bouncing and is perfectly smooth.

graceful wolf
#

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

graceful wolf
#

No but I ended up fixing it

#

I needed to change the collision mode to Continuous Speculative

cerulean lava
#

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

warped ether
paper basalt
#

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

thick ruin
#

Hi

fallow gorge
dusky prism
#

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 ?

bleak umbra
dusky prism
bleak umbra
#

Issues come up if you have many colliders close together and raycasts/collisions/overlaps that need to consider them all.

bleak umbra
dusky prism
bleak umbra
#

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

civic hill
civic hill
stuck bay
#

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?

timid dove
#

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

timid dove
dull shuttle
#

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)

bright frigate
#

I wanna see scripts

timid dove
dull shuttle
ruby perch
inner thistle
#

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

ruby perch
ruby perch
inner thistle
#

It should have if you want reliable collisions

#

Moving the transform teleports it around so it can easily skip over player

ruby perch
uncut anvil
#

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

sweet snow
uncut anvil
sweet snow
#

put moveSpeed to 5000 and you'll see if its friction or not

uncut anvil
#

It was the move speed being too slow! Thanks for the help 🙂

slow edge
#

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?

inner thistle
#

You'll have to show the code, but best guess is that you're calculating the required torque from Euler angles

slow edge
#
  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
timid dove
#

Transform.rotation is a quaternion, not a set of euler angles - this calculation is not going to give you anything useful.

inner thistle
#

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

timid dove
#

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;```
slow edge
#

Rotation glitches out insanely with either of those snippets

timid dove
#

what if you scale the torque down?

slow edge
#

Nah just constantly spinning

#

even at 0.001

timid dove
#

the weapon target transform is not a child of the rigidbody is it?

slow edge
#

Nope

severe moth
#

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.

patent bramble
#

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?

severe moth
#

For example layer matrix

patent bramble
severe moth
#

Ah disabled autosimulation, that'll do it

patent bramble
#

I have no recollection of even touching it

#

is this supposed to be None?

#

I can only choose PhysX

severe moth
#

Physx is the only sdk there is unless you have unity pro I think

patent bramble
#

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

slow edge
dull adder
#

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

ebon oasis
#

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)

#

any ideas what could cause this?

#

btf I am really new and not good at this

timid dove
#
  • add CompositeCollider2D to the tilemap object
  • set the "composite operation" field on the tilemap Collider to "Merge"
silk dirge
#

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.

timid dove
#

This isn't a physics question, but just press F

wintry pewter
#

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

silver moss
#

You probably wont find too much info if you search for "dancing" ragdolls specifically

sage whale
#

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

silver moss
#

Might also need to move the rigidbody, in case its pivot is not in the same position as the joint's anchor

wintry pewter
sage whale
#

afaik, a spring force just applies torque in a certain direction

wintry pewter
#

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

silver moss
#

Probably just rb.MoveRotation (or rb.rotation if you don't want interpolation)

#

Or rb.Move if the pivot is offset

sage whale
#

joints themselves cant, it would be nice if they could

wintry pewter
#

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"

silver moss
sage whale
#

like HingeJoint.SetAngle(0f) which would reset the hinge back to a rotation of 0

stuck bay
#

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"

stuck bay
#

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?

timid dove
#

If you want physical simulation you wouldn't use verlet integration. They are two different techniques entirely. Pick one or the other

stuck bay
#

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

timid dove
#

You would redo it as a chain of Rigidbodies connected via joints

timid dove
#

You could also use verlet integration to pose some kinematic rigidbodies but it wouldn't be affected by other objects that way

stuck bay
stuck bay
# stuck bay

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

stuck bay
#

Is that sarcasm? Or did it work

#

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

thin crag
#

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?

tender cobalt
# thin crag feel like this would fit into physics, I'm trying to have a rigidbody lever kind...

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.

thin crag
tender cobalt
#

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

thin crag
#

Ohhh gotcha tysm

#

so the nodes are physical points in the world and the edges are just the paths between them

tender cobalt
#

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

thin crag
#

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

tender cobalt
#

So you would:

  1. 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.
  2. Add an Empty with the Graph script. This could for example be the parent object of the nodes just to keep things tidy.
  3. 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

thin crag
#

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

tender cobalt
#

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

thin crag
#

tytyty

tender cobalt
#

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

#

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"

feral holly
#

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?

feral holly
#

I dont want to use the bezier curve system because then bounces will be a pain

sweet wing
#

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)

viral field
#

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

sweet wing
#

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?

verbal bolt
unique cave
timid dove
#

(Use the Splines package)

unique cave
#

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)

sweet wing
#

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

unique cave
#

Sounds like custom spline based solution would be sufficient then

sweet wing
#

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?

unique cave
timid dove
#

It's not that complicated tbh

#

Especially if you think of it in terms of kinetic vs potential energy involving the y axis position

unique cave
#

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

sweet wing
#

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

unique cave
sweet wing
#

Yea if you dont mind, btw i see youre finnish, idk if were allowed to talk it here or strictly english

timid dove
#

and then you move at velocityMagnitude along the spline

unique cave
timid dove
#

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

wispy iron
#

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

balmy raptor
#

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

timid dove
#

this is what happens when you move a Rigidbody directly via the Transform

weak lantern
#

ignore the rotation i disabled it but the problem of him being able to cling onto a wall is still there

icy trout
#

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

balmy raptor
timid dove
balmy raptor
#

ok

balmy raptor
plucky tinsel
#

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?

timid dove
#

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);
}```
plucky tinsel
timid dove
#

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

plucky tinsel
#

thanks for the help ❤

#

I'll do the rest myself 👍

plucky tinsel
gritty bolt
#

is a capsule collider fine for a barrel prop or should i make a custom

#

nvm

stray iron
#

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

timid dove
stray iron
# timid dove 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

timid dove
#

It's almost certainly an issue with how you're moving the objects

#

Or some settings on your XR stuff

#

Are you using Cinemachine?

stuck bay
#

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?

timid dove
#

at least, Physics.Raycast does

gritty bolt
#

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

stuck bay
timid dove
crimson tundra
#

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?

silver moss
crimson tundra
# silver moss 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.
inner thistle
#

That's not the same script that's on the object

crimson tundra
#

Yes it is, I just changed the name

inner thistle
#

So it's still happening if you remove the component?

crimson tundra
#

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..

silver moss
#

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

crimson tundra
#

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

silver moss
#

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

silver moss
#

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

crimson tundra
#

@silver moss thanks for the help. My problems were coming from using the world position instead of the local position

worn mantle
#

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

timid dove
worn mantle
#

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?

timid dove
#

why not use OnTrigger/CollisionEnter and Exit?

sage whale
#

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)

worn mantle
#

oh, and also, this object can spawn inside another object.

timid dove
#

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

worn mantle
#

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

timid dove
#

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

worn mantle
#

yeah, really depends on the mesh itself. Like for example my log object has a "cyllinder" mesh collider (low poly invisable version).

#

thank you for the help