#⚛️┃physics

1 messages · Page 17 of 1

tired wasp
#

Like this

    public bool rotation = false;
    private Rigidbody rb;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    void Update()
    {
        if (rotation)
            rb.angularVelocity = Vector3.forward * rotationSpeed;
        else
            rb.angularVelocity = Vector3.back * rotationSpeed;
    }
neon widget
#

İt's radian, not degree

tired wasp
#

It worked with angularVelocity, thanks

timid dove
spring ivy
#

I have a Capsule. And two cubes at tow ends as child. The capsule has rigid body. the cubes don't. They all has colliders. So when the capsule collides with any collider in the environment, I want it to take damage. So I wrote a script and attached to the parent. This works fine when the parent hit anything. But, If the cubes hit anything, the game object still takes damage. I don't want the gameobject take damage when it collides with the cubes. Only when collides with the parent object, the capsule hits anything, then take a damage. How do I do this?

modern sedge
crude notch
#

Just want to say - massive thanks for mentioning this. I would have had no idea where to even look at and it feels like I've struck gold not just for this problem but a variety of other challenges I faced in previous attempts 😅

timid dove
#

Yeah it's an extremely useful concept

still prism
#

Hey guys! I'm in a big need of help. I'm making a game for Nintendo Switch, and the "FixedUpdate.PhysicsFixedUpdate" is taking around 7% of the total CPU time.

timid dove
#

physics isn't free

still prism
#

We do not use them for anything apart from a couple OnTrigger / OnCollision events

#

There is 0 rigidbody simulation, all are kinematic

timid dove
#

Yes, you pay for that.

#

the physics engine has to update all the object positions and look for collisions etc

#

Are you having a performance issue?

#

if so, what's taking up the other 93% of CPU?

still prism
#

From what I know (and what I've been told), FinishFrameRendering usually takes a good chunk of the CPU performance

#

The "EndGraphicsJobsAfterScriptLateUpdate" is us being draw calls bound. We are working on that too

timid dove
#

ScriptRunBehaviourUpdate is your script code in Update

still prism
#

And then there are our scripts (mostly a flocking system), and Physics + NavMeshAgents

timid dove
#

FinishFrameRendering is rendering yes, use the frame debugger to check that out in more detail

still prism
timid dove
#

i mean.. probably yes but rendering is 24ms so you should probably start with that

still prism
#

For info, on PC it takes 1.75 ms

still prism
timid dove
#

oh sorry yeah

#

Whether a number of ms is acceptable is really up to you

#

what's your target framerate

#

if it's 60fps, you get a frame budget of about 16.67 ms

still prism
#

It is 60 FPS yep

timid dove
#

In that cause I would say rendering taking almost 9ms is probably not acceptable, and that would be the first thing I'd try to optimize

still prism
#

I'll go back on that then, thanks for your insight.

formal fox
#

Hello guys! I am a complete newbie in the Unity btw, and I have a quick question but with a complex answer 😄

What is the best way (perfomance and maintainability) to detect layers? I mean, now I am using "Physics2D.OverlapBox" to check if Player/Enemies are grounded and on wall. In my enemy, I was thinking in create a child game object and put a trigger box collider to detect if Player is inside. This way is better or should I keep using the raycast?

I really don't know which solution could impact on perfomance. I am thinking in a Scene with 30 enemies patrolling and check for tha player, for example.

Sorry if this is a dumb question and thanks for your time 🙂

stark cloak
#

Not a dumb question , I'm also intrigued about the answer I use physics.spherecast but that's for 3d to check if my character is grounded

#

I think you should use the 2d version which is physics2d.circlecast as I believe it's far much precise, to optimize the overlapbox you could use the nonalloc method

formal fox
#

I think it would be simpler to create properties to change the width of the box and then I have the same script to any game objects, avoiding creating children objects to trigger stuff. But idk.

stark cloak
formal fox
#

Very nice, I will take a look on this. But in perfomance aspect, what do would suggest? Idk, it's sounds weird to me always have to create a child object to trigger stuff. In this example, I can use the Collision Detector in the Player and in the enemy and both works fine. I'm afraid this easiness could drive me to perfomance issue when I have 30 enemies on scene.

formal fox
stark cloak
stark cloak
formal fox
#

Nice. I have to learn about test and check perfomance in Unity to be sure, but for now I think I will keep the raycast. Thank you!

humble lake
#

Hey, i have been having problems with rigidbodies losing velocity for no apparent reason. for example if i have a door consisting of a cube shaped into a door with a hinge joint and rigidbody with no drag or angular drag and a physics texture with friction 0 and friction combine as minimum that is floating and does not have gravity. Now if i apply a force once at the position where the handle is, the angular velocity slowly decreases. anyone know what else could be causing this?

proper sluice
#

im adding an impulse force and torque to these dice and have some invisible borders like this red highlight here to prevent them from rolling off the table. the dice are leaning and stopping on them sometimes though which i dont really want, i tried adding a physics material with no friction hoping theyd slide and settle down or something but that didnt work, what else could i try to make the dice land flat and not get stopped on the wall? adding bounciness seems to help a bit but not totally

inner thistle
#

Add a small amount of force to the opposite direction when the dice hit the border or if they stop and are touching the border

neon widget
#

you can set a starting velocity and direction and lower it's value overtime. then when the dice hits the wall, change the velocity direction

uncut spade
#

I know Unity has a function for this, but I'm curious about how it works. How could one calculate the normals in a circle?

Like, if I have a point at {0, 0} that goes right. Imagine a simple Vector2.right or {1, 0} for the speed and there's a circle at any point between {4, n} where n equals any point between -1 and 1. How do you calculate the normals like that? Oh also, the circle would have a radius of 1. I want to be able to sort of calculate, where would that ball's velocity end up once it collides with the circle? I can kind of make an idea with how to do it if it was a segment, but how do you do it with a sphere? or well, how does Unity do it?

timid dove
#

The normal of a circle at any point on the perimeter is just pointOnPerimeter - circleCenter

#

is that what you are asking?

uncut spade
timid dove
#

that point would be at (1, 0)

#

so pointOnPerimeter - circleCenter would be (1, 0) - (0, 0) which would give you (1, 0) as the normal

#

essentially, for a circle, the normal is the same as the actual position of the point (adjusted for where the center of the circle is).

uncut spade
#

So it would be the direction vector between those points

#

Is it a coincidence that it is exactly perpendicular to its tangent?

timid dove
#

it's the vector perpendicular to the surface normal

#

So no, not a coincidence.

dapper eagle
#

Is this how the sleep threshold of a rigidbody is calculated properly?

float kineticEnergy = 0.5f * body.mass * body.velocity * body.velocity

Below i think is the comparison

kineticEnergy <= sleepThreshold * body.mass
uncut spade
#

Make sure to add parentheses to (body.velocity * body.velocity) because PEMDAS

timid dove
#

it doesn't matter which order you multiply things in

#

multiplication is commutative

crude pendant
#

I encountered: a physics related problem could u guys see if u can help

unique cave
static kestrel
stuck bay
#

guys my camera is shaking when i climb hills and i have a rigid body and i think that's causing the issue, how do i fix ?

#

cinimachine camera

unique cave
stuck bay
#

i played with all the rigid body values none of them helped

timid dove
#

Often that first one is the problem

stuck bay
#

i don't have ik system right now

timid dove
#

I didn't say anything about IK

#

Also your player doesn't turn at all?

#

I doubt that

stuck bay
#

it turns in camera's direction

#

rigid body rotations i mean

#

they are disabled

timid dove
#

Right that's a problem

#

If you do it wrong you will break interpolation

stuck bay
#

ok i solved the shaking issue with rigid body transform but the gravity is extremly slow

static kestrel
# unique cave ”this kind” is about as vague description as one could possibly give. To me look...

it's the projectile it has a disc movement where it doesn't rotate like crazy I made a prototype on a cube but i don't want it to rotate chaoticly the code: ```protected override void HandleCollision(Collision collision)
{
if(DoneReflecting) OnDestroy();
ReflectProjectile(collision);
base.HandleCollision(collision);
}

private void ReflectProjectile(Collision collision)
{
    // Get collision point and normal
    Vector3 collisionPoint = collision.contacts[0].point;
    Vector3 collisionNormal = collision.contacts[0].normal;

    // Calculate reflection direction
    Vector3 reflectionDirection = Vector3.Reflect(transform.forward, collisionNormal);
    
    // Add force to reflect the projectile
    projectileRigidbody?.AddForceAtPosition(reflectionDirection.normalized * discProjectileForce, collisionPoint, ForceMode.Impulse);
    Debug.DrawRay(collisionPoint, reflectionDirection, Color.green, 1f);
    _reflectionCount++;
}```
timid dove
viral beacon
#

is there any way to retreive all of the forces currently influencing a rigidbody? Im trying to do some of my own collision detection and it would help to have the current forces so I can compensate for them being applied after my script.

timid dove
#

That gets all the AddForce that has been done so far before the physics sim

viral beacon
timid dove
#

I assume ConstantForce just calls AddForce in FixedUpdate

#

so if you look before or after it will make a difference

karmic jolt
#

simulate your own friction and drag force

timid dove
#

The gravity force is very easy to calculate btw

viral beacon
#

well as long as all other forces are accounted for I can just add it to those

#

the problem was that I am calculating force values to be applied (for friction) that arent applied until the end of the frame (with the rest of the forces) so technically all of my calculations are behind by a frame. So to supplement that, I can mutiply all other forces by the timestep to predict the change in velocity and add it to the current velocity.

static kestrel
#

What is the most optimal approach for determining if an object has stopped moving or too slow at a certain point, focusing on both performance and precision?

#

current code for it: private IEnumerator CheckProjectileMovement() { bool isMoving = true; while (isMoving) { Vector3 startPos = transform.position; yield return new WaitForSeconds(secondIntervalToCheckMovement); Vector3 finalPos = transform.position; float distanceMoved = Vector3.Distance(startPos, finalPos); if (!(distanceMoved > movementThreshold)) { Debug.Log("the object stopped moving"); isMoving = false; OnDestroy(); } else { Debug.Log("the object is moving"); } } }

timid dove
static kestrel
#

yes

timid dove
#

use velocity from the Rigidbody

#

if (rb.velocity.magnitude < threshold)

static kestrel
#

something like this: private IEnumerator CheckProjectileMovement() { bool isMoving = true; if (!projectileRigidbody) yield break; while (isMoving) { // Check if the object still exists before accessing its Rigidbody if (projectileRigidbody.velocity.magnitude < movementThreshold) { Debug.Log("The object stopped moving"); isMoving = false; OnDestroy(); } else { Debug.Log("The object is moving"); } yield return new WaitForSeconds(secondIntervalToCheckMovement); } }

timid dove
static kestrel
#

It's currently being triggered in start and breaks the code when I do that

#

I probably do it in a bad way

timid dove
#

wdym by "breaks the code"?

static kestrel
#

it instantly despawned the projectile on press

#

I added 0.1 sec delay and it seem to have fixed it

timid dove
#

You'll need to obviously not start checking until after you give it a velocity

static kestrel
#

I added force beforerunning it in start

timid dove
#

AddForce doesn't change the velocity until the physics simulation starts

static kestrel
#

this is being run in Start(): protected override void Fire() { baseOnFireSound = onFireSound; RigidbodyConstraints constraints = RigidbodyConstraints.None; constraints |= freezeRotationX ? RigidbodyConstraints.FreezeRotationX : 0; constraints |= freezeRotationY ? RigidbodyConstraints.FreezeRotationY : 0; constraints |= freezeRotationZ ? RigidbodyConstraints.FreezeRotationZ : 0; projectileRigidbody.constraints = constraints; projectileRigidbody.useGravity = true; base.Fire(); projectileRigidbody?.AddForce(transform.forward * (baseForce + discProjectileForce), ForceMode.Impulse); StartCoroutine(DespawnAfterDelayCoroutine()); StartCoroutine(CheckProjectileMovement()); }

timid dove
#
projectileRigidbody.velocity = transform.forward * (baseForce + discProjectileForce) / projectileRigidbody.mass);``` instead of AddForce would fix it.
static kestrel
#

Hmm, I just read somewhere that force is more realistic simulating physics than velocity

timid dove
#

these are equivalent lines of code

#

the result of AddForce is to change the velocity

#

what you read was referring to constantly setting the velocity manually to a fixed thing.

#

That's literally all that AddForce does, it changes the velocity.

#

it doesn't do anything else

static kestrel
#

ahh, so velocity is better for projectile where add force is better for simulate fx a flying rocket

timid dove
#

no... you're misunderstanding

static kestrel
#

velocity is instant

timid dove
#

so is AddForce

static kestrel
#

add force takes time to trigeger

timid dove
#

no

#

the difference in your example is that you're calling AddForce every frame

#

vs just setting the velocity one time at the start

#

which is equivalent to adding force just one time at the start

#

AddForce is also additive vs setting velocity which overwrites the velocity, but you can of course compensate for that by simply setting it to something added to the current velocity.

#

They are ultimately doing the same thing, and as long as you know the math, you can achieve the same effect with either one

static kestrel
#

ahh so it's almost the same the one just adds to it

#

so addforce would be better if i want to add to something that is already moving

timid dove
#

yes it's adding vs setting

#

but under the hood adding is really just setting while taking the current value into account

#

think:

x = 5;
// vs
x = x + 5;```
#

in both cases we're still setting x with =, but the second one takes the current value into account

static kestrel
#

alright then it's very simple

#

velocity if I want to override the force, addforce if I want to add additional velocity but they both can do the same

#

that spared me adding delay for every check aswell 😄

static kestrel
#

I think .point is the point it hits and normal is which surface or something collision.contacts[0].point; collision.contacts[0].normal;

timid dove
#

Normal is the normal of the surface that it is touching.

#

also it's more efficient to use collision.GetContact(0)

static kestrel
#

It's a bit confusing how to use it to send velocity on a reflected direction

#

I try to achieve so when an object hit a point it should fly in a reflected direction with it's speed slowed with maybe 20% after each reflection

static kestrel
#

Something like this ```private void ReflectProjectile(Collision collision)
{
ContactPoint contact = collision.GetContact(0);

    Vector3 incomingDirection = transform.forward;
    Vector3 reflectedDirection = Vector3.Reflect(incomingDirection, contact.normal);

    // Calculate the magnitude of the reflected force with energy loss
    float reflectedForceMagnitude = discProjectileForce * lossOfEnergyPerHit;

    // Apply the reflected force at the collision point
    Vector3 reflectedForce = reflectedDirection.normalized * reflectedForceMagnitude;
    projectileRigidbody?.AddForceAtPosition(reflectedForce, contact.point, ForceMode.Impulse);

    // Increment reflection count
    _reflectionCount++;
}```
timid dove
#

wouldn't it be collision.GetContact(0).relativeVelocity?

static kestrel
#

it something like this im trying to emulate

#

But yeah I can see something is wrong in the code as the projectile fly weirdly

#

but calculating the velocity from both objects when they hit would definitely make it reflect better

tender crow
#

I am changing the Layer of an entity at runtime, and while the setting seem to take (via Entity Inspector the value of the layer is changed), physics still thinks the entity still has the previous Layer value. What is the proper way to do this?

#

I check using CollisionWorld.CheckBox() and set the filter to 1 << 16 and then previous value 1 << 15. CheckBox() returns true on 15 (previous value) and does not on 16 (new value).

unique cave
# static kestrel https://www.youtube.com/watch?v=xWhnIZL0rm0

If you want to keep the projectile flying and rotating stable as in the video, I wouldn’t even consider using physics because I’d assume it just messes everything up and causes unexpected rotations etc. I’d just raycast/boxcast/spherecast to figure out the path of the projectile so you wouldn’t need to worry about physics messing with the collisions and rotational momentum

static kestrel
dense stirrup
#

Working on a simple bouncing ball type thing, i've got it set up so that the ball flies off based on where it lands on this cube, but I've found that sometimes it bounces off in the complete wrong direction, as if it hits the collider twice, and is just generally inconsistent

public Vector3 startPos;
    public Vector3 centre;
    public float racketWidth;
    public float initialZ;
    public float initialY;
    [Range(0f, 45f)]
    public float maxReboundAngle;
    [Range(-45f, 0f)]
    public float minReboundAngle;
    public ProjectileSphere sphere;    
    void Start()
    {
        initialZ = transform.position.z;
        initialY = transform.position.y;
        centre = transform.position;
    }
    
    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            mousePosition.z = initialZ;
            mousePosition.y = initialY;
            transform.position = mousePosition;
        }
    }

    private void OnDrawGizmos()
    {
        Debug.DrawLine(centre, new Vector3(centre.x + (racketWidth / 2), centre.y, centre.z));
        //Debug.DrawLine(centre, new Vector3(centre.x + 2, centre.y + 1, centre.z));
    }

    private void OnCollisionEnter(Collision collision)
    {      
        float relativePosition = collision.contacts[0].point.x - centre.x;
        float launchAngle = Mathf.Lerp(minReboundAngle, maxReboundAngle, (relativePosition + racketWidth / 2) / racketWidth) + 90f;
                
        
        float launchAngleRadians = launchAngle * Mathf.Deg2Rad;        
        float velocityx = Mathf.Cos(launchAngleRadians);
        float velocityy = Mathf.Sin(launchAngleRadians);
        Vector3 direction = new Vector3(velocityx, velocityy, 0f);        
        Vector3 launchVelocity = direction * sphere.launchSpeed;        
        sphere.body.velocity = launchVelocity;
        
    }
#

The 'racket' itself only has one box collider with a physics material on it, but I'm not sure why it's behaving that way

timid dove
#

You're not accounting for the fact that it moves

#

Why not just read transform.position at the time of the collision?

dense stirrup
#

ah, good spot

#

just felt natural when I made it, but I suppose that works too

#

now though it's not rebounding based on where it lands. will see if I can fix that

timid dove
#

I'm not sure your launch angle logic makes sense either but it's too early for my brain

dense stirrup
#

maybe, but it's odd that it seems to bounce twice on the same object

dense stirrup
#

ay, fixed it. Turns out there's some messy stuff that happens when using on collision enter to change the velocity while also using the physics system

wary crater
#

Is there any possible way for an item to be picked up which would remove collisions but also have some sort of trigger when it hits another object?

#

When I pick something up this happens:

#

But I was hoping for it to turn out like this but still have some sort of collision

timid dove
#

But really for the attacking part you should just use direct physics queries not OnTriggerEnter

#

E.g. Physics.OverlapBox or something

wary crater
#

Oh right, do both methods work or does Physics.OverlapBox perform better?

#

Also when I turned on Is Trigger for the item, it just noclips

timid dove
#

It's not about performance, it's more about how awkward it would be to rely on waiting for a physics callback that happens later vs getting immediate answers from the physics query

timid dove
wary crater
#

Ah ok, thanks I'll check out physics.overlapbox

wary crater
#

Going back to this I was having a look at it and made a collision method for it

Collider[] colliders = Physics.OverlapCapsule(point0, point1, treeCollider.radius);
        if (colliders.Length > 0)
        {
            Debug.Log(colliders.Length);
            for(int i = 0; i < colliders.Length; i++)
            {
                if (colliders[i].transform.tag == "Item")
                {
                    Debug.Log("Hit by item!!!!");
                }
            }
        }```
#

I also have the settings for the collider when I pick up the item

if (rightHand != null)
            {
                transform.parent = rightHand.transform;

                GetComponent<Rigidbody>().detectCollisions = false;
                GetComponent<Rigidbody>().isKinematic = true;
                GetComponent<Rigidbody>().useGravity = false;

                transform.localPosition = new Vector3(0, 0, 0.5f);
                transform.rotation = Quaternion.Euler(0, 0, 90);
            }```
#

But I guess because I am turning off collisions it won't detect the collision

timid dove
#

I would recommend turning off the collider for the object when you pick it up

#

we are replacing that collider with the OverlapCapsule manual check

wary crater
#

Ohh right I'll check that

timid dove
#

you wouldn't check for the item tag

#

you are looking for objects that you are hitting with the item

#

(unless those are also items)

stray belfry
wary crater
#
GetComponent<BoxCollider>().enabled = false;
//GetComponent<Rigidbody>().detectCollisions = false;
//GetComponent<Rigidbody>().isKinematic = true;
GetComponent<Rigidbody>().useGravity = false;``` so I changed it to this and it seems like the tree isn't detecting it
timid dove
#

not the other way around

wary crater
#

ohh right

timid dove
#

you swing into the world (do overlapbox) and see what you hit

wary crater
#

I haven't applied it to the swing animation yet but I guess the usage of the condition would be the same

#
Collider[] colliders = Physics.OverlapBox(center, halfExtents, Quaternion.identity);
        if (colliders.Length > 0)
        {
            for (int i = 0; i < colliders.Length; i++)
            {
                if (colliders[i].transform.tag == "Tree")
                {
                    Debug.Log("Hit tree!!!!");
                }
            }
        }```
#

Just wanted to check if getting the center and halfExtents are correct since it's not detecting the tree

#
center = transform.position;
halfExtents = new Vector3(transform.localScale.x / 2, transform.localScale.y / 2, transform.localScale.z / 2);```
viral beacon
#

is this an appropriate means of calculating friction force?

float forwardFrictionMagnitude = Mathf.Clamp(slideVelocity / Time.fixedDeltaTime, Friction * -springForce.magnitude, Friction * springForce.magnitude);
Vector3 frictionForce = forwardFrictionMagnitude * -_slideDirForward;

Im using the formula f = μN as the clamp bounds for the magnitude force I am applying, then I am applying that to the inverse direction to that which my object is sliding. I felt it was kind of weird for me to have to divide by the timestep, but if I dont then the object can almost never stop on an inclined surface.

timid dove
viral beacon
#

forcemode force

timid dove
#

i.e. which ForceMode you use

#

Yeah if you use Impulse then you can get rid of that division

#

I'm not sure what springForce is here though

viral beacon
#

oh, its a kind of suspension raycast setup, since that is suspending the object its my N force

timid dove
#

friction usually involves objects sliding along each other

viral beacon
#

well yeah, the raycast hit represents the point of intersection.

#

or contact

timid dove
#

I don't see that represented in your code

viral beacon
#
Vector3 nextVelocity = _rb.velocity + (_rb.GetAccumulatedForce(Time.fixedDeltaTime) + Physics.gravity) * Time.fixedDeltaTime;

if (Physics.Raycast(transform.position, -transform.up, out _hit, rayDistance + 0.001f))
{
    // Calculate the force to push the parent object up
    float penetrationVelocity = Vector3.Dot(nextVelocity, -_hit.normal);

    // Calculate penetration distance
    float penetrationDistance = rayDistance - _hit.distance + penetrationVelocity * Time.fixedDeltaTime;

    _slideDirRight = Vector3.Cross(_hit.normal, nextVelocity).normalized;

    //Get the direction that the object would slide
    _slideDirForward = Vector3.Cross(_slideDirRight, _hit.normal).normalized;

    //calculate the velocity the object is sliding at
    float slideVelocity = Vector3.Dot(_slideDirForward, nextVelocity);

    //calculate the spring forces
    Vector3 springForce = _hit.normal * penetrationDistance * springConstant;

    float forwardFrictionMagnitude = Mathf.Clamp(slideVelocity / Time.fixedDeltaTime, Friction * -springForce.magnitude, Friction * springForce.magnitude);

    Vector3 frictionForce = forwardFrictionMagnitude * -_slideDirForward;

    _rb.AddForce(springForce + frictionForce, ForceMode.Force);
}
timid dove
#

```cs
// code here
```

#

like this

#

that can be used as the N (normal force) in the formula

#

oh wait sorry

#

this is a raycast

#

gtg lunchtime

viral beacon
#

alr

#

I mean, in general this seems to work fine, the friction just tends to behave a lot more strongly than I expect. I just wanted to know if something outright looks off in this code.

stray belfry
#

damn

oblique grove
#

Also worth checking if it's actually ignoring the OnTriggerEnter2D() call, or if it's just ignoring the side effects (i.e. the chomper dying and the Knight bouncing)

oblique grove
#

On an unrelated note, can anyone explain why this is happening? I have a capsule collider and a wedge-shaped mesh collider. When I mark the wedge as "convex", ComputePenetration() calculates an excessive overlap (marked by the red sphere). But if I change it to false, then it's fine. I know Unity simplifies overlap calculations for meshes marked as convex, but the mesh of the wedge model is mathematically convex, so I don't understand why computing the penetration when it's marked as convex would result in something inaccurate like this.

dapper lichen
# viral beacon ```cs Vector3 nextVelocity = _rb.velocity + (_rb.GetAccumulatedForce(Time.fixedD...

" I felt it was kind of weird for me to have to divide by the timestep, but if I don't then the object can almost never stop on an inclined surface." The friction value is supposed to a force (right?) and F=ma .. where a=>acceleration: the change in velocity per second (why you divide by timestep). I'd expect youd want something like (CHANGEinVelocity/timeStep) * mass for that first term in your forwardFrictionMagnitude (CHANGEinVelocity could indeed be the total velocity, if it changes to that in one timestep)

dapper lichen
oblique grove
#

Sure, the green capsule is the capsule collider, the blue sphere is the base of the capsule collider, and the red sphere is the base of the capsule if the depenetration vector computed by ComputePenetration() were to be applied
This is the code:

    private void OnDrawGizmos()
    {
        Physics.ComputePenetration(
            colliderA: _collider,
            positionA: transform.position,
            rotationA: transform.rotation,
            colliderB: _wedgeCollider,
            positionB: _wedgeCollider.transform.position,
            rotationB: _wedgeCollider.transform.rotation,
            out Vector3 direction,
            out float distance
            );

        _overlapDistance = distance * direction;

        Vector3 capsuleBase = transform.position + (0.5f * _collider.height) * -transform.up;
        Vector3 capsuleBaseCentre = capsuleBase + _collider.radius * transform.up;
        Vector3 correctedCapsuleBaseCentre = capsuleBaseCentre + _overlapDistance;

        Gizmos.color = Color.blue;
        Gizmos.DrawWireSphere(capsuleBaseCentre, _collider.radius);

        Gizmos.color = Color.red;
        Gizmos.DrawRay(capsuleBase,  _overlapDistance);
        Gizmos.DrawWireSphere(correctedCapsuleBaseCentre, _collider.radius);
    }
#

I'll try with the sphere collider

#

Okay so the capsule is just quirky like that

stray belfry
oblique grove
# stray belfry ok so it is skipping over the collision due to the high speed, but the players r...

I found this:
https://forum.unity.com/threads/continuous-collision-detection-not-working.1417548/
MelvMay (works at Unity): "Continuous doesn't work with Triggers"
Seems like the best workaround in your case is using boxcasts/circlecasts/Rigidbody2D.Cast instead

#

Just another thought though, If the knight is supposed to bounce of the chomper's head anyway, does it need to be a trigger? As in, you only need triggers if you need to pass through the collider, which the Knight doesn't (from what i understand).

stray belfry
stray belfry
karmic jolt
#

[2D physics]
I have an static physics object and a player rigidbody, the two is colliding. If the player collides with the object perpendicularly, would it negate all of player's velocity on that axis? if it's not perpendicular, how can we calculate the velocity negated by the collision.
I am currently making player able to slide through ledges of walls to correct players' movement error and I would like to preserve's player's velocity on collision with walls by making them able to slide through those ledges and continue with their old velocity like in Celeste or other platformer

#

I have tried using collision.relativeVelocity but the relative velocity that it pumps back is much higher than what I expect it to be.

karmic jolt
#

nvm im dumb

forest spire
worldly axle
#

when unity simulates physics, what is the closest real world unit of a rigidbody's mass ?

timid dove
#

The unit of distance is the meter

#

And the unit of force for AddForce (in ForceMode.Force) is the Newton

#

it's all pretty standard SI units

worldly axle
#

okay thanks

viral beacon
#

If a trigger component is intersecting multiple other colliders, is there a way to get a list/array of those intersected colliders? I believe the "OnTriggerStay" function only gets 1 collider as its parameter.

Or better yet, is there an efficient way to do a compute penetration for all objects intersecting the collider fed into the compute penetration operation at the position and with the rotation?

#

Seems like overlapbox might be what im looking for.

gilded fossil
#

Is there a way to make two triggers that can freely intersect, and when they do, they both trigger one another? I want weapons and armor in my game to be the same type of object, so when one hitbox intersects others, it should trigger events without any of them being solid

#

So like, I want a sword that can pass through a shield, and both the shield and the sword trigger an event when they collide/trigger one another

viral beacon
gilded fossil
#

So it can't be used with a mesh collider, then?

viral beacon
#

though I believe that compute penetration requires a convex mesh

gilded fossil
#

Damn, so there's not a simple way to just like, make hitboxes that can intersect, then.

viral beacon
#

Well, intersection events wont generate unless theres a rigidbody

#

if you dont mind using rigidbodies I guess that works.

gilded fossil
#

I don't mind using rigidbodies, what I'm trying to do is actually very similar to yours.

#

I just need a non-solid sword to be able to go through a non-solid shield and fire events for both of em when that happens

#

after doing some research, it looks like what I want to do is use Kinematic Rigidbodies, which skip the physics calcs?

gilded fossil
#

Yup, works perfectly with a kinematic rigidbody. I assume all I need to do now is make sure all hitbox objects are on one layer, and can only collide with one another.

#

How expensive are Kinematic Rigidbodies? research says that Kinematic disables all physics for the object, but is it cheap to have tons of them? At absolute max, I would probably end up needing around between 50 and 500 of them in a scene, but none of them interact with any actual physics-enabled objects

dusky eagle
#

Hi. I'm getting a strange result when Debug Logging Collision.gameObject.layer. The debug log outputs "13" but my layer 13 has no interactions set (and no objects involved in this collision are on layer 13). Am I misunderstanding something?
Ah, it gets the parent's layer and not the collider object's layer. Weird.

timid dove
timid dove
#

Use collider if you want the exact collider you hit

viral beacon
#

Would it be possible to get the deepest intersected point of a OverlapBox, regarless of collider type?

#

Im trying to do OverlapBox then Closestpoint on each collider returned, but it freaks out when the other collider isnt convex.

bleak umbra
viral beacon
#

I guess I can add a collider to my script object, I was hoping to avoid that though.

bleak umbra
#

overlap is only supposed to answer that simple question: "do they intersect", for everything else, the actual physics collision API is more helpful

viral beacon
#

also doesnt computepenetration not account for scale?

viral beacon
viral beacon
bleak umbra
tacit laurel
#

re: Raycast from within a collider, docu has this

#

but then there is that Physics.queriesHitBackfaces = tmp;

#

so, which is it?

bleak umbra
tacit laurel
#

Ah, a shame, would have made life easier. Does OverlapSPhere return true if the sphere is within any collider? even with a very small radius

wide osprey
#

I want to calculate the Z angle of a collider with raycasts. Anyone know how?

#

or to rephrase it i wanna calc the Z rotation

wide osprey
#

I fixed it. For anyone curious this is the result of me fiddling with procedural animation for 1 day. Still need to tweak and add A LOT. But its a really solid start imo

timid dove
wide osprey
#

yes i got that

timid dove
#

Then you have what you need

timber tulip
#

QQ: I'm changing the connected body of a configurable joint in code. setting the target rotation back to identity doesn't seem to be fixing the anchor tx, does it get baked somewhere else.?

#

Something is maintaining the angular offset between joint and connected body. And it doesn't seem to be a setting on the joint...

hexed spear
#

Hi guys, I have a weird issue at the very beginning of my 2D project.
The collision is not working well, as you can see, we the ball is falling, it stops at the platform level, but there's a gap between the ball and the platform, and I don't understand why. Here is with the Player inspector focused on box collider :

#

Here with the platform collider :

#

Any ideas about this issue ?
I'm on it for like one hour already and cannot understand why the physics is doing this

timid dove
#

and they're offset by the default contact offset

hexed spear
# timid dove Well your objects are tiny

Yes but I tried also with normal sizes (with value > 1) and it does the same.
Ok I check regarding the offset because I don't really understand what you mean here (probably due to my english also 😄 )

#

Ok I checked, I understand what the Default Contact Offset means, but the fact that I have the same behavior when I set the objets way bigger tells me that this is still weird and that the default contact offset should not be the cause of my issue

#

Mmmh I tried with wa bigger objets and obviously the gap seems now insignficant, ok seems alright

#

So conclusion :

I was basing my objects size (the ball is a golf ball, so around 4,5cm), but I shouldn't, right ?
I mean, how to have a size "reference" when your objects in your game are this small ?
Just take everything and multiply it by 10 ?
Or changing the scale reference in Unity Settings ? (value "1" is 1 meter by default)

timid dove
#

otherwise the feel will be way off

#

You can reduce the default contact offset if it doesn't suit your needs.

hexed spear
#

Ok thank you very much for your help, I will reduce the default contact then 🙂

wary crater
#

Is it possible to detect collision when you are moving an object through a script?

#
public IEnumerator moveTrees(GameObject _currentTree)
    {
        Debug.Log(_currentTree.GetComponent<TreeBehaviour>().isCollidingWithLand);

        while (!_currentTree.GetComponent<TreeBehaviour>().isCollidingWithLand)
        {
            _currentTree.transform.position = _currentTree.transform.position - new Vector3(0, 1, 0);
            yield return null;
        }

    }``` Example - I want to loop through moving a tree down until it hits land
timid dove
crude pendant
#

rb.AddForce(jumpForces, ForceMode.VelocityChange); this is what i used for the jump (Jumpforces is Vector3.up * jumpForce) and rb.AddForce(transform.forward * 1000, ForceMode.VelocityChange); is what I used for slide

timid dove
viral beacon
#

Could someone help me with my friction computation?

if (Physics.Raycast(transform.position, -transform.up, out _hit, suspensionDistance + wheelRadius))
{
    Vector3 externalForces = _rb.GetAccumulatedForce(Time.fixedDeltaTime) / _rb.mass + (_rb.useGravity ? Physics.gravity : Vector3.zero);

    Vector3 nextVelocity = _rb.GetPointVelocity(_hit.point) + externalForces * Time.fixedDeltaTime;

    // Calculate penetration distance and suspension velocity
    _lastLength = _springLength;
    _springLength = _hit.distance - wheelRadius;
    _springVelocity = (_lastLength - _springLength) / Time.fixedDeltaTime;

    float penetrationDistance = suspensionDistance - _springLength;

    //calculate the spring forces
    float springForceMagnitude = penetrationDistance * springConstant;

    float springDampingMagnitude = springDamping * _springVelocity;

    Vector3 springForce = _hit.normal * (springForceMagnitude + springDampingMagnitude);

    nextVelocity += springForce / _rb.mass * Time.fixedDeltaTime;

    Vector3 localVel = transform.InverseTransformDirection(nextVelocity);

    float frictionClamp = Friction * springForce.magnitude;

    float forwardFriction = Mathf.Clamp(_rb.mass * localVel.z / Time.fixedDeltaTime, -frictionClamp, frictionClamp);
    float sidewaysFriction = Mathf.Clamp(_rb.mass * localVel.x / Time.fixedDeltaTime, -frictionClamp, frictionClamp);

    Vector3 frictionForce = forwardFriction * -transform.forward + sidewaysFriction * -transform.right;

    _rb.AddForceAtPosition(springForce + frictionForce, _hit.point, ForceMode.Force);
}
#

I seem to get a very jittery and unstable simulation from applying friction force that I calculate at the contact point with the spring force. I found that I was able to get some stability back by expanding my parent rigidbody's collider to reach to each of my ray origins, but I still get a concerning amount of shaking.

I presume the issue derives from the fact that my friction force is calculated based on a desired change in velocity, which when applied to a point besides the center of the object will instead create a torque which may not place the contact point in the position assumed from the calculation.

hexed spear
#

Oh ok my bad for pinging you for nothing. My Unity was just not saving the modifications, I had to reboot it, and now it works..
Seems there is a bug with Unity somehow..
Thank you again for your help 🙂

fierce ingot
#

Anyone have an easy solution to why player's children objects are getting stuck to a certain spot on the player

#

not in playmode vs in play mode

#

I want it higher up but it keeps locking to the same spot

timid dove
#

It doesn't just happen

#

Also this has nothing to do with Physics

idle sluice
#

Need 2D Physics help. This pipe (Tilemap CompositeCollider2D) moves across the screen and if it collides with the player (BoxCollider2D with considerable edge radius), it will push them to the left. However, these pipes will continue to spawn and increase in speed, and the faster the game gets, the more the colliders will overlap.

This is the current overlap level (fairly far into the game's Endless Mode, but easily achievable). There's about 2.5 pixels' worth of overlap that should not be there, as it causes the game to think you're constantly touching the ground and thus allows you to jump multiple times while touching the wall.

I have messed with everything I thought would make a difference in the Physics2D settings. Doubling Velocity and Position iterations had no effect. Messing with the Baumgarte Scale had no effect. Increasing Max Linear Correction from 0.25 to 1 had no effect. Decreasing it to 0.1 had no effect. At this point I have no idea what to do.

This is the last major fix I need to make before I can release this project, and if I don't, the game's Endless Mode will break well before I believe it should.

#

The only thing I know that could possibly work is decreasing the Fixed timestep and ohhhhhhh my god I’m not doing that because it would basically throw off everything else in the game.

timid dove
#

Also your grounded check can be improved if that's the main issue here.

idle sluice
#

dude that’s too much overlap for my Ground Check to be the issue

timid dove
#

No I'm saying you can fix your grounded check if the grounded check is the only problem you have with it

timid dove
idle sluice
#

The player is a Dynamic Rigidbody2D. Its velocity is set using a SmoothDamp function in the character controller script.

The pipe is a child of an object called the Rail. It is a Kinematic Rigidbody2D that moves with a set velocity.

timid dove
#

By setting the velocity property?

#

Or else wise

idle sluice
#

Yes.

#

It always moves left. Its velocity increases with the player’s score so that the game gradually gets harder.

slim kestrel
#

Im trying to be able to stand on rigid bodies for a gravity gun system im making

#

Whenever I jump on the object, it goes through the floor tho

#

I know its because I have a rigid body, but I want to know if there is anyhting I can do to fix that so I can stand on top of these objects or if its impossible

#

Thank you to anyone who might have an idea of how to fix this!

timid dove
#

You should be able to stand on objects by default as long as they have colliders

icy obsidian
#

Can anyone tell me, why my car with rigidbody just goes flying when i start the game?

round hinge
#

hi, whats the downside of using ArticulationBody in Unity?

#

i used them a bit and found out they're vastly superior to rigidbodies, so whats the catch? the docs keep saying this component is for dynamics simulations and not for games, but doesnt mention why

timid dove
timid dove
round hinge
celest fern
#

@inland stone Well I have obstacles that move up/ down or in circles etc

#

The collisions there seem okay, but an even bigger problem was my collision of the Players' Weapon with enemies

#

I move the weapon in an attack animation and it has a trigger collider, so do the enemies

#

Oftentimes the colliders would obviously overlap but OnTriggerEnter would not be called

inland stone
celest fern
#

yeah

#

Not sure if im allowed to post links to a vid here?

inland stone
#

Not sure about vids, but a common oversight is forgetting a RigidBody component on one of the objects

tawdry wave
celest fern
#

this is how it looks

#

Kinematic with continuous collision detection

#

Could interpolation cause problems?

#

And this is the enemy for example

timid dove
# celest fern

for a weapon relying on OnTriggerEnter etc isn't really the best

#

you should just use like Physics2D.OverlapBox for example

celest fern
timid dove
#

that's not a problem

celest fern
timid dove
#

Does your player do an attack swing?

celest fern
timid dove
#

Or you're just supposed to kind of... prod your way into the enemy with the sword?

celest fern
#

The character has a swing animation

timid dove
#

Yeah meant player**

celest fern
#

here is how it looks

timid dove
celest fern
#

Okay I will read up the docs on how to use those! Didnt try these yet)

#

actually the overlapbox seems very nice on first glance cause I can easilly do the different attack ranges

#

Instead of having to manipulate collider size

inland stone
#

@celest fern
Just on the topic of colliders, since the enemies are not responding to any Physics interactions, you can have the Rigidbody on the weapon, and none on the Enemy.
This will make the performance better

timid dove
#

If the enemy is moving it should really have a Rigidbody

celest fern
#

The enemy does jump/ have gravity and collides with the map

#

So i think I need it there

#

But if I use overlapBox I dont need a rigidbody on the playerweapon right?

inland stone
timid dove
celest fern
#

yeah thats nice

#

I will try those for sure

#

Thanks alot both of you!

lucid finch
#

Looking for help programming a collision box for a physics based roller coaster sim in Unity

#

Anyone have advice? I want to start a voice chat or find an easy to follow tutorial

timid dove
#

Unity already has a physics engine and colliders programmed for you.

lucid finch
#

Yes: But I have a point where I want my roller coaster to climb up this hill

#

My idea is to have it accelerate when it collides into these boxes, unless there is a smarter option,

timid dove
#

For a roller coaster though I would probably not use Unity's physics engine. I would probably use a spline library and code my own kineticenergy/potential energy calculation

timid dove
lucid finch
#

Can I dm you to screen share?

#

Much easier to explain

#

@timid dove

timid dove
#

no

#

make a thread

#

here

lucid finch
#

I do not have time for that

timid dove
#

It's already done

#

I don't have time for a screenshare

lucid finch
#

Well who else does?

#

I do not want to waste time making a video

wary crater
#

I'm hoping to have a player move with the boat when a button is pressed. What I've done is that I've made the player a child of the boat and remove the rigidbody by using isKinematic = false but this is what happens:

https://gyazo.com/5610bb89be37c59c7400ece4ede5caf1.gif

is there a reason for why this happens?

#
if (Input.GetKey(KeyCode.A))
            steer = 1;
        if (Input.GetKey(KeyCode.D))
            steer = -1;

        Rigidbody.AddForceAtPosition(steer * transform.right * SteerPower / 100f, Motor.position);

        //compute vectors
        var forward = Vector3.Scale(new Vector3(1, 0, 1), transform.forward);
        var targetVel = Vector3.zero;

        //forward/backward power
        if (Input.GetKey(KeyCode.W))
        {
            PhysicsHelper.ApplyForceToReachVelocity(Rigidbody, forward * MaxSpeed, Power);
        }
            
        if (Input.GetKey(KeyCode.S))
        {
            PhysicsHelper.ApplyForceToReachVelocity(Rigidbody, forward * -MaxSpeed, Power);
        }
            ``` (this is the code for moving the boat)
gilded fossil
#

Do Colliders with Triggers still activate OnTriggerEnter when intersecting, if they've been set to ignore one another's collissions?

topaz kite
#

Hello, anyone with a kind heart could please help me solve my issue? my camera system and character movement system works fine, but whenever the Player collides with a object the camera starts shaking and only goes back to normal when I hit a flat surface

my code:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
public Camera cameraObject;
float rotationY, rotationX;

public float Speed;
public float Sensitivity;

// Start is called before the first frame update
void Start()
{
    Cursor.lockState = CursorLockMode.Locked;
    Cursor.visible = false;
}

// Update is called once per frame
void Update()
{
    float MouseX = Input.GetAxisRaw("Mouse X") * Sensitivity;
    float MouseY = -Input.GetAxisRaw("Mouse Y") * Sensitivity;

    rotationY += MouseY;
    rotationY = Mathf.Clamp(rotationY, -90, 90);
    rotationX += MouseX;

    Debug.Log(rotationY);

    cameraObject.transform.rotation = Quaternion.Euler(rotationY, rotationX, 0);

    Vector3 verticalInput = cameraObject.transform.forward * Input.GetAxisRaw("Vertical") * Time.deltaTime;
    Vector3 horizontalInput = cameraObject.transform.right * Input.GetAxisRaw("Horizontal") * Time.deltaTime;
    Vector3 playerInput = (verticalInput + horizontalInput).normalized * Speed;
    playerInput.y = 0;
    gameObject.GetComponent<Rigidbody>().velocity = playerInput;

    gameObject.transform.rotation = Quaternion.Euler(0, cameraObject.transform.rotation.eulerAngles.y, 0);

}

}

topaz kite
orchid path
#

does Rigidbody's interpolation(or extrapolation) still take place when you modify .velocity directly?

forest spire
#

When using RaycastCommand.ScheduleBatch with multiple hits enabled, is there any way to detect which RaycastCommand originated a given RaycastHit?

worldly axle
#

is there a way to have infinite friction, like when no force is applied an object doesn't move ?

inner thistle
#

You don't want to use friction for that. It would mean that the object won't move even when force is applied. Set the velocity to 0 when no force is applied

timid dove
worldly axle
forest spire
#

So if you pass 32, it will be grouped in groups of 32 RaycastHits

stuck bay
#
 void Update()
 {
     if (Input.GetMouseButtonDown(0))
     {
         Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
         _canForce = true;
         RaycastHit hit;

         if (Physics.Raycast(ray, out hit, Mathf.Infinity, LayerMask))
         {
             transform.position = hit.point + transform.localScale/2;

             transform.rotation = Quaternion.FromToRotation(transform.up, hit.normal);

         }

     }






 }
 private void OnTriggerStay(Collider other)
 {
     
     if (other.transform.tag == "Player" && _canForce)
     {
         _rb.AddForce(Vector3.up * _turnSpeed * Time.deltaTime, ForceMode.VelocityChange);
         _canForce = false;
     }
 }

Hello guys, I have some question. As you can see in the code that i sended. When I press mousebutton(0) im adding some force on my object. BUT when i spam the button velocity is getting increase every click. What I want is I just want to apply same force every click. I couldn't figure out how to do that

#

Okay okay i fixed, I reseted the velocity right before add the force by _rb.velocity = Vector3.zero

clear pewter
#

Hi guys,i am having a problem with an object,i want to make it rotate but it starts to rotate if i give him a lot of rotational force,how can i decrease it
the friction is set to 0

zealous shoal
wide glacier
#

@zealous shoal There's an option on the Rigidbody named exactly that, uncheck that and you'll likely be able to set it manually

#

It's right below angular drag

#

(I didn't exactly process the entire question before I answered lol but still, same answer)

zealous shoal
wide glacier
#

Yeah, but unless you change things after, it'll likely be a set and forget

#

I'd put it below 0 on the y, that'll be why it flipped over when you unchecked it in your vid

zealous shoal
wide glacier
#

0, 0, 0 will probably be where the objects world pivot is, so just tweak it from there

zealous shoal
wide glacier
#

Maybe your center of mass thing on your car controller script is fighting it?

#

Unless you're not doing anything with that, otherwise I have no clue, I was just suggesting what made the most sense to me lmao

zealous shoal
#

Welp it wasn't that either.. But thanks for your help anyways!

orchid path
#

If two trigger colliders hit each other, should both always receive the OnTriggerEnter call?

timid dove
wraith wren
#

Speaking of, my collision doesn't seem to be working and I can't figure out why. Both objects that are meant to collide (the player model and an obstacle) have a box collider, both "isTrigger" boxes are checked and the obstacle has a "OnTriggerEnter" call, yes that call doesn't work when the two objects come in contact. Is there something I'm forgetting ?

wraith wren
#

Apparently I needed a rigidbody, okee dokee

young barn
#

I'm new to Unity and I've looked around a bunch but haven't found out how you fix a problem I've been having. I'm making a 2D platformer and am just using the default physics settings and physics material. I'm also using the latest 2022 LTS version. My problem is when I "Build and run" my game the acceleration is much slower than when I test it in the editor . I'm just using the add force command if the x velocity is under a top speed and a button is being pressed. does anyone know how to fix this?

timid dove
#

Without seeing the actual code, it's hard to say more than that.

young barn
#

if (Input.GetKey(KeyCode.A) && myRigidbody.velocity.x > -topSpeed)
{
myRigidbody.AddForce(Vector2.left * accelleration);
if (!isClimbing)
{
FacingLeft = true;
}
}

timid dove
#

Physics belongs in FixedUpdate

#

Also please share code properly here

#

!code

flint portalBOT
young barn
#

so should I just change it from update to fixed update?

timid dove
#

I can't answer that with only seeing such a tiny code snippet

#

I can just tell you that any AddForce calls belong in FixedUpdate otherwise you will get framerate-dependent behavior

young barn
#

for singular AddForce calls where instead of constantly apllying force it does one call where it adds force will fixed update effect them differently?

timid dove
#

Think about it

#

It's really about how many times the thing gets called

#

if it gets called once, it doesn't really matter where that one time happens

#

that being said it's still best practice to only do it in FixedUpdate (or other physics callbacks like OnCollisionXXX/OnTriggerXXX)

#

but you can get away with one-off forces not in FixedUpdate

young barn
#

the difference is gone. thanks for the help.

scarlet sundial
#

is it possible to have non static colliders completely ignore contacts? so they are only responsive to casts - for physics 2d (incase that makes a difference)

fleet adder
scarlet sundial
#

already have such set up, the matrix is essentially empty- the only way i can get physics2d to stop calculating contacts appears to be by turning off simulate on the kinematic rigidbody

#

surely there's a way to do this 🤔

fleet adder
scarlet sundial
#

they're not actually colliding, but there appears to be significant overhead calculating contacts accoridng to the profiler

#

i guess the ultimate crux of the question is: what is the absolute minimum setup in terms of overhead for having non-static colliders in a scene that only respond to casts.

#

hmmmm just had a thought- what if i set update to script and run a single update whenever a cast is made

#

interesting.... casts still register even without any updates triggered via a script

fleet adder
#

seems like you have a ton of those, my first thought went to using entities and their physics system instead
but if you can get away with just running it from code, that does sound like a better idea

fleet adder
#

and still trigger the casts even if the collider's gone

scarlet sundial
#

what a mysterious system

#

this is with updates set to script

#

and casts do capture moving colliders at their given position

timid dove
#

If you want to update collider positions you can use Physics2D.SyncTransforms

scarlet sundial
#

Ahhh good to know! thanks. but they are responding to casts regardless of either an update or synctransforms call (while physics2d settings are set to Script)

#

am I missing something?

scarlet sundial
#

i'm going to try and reproduce in a clean project- i assume it's a package or something calling simulate or sync transforms somewhere

orchid ether
#

So I have a vehicle with a working script but for some reason it just slowly falls through the map as it goes forward. I fixed this issue awhile ago on a different game but can't remember what fixed it, any ideas? I would think it would be a collider issue

timid dove
lyric timber
#

Anyone have any thoughts about how one might go about calculating an inertia tensor/rotation for a Rigidbody in which the mass is very much not uniformly divided across all child colliders? AKA, how to simulate colliders with distinct densities? From what I understand, Nvidia Physics under the hood does just that, but Unity overrides it with the rigidbody mass instead.

timid dove
lyric timber
opal frigate
#

hi, im trying to add something i made in blender to a avatar i have and give it physics and i need some help. can anyone help atall it would be much appreciated

fresh osprey
#

Hi, I have an anoying problem with colliders, my player can get inside a collider and then "sit" on top of the one bellow, how can I avoid that?
He is not going fast just jumping on it.

austere vigil
#

is it possible to make a distancejoint2d stronger?
it seems far to easy to break

austere vigil
fresh osprey
#

Even with friction to 0 it still “sit” on the lower collider, they are perfectly aligned. So I don’t understand

brazen skiff
#

I need help. I have a ball (player) which is able to move by calculating a force vector from mouse dragging (start-end points).

Problem is that whenever for some reason player tries to shoot the ball towards the platform it stands on, rigidbody gets stuck inside the platform.

#

Rigidbody Settings

#

Applying a Physics Material 2D with no friction doesn't work.

fresh osprey
# timid dove Player movement code?

Executed in FixedUpdate

private void Move()
{
Vector3 movement = new Vector3(m_movementInput.x, 0, m_movementInput.y) * m_moveSpeed * Time.fixedDeltaTime;
m_rigidbody.MovePosition(m_rigidbody.position + movement);
}

brazen skiff
timid dove
#

You should do this:

private void Move()
{
    Vector3 movement = new Vector3(m_movementInput.x, 0, m_movementInput.y) * m_moveSpeed;
    m_rigidbody.velocity = movement;
}```
fresh osprey
#

It happen when the character slide down the wall

#

I want to round the edge of the collider but a mesh collider does not work and by player is a rounded cube, so a sphere collider is making it miss the corners on the collision

fresh osprey
#

it's in 3D

jovial bolt
#

yo

#

anyone here

#

say yeah if ur here now

#

calm no one

hybrid sluice
#

I'm trying to make this ball for breakout and sometimes when it hits a wall it dose not bounce and just loses all X or Y velocity everything has this physics material

hybrid sluice
#

increing the add force seems to have fixed it?

#

basically the box is a edge collider, and the ball has no drag, or gravity a mass of 1 and the physics material shown above

coral moat
#

hey idk if thats the right channel but im trying to code a paperplane in third person and have completely no clue of physics and 3d coding in general, so could somebody give me a few tipps or do you have some good tutorials in mind?

timid dove
#

Then you can model those forces in your code and it should give you the behavior you want.

#

For a paper plane you have:

  • Gravity
  • lift force from the wings, which is proportional in some way to the current velocity along its "forward" direction.
  • air resistance (which varies at different parts of the plane) which is also proportional to the velocity and the angle at which the air is hitting various parts such as the tail and "ailerons" of the paper plane
coral moat
#

ok ty but i have no idea how to implement air resistance for example. do you got any basic tutorials?

timid dove
#

it's just a force like any other

#

you'd calculate it and apply if to your Rigidbody with AddForceAtPosition

coral moat
#

ok

static kestrel
#

I'm trying to achieve a homing missile/projectile. This are the code: https://pastebin.com/wFzvUb5s. It finds a target but flyes towards it in a weird way that doesn't make sense like circling around until it randomly hits. MovePhysics are ran on FixedUpdate. Fire is on Awake() and fire is on Start(). I also want it to be performant so any input would be awesome

inner thistle
#

It would help to see what the "weird way" actually looks like but circling around the target is typical if the rotation speed is too low compared to the movement speed

static kestrel
#

weird way looks like this

#

updating the rotate speed helped, now it doesn't move in a weird circle and goes towards the target

dapper ember
#

Is it possible to design a character's movement system with Bezier Curves, or can I somehow turn bezier curves into unity physics?

timid dove
#

Yes for the first question

#

Maybe for the second? The second question is vague

dapper ember
#

I want to have an object be movable in various different ways; fast and dynamic, dashing, hovering, and slow.

#

i've been using bezier curves in blender to create the type of movement I'd like to have for each of those, and I'm wondering how to implement that in the actual game

timid dove
#

I wouldn't really consider it physics though.

tulip pier
#

is it better to use multiple box/capsule colliders or a single mesh collider?

timid dove
#

depends

#

for what?

tulip pier
#

i have a simple spaceship interior and i just want to set it up so that the player cannot fall thru the floor and walk thru the walls

timid dove
#

Does the spaceship ever move

tulip pier
#

it will be fully static

timid dove
#

you can use a single mesh collider here if you wish

#

however it would not be this mesh

#

Since the geometry of this mesh looks pretty degenerate by physical standards

#

also those cables don't look like something you'd typically include in a collder

tulip pier
#

i kinda want them to collide because i want the player to be able to move objects and i dont want them to clip into them

timid dove
#

This is quite a complicated mesh. You can tryitandsee

tulip pier
#

and if it weren´t static the several box meshes would be better?

timid dove
#

If it weren't static you would have no choice but to use primitives or a convex mesh collider

#

and this is kind of the opposite of convex

#

this is extremely concave

tulip pier
#

oh okay thank you

viral beacon
#

does anyone know how the unity wheel collider calculates sideways slip?

#

Slip ratio I mean, the forward ratio equation is pretty easily found online.

dapper ember
#

This is a simple cube with a rigidbody. The current movement is just basically:

transform.velocity = Vector3.zero;
rb.AddForce(transform.right * speed, ForceMode.Impulse);

How could I add a "bungee" effect to it? ie if it's going to the left and user presses D to go right, then it keeps going left but speed decreases pretty quickly to 0 and it starts speeding in the right direction?

#

^^^ it's being moved with A and D keys.

timid dove
#

What you have right now is just a roundabout way of directly setting the velocity

dapper ember
fierce rapids
#

how does the swap bodies setting work for the configurable joint? i didnt understand the unity docs.

dapper ember
#

do you guys know any resources on physics for game dev? it would be useful if there was a collection of all kinds of physics game mechanics (e.g flying, hovering, etc.) and a guide for how to implement each one

bleak umbra
dapper ember
#

Is it an inefficient way to implement a trampoline by creating a grid of springs and in a script creating the vertices and calculating the triangles? And then creating a Mesh and every frame, updating the vertices of the mesh?

bleak umbra
#

My guess is that you can optimize this setup by a lot (in terms of performing the calculations) if you know the topology of the spring connections. A generic spring might not be able to make many assumptions that would allow it to be fast.

#

Maybe a trampoline can even be described by a closed equation and doesn’t need any simulation

gaunt turret
#

Does anyone know why the size.Y value is astronomical for this BoxCollider2D while the size.X value is 1, and the Y only looks about twice as big? This GO's scale is 1x1x1 and its parent's is 2x2x2

#

Ah figured it out - the parent had a 90 degree X rotation so the Y dimension in 2d was compressed to almost nothing.

viral beacon
#

How do I overcome the sliding of my custom wheel collider on an inclined surface? This seems to be an issue that nearly every custom wheel solution I have come across has also faced.

bleak umbra
viral beacon
#

could you link me to some resources that would help with that?

bleak umbra
deep gate
#

Anyone knows whats wrong with the physics / Colliders here?
Already set the Default Contact Offset to the lowest possible amount, is looking better but not good enough 🤔

#

or is there another work around to make a collider "not filled" without the polygon collider component ?

timid dove
#

but no, you can't have a "hollow" circle collider

#

why are you doing this btw?

deep gate
timid dove
#

& why not just rb.velocity *= 0.00001f;

deep gate
timid dove
#

but yeah what's the idea

deep gate
timid dove
#

Also why are you doing either one?

timid dove
#

I was talking about doing this

#

oh wait

#

that's a +

#

not a *

#

I see

deep gate
#

yea xd

#

this should be the problem

#

anyways, i got it to work

#

looking fine now

timid dove
#

So actually this would be more correct though:

Vector3 vel = rb.velocity;
float magnitude = vel.magnitude;
float newMagnitude = magnitude + speed;
rb.velocity = vel.normalized * newMagnitude;``` @deep gate
#

because just doing like +.001 to x means it will speed up when moving right but slow down when moving left, for example

timid dove
#

another alternative is:

rb.velocity *= (1 + speed);```
#

that one is exponential instead of linear though

deep gate
#

is this a big difference in your opinion?

timid dove
#

with small numbers there's not likely to be a noticable difference, especially over a short time frame

#

also friction and random energy loss from inaccuracy or inelastic collision is likely to be significant

deep gate
wheat shard
#

how would i add collisions to a tile pallete?

#

so i can draw area a character cannot pass through by just using the pallete

timid dove
#

You can edit the physics shape of each sprite from the sprite editor

wheat shard
somber bone
#

Hi
I set up a box collider 2d on the cube and drop countless Rays from the sky against the lined up cubes.
The RaycastHit2D results show that in most cases the normals are (0,1). (This is the expected result.)
However, in rare cases, it returns non-zero X values, such as (-0.075048953294754, 0.997179865837097).
This causes the ball to bounce when it is rolled over cubes.
Is there any way to avoid these mysterious normal values?

round hinge
#

hey, anyone has an idea on why velocity is downwards while the object is in fact still?

#

using the default physics settings, except gravity is -100 towards bottom

#

and it's an ArticulationBody and not a rigidbody

round hinge
timid dove
somber bone
timid dove
deep gate
#

What’s the keyword I can search for to animate him but also keep the physics ? Lets say he’s walking and getting a hit from the side, so he don’t fall over but dynamically stabilize itself ?

somber bone
deep gate
timid dove
somber bone
#

It is certainly possible to attribute the colliding object and set the normals
But is that the correct implementation?

static kestrel
#

I have a projectile and a player the player has gameobjects inside. Is there a smart way for the projectile to detect the gun, player etc as one unit. I try to keep it open for multiplayer as it will have multiplayer implemented later. Which approach is best for this?

timid dove
static kestrel
#

Rocket jump, self damage, some projectiles ignores the player etc

timid dove
#

pick one

static kestrel
#

Currently i'm trying to implement rocket jump

timid dove
#

rocket jump should probably only deal with the main capsule of the player, assuming it has one

#

is there a reason the gun actually needs a collider?

static kestrel
#

probably not

#

Would you just fetch the gameobject id?

#

and based on that apply explosionforce

timid dove
#

Why would you want a gameobject id

#

You would do like an OverlapSphere

static kestrel
#

to know it's the owner

timid dove
#

and from the collider you can find the player's Rigidbody e.g. with GetComponentInParent<Rigidbody>

static kestrel
#

but it has to be the owner it could also hit a teammate which also has a player gameobject structure

somber bone
regal summit
#

Is there some way I can encourage this capsule collider to fall over? I am not even sure how its physics-ally staying up. Is this happening because of the pivot point?

timid dove
#

so it's behaving like a top

regal summit
#

at that low a speed I would imagine a capsule would fall over to its flat length side

#

Can I change something in the code or the physical properties to make it fall over easier?

#

currently just using default RB parameters so I am not super familiar with how they affect the sim

timid dove
regal summit
#

Oh didn't know that existed 👀 Will swap that in

timid dove
#

but... you spun the thing

#

and the spinning causes a gyroscoping effect

#

causing it to not fall over

timid dove
regal summit
#

Oh yeah when I bonk it, I turn off kinematic first

regal summit
#

That shouldn't be able to support itself and I don't want it to be able to do that behaviour

#

The question is how do I tell Unity/the mesh that

regal summit
timid dove
#

I feel like getting that top effect should be pretty rare... is it happening consistently?

regal summit
#

Yes actually, about 1/3 of the time I call that bundt code

regal summit
#

yeah most of the time, it resists falling down heavily

#

even the slightest 'spin'

timid dove
#

maybe just constrain its rotation on the y axis?

#

or set the y part of the torque to 0?

unborn cave
#

im no expert, but i feel increased mass & less friction (w physics material) would help

vestal steppe
#

Issue with Animator to Ragdoll transition

#

Oh, and I have heard that this is a common issue

#

It would be helpful to either link resources or help with my issue directly. Thanks.

viral beacon
#

Is there a means of getting the normal at the contact after the result of computepenetration?

timid dove
viral beacon
#

It doesnt consistently point outwards of the collision

gilded sparrow
#

Hi quick question. Apparently OnTriggerStay2D only gets called when object is moving. Is it normal to have the player and enemies have their RB set to SleepMode.NeverSleep?
Then what if i expect to have many enemies, but some not moving, and want their TriggerStay reliable?
I only want the trigger to be reliable for static/level's colliders. Is there still a way to avoid having units set to NeverSleep while still having a reliable TriggerStay just between dynamic and static?

To clarify, i dont want to have to set all my units to NeverSleep
I dont need reliable dynamic to dynamic TriggerStay. Only dynamic with static

timid dove
#

With yield return new WaitForFixedUpdate and StopCoroutine

wispy patrol
#

Hi, I switched my project to Unity 6, but now I'm getting errors like this:

Failed to create Physics Mesh from source mesh. One of the triangles is too large. It's recommended to tesselate the large triangles. Source mesh name: pb_Mesh31822

Failed to create Physics Mesh from source mesh. One of the triangles is too large. It's recommended to tesselate the large triangles. Source mesh name: pb_Mesh-749494 UnityEditor.EditorApplication:Internal_RestoreLastOpenedScenes ()

regal summit
#

What am I doing wrong here that prevents this capsule collider from falling over?

#

I don't know how or why but it behaves like one of those cannot fall over pill toys

#

it keeps self righting and that's the exact opposite of what I want, I want it to fall over

#

Been struggling heavily to get this thing to behave 'real' at all, if I throw a cup at the floor I can verbally tell you HOW it should behave, how do I tell unity this?

#

its like its falling over in slow motion as well, I don't get why gravity is so weak

#

I havent done anything, its all stock unity default values, but its nothing like physics or reality

charred jetty
#

Using the gravity formula, is this the correct way to calculate the gravity, applied in FixedUpdate?
_gravityForce is 9.81f and _gravitationalConstant is 6.67e-11f.
Also, should the distance be changed every frame or is it a constant value?

float gravity = _gravityForce * _gravitationalConstant / Mathf.Pow(distance, 2);
timid dove
#

Is this for an orbital simulation or something?

The distance is definitely not a constant

wispy patrol
#

Hey guys, I'm still having this error:

Failed to create Physics Mesh from source mesh. One of the triangles is too large. It's recommended to tesselate the large triangles. Source mesh name: pb_Mesh-749494 UnityEditor.EditorApplication:Internal_RestoreLastOpenedScenes ()

_
I'm not sure how to look up mesh name: pb_Mesh-749494

timid dove
#

It's being generated from one of your ProBuilder Mesh objects

viral beacon
#

Is there a way to do computepenetration in such a way that it uses the next physics step? Im trying to do this right now by adding the rigidbody's current velocity to the position, but because I have multiple bodies adding force to one main parent body I think the prediction is being obscured.

Im trying to make a suspension-like system where I align a rigidbody wheel to a fixed axis and modify its position using a velocity I calculate as a result of computepenetration.

#

I guess I could make a parent object that keeps track of the forces added and uses them accordingly, but if theres a more commonly known way let me know.

bleak umbra
#

in such cases it may be more convenient to make a custom simulation for the parts that need this

coarse tiger
#

When lagging is AddForce() with ForceMode.Force in FixedUpdate() adding force per real life second or always multiplied by constant Fixed Timestep?

timid dove
kindred lion
#

can someone help me i have no clue why my character just flips

timid dove
#

but basically it's falling over because that's what happens to physical objects when you throw them around

kindred lion
#

oh right thanks

#

oh shit right i forgot to freeze z rotation that fixed it thanks

sly flame
#

It would be an unique twist in the game. It's a bug feature!

elder cave
#

i have this problem with a tileset im using, appeared suddenly and dont know how to fix this

timid dove
elder cave
#

i did both

timid dove
#
  • Check the settings on the composite collider
#

share those things here if you didn't see what's wrong

elder cave
#

okk

#

i even tried to set the generation type to manual and regenerate the collider

timid dove
# elder cave

You have "extrustion factor" set to 1 on the tilemap collider?

elder cave
#

whats that?

timid dove
#

I would guess... it extrudes the collider? Perhaps resulting in what you're seeing

elder cave
#

i set it to 0 but still noithing

timid dove
#

make sure it gets regenerated

elder cave
#

oh ok

#

omg thank you it worked

sand ruin
#

Anyone know why my Mesh Collider doesnt auto create a mesh for my selected object?

timid dove
#

If you attach one to an object that has a MeshFilter, it will borrow the mesh from the MeshFilter to generate its geometry

#

otherwise, it will do nothing unless you manually assign a mesh

sand ruin
#

Ahh alright. But why cant I attatch my actual model into the mesh component and use that to actually form the collider?

#

Like my model doesnt show up as an actual option.

timid dove
#

You can drop any Mesh you want into the MeshCollider

#

When you say "my model" can you be more specific about what you're referring to?

timid dove
sand ruin
#

Okay, so I made a simple model in Maya and then exported it into Unity to be used.

#

I tried dragging the model into the "Mesh" part of the Mesh Collider and it doesnt wanna work.

timid dove
#

Can you show screenshots?

sand ruin
#

Sure.

timid dove
#

In the project window, when you look at your model fikle, you can generally expand it to see what Meshes are inside. You can then drag one of those meshes directly into the MeshCollider's field

sand ruin
#

So this is the model im talking about. Low poly nothing special.

timid dove
#

I'm less interested in scene view/game view

#

more interested in the project window and inspectors

sand ruin
#

Alright. So this is the model unwrapped. And the components of the object.

#

I can drag and drop the cubes into the mesh. However its not the size of the model. Its like really small compared to the full scale of the model.

#

Unless there is a way to change the actual mesh size. Then that would be helpful.

timid dove
#

theseare the only things you'd be able to drag into the MeshCollider's "mesh" field

sand ruin
#

Yeah. Those I can drag into the mesh section.

timid dove
#

Is there a reason you need a MeshCollider for this?

#

Wouldn't a BoxCollider suffice?

#

Anyway for performance reasons it's probably better if you make this all into one Mesh instead of several different meshes.

sand ruin
#

I have other models too that are not simply shaped like this one. However I did try the box collider, but the box collider is too big and when i tried changing the collider it changed the model size too.

sand ruin
#

Dont worry. Problem solved.

timid dove
fierce helm
#

Hello everybody can someone help me with this sh*t?
From the beginning i had buy 3D project and i just need to replace 3D character into 2D sprite i did it but now i have this crash on Android system... I don't know how to fix it.

This is the full logcat: https://pastebin.com/csKiwzzX

silk zodiac
#

I need help. In my game I want the walls to stop the player but if you just keep holding the button and push it into the wall it causes the rigidbody to just start floating away in the opposite direction once you let go of the button.

timid dove
#

sounds like maybe you're moving it in a way that isn't physics friendly so it's being pushed inside the wall and getting depenetrated out.

silk zodiac
#

I'm using this in fixed update:
rb.transform.position += transform.rotation * new Vector3(0, 0, Input.GetAxis("Vertical")) * moveSpeed * Time.fixedDeltaTime;
rb.transform.rotation *= Quaternion.Euler(0, Input.GetAxis("Horizontal") * rotationSpeed * Time.fixedDeltaTime, 0);

timid dove
#

yeah you're bypassing physics entirely

#

If you want to do it right:

rb.velocity = rb.rotation * (Vector3.forward * Input.GetAxis("Vertical") * moveSpeed);
rb.angularValocity = new Vector3(0, Input.GetAxis("Horizontal") * rotationSpeed, 0);```
@silk zodiac
silk zodiac
#

should I still multiply it by Time.deltaTime or does it not matter

timid dove
#

it matters a lot

#

and you should not

#

the physics engine handles that bit

silk zodiac
#

ah ok

#

this works perfectly. Thank you

silk zodiac
coral mango
#

You can use a character controller, though it'd take a bit of code reworking.

woven schooner
#

I have a problem with intractable items colliding with my XR Origin and making me move, putting these on a different layer and changing the physics on them just made it so that I couldn't interact with the object anymore, anyone able to help me?

languid cipher
#

hi guys i need help with the box collider 2d where can i sent it?

stiff topaz
languid cipher
echo sage
#

Hi all, wondering if anyone can help me with understanding ArticulationBodies and using AddForce with ForceMode.Acceleration .

I'm working on a vehicle controller and using articulation bodies on the car. The articulation bodies are nested in this hierarchy; Vehicle > Axle > Suspension > Steering > Wheel.

When I calculate the needed acceleration using the vehicle's mass and the final output torque at the axle (using wheel radius), I get -for example- 3.6m/s/s.

When I apply this 3.6m/s/s to the vehicle root articulation body, the vehicle seems to move at an appropriate speed. Unfortunately, I need to apply this acceleration force to each wheel. When I try to apply the same 3.6m/s/s acceleration to each wheel, the vehicle moves extremely slowly.

For reference, the vehicle root calculates and adds all of the vehicle masses together to have the total mass (which is what I'm using to calculate acceleration). What I'm wondering is; if the vehicle mass is -for example- 2000kg, and the wheel itself is 15kg, is the acceleration being applied to the 15kg? And if it is, wouldn't that make it go faster? Also, if this is the case, how do I proportionately increase the acceleration because of this?

timid dove
#

is the acceleration being applied to the 15kg?
Yes
wouldn't that make it go faster
No because the total momentum/kinetic energy of a 15kg object moving at a certain speed is much lower than a 2000kg object moving at that same speed

#

so when the 15kg object expends its energy into the main body, you will end up with a much lower velocity

#

What's the goal? For the whole body to accelerate at 3.6m/s ?

echo sage
#

WOW I'm blown away by your speedy timing! And yes, that is the goal, to make the whole body accelerate at that speed.

echo sage
# timid dove > is the acceleration being applied to the 15kg? Yes > wouldn't that make it go ...

I'm trying to make (another) vehicle controller based on "realistic" simulations. I started with the motor (basing it off of an E46 M3) using its horsepower, power curve and rev limits, calculating torque curve, then sending torque and RPM through the transmission and final drive (I have more components, but this is asimplistic explaination). I finally send the calculated Torque and RPM to the rear wheels.

I am using articulation bodies and sphere colliders to get more information than a simple wheel collider, so I'm trying to figure out how each wheel can supply the appropriate acceleration to move the car in the correct manor

#

I've been working on this engine controller for days now trying so many things to make this work "realistically". What I initially thought was just to use the torque in Nm / wheelRadius to get the force needed to use AddForce with default Force mode. But when the gear is shifted to second gear, the gear ratio is smaller, making the torque and force smaller which slows the vehicle down. So I decided to try using Acceleration force mode.

timid dove
#

Or just add the totalForce to the main body

echo sage
timid dove
#

if you want to generate this force using torque from your wheels, that'd be another layer of calculations

echo sage
# timid dove if you want to generate this force using torque from your wheels, that'd be anot...

Yeah, I want to try to make it as realistic as possible. I have the RPMs and the Torque. I can calculate the desired wheel speed at a specific RPM, but then I need to see where the torque comes into play, or vice versa.

The closest I got, logically thinking is I calculate the desired wheel speed and get the current wheel speed. If the desired wheel speed is greater than the current wheel speed, check to see if there's enough torque to break traction (calculated by tractive forces). If the current force needed is less than the maximum tractive force, then... use the torque somehow to get the car up to the proper speed?

stiff topaz
#

Hello all, I have a script that lets a player fall through a platform if you hold down and the jump button, and you do fall through it (it disables the box collider 2d), but if you let go too soon (I have the box collider be enabled when you let go) it pops the player back on top of the platform, even when I make the platform have a height of 0.02, the platforms have a platform effector and i have the script turn off the box collider and platform effector when you hold down and jump and turn them back on when you let go

echo sage
stiff topaz
#

unfortunately some platforms are rotated

#

I think I figured it out, I added an extra box collider as a trigger and when player exits trigger it turns back on

#

it seems to be working as I wanted

echo sage
#

Gotcha. My next thought would be to temporarily ignore the specific collider until it's no longer overlapping (like watching the OnColliderStay or whatever it is

#

That's good you got it working though 🙂

stiff topaz
#

thanks!

spark otter
#

quick question, does the "is trigger" on a box collider allow me to use Ontrigger on it

timid dove
#

Yeah that's the point basically

#

OnTriggerEnter/Exit/Stay

#

It also you know... makes it a trigger of course

spark otter
#

okayokay

winged herald
#

Is it intended for OnDisable and OnEnable to be called when reparenting GameObjects between scenes that are loaded in with the Physics2D LoadSceneMode?

sweet flame
#

I am trying to change the friction of the physics material of my object but I just cant get it to work

#

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
public float dynFriction;
public float statFriction;
public Collider coll;
void Start() {
coll = GetComponent<Collider>();
coll.material.dynamicFriction = dynFriction;
coll.material.staticFriction = statFriction;
}
}
I have been trying this but It says there is no collider but the script is trying to access it

#

there is a collider, a boxcollider2d, I tried replacing the "Collider" parts with "BoxCollider2D" and now it says Object refrence is not set to an instance of the object

timid dove
#

As for the second error you probably don't have a physics material assigned to it

keen spoke
#

sort of a physics problem here.
For several reasons I had to make a custom xr grab interactable script to get interactions to be exactly the way i want, and the last thing I need to add for it to be pretty much perfect is letting the player throw what they are holding under certain criteria. the carried object has an attached rigidbody but is moved via temporarily parenting to the player's hand(s) while holding. It is also set to kinematic while being held.
I have to mathematically find the "velocity" and "angular velocity" of the carried object so that when thrown, it accurately moves where the player swings it before releasing.

The current method works perfectly for normal translational velocity, but angular velocity is totally unpredictable. Even scaled down to 1% force application, the thrown object sometimes ends up spinning in a seemingly random direction at hundreds of RPM, and sometimes is fairly reasonable. I have tried numerous methods to get it to work correctly but it is different every time i "throw" the item.

#
{
    if (throwOnRelease)
    {

        if (throwThisUpdate)
        {
            Debug.Log("Throwing");

            PositionalVelocity = (transform.position - lastPosition) / Time.deltaTime;
            AngularVelocity.x = Mathf.DeltaAngle(transform.eulerAngles.x, lastRotation.x) / Time.deltaTime;
            AngularVelocity.y = Mathf.DeltaAngle(transform.eulerAngles.y, lastRotation.y) / Time.deltaTime;
            AngularVelocity.z = Mathf.DeltaAngle(transform.eulerAngles.z, lastRotation.z) / Time.deltaTime;

            rigidbody.AddForce(PositionalVelocity * positionalThrowScalar, ForceMode.VelocityChange);
            rigidbody.AddTorque(AngularVelocity * angularThrowScalar, ForceMode.VelocityChange);

            throwThisUpdate = false;
        }

        lastPosition = transform.position;
        lastRotation = transform.eulerAngles;
    }
}```
kind estuary
#

Hey, I'm trying to make a Zero Gravity racing game demo and I've reached a roadblock with the physics right now.
I'm able to obtain the desired normals of the player and rotate it towards these normals when grounded but my problem arises when I try to transfer from one track to another that is above or beside my track (I detect the nearest track and gravity changes to that direction accordingly).
I just need to be able to smoothly rotate the player to the desired / detected normals after getting the point on the nearest track that we want to attract to but I can't seem to get it to work. It's super wobbly and unstable and since I am constantly trying to detect for the nearest point and it's desired normals I end up changing the desired rotation before reaching the previous one it seems.

Here is my code to orient the player to the correct rotation:

Quaternion toRot = Quaternion.FromToRotation(playerScript.transform.up, playerScript.groundDetectionScript.desiredNormals.forward) * playerScript.transform.rotation; playerScript.rb.MoveRotation(Quaternion.Lerp(playerScript.transform.rotation, toRot, orientSmoothness * Time.fixedDeltaTime));

timid dove
#

order of operations matters for quaternion composition

timid tulip
#

Hello, I need some help with some physics calculations that I've definitely implemented wrong.

I'm working on a VR fishing game, and have it designed where, at the moment, when the fishing rod is cast forwards and the lure's rigidbody reaches a certain velocity, we instantiate a new lire and fire it out with the same physics parameters as the lure attached to the fishing rod.

This has been a bit on-and-off, but working for the most part. However, I have noticed that now it is almost always firing the new lure out behind the direction of the cast, and seems to have a trajectory of directly down.

Not sure what might be helpful to include, so I'll attach a short video and my instantiated lure snippet here.

[ContextMenu("InstantiateFreeLure")]
    public void InstantiateFreeLure()
    {
        if (LureInstantiated) return;

        // Debug: Print the velocity
        Debug.Log("verletPhysicsLure is moving in direction: " + verletLureRb.velocity);

        // Get rod lure position and rotation for instantiating the free lure
        Vector3 lureSpawnPosition = verletLureRb.transform.position;
        Quaternion lureSpawnRotation = verletLureRb.transform.rotation;

        // Get physics info from lure rb
        Vector3 castingDirection = verletLureRb.velocity.normalized;
        float castingForce = verletLureRb.velocity.magnitude * .05f;

        instantiatedCastLure = Instantiate(freeLurePrefab, lureSpawnPosition, lureSpawnRotation);
        Rigidbody freeLureRb = instantiatedCastLure.GetComponent<Rigidbody>();

        Debug.Log("Lure spawn position: " + lureSpawnPosition);

        //freeLureRb.velocity = verletLureRb.velocity;
        //freeLureRb.AddForce(castingDirection * castingForce, ForceMode.Impulse);

        LureInstantiated = true;
        
        drawTrajectory.trajectoryRb = freeLureRb;
        drawTrajectory.DrawTrajectoryOnce();
    }
#

The green line there is trajectory from the starting point of the instantiated lure, which also appears to be behaving not as I want / expect. This lure is at the end of a Verlet Physics line, so its definitely something to do with that being mismatched from where I would want / expect it to be on the rod throughout the casting process.

Doesn't explain the trajectory being straight down though

timid tulip
#

So still having an issue with determining direction and trajectory, at least as I want it.

In the first cast it is behaving correctly and as I want, casting when it reaches a certain velocity. Problem is, that velocity is pretty impossible to achieve with your arms. Second cast is at a lower velocity, but for some reason, fires not in the direction of travel. Unsure exactly why this is happening, but I assume that, because the lure is attached to a springy rope, it is heading backwards for a bit as the rod is swinging forward, reaching the velocity threshold, and casting at that point?

What's the best way I can work around this?

wind meadow
#

question how does physics.overlapbox work?

#

like if an object is completely inside the box, will it detect it?

wind meadow
#

disregard found out the cause of my issue

dry wraith
#

I'm trying to get a stained glass window to break when it gets hit by an object, and each piece is a Rigidbody, but Unity refuses to let me use any Rigidbody except convex ones, but the pieces are mostly concave and start out all right next to each other.

#

Putting them next to each other makes them all fly over the place as soon as I press play in the editor.

keen spoke
#

you could put them in the same layer and disable same-layer collision

timid dove
#

Also you should probably only replace the "whole window" with "lots of little pieces" and the time of breakage

#

to avoid things like what you described.

wintry sedge
#

does anyone know any good tutorials for making a 3D active ragdoll?

dry wraith
#

I was considering just replacing them with convex pieces. The concavity was due to me having it split by where each different-colored piece was. But complex colliders might work better.

raw badge
#

Hey there I am a beginner in Unity and I have a problem with edges. So I tried fixing a bug where u stick on walls, to solve this I made a material with 0 friction. This fixed the problem but now when I jump or stand on an edge I shake around and clip into the edge. I tried using a composite collider on the tilemap, but that just made it less amplifed :/ Does anyone have a solution?

raw badge
sturdy wren
#

running into issues with enemy ai for my game.

their ai is incredibly simple; they move in a random direction and when they touch a wall, they swap direction.

#

issue im running into is when i deal high knockback to an enemy they will get stuck inside a wall and constantly flip back and forth, and i dont know how to get the wall to push them out of it

#

lemme showcase this

#

the walls have a material with 0 friction attached and this is the code for switching directions in the enemy pathing

timid dove
#

I mean

#

just read your code line by line here

#

and think about what's going to happen

#
  • we check if isreveresed
  • it is, so we set it false
  • we check if it's false
  • it is, since we just set it false
  • we make it true again
#

so it will just always be true at the end of this code

#

Also E_speed = + E_speed does absolutely NOTHING as a line of code

#

It's the same as E_speed = E_speed; You're just assigning it to itself

#

You probably want two seperate variables:
current_speed and normal_speed

#

And you can set it to positive or negative as needed:

current_speed = normal_speed;
// or
current_speed = -normal_speed;```
sturdy wren
timid dove
simple cloud
#

I have a character Controller on my player and a rigidbody and I want the player stick to a moving platform when on it, Therefore i am parenting the player to the moving platform. At first that didnt work but after moving the platform in FixedUpdate() Instead of Update() It now works fine, but the platform moves extremely stuttery. Any advice how to fix that? If wished I can make a video or send code snippets

simple cloud
timid dove
#

However, if you're using CharacterController based motion you've kind of trapped yourself

#

Because CharacterController doesn't do interpolation

#

It's meant to move in Update to be smooth

#

I'm confused by this though:

I have a character Controller on my player and a rigidbody

#

Both of those are on the character?

simple cloud
#

Yeah i fixed it now without parenting. I gave the delta movement from the platform to the players character controller and that kinda worked

#

But thanks for still trying to help not many do this

prime niche
#

Hey guys, sorry if this is a dumb question i tried looking it up and im seeing a few forum results but im not sure i undertsand

So i have just an empty project with a plane at 0,0,0 and a capsule. On both of them i have colliders and a rigid body on the capsule with default everything. I have a very simple movement script on the capsule which just does this

public class PlayerMovement : MonoBehaviour
{
    private Rigidbody playerRigidBody;
    private float horizontalInput;
    private float verticalInput;
    private float walkSpeed = 5.0f;

    // Start is called before the first frame update
    void Start()
    {
        playerRigidBody = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        horizontalInput = Input.GetAxisRaw("Horizontal");
        verticalInput = Input.GetAxisRaw("Vertical");
    }

    // Update is called once per physics frame
    private void FixedUpdate()
    {
        playerRigidBody.velocity = (new Vector3(horizontalInput, playerRigidBody.velocity.y, verticalInput)).normalized * this.walkSpeed;
    }
}

But my issue is that whenever i start the game, there is a very slight movement forward on the z axis. Its very small like 1^-25 but its gradually increasing. Im wondering what is causing this? Is it my code? Is it just that the bottom of the collider is not a perfect flat surface? Is there anything i can do to stop this movement?

#

Heres literally all i have in the project

#

Ive seen people also say it could be floating point error as well but im not sure if thats the only reason

#

I do have a material on the plane but its just a default new material with a selected Albedo

#

Also when i move on the z axis apparently the x-axis starts doing the same gradual increase out of nowhere, and at some point the y axis started decreasing to -0.001 then -0.002 etc. I have no idea whats causing all these movements 😭

timid dove
#
    private void FixedUpdate()
    {
        Debug.Log($"Input: ({horizontalInput.ToString("F8")}, {verticalInput.ToString("F8")}");
        playerRigidBody.velocity = (new Vector3(horizontalInput, playerRigidBody.velocity.y, verticalInput)).normalized * this.walkSpeed;
    }```
#

for example

prime niche
#

I did this Debug.Log("Horizontal: " + horizontalInput + " , Vertical: " + verticalInput);

#

And its giving 0 on both

#

And heres ur way

timid dove
#

Show the inspector of the ground

#

and of the player

#

And also your physics settings (what is gravity set to?)

prime niche
#

First 2 are the capsule, then platform, then physics

#

I also removed the material just in case but still same thing

#

Heres the issue im talking about by the way. I know its a really small amount but its constantly increasing and i want to know if its just.. sth with unity or me

timid dove
#

There's notjhing elsse in the scene?

prime niche
#

Camera child to the capsule just so i can make it like first person but other than that no

timid dove
#

If you disable or remove the script on your player, does it still happen?

prime niche
#

Let me check

#

It does for a second then stops

#

Whereas with the script it keeps going up

#

Like it moved up to 1^-20 then stopped

#

With the script enabled it kept going up

timid dove
#

Did you maybe attach a collider to it by accident or something?

prime niche
#

And the hierarchy is just this

#

I also deleted the material and made it default just in case something was happening there, still nothing

#

Im gonna try remaking it in a new project and see if its the same thing

#

Yeah no same exact thing

#

I made the player a cube and now it has a permanent upward velocity for some reason😭

timid dove
#

Make a fresh scene

#

You have something weird in this one

#

Also reset your physics settings

prime niche
#

And its doing the same thing, and i dont even know what the cube is doing

#

Im not on the newest version of unity. Let me try uninstalling it and going to the newest recommended one maybe that changes something. But i honesty dont know why the cube goes upwards...... there is nothing that should cause it to fly upwards??

timid dove
#

It's hard to say without having your project in front of me

prime niche
#

Alright new unity install same issue still

#

I reset the physics and it didnt do anything

#

The physics is acting weird on everything.. idk why.. the capsule suddenly floats upwards if it falls over when i dont constrain rotation

#

To reset physics do i just go into project settings > physics > reset? Cuz i did that

#

Is this like.. horribly wrong and im not understanding . Doesnt that just mean that y stays as it is? Why the random upwards force 😭

timid dove
#

You're normalizing the y part of the velocity

#

Or at least including the y when you normalize

#

You're also multiplying it by 5

#

Basically the Y part needs to be added back in after you do all that stuff. Because you want to leave it alone

prime niche
#

Oooh thanks that fixed the random floating issue

#

But the initial issue is still there

#

And idk whats causing it 😭

#

I think its just cuz its a capsule i just tried and cube works fine

timid dove
#

Honestly I wouldn't worry about it

#

10e-20 That's like the size of one molecule

edgy olive
#

I am building an app where you input a date and it will show you the number of days till that event represented with 2d squares that you can drag around and mess with, I spawn these cubes randomly across the screen leading to some spawning inside each other. I have seen people use things like a Physics2D.OverlapBox to solve this issue, but if the screen fills up completely with cubes then it causes an infinite loop. I don't care if they spawn inside each other as long as there is a way to get the physics to separate them automatically. Sorry if I am missing a simple solution, does anybody have any ideas to fix this?

#

screenshot:

scarlet mauve
#

Hey, I’m making a game which heavily relies on consistency. I have several elements which use the inbuilt physics engine, however, I am uncertain about it’s reliability. Do scripts execute a physics update in a constant order, or is script prioritisation indeterminable? And if objects are added during runtime, is their placement in the order consistent? Thanks.

novel light
gray meteor
novel light
timid dove
gray meteor
timid dove
#

Just small precision-level differences which will add up over time until a macro level thing happens like a collision being missed or hit that it wouldn't on different hardware.

#

Different CPUs do floating point math with different levels of precision

gray meteor
#

i am making a physics platformer based on using rope tension to launch yourself and puzzles like that. the inconsistency of launches based on an inverse force of something pulling you towards another point seems like something that might need some amount of extra determinism

#

or maybe that kind of movement is more stable than i think

scarlet mauve
#

However, I am concerned about the performance of constant physics scene reloading.

gentle axle
#

Hey all, Can I use Navmesh link for mobile?

timid dove
#

Why not?

winter swallow
#

What's navmesh

polar shell
#

Hi ! I'm making a endless runner game and my game object is going so fast horizontally that it goes through the wall. Does anyone have an idea ?

unique cave
#

Why are you setting velocity for a kinematic body? You may want to consider using rb.MovePosition or even transform.position if you don't want to simulate physics on the object itself which setting it to kinematic would suggest

unique cave
polar shell
unique cave
wintry sedge
#

how can i make a configurable joint more stiff and less wobbly for a ragdoll?

silver moss
#

Should help with wobbliness at least

#

If that doesnt help, show your joint settings

unique cave
#

IsTrigger will make you go through walls and so will IsKinematic, enabling both won't cancel each other out and magically make you not go through things again. You should look for collision messages instead of trigger messages if you want to get notified by collisions and keep physics working

drowsy atlas
#

I am currently making a putt-putt game and I am getting weird collisions when the ball is bouncing against the walls. I am using a tilemap collider for the walls and a circle collider for the ball. Any potential fixes for this issue?

drowsy atlas
# timid dove define "weird"

For example, the ball will hit off of the wall in unpredictable ways as opposed to simple reflecting off normally. Even though the walls are flat

unique cave
#

Could you share a video recording of that behaviour?

drowsy atlas
unique cave
# drowsy atlas

What collider types are those walls? Usually that happens when object hits at the exact point where two colliders meet

drowsy atlas
unique cave
#

You can also try to use composite collider or use the delaunay triangulation to hope for better results but haven't used those either so no idea how effective either would be (combining the tiles into one and triangulating them again to reduce collider edges inside the walls intuitively sounds like it should work to some extend atleast)

drowsy atlas
unique cave
#

@drowsy atlas Just to illustrate the reason behind the bug: when the ball hits the corner of the tile, especially if at high speed, the engine might think the ball should be sent to the "direction of the corner normal" instead of the reflected direction (in the given example should be straight down). This is a problem that occurs with most discrete 2D and 3D physics engines at the meeting points of colliders and is sometimes really hard to prevent though in this case using compound collider alone could do the trick

calm thistle
#

Hey!
I'm trying to create a top-down FOV system
It's working correctly as per the example, but my issue is that you cannot see the walls since I'm using raycasts
I want the raycast to continue after hitting the collider until it reaches the middle axis (so that the yellow-colored zone would also be visible)
Is there any efficient way to achieve a similar result?
Thank you!

unique cave
calm thistle
#

You're right, apologies haha

unique cave
calm thistle
#

the FOV system is already implemented, I just don't know how to push the raycast hit positions towards where i want them

unique cave
#

Pretty much the only "accurate" solution that I can think of would be to have separate set of inner colliders (edge colliders potentially) for each wall to raycast against but that sounds tedious task to implement (especially if your map is large enough)

calm thistle
#

It's a tilemap, is it even possible to set multiple colliders on different layers on tilemaps?

unique cave
formal sequoia
#

these are my settings

timid dove
formal sequoia
timid dove
tender crow
#

I've updates 2022.3.31f1 and now it is erroring on PhysicsWorldSingleton, anyone know what has changed?