#⚛️┃physics
1 messages · Page 66 of 1
The hinge joint is rotating in all axis : ( i dont get it
Im trying to build a free deathmatch dungeoun
4player
Hi! I'm currently making a VR tennis game, and I'm having trouble with the racket physics. All i need is for the racket to always be tied to the player's hand. One way i did it was just by setting transform.position, which didn't work because the position wasn't being controlled by Physics.
(the racket went through the ball). Same goes for parenting the racket. Using Rigidbody.MovePosition makes the collision work, but its wayyy too hard of a collision. A simple hit will send the ball FLYING, same with using OVR Grabbable/Grabber. How do I get around this?
Like, is there a way for me to reduce the scale of the collision force for Rigidbody.MovePosition?
Setting the chain.z velocity to 0 seams good enough for government work
No not satified, not good enough
@dusty stone still here?
i can explain how to use the configurable joint
Squirl?
@dusty stone i can explain the config joint to you but i need a few details about your desired use
depending on what you need, you must make sure that the joint anchor is oriented and placed correctly, that you're locking the right axes of linear and angular motion, and a few other settings
i got my cirtual muscle controller worked out i think
is the game meant to be 2d?
in other words, are you already constraining all rigidbodies on the Z?
depending on how your physics is meant to operate, constraining the physics might lead to unrealistic immovable objects or cause strange feedback issues
this usually happens when an unconstrained rigidbody meets a constrained one in the wrong way
Mm hmm
so if during this swinging stuff the player body is Z constrained, you can probably constrain the rope with no issues
im assuming the rope dangles from a high point?
Yes
ah yea now i see it
Sometimes very high
do you want it to just be a dead chain, that players can hang from?
Jump swing chain
(swinging on chains/vines like george of the jungle isn't exactly physics realistic lol)
i actually made something like this in VR. one sec
it basically works like i assume you want (except in 3d)
Yes exactly like that lo c ked to the z plane
so aside from the chain itself, i am creating a joint at runtime to link the player to the chain
it's an OnCollision() thing
this way you dont have to fuck with the rigidbodies too much
Nice
so assuming you get the chain working, you can do the grab feature with a runtime joint
it's tricky to initialize them in code, but you will quickly get used to it
Thats what i need is the chain working : )
The hinge joint wasnt acting like a hinge
the hinge joint is hot garbage
never use it
all the joints except configurable are hot garbage actually
Ahh
: D
first step is literally to make a chain of joints. the way that works well is to have one rigidbody be your anchor, and then the next link of the chain connects to it
let me make a quick drawing
I did that
I made the top and it builds to height
Set number of links with a gizmo
So i can visualize it in the room prefab variants
Links em together
my guess is that you're not correctly setting up the joint axes or anchor points
why hasnt it been working?
It rotates in the x axis and y and i just want z rotation
The chain swings off the z plane 0
you need to lock the axes you aren't using
that will do it through the joint, but you can also use rigidbody constraints
They werent playing nice with the hinge
free will probably work for your angular motion in the z
Kewl ok got it
and just lock everything else
if you constrain via rigidbody, then all the angulars set to free is fine
What makes them link together ill try it hold on
actually..... yea... just make sure your rope doesn't twist
at the top
connectedBody
that is a reference to the rigidbody that the joint links to
Yes
without that reference, the joint will pretend to have some kinematic anchor
do you mean twisting?
I checked in chanell box while playing
Twisting and double bending just swinging around
your joints aren't sharing the same rotation then
you are probably offsetting them when you build it, right?
to make the chain look like a chain?
Yes
the joint axes probably are referring to different directions individually, so as a whole the chain can move in those dimensions
Hmm interesting
so, the solution here is to change the nature of your chain-link prefab
this is something i ALWAYS do with rigidbodies
have an empty game object as the parent, with 1:1 scale, and give that parent the rigidbody
put whatever collider and renderers in as children, and reshape them there
this way, instead of offsetting the rigidbody to make your chain, you can just offset the renderer/collider
Yes i did that but the colliders are with the rigid body
and since the joint will be on the parent/rigidbody, it can be given a sane starting rotation
colliders dont need to be with the rigidbody
they can be in children
Oh what
it will still calculate the same center of mass, inertia, etc...
you will still get collision events in the rigidbody for all the child colliders
etc...
2d and 3d
the major benefit of doing this is that you dont need to rescale your rigidbody
yes, 3d colliders will work for your 2d chain concept
and that is as it should be if you are working with 3d colldiers already
My rigid body is one to one, nice thanks ill give that a try i think youve solved it thank you anything else
yes there is one more thing
I dont understand why all joints are acting like rope swings no matter how i cuntrain them
you can constrain the Z motion of the rigidbody to make the chain stay on the Z plane. You might still need to deal with the chain links twisting, but that is a joint thing
it's because your chain building function makes them that way by offsetting their rotation
so each joint has an offset Z axis
you need them to all have the same origin rotation
Ill try it with configurable ahh kewl
or else you need to approach it from rigidbody constraints
you can make your hinge version work
just use child colliders
make sure all the links have the same rotation
Thanks buddy yeay
the rigidbody must have teh same rotation
the child collider and renderer can be offset
Itll be tricky to move the pivot right
what do you mean?
you can offset the placement of the child collider
that way you can have the default pivot be exactly where you want it
Uh im preciceley positioning the chains and their pivots
Im confused but i think i can figure it out you want me to move the mesh and colliders but not rigid body right
I was shifting the links rigidbodies down the y axis
yes. The position of the parent /w rigidbody should be your joint pivot point
that way you can spawn it in right at the place where you want the pivot to happen,
and the child collider offset will take care of the rest
i think your chain building func will just need to rotate the child collider instead of rotating the parent
they look rotated
I know i have two versions thats an old pic
I will try child collider technique thank you very much
welcome
@mighty sluice its as i feared the boxcolleder doesnet push the 2d hinge, ill have to try configurable joint again
@dusty stone why not try the 3d hinge?
@mighty sluice i did it swings in all axis for some reason : (
constrain the rigidbody's of all the chain links
constrain the Z motion
or whatever is your depth
@dusty stone use the edit angular limits gizmo so you can visualize the joint rotation axis
it's the top button
select all the chain links and press that button
Ok i will i have all settings locked except for angular z hmm ok ill try limits too
The first configurable joint werks perfectly but the next one in the chain rotates in all axis
how is that possible if you constrain the z motion?
check the freeze position option for Z
Probably want to constrain x and y rotation too
@timid dove the hinge is not abiding by its set limits after the first link and freeze rotation x and or freeze position z on rigidbody makes the hinge malfunction
(bump)
anyone? any thoughts/ideas .. ?
@mighty sluice. I subtracted the joint position.z from room.z 0 and applied it to the velocity, and set the angular x velocity to zero and rotatation x and y to zero, a viola flawless 2d simulation of 3d chain omg its beautiful : D thanks for the help
Hello I bought an asset off Unity and I have no idea how to turn it into a physical object. Now, with a 3D cube I know how to add gravity and make it a rigid body ect. Currently I'm working on a VR project and I've added scripts to cubes to pick them up. However, I have a glass beaker I want the model to have the same shape and what not while being a physical object. I wanna use Nvidia Flex for water physics and fill the beaker with water. I have no idea what I'm doin! halp.
Here is the object
Should start with a physics tutorial at least on Unity Learn, not going at it blindly. Dynamic object needs rigidbody and a convex collider.
Ok great and I can find that on the Unity page?
Why would someone use physics2d.circlecastall over a circle collider2d component, when building 2d melee mechanic?
🤔 I'd say the first one allows you to check on-demand ? (only when player/agent punches for example). The latter would be always there and consume computing during the physics simulation step, every frame.
- maybe some other things I don't think about right now
so the circlecast is only active for the frame that its called? that's awesome! Attack the componant to follow a sword and draw it the size of the weapon, then animate it during the attack() call and you've got a hyper accurate collider. But I'm guessing it would only cast during the first frame of the animation?
Yeah it will cast the circle from origin, towards direction, along a linear path. and yeah all the way in the frame, it won't lerp between the beginning and ending of your animation, if that's what you wonder about.
attaching a trigger collider to your sword and just animate your sword will work too
and allow non-linear movement
casting shapes helps a lot detecting missed collisions between 2 frames when movement is too fast for the engine
all depends on the complexity of your game and if it's arcade-ish or heavy simulation
you can go as simple as doing a distance check in the middle of the action, and below an attack range threshold you hit, above you missed
@supple sparrow you are saving me right now! Would you share your experience with me just for a moment? I am dreaming of this 2d physics arcade style game. It's top-down 2d pvp combat. The goal is to have many, flashy, differentiated abilities, which can interact with the environment, other abilities and players.
Understanding collisions and animations was just the beginning for me, because I wanted to be able to create a sword/shield character but wanted the physics of your placement to be important. The different between a few pixels, or how a sword swipes, being very important.
Last piece: So I started with attaching colliders and creating animations to swing the sword. For spells, I was creating effects and letting them collide as well. I was thinking about attaching effects on gameobjects I will instantiate, to create placable/moveable spells. What's your take on this? Some pointers, or just a piece of advice based on your experience would be amazing!
That's a broad question 🙂 but that's a good start. I would probably start with instantiating GO for effects too, yeah.
Unity's physics can be nerve-racking sometimes, so just go with your ideas and see if that works. Don't forget to stress-test and profile with a lot of gameobjects when you think you get something working.
For instantiating a lot of quick effects as gameobjects, look into object pooling to recycle old ones instead of creating new ones each time (that's an optimisation that can be done later, focus on fun gameplay first)
If your idea does not work, search how others did on that specific topic but whatever you try, have fun along the way and you won't give up
I've recently implemented companions in my game (without a NavMesh Agent) and it all works nicely except for one thing.
If I'm colliding (Rigidbodies) with my companion, the player will stop.
I've tried to implement stuff like this:
private void OnCollisionEnter(Collision collision)
{
// how much the character should be knocked back
var magnitude = 1000;
// calculate force vector
var force = transform.position - collision.transform.position;
// normalize force vector to get direction only and trim magnitude
force.Normalize();
myRB.AddForce(force * magnitude);
}
And it does push my companion away, but not the way I want to. It's pushing the character in the way I'm moving, so that partner still blocks my path. I want it to push my helpmate away/aside, so that it doesn't block the path of my player.
This: https://imgur.com/a/mGcHNXN is what I'm trying to archieve.
I'd prefer to not change anything about the player's rigidbody, since I already adjusted these properties for a good movement.
If anyone has any idea on how to implement this, please let me know.
Thanks in advance!
Rigidbody properties
@torn parcel that sounds really fun top down pvp with swords and spellz, i get by with physics alright and design games, so message me if you want to chat 🐌
Why are these cubes slightly hovering above the ground? And why is one of them slightly higher than the other? They both have character controllers.
Try lowering the Skin Width
it seems slightly better, but there is still a height difference. i would be perfectly fine with the hovering as long as they were hovering at the same height
their skin widths are both the same
Is everything else the same? Including their transform scales?
yes
I don't see any difference in those screenshots
its a difference of about 1 pixel on the screenshots but its very jarring
heres a more zoomed in shot
Are you sure it's just not the fact it's not pixel perfect?
i played with the positions of the ground and of the boxes and its fixed now
Hi guys!
I created code in unity based on C# language and Path Creator plugin(spline).
However, my code doesn't work with the plugin
I need to rewrite the code, or to make it always show the current speed in the variable.
So how do you do that?
My code: https://pastebin.com/FaLuKG0d
Is it possible to somehow adapt this data to the plugin?
I accept all proposals
Thanks in advance!
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Not sure you have explained what you're having trouble with exactly
I have made a rigidbody player movement controller and I am experiencing something weird... When I freeze rotation for the rigidbody, the rigidbody seems to experience friction with the surface, which does not happen when I do not freeze rotation. This is happening even though everything has an assigned physicsmaterial with friction set to 0. What is causing this?
nvm... I am stupid
I'm having an issue a few people seem to have had, but I can't find a solution I like; Rigidbody objects being able to zoom up steep slopes
I'm making a car game, so I want to be able to traverse some slopes, but at the moment, cars can travel up vertical walls
shouldn't happen unless you're doing some serious direct velocity or position modification
Rigidbodies will generally respect conservation of energy (though definitely not perfectly)
what I've done is to alter the position of a sphere object and have the rigidbody follow it
transform.position = Vector3.MoveTowards(transform.position, theRB.transform.position, speedInput * Time.deltaTime);
where theRB is the rigidbody of the sphere
the options I've found so far are to set up a raycast (but that means if the car hits something the ray misses, it could shoot into the air) or a sphere cast. but I think that might inhibit the traversal of acceptable slopes
I'm confused
which object is that code on
that code seems to be moving an object towards a rigidbody
that code is on the vehicle
so what is theRB?
the vehicle is set to follow a sphere rather than be directly controlled
theRB is the sphere the vehicle is following
adding a force directly to it
then it's just a matter of how much force you add and in what direction, no?
I don't know to be honest - this is how the sphere is being moved:
Hi.
I have small problem with Rigidbodies and hierarchy on the scene.
I have a car with rigidbody, and in this car I have a hood, doors, screws wheels, etc. as children with rigidbody too.
In this car you can take off the wheel and screws, so they own rigidbody and colliders.
I want to make car non-kinematic, but it collides with its own children and car is flying because of these collisions.
I thought I can make simple script where the car detects OnCollisionEnter if a wheel is currently his child, and if is, to set Physics.IgnoreCollision with it.
Is it a good solution?
I don't want to create layers, because it has to be interactable with each other.
OnCollisionEnter is too late
By that time the collision has happened and any depenetration/collision impulses will have happened too
Ah, You're right.
So what can I do?
THere's an experimental API that maybe could help you? https://forum.unity.com/threads/experimental-contacts-modification-api.924809/
But I would say that when you make something a child of the car the child should be kinematic
It is when is a part of the car and is non-kinematic when you take it.
Do the parts have to interact with the car when they're removed?
They have to collide with this car.
I guess you want it so they collide with the car but only after you've pulled them clear from the car?
Yes, exactly.
It's tricky but
you could probably do it with a separate trigger collider inside the car
moving, if you're using the physics engine for it
otherwise no
correct
that is a simple math calculation
I'm using triggers to pick up items, so every part have colliders and one trigger collider.
If I understand correctly, I would add a trigger to the car that would turn ignoring on and off
But this will collide with picking up items
yeah you'd have to probably put it in a whole separate layer... it would be quite messy
I was afraid of using separate layers and wanted to avoid it.
Is there really no ready-made solution in Unity?
I thought that something like this should be because it would be very useful.
layers are a ready made solution in Unity
but this whole car attach/detach thing is quite a specific use case
Hm, What if I put a separate object into the car with its own trigger and without rigidbody on a different layer that would ignore picking up objects?
Would that make sense and would be the optimal solution?
i have an asset map for some demo game but the tree collider is not working, any way to fix this ?
Hey guys! Anyone can help me with a parabola projectile? I'm using a rigidbody and I want to give it the distance, speed and height desired and then have a method to calculate the force needed. After that just use rb.AddForce(force). But how can I do this?
If you know the desired height and the gravity, you can calculate the y component and the time it takes.
Now that you have the time you can see how fast you need to go in the x/z directions.
You now have all 3 speed components of the force vector, you just need to adjust for object weight.
If this is 2d, then you can ignore z
Im trying to do a type of angry birds game, so this is my scene now
But when I press play, the bird place itselfe in a diferent possition...
Can someone help me fix my bird lol
Ok nvm, i got it
And how can I make all those calculations? Its 3d
timeToFall= Math.Sqrt(2 * gravity * height);
Force is an impulse (only happens once) so you only need to worry about speed at first)
x and z speed is based on traveling those distances in 2 * timeToFall (since that is only half of the parabola)
y speed is gravity * timeToFall
Then you multiply this x,y,z vector by the mass of your object and you will have the force needed
like this? it is not working properly...
hello, could someone tell me why this does this when hitting corner of object. I am using boxcast
@severe merlin one if not all of your x,y,z coordinates match that of the object and because your object is assigned a collider your "player" can't go through it, so it's going on top of it.
hellooo - I have an object following a path using the following:
transform.position = pathCreator.path.GetPointAtDistance(distanceTravelled);
transform.rotation = pathCreator.path.GetPointAtDistance(distanceTravelled);
it works fine, but because it's using transform.position, it's ignoring object collisions. What's the best way to change this so that it can interact with colliders properly?
I mean why it is going up and down
I think rigidbody. is depricated it seems?
Hmm I'm not sure you'll have to wait for someone else, but it would probably help if you listed each objects component and a snippet of code related to the collision of both objects.
if(Physics.BoxCast(wall.GetComponent<Collider>().bounds.center, new Vector3(wall.transform.localScale.x-wall.transform.localScale.x/2, wall.transform.localScale.y, -range), cam.transform.forward, out hit, weaponPos[0].rotation, range)){
if(hit.collider.name != "Terrain" && !hit.collider.isTrigger){
weaponPos[0].position = new Vector3(weaponPos[0].position.x, hit.collider.bounds.max.y+wall.transform.localScale.y/2, weaponPos[0].position.z);
}
}
here is what changing position of the wall if boxcast hits object. weaponPos[0] is the position where wall is instantiated and also it is parent of wall
And on the video you can first see when it hits on corner of a object it starts going up and down but when hitting flat surface it is working fine
hmm, I've changed my script to Rigidbody.MovePosition and Rigidbody.MoveRotation, but I'm still not having any luck in getting it to collide with an object
it's running in FixedUpdate, the collider of the object is fine (other things collide with it)
this method shouldn't ignore colliders should it?
and rigidbody positions aren't locked and it is not kinematic?
correct
interpolate, continuous dynamic
I'm totally lost, the script is set to follow a path, which it is doing, and it's interacting properly with the ground
yet it can move through a box collider as if it's not there
Does it have a collider (the rigidbody object)?
Is the box collider a trigger?
Is either collider a trigger?
what's the best method? imgur for the screenshots?
ok so you're trying to move the sphere on a bezier path
yeah
but have it stop at a collider
so it's just going through as if the box wasn't even there?
yep
Or is it stopping for a bit and then going through
it just goes straight through
I thought it would stop and then eventually turn
as far as I understand it, the code just moves it towards the direction of the path, rather than altering it to be in the same position as the path
Hey Guys, I have a wand in VR and I am trying to catch the velociy of the wand (to cast a spell) and generate the velocity of the spawn prefab based on the magnitude of the wand movement.
@timid dove 🙂
void FixedUpdate()
{
velocity = rb.velocity.magnitude;
}
I am displaying this velocity magnitude in this inspector and was expecting this to be updated constantly but its not the case.
it's changing but not instantly
The physics update is not as frequent as your framerate
it's only every 50th of a second by default
It certainly could be MORE frequent on weak hardware
phew, fixed it - edit > project settings > max depenetration velocity was set to 10
I've upped it to 1000 and that's working as expected now
So how would I transfer the velocity to another object then? I need to capture the movement of the wand ( in the meantime I configured a classic addForce to the spell for now but since I am going to create target to aim at, I would like to be able to put them in different depth
@terse thicket keep track of the position of the tip of the wand
(newpos - oldpos)/deltaTime is your spell shooting velocity
So we will not capture anything from the source Rb then? But only the transform?
You should use the RB. Get the velocity of the tip with https://docs.unity3d.com/ScriptReference/Rigidbody.GetPointVelocity.html
As for transferring it to another object - if it needs to be in Update you will have to interpolate
If I have a an object with high bounciness collide with another object with high bounciness on a slope is there any reason the collision event would fire off (tested with debugging and noteworthily plays sound effect) but wouldn't actually cause a bounce to occur? The bounce works fine on other surfaces so long as they aren't sloped.
(This is in 3d physics not 2d)
How complex are the respective colliders?
Box and Capsule
capsule landing on top of box
or moving into
The ground is a mesh collider though
rotation * Vector3.whicheverDirection
forward? I dunno, what are you looking for?
It's like asking what's the default side of a cube
given a quaternion u can draw an arrow , also given an normal u can draw a plane
Given a quaternion you can draw many arrows
how to do draw a normal given a quaternion then ?
depends what axis you care about
no ?
emm ok how do u convert euler to vec3 ?
euler angles are already a vector3
and again, they don't have a direction associated with them
they don't have a normal.
If your system thinks a normal is the forward vector, then use that
if it thinks it's up, then use that.
I mean normal to a plane.
how can i get a normal given rotation ?
I'm not going to repeat myself
lets say default is UP
rotation * Vector3.whicheverDirection
so rotation * UP ?
yes.
a bit weird. but ok
thanks , i just don't understand quats i guess
that's what i got and it does seem to work ...
Quaternion YToZ = new Quaternion(0, Mathf.Sqrt(2) / 2f, Mathf.Sqrt(2) / 2f, 0);
var normal = ( Quaternion.LookRotation( p ) * YToZ ) * Vector3.forward; /// times Forward as its the engine's Default AXIS.... ? ? ?
my confusion is mainly because you still can see all the relative local axis in the editor when rotating a transform
so it sort of retains the information of each axis's "normal" / pointing direction
what is that YToZ doing?
moving Y to Z
seems overcomplicated
I'm a little confused by what exactly you're doing, you have a direction and you construct a new rotation using it, then you rotate that again, and then convert that back to a direction
all i want is a right angle to the axis i have
p is being that axis
the right angle would be another axis
I'd just do two cross products
or, one even. Like, what you're doing is already creating a rotation where it's up is aligned to Vector3.up
Quaternion.LookRotation( p ) gives rotation based on vector p , then im turning it 90 degrees
later im converting it to vector
It gives a rotation based on p and up
hmmm
but seems like whatever value of p i feed it , it will give me back a right angle to that value
not sure how to do it otherwise
i get it that quat is a normal + angle combo
basically the same as Vector3.Cross(dir, Vector3.up).normalized; is all I'm saying
it'll also have an issue when looking directly up or down afaik
just fed the formula above and it looks off
white is the one i quoted above , black is the one u just shared
here are the points for reference
basically what i got using this odd sqrt(2)/2 is the result if you rotate the handles gizmo green arrow towards any point , and the result would be the blue axis
hence why i said 90 degrees rotation
relative to the quaternion
anyhow it's what i needed so thanks @hollow echo
Quaternion.LookRotation(dir) * Vector3.up;
should be the same
the YToZ thing is just confusing
ah right
it's probably easier than cross products, because LookRotation is automatically handling the continuity issue at the poles. Anyway, glad it's working 👍
what are continuity issues in a cross product ?
a cross of the same directions is invalid
LookRotation takes two inputs, and when it sees that they are the same direction it automatically swaps out the second direction for something else that works
Like if you provide two Vector3.up to it it will swap the second one for a Vector3.right
interesting
https://streamable.com/3n7116
i'm trying to push a ball using rigidbody the player collider moves out of position when i do it, is there any way to fix this or recenter the collider to its initial postion!
You should use Joints for this kind of thing I think
And fake the rolling like they do in the Unity Roll A Ball video
Don't they use straight up physics to roll the ball?
@woeful cypress Maybe you could keep resetting the player's position throug RB MovePosition, though you need to be careful to not mess with the pushing
Could fake the pushing by applying the force directly on the pushed object and just having the character follow it
you know what - I'm totally thinking of a different video
Did this for now, until i find a proper solution
used a trigger to toggle constant force
seems like a good solution to me
Hello there! I've got a little physics problem
So i've got an XR project set up with a pistol, some magazines and a few enemies
And i've got this system set up where flicking the wrist "pulls" objects towards you, like in Half Life: Alyx
I've got this equation (screenshot) set up which sets the velocity of the pulled object to a parabola that goes from the targeted object to transform.position (in this case the left hand)
it works, but i've got a problem where pulling an enemy (not intended just for testing) works great, but pulling pistols isn't strong enough and puling magazines is too strong
all rigidbodies have the same settings, mass gravity everything.
also changing the displacement value (pullH) doesnt fix it either
Pretty sure you need to multiply the velocity by the objects mass at the end, not gravity
timeUp=sqrt(2 * hUp/gravity)
timeDown=sqrt(2 * hDown/gravity)
velY=gravity * timeUp
velX=distanceX/(timeUp+timeDown)
velZ=distanceZ/(timeUp+timeDown)
force=vector(velX,velY,velZ) * objectMass
that might be it, i'll try that out! @reef lance
If I remember well, Unity puts them as some kind of sleeping mode (or kinematic maybe 🤔 ) so they don't cost as much for the simulation
Why can't wheel colliders be used with ignorecollision
my character controller is able to push around my car just by walking into the wheels
can anyone tell me why my player is stuck in the floor?
RIP
Can you provide more info ? how are the collider setup for player and ground, do you use the character controller from unity, do you set Y position yourself, do you spawn him above the ground, is the player origin at center of mass or at the feet, .... ?
Then it would be easier for someone here to help
can someone tell me how to adjust the rate of acceleration using ForceMode.Acceleration?
By changing the Vector3 you pass into the function of course
at the moment, the Vector3 I'm passing in is transform.forward:
theRB.AddForce(transform.forward * speedInput, ForceMode.Acceleration);
I can't find anything in the documentation about which part is supposed to affect the rate though
Yeah, I've just tried breaking down the vector3 into constituent parts, and they all control the vector, never the rate. Are you saying I can pass a function specifically to ForceMode.Acceleration?
No, that's not the case, ForceMode.Accelerate is not a function
theRB.Acceleration = vector3
I'm lost here. I thought ForceMode.Accelerate was supposed to add a force to my rigidbody in a way that mimicked acceleration, i.e. increasing over time
but I can't find a way to adjust the rate of acceleration, only the force input
This is all that ForceMode.Acceleration does:
- Take the Vector3 you passed into it
- Multiply that Vector3 by Time.fixedDeltaTime
- Add the result to rb.velocity
so if you want faster acceleration, you pass in a larger Vector3
If you use ForceMode.Velocity change it does exactly that same thing, except it skips the multiplication by Time.fixedDeltatTime
The definition of "acceleration" is simply "change in velocity"
Hmm. Essentially, I've tried messing around with the vector3, butall it does is accelerate at the same rate with a lower max speed
What you're describing is how I thought it should work, and that it should just keep adding force to the object, but that doesn't appear to be the case, it looks like it's working as a multiplier with a capped value
if it's being capped - something else in your code is capping it
try printing out the velocity of your object right before and after the AddForce call
The input is being capped by me, but I have a debug outputting that to the screen. It never goes above 200, but if I halve it to output 100, it will never reach the same velocity no matter what time
In the same way, the input is linked to the trigger, so if I squeeze halfway, the velocity won't keep increasing past a certain point
Hi guys, I have a cube with a rigidbody attached and I try to move it in the direction the camera is facing.
So I have a camera as a child and retrieve the forward direction.
I use that direction in the AddForce method on the rigidbody but my cube is only rotating and not moving in a particular direction
Do you have drag on your RB?
show code?
public void Update()
{
if (Input.GetKey(KeyCode.W))
{
_rigidbody.AddForce(_cameraTransform.forward, ForceMode.Acceleration);
}
}
_rigidbody = GetComponent<Rigidbody>();
_cameraTransform = GetComponentInChildren<Transform>();
I do, I've tried altering it at runtime via the inspector and it doesn't make any discernabke difference
You shouldn't really do this in Update, It should be in FixedUpdate
but it should still push the object in the correct direction
Do you have any constraints on the Rigidbody?
show a video maybe?
GetComponentInChildren<Transform>() is actually just going to give you your own Transform most likely
I think you have the wrong transform reference
instead try ```cs
_cameraTransform = transform.GetChild(0); // If the camera is the 0th child
Or just Camera.main.transform
Don't worry about it - I'm 95% sure it's your transform being wrong
No it still doesnt work
what did you change to
_cameraTransform = transform.GetChild(0);
is the camera the first child?
Its the only child
what issue are you having
dont working
Care to elaborate?
ok
this is player
this is wather (i want to stop player when it touch te water)
@timid dove
1 yes
2 i moving player by changing transform
- If you don't have a rigidbody then Unity just considers your colliders as static colliders. No collision will happen between two static colliders
- If you do add a rigidbody to your player, you should not move it by directly changing the transform
or you will still go through walls
You either need to use Rigidbody or use a raycast-based Character Controller script
Thank you
but how can i change position using rigidbody
You don't.
You set the velocity or add forces, and the Physics engine moves the object for you
can we check layer with raycast?
Check layer, or limit layer?
If you want to limit which layers it hits, use a LayerMask. If you want to check the layer of the thing you hit, there's a layer property on the GameObject
this is what basically i am trying to do
trying to detect if ray hits a layer
but its not giving any output
Why Physics.BoxCast takes only one vector for a ray? Shouldn't the ray be defined by starting point and its direction?
At first glance this seems fine
It takes both
Center, direction, and distance
the center is the center of the box not the start of the ray
center Center of the box.
Or I should just move the box relatively the ray... alright then
does all raycast needs some kind of collider?
Yes
There's no ray. You're sweeping the box itself through the scene
Got it. Thanks
I'm doing a top-down car controller and I want to use rigidbody to control the accleeration, deceleration, etc.
Is there an easy way to calculate what drag power I need if I want my car to accelerate with an X value, to a top Y speed, and decelerate with a Z value ?
Or should I manually add a speed limit, acceleration and deceleration rate, and don't bother with rigidbody's linear drag ?
can anyone help me figure out why my character is running through these colliders, and how to fix it so they can't? I think I am missing something really stupid.
inspector of one of the colliders
How are you moving plejer
with a character controller, but the character wasn't moving through similar colliders with identical components
oh hold o
on*
ugh
okay i "fixed it"
he now colliders with them but if he keeps running he teleports through it suddenly rofl
Ok
sigh
well i fixed it. I don't know why, but the colliders were only working one way
i rotated them around and they work fine
they need to have rigidbodies
nah they don't
thanks though i got it
i set them at walkable layer and my character controller collides with colliders on layer walkable
without need to add rigidbody
hey the code i wrote was for 3d is there a way to write similar code for 2d?
layer check for 2d
it's similar for 2D except you use Physics2D.Raycast
oh wait sorry
for a moousee click
you would use
uhm it doesnt take any ray parameters and obviously it has only 4 directions
yea
Physics2D.GetRayIntersection
oh okay
thank you 🙂
this would work directly in if prethesis right
No
it returns a RaycastHit2D
you have to do like
RaycastHit2D hit = Physics2D.GetRayIntersection(...);
if (hit.collider != null) {
print("Hit!");
}```
god finally works man ._. god i was so messed today because of this thanks
np!
just one more thing
can i filter out child layer somehow?
its detecting layer 0 right now
which is the whole object's layer
i want to detect child's layer with raycast which is child of that object
You can filter which layers the raycast hits with a layer mask parameter
thank you i managed to do it 🙂 thanks for all the help
would this be the right channel to ask for help with creating a hex-shaped grid system for placing 3D hex tiles at run-time?
uhh
when I release the physics on a bunch of rectangles
they skew
when they rotate
instead of rotating normally
Do you have a bunch of parent/child relationships with non-uniform scaling?
Yes.
Does anyone know why this capsule collider rigidbody behaves like this?
I'm advancing per frame in this video
The object has a drag of 15 and I use AddForce to apply a custom gravity
Make sure you are applying everything in FixedUpdate and not setting any overriding rigidbody properties directly.
I did set 2 Physics.IgnoreCollisions, so that is probably the culprit?
Because there is something in the way here that is not visible that this rocket should not collide with
Okay, I found out what it was
I was using transform.LookAt to make the rocket always face the direction it's flying in, but forgot to deactivate it after it started drowning in water
Hey, could anyone look at my simple platformer physics?
They are handwritten, and are mooostly useable, but I have a slight issue where sometimes the player cannot jump
private bool PlaceMeeting(Vector3 position, string tag)
{
// Get all overlapping colliders
float x1 = position.x - physicsCollider.bounds.extents.x;
float y1 = position.y - physicsCollider.bounds.extents.y;
float x2 = position.x + physicsCollider.bounds.extents.x;
float y2 = position.y + physicsCollider.bounds.extents.y;
Vector2 p1 = new Vector2(x1, y1);
Vector2 p2 = new Vector2(x2, y2);
// Get overlapping colliders
Collider2D[] overlappingColliders = Physics2D.OverlapAreaAll(p1,p2);
// Check if any colliders are relevant
bool overlap = false;
foreach (Collider2D overlappingCollider in overlappingColliders)
{
if (overlappingCollider != null && overlappingCollider != physicsCollider && overlappingCollider.gameObject.tag == tag)
{
overlap = true;
}
}
// Return
return overlap;
}
// Collide velocity x
Vector3 xVector = new Vector3(velocity.x, 0.0f, 0.0f);
Vector3 xVectorEpsilon = xVector.normalized * overlapEpsilon;
if (PlaceMeeting(transform.position + xVector, "solid"))
{
while (!PlaceMeeting(transform.position + xVectorEpsilon, "solid"))
{
transform.position += xVectorEpsilon;
}
xVector.x = 0.0f;
velocity.x = 0.0f;
}
transform.position += xVector;
// Collide velocity y
Vector3 yVector = new Vector3(0.0f, velocity.y, 0.0f);
Vector3 yVectorEpsilon = yVector.normalized * overlapEpsilon;
if (PlaceMeeting(transform.position + yVector, "solid"))
{
while (!PlaceMeeting(transform.position + yVectorEpsilon, "solid"))
{
transform.position += yVectorEpsilon;
}
yVector.y = 0.0f;
velocity.y = 0.0f;
}
transform.position += yVector;
This is the most important code
PlaceMeeting is an overlap function to check if the player would collide with a solid at a given coordinate
The second code snippet is my collision resolution logic inside of FixedUpdate()
The code is almost exactly as I want it:
As you can see the behaviour is pretty reasonable for a platformer
However - and you can't see this - the player is unable to jump sometimes
They'll be on the ground but the jump input will be eaten
..........wait
hooold that reading comprehension a second. I think I might be an idiot and this is just an input problem
hey uh, I'm doing a topdown car game and I'm using rigidbody and forces for movements
Which makes the car to drift, and do weird stuff like sliding on the ground, on the car's X axis :I
How can I prevent the car from drifting and sliding sideways ?
Hello! I have a quick question regarding ray casts in Physics2D (or in general?). I have a grid and for each cell in the grid I have to initially check if there's an entity present in it and what their layermask is. I was going to handle this with ray casting and I'm wondering what the performance differences are between the different casts (e.g. Physics2D.Raycast vs. Physics2D.Boxcast). I was going to use Physics2D.Boxcast since my cells in the grid are also squares... but is that a good idea at all?
Also a question regarding Physics2D.Boxcast...Assuming I have a square that I want to cast a box onto and the origin is 0;0 with a radius of 0.5... how would I go about casting a box exactly onto that square? Physics2D.Boxcast requires at the very least the origin, size, angle and direction. Does a direction of Vector2.zero go "outwards" from the origin or do I have to use something like:
var origin = new Vector2(-0.5, 0.0);
var size = new Vector2(1.0, 1.0);
var direction = Vector2.right;
Effectively casting a box from the left side of the square to the right onto the square.
For the origin, you can get to the center of the square pretty easily, and for the direction, you could use the transform.right attribute of the gameobject your square is in, I guess
If you want to just check if there's an entity present, why use RayCast/BoxCast at all?
Why not OverlapBox?
or CheckBox
Hey there! I have a quick question about collisions. I have a player and enemy, bot with a rigidbody. The rotation for the enemy's rb is frozen for all axis, movement is frozen on the y. But whenever the player comes to closes the enemy seems to tilt upwards. Vice versa, when the enemy comes to close to the player, the player gets pushed back. What is the reason for this and how can I solve this?
It's just a difference between these two... I'm wondering if the first one works like that or if I have to work with an offset:
OverlapBox is definitely what you want...
Boxcast will not expand outwards
It's a fixed size box that sweeps in a line
Works for me... I'm not picky. 🙂 Isn't OverlapBox more or less the same as a BoxCast in this scenario though?
It's simpler
It's boxcast without the sweeping
Just... "Tell me if there's anything in this box"
According to the API you still get access to the Collider2D at the very least. I think that'll be more than enough for my use case.
Yep
Can you give a me a quick run down when you'd want pick a BoxCast (or ray cast in general) over something like a OverlapBox?
Boxcast is when you want to simulate a projectile or something that will be moving through space
And you want to know what the first thing is that it hits
Like if you were shooting a laser gun you would use raycast to see what if anything the laser beam hits
Boxcast is similar but instead of an infinitely thin beam, it's like throwing a box through the scene (at lightspeed) and seeing if the box would hit anything on its path
It's useful for checking if an object would fit through an area without hitting something or simulating a "bulky" hitscan attack
So I guess the big difference is that a ray/cast can move, while an overlap just checks a specified area once?
basically
even though the "casts" "move" just remember they still do so instantly it's not over time
Anyone who can help me with this? 😊
Awesome, thanks a lot for your help and explanation! 🙂 I think I get it!
hey uh, I'm doing a topdown car game and I'm using rigidbody and forces for movements
Which makes the car to drift, and do weird stuff like sliding on the ground, sideways
How can I prevent the car from drifting and sliding sideways ? Like, just going straight where I steer
Let's say your car is pointing towards the black arrow. The current velocity is the Green arrow.
I would take the current velocity (green) and project it on the plane whose normal is the forward direction (the black arrow). This plane is represented by the blue line. The projected velocity on this plane is the Purple arrow.
This purple arrow tells you your velocity that is not aligned with your car's current direction. (sideways velocity so to speak)
You can then apply a force like the Red arrow in the opposite direction as this purple velocity to counteract that sideways velocity. You can think of this as a friction force of the wheels resisting moving sideways
You can make the red force proportional to the purple velocity to act like friction, and tweak the coefficient until it feels right. If you use a high coefficient it will be very sudden, like you're on a track. If you use a low one, you will be a able to drift a bit.
I'd play with it until it feels right
(of course do all of this in FixedUpdate)
That's what I tried to do in the first place, but I couldn't even figure out how to get to the purple arrow stuff
As long as the car is perfectly vertical, this is easy :T Just need to add a counter force with the same amount as velocity.x
but what if the car it rotated by, say 30° ?
This is where I'm stuck : trying to get the velocity, rotated to match the blue line when the car is rotated
You just need project the velocity vector onto the plane defined by the facing vector
something like this:
wait is this 2D or 3D
btw
It's 2d
I'm just gonna use the Vector3 functions because's no built in projection function for Vector2
// black arrow
Vector3 forward = car.forward;
// green arrow
Vector3 velocity = rb.velocity;
// purple arrow
Vector3 sidewaysVelocity = Vector3.ProjectOnPlane(velocity, forward);
so now sidewaysVelocity is the purple arrow from the diagram above
so then you can apply a force proportional to -sidewaysVelocity (the red arrow)
Mmh, what does project do concretely ?
It's a vector projection
so given a and b you can get a2
b is the "forward" vector from above
and a is the current velocity
oh, ok
So a2 is just the "sideways" part of the velocity
This is a better representation of what we're doing
We're projecting the blue vector onto the plane defined by the straight-up vector in this image
which gives us another vector that is lying flat on that plane
oook
I suggest trying to maybe Debug.DrawRay on all those vectors to visualize this in your game
ye ok, I was trying to do that stuff, but with maths and stuff I didn't understand :I
This works wonders \o/ Thanks !
I've spent 5 hours trying to figure out this
I find that this kinda stuff is pretty intuitive if you just draw out what's happening with arrows for velocities and forces, and get a good concrete idea of what you are trying to do exactly. You can figure out the maths part of it later once you have a good expression of exactly what you need to figure out how to calculate
It might sound obvious, but I've been teaching myself via tutorials and they haven't explained this yet - I've gone to edit the script and it's behaving oddly
can someone help me with my ragdoll? the limbs are freaking out and im not sure how to fix it.
also im trying to make an active ragdoll
thank you 🙂
I'm trying to create an object with this sort of physics motion. I've been trying to use a springjoint with no luck. Any ideas?
@storm shore bunch of hinge joints like a rope could do it
Yo, wondering if people offer support here for a logical type of code?
Basically (mind the texture, sync issue that will be resolved tomorrow), got a player who is a sphere.
Sphere moved by adding force based on WASD input.
Attached to the sphere is a beetle, and we wanna make it look like the beetle is pushing the sphere around.
I understand that I can rotate around the sphere, on a certain axis (usually Vector3.up, the sphere was upright and stationary), however I want the beetle to stop rotating if it is behind the sphere (i'd assume using the sphere transform.forward * -1 somehow?), but also, to still rotate around the world's vector3.up as opposed to the sphere's...
@ me or reply if this is something you can help with, as I'm sleeping now. Thanks! 😄
lol
so you want like Katamari Damacy
I would make them children of the same object, that should automatically handle orientation and location.
So the effect I would like to achieve would be for the cube on top to follow the sphere more like a rc car antenna but instead it just kinda goes wild. Right now I'm just getting the direction from the cube to it's target (a point above the sphere) and then I'm just using Rigidbody.AddForce but as you can see it overcompensates. Not sure how to avoid that.
Scale that force down
Scaling the force down causes the cube to take forever to catch up to the sphere
Maybe make it not linear. Make it proportional to the square of the distance
Might be easier to handle manually instead of through force.
Create formula that finds a point on a sphere given an xz direction and an angle.
The input to xz direction is the opposite of the force direction and the angle is based on the time since the last force application combined with the magnitude of the force.
@storm shore you prob used the spring joint wrong
I'd like to make the rigidbody of my vehicle either not rotate on the Z axis while airborne, or severely dampen the rolling. I thought I had it with this code - there's a ray pointing down from the car that detects if there's ground right below, and if not, the car is not in the grounded state
I apply a force to the rigidbody then add a transform on the X axis
I would have thought adding a vector3 of value (n, 0, 0) would say to exert zero force along axes Y and Z, but apparently that doesn't mean clamp those values
I had the idea to modify transform.rotation.z directly, but apparently that's a read only value
Anyone here a phycics guru,i need help with collisions in my racing game 🙂
m not at all, but I have been dealing with lots of issues so maybe I can help
what's the issue?
Basically my cars/spaceships when hitting the boundries of the racetrack either snag or clip through the mesh collider,everything is set to continuous and interpolation is on
still getting weird results
ok, go into your game settings, and there's a value called depenetration velocity
I was having the same issue, you want to up that setting by an order of magnitude
What value would be suitable you think?
edit > project settings > default max depenetration velocity
I have mine set to 1000
and no issues since
give that a go
Let me try
It looks better but a new problem started
If going to fast it just breaks the rotation,must i lock the rotation of the rigidbody?
just looking at the vid now
ok, I see what you mean
so you hit a wall, and it sort of sticks the vehicle at a certain rotation
yes
does it return if you just leave it?
if it hits it once then yes
I have had a similar issue, but long since fixed
are you using a box colider?
*collider
mesh
ok, I don't think this will fix the issue, but I think it will help
This is the real collider not the wall u saw
in the start , set the center of mass for the rigidbody slightly lower on the y axis
for example:
com = new Vector3(0, -1 , 0);
theRB.centerOfMass = com;
that's what I've done for my game to mitigate rolling slightly
However I have a hunch that what you're seeing is essentially a byproduct of physics and high velocities, and that you may need to self-correct somehow
because my velocity is quite high
I had another thought... And I don't quite know how to word it, but a lot of the times a transform position is related to the current position of the object - but you may want to map the Z axis to the world somehow
so that instead of rolling compared to its own position, it rolls compared to the ground position
ah right that makes sense
well the center of mass should help it re-balance, but I don't think it will prevent it from happening.
hopefully someone else can help further!
np, game looks really good, hope it gets sorted!
ok, I fixed my rolling problem. I see that I was actually adding values to the existing euler angles. I simply made a new vector3 where I added x, y and z clamped to +-1 of itself, and that seemed to dampen the airborne roll significantly
Hi guys, I would like to stop a collision event to reach other components if some conditions aren't respected.
o be more precise, I want to add a sphere boolean operation on top of any collider, is that possible? DOTS or not.
I'm using a rigibody for now so it won't be possible, but I plan to use some kinematic object.
if it helps, you can add .isTrigger to the collider via code, will that help?
I'm still not certain what you're trying to achieve though
how would i make a self balancing ragdoll?
@sonic spire
1- Kinematic rb animated character
2-Dynamic rb ragdoll character
3-Attach each limb pair except the hip with a rotation constraining joint (can use configurable joints)
4-Make kinematic characters hip inherit its rotation from the dynamic character
With these, you should have a proper ragdoll animation following
And then if you wanna make it stand up, you can add some forces and torque to keep the body up however you want
Can do any of these:
-You can apply upwards force from head
-You can use some torque to rotate a part of the body (preferably close to center of mass) like hip or spine and other parts will follow
I have an issue with wheel colliders catching on terrain. At first I thought it was the box collider, but I tried adding some other colliders, then removing them all (apart from the actual wheel colliders), and it still happens.
The way it manifests is while travelling over uneven terrain, if it catches, the vehicle will spin around where it's caught, or on launching over a slope, it will turn. I don't really have any clue how to counteract it, any suggestions?
ok my gosh I'm tired, but I think I've found it... I think
so the ray fires down directly from the car and rotates the position in accordance with the normal of whatever the ray hits
but this is only ideal when the vehicle travels up a nice broad slope. As soon as a curve is involved, I think this is what's spinning the car
so I have to work out how to transform only on the x axis I think
nope. It's definitely the wheel colliders clipping through the ground, I see them
FML
vehicles are really difficult to get right, most people achieve more success by simplifying the physics
or using an asset from the store 😛
It's so annoying, I bought Edys Vehicle Physics but it wasn't what I wanted
Then I followed a simple tutorial and it was perfect, but it relied on transform position and didn't have a usable collider (it used a sphere and updated position based on that)
So I tried to adapt that to get where I wanted and I got so close
It wasn't that one but probably close. I'll take a look
Yeah it's almost exactly the same as that vid. The only problem is that I couldn't find a non-intrusive what to add a collider, so the car just travels through everything because the sphere is the only solid object, and it also just shoots straight up vertical surfaces. Adapting the rigidbody to the car and adjusting everything took care of that, but then introduced these new problems
the trick is to use more than one for different purposes.
what do you need to collide with other than terrain?
you could try using a cylinder instead of a sphere it would work in a similar way except you'd have to actually turn it. Then it could encompass the entire vehicle and serve the purpose of colliding with terrain
then use a box collider to hit trees and other players.
seeing working solutions using wheel colliders are few and far between in here 😦
My original also used wheel colliders, but I think they were more to provide suspension to the car mesh
Is it possible to set a box collider to ignore ground collisions and only interact with another group?
I imagine so, I think I need some sort of walkthrough
At least I've learned things I suppose
I don't understand why though, it just seems to be that wheel colliders are really janky
Hey guys! I have an issue with Physics2D.OverlapBox and multiple close by layers... and I bet I'm just using Physics2D.OverlapBox incorrectly. This explains my issue:
Basically I use 0.5;0.5 as the origin of the overlap and use the size of "one". The overlap seems to touch Layer A instead of Layer B though. I assume I'm going to have to use some sort of margin to make sure Layer A isn't touched by accident?
e.g. size = new Vector2(0.95, 0.95) instead ?
Does the collider have to match the entire width of a tile? Can you not just use a raycast?
I'd like to make a sphere look an act more like a blob. Is there a simple way to do this via physics or should I look more into using a shader?
Actually in this case I just want to check which layer that cell belongs to... so technically I could just cast a ray into the center of each cell, but since this'll happen lots of times I figured an overlap might be more performant.
Not sure how it would be more performant. And why do you need to know every frame which layer every tile is on?
Ah, not every frame, just once in the beginning. It's a large grid though. I was under the assumption that overlaps are faster(?) than raycasts.
Maybe? You would have to profile it. And it might be negligible.
Optimize if it's a problem, just use a raycast and save yourself the headache.
So, I think I'm doing something dumb with a raycast here, but I can't seem to spot it. I want to cast from the center of the camera forward into the scene.
RaycastHit hit;
Transform rayOrigin = Camera.main.transform;
int mask = 1 << LayerMask.NameToLayer("UI");
if (Physics.Raycast(rayOrigin.position, rayOrigin.forward, out hit, Mathf.Infinity,
mask))
{
Debug.DrawRay(rayOrigin.position, rayOrigin.forward * hit.distance, Color.yellow);
Debug.Log($"Hit: {hit.transform}, {hit.transform.gameObject.layer}");
}
else
{
Debug.DrawRay(rayOrigin.position, rayOrigin.forward * 1000, Color.white);
}
But the rays are like... all over the place seemingly at random. Straight up and down the left and right of the screen, sometimes random forward angles, I can't seem to make sense of it.
Potato-quality demonstration
I thought that maybe .forward wasn't right for some reason, but if it weren't I'd expect the rays to be consistently in the same wrong direction, not random/crazy
Is there something about using Cinemachine that makes it a bad idea to use the main camera's transform maybe?
Tried it with ViewportPointToRay instead, same craziness.
first page of the manual says why 😄
Cinemachine does not create new cameras. Instead, it directs a single Unity camera for multiple shots
try using one of the virtual camera's transform
Yes, I know. That's why I would think Camera.main (the one with the brain) would work regardless of which VCam happens to be active
Is that not how it works?
I thought it was the active VCam was positioning the "real" cam
no idea, but seeing how it works with the correct virtual camera might help. You might also try looking from another direction. If it was working you'd only see a white dot in the middle of the screen
It is a good idea to try. How do you query the "Live" VCam for a given brain?
She actually has two following her to allow a "zoom in" view so I can't assume it a particular one
i dunno i never used cinemachine i just thought you'd keep track on your own somehow 🤷
could be that it works just fine and the way it's drawing lines is weird due to the type of camera
I'll look into it at least, no other leads 🙂
Hi, is there any way to make OnTriggerEnter trigger with a terrain? It's the only thing it isn't triggering it
Hmm i see it sometimes can trigger it, but it's like 1 time of 10 🤔
In continuous dynamic detection mode
To followup on my issue above, it seems it DID have to do with Cinemachine. I wasn't wrong that the brain "pilots" the real camera into position, but apparently some weird stuff happens per-frame, and you get crazy results if your Update() happens before it's decided on a position for that frame. So in OnEnable() you can do:
CinemachineCore.CameraUpdatedEvent.AddListener(OnCameraUpdated);
Then:
void OnCameraUpdated(CinemachineBrain brain)
{
Camera camera = brain.OutputCamera;
<whatever>
If you raycast from there, all works as expected.
I'm thinking collisions is a physics thing so
I've got some lab equipment in my project, all of it has mesh colliders, which means I can't put stuff inside it - how would one get the ability to do so?
I am working with a NavMesh and an Enemy with a rigidbody, but I have a very weird problem where in some cases, when it seems to get stuck, the FixedUpdate function just does not get called at all anymore. And I honestly have no idea why that's happening.
But why?
Needs more context. Do you have any Colliders there?
Also is this normal physics or like ECS?
No. I do provide all required data, don't I?
Because I see float3
I'm asking if there are actually any colliders in that area
No, that's for sure. I thought it detects collisions with the box in input arguments
It casts a box through the scene and tells you if it hit any Colliders
lol. That's a big surprise for me
Really? I'm confused about what you expected ot does : 🤔
So I specify a box center, its extents, the direction of the ray to cast. I expected that it will tell me if the ray intersects with this box
Nope
You specify the center of the box, the extents of the box, and the direction in which to cast the box through the scene
You could use Plane.Raycast for pure math kinda stuff? Not quite a box though :)
There's also Collider.Raycast
Alright then. I think its pretty easy to implement myself. Thanks for explanation
Not sure if this stuff is available in ECS though
if i set math.infinity distance in Ray would it be heavy to compute for unity?
Nope
It's the same as any other raycast i believe
hello, i cant apply psychic material. i created psychic material but when i drag it on some object nothing happens. when i want to change psychic material on some object the material that i created doesnt show there
ok i just fixed it, i tried to apply 3d material to 2d object
physics makes me go YES
Hey I have a question. So basically I have my character checking if he is grounded with a simple raycast/check sphere to see if there's a ground under him and it works fine. The only problem is that whenever I put it on top of a mesh collider it does not detect the mesh collider as ground. I checked everything. Tags are fine, the collider works, I even created the mesh physics material but he still doesn't trigger IsGrounded variable on custom meshes. Any clue on what I'm doing wrong?
debug out all the objects hit by your raycast to see if it's being hit at all
@glacial jolt Without the layer mask?
yea, try it initially without any layer mask passed into Raycast to get all possible objects
then narrow it down to see which part is causing it not to be found by your ground detection
it does
@glacial jolt ok, i found something. It's weird tho. Basically the sphere doesnt check the custom mesh at the height in which the collider is at... it kinda has to be inside the collider.
this is true (thats a normal cube collider)
yet this is false
but this is true
the last 2 are from the custom mesh
possible that the position of the sphere is not centered on the transform?
it is. i made a script just for that that uses "transform.position" as the origin
i have a theory but it makes 0 sense
For some reason my brain is telling me that it might have something to do with the normals of the mesh. It makes no sense since the mesh that is causing problems is a cylinder from unity itself
can you turn gizmos on? Hard to see what you're trying to show in these images
With gizmos on you can see the colliders in green wireframe
Hey, is there away to make an object ignore capsule collider of another object?
Im having this problem
Thank you so much yo! 😭 You the goat fr
How can I calculate how much force I need to add to Rigidbody2D's AddForce in order to guarantee that my player jumps can reach a platform of a certain height?
My platform heights are based on my camera's viewport, so I'm concerned that with different screen sizes on different devices, the viewport will change, so the platforms would be at different heights and the player's jump won't be able to reach it.
EDIT: Kind of worked around this for now, but would still appreciate an answer
Hey there, so I have a smol problem rn and I think it's collision based
basically when I get close to an objects edge, my jump starts getting messed up and I don't know why. here's an example
I made mesh colliders for these "treestumps" because there are no cylindric colliders afaik and capsule colliders aren't doing it
but for example, when I jump against a solid object, collision works just fine
like this
Hi all, I'm currently planning a project for a conference competition this summer and I really want to leverage Unity's physics/particle system for it. My project proposal is simulating how COVID-19 particles travel through the air in an enclosed room. I was curious what your alls thought on the possibility of this being implemented with unity is?
Rather simple set up I just want to have a single source that would emit the covid particles, they'd interact with the air particles and objects in a room. Obviously this would probably require a hefty amount of particles and some acceleration techniques but based on what I know of Unity so far this seems to me like a task Unity is well suited for
Worth noting this is just a student concept competition so this doesn't have to be something with bleeding edge levels of accuracy
I'd suggest using VFX graph or a compute shader
many thousands of particles is a bit too much for the normal particle system (shuriken)
I agree actually I think that'd be a smart idea
Good way to off load it to the GPU
Hey guys
I just want two cars to move towards each other and when they connect, I want the one with the higher mass to push the other one. I almost did it, with wheel colliders + box colliders and a rigitbody setVelocity script. But the dang cars start rotating once they connect.
I feel like there's a much simpler way to do this
@minor dew it sounds to me like you are after realism
maybe you are working a casual-like like game
maybe you'd wanna have just a box for a car
it will get rid of a great deal of complexist and your results should be similar to what you are expecting
That's what I did next, I deleted all the wheel colliders and just used box collider for the cars and I will make the tires turn with animation. But there is still some rotating and once it rotates they start spinning and rotating more
But I think it is because they are just moving "forward" related to their facing
Tomorrow I will try to make them go forward in world position so when they collide, even if little rotations happen due to physics they will still try to move past each other
But in this way, I feel like there is still too much of a chance for error because one might slip eventually due to physics
I'm most likely missing even a simpler way to do this
Is there a way to make objects push each other with rigidbody and colliders without any chance of sliding to the side and/or rotating
Like a straight line
Yes it's just going to be a casual game where cars push eachother to the finish line. 3D with a birds eye view
But I need that straight line movement desperately. I'm usually fine finding answers on youtube but this time I don't even know how I can search this
This doesn't sound like something you would normally use the physics engine for
So no rigidbody just colliders and code in their mass?
Or their pushing force or whatever
This is my first game so pardon me if I'm way off
@minor dew are you looking for a perfect solution?
a little slipping and stuff acceptable?
@minor dew here is what i would do:
inside oncollision stay, i would try to fight against rotation
and align the cars forwards (via pushing them together)
and also dampen cars relative velocities
on collision axis plane
hey guys my player does not collide with objects
i have setup box colliders
on the objects it should collide with
The player needs a collider too I think - it can be a trigger
ok let me try
two things - player needs a collider - but also your player is kinematic - which makes me wonder how you are moving the player
Recording #8
generally kinematic rigidbodies don't respect forces or obstacles
aha i bet its setposition
Yeah - Kinematic rigidbodies are like unstoppable forces
they go where they want, and ignore collisions (although they will push dynamic bodies out of the way)
there you go then, uncheck that box 😄
got it
Well that's a whole different can of worms - but yes your player will then respect collisions
heya, ive been making a ground detection system but for some reason whenever i hit the wall (even if standing stil against it) it counts as collision despite the ground collider being quite a bit away from the wall? any ideas on how i could fix this? (red = groundcoll (isTrigger), blue = player (regular square collider2d, cyan = wall(mesh collider))
all i know is that offcourse it sets the player in the wall before the collision correction and it counts as detection (i assume, anyways), but i have no idea on how i would fix this
oh and its apparently fine when the wall is on the left side, but not right?
huh i fixed it by making the hitbox a bit smaller, but i assume it'll happen again at a lower fps, so it's still a problem
making the collision detection continuous might help if it's a clipping issue
I have written the code of collision right but still it's not detecting collision with obstacle
idk why
pls help
i have tagged obstacle too
where is the obstacle?
it comes when the game starts
it's a prefab
will instantiate after game starts
yo, Im trying to use physics overlaysphere to detect only colliders on the 'enemies' layer using a layermask, but for some reason its detecting colliders on all layers for some reason?
the room the player is in is definitely set to default, Ive checked this during run time, so I have no idea why the colliders are being detected
figured it out lol
Im missing a parameter in the overlay call
sadly already have continuous on and it's still an issue
to avoid that, you need to just let the collision happen and not handle it, or also detect when you're against a wall to prevent movement in that direction
Hello, can anyone help me figure out how to make my walls ultra solid. I am pretty new and am taking this udemy course and my walls work until I increase my player speed to anything above ten which is painfully slow.
try continuous detection mode, make them fatter, or use casting functions
Ok I'll try that
Where is continuous detection mode? I was told to use the box collider, is it a different one?
that setting is on the rigidbody
It didn't work. Does adding a material to the colliders help with anything?
it won't help with tunnelling
which is the problem you're facing
ways to fix it:
- Decrease the game's fixed timestep
- Make your walls thicker
- Make your player thicker
- Change Rigidbody collision detection mode
- Use custom box/capsule/sphere casting in FixedUpdate to detect obstacles
Ok thank you I will try those
and if all that fails, there's a pretty old script I found called dontgothroughthings, that uses a raycast to detect if a wall is coming, and through some sorcery, prevents clipping through walls
I couldn't get it to work when I tried, but apparently its a thing, ill find it for ya
I didn't really spend that much time trying to implement it, so not getting it to work is likely my fault
Yeah I'm like super new to coding and unity so it will probably take a bit to understand a lot of the stuff
I appreciate everyone for trying to help though
That's not sorcery, that's the ray/collider casting MICKEN and PraetorBlue were talking about 😉
I'm trying to have a box that the player can only push around a designated area. So I need a box that collides with the player and some walls, and walls that collide with the box and not the player.
How would I go about doing this? I'd imagine there's a "one-off" solution as well as some sort of general solution (using layers maybe?).
Layer based collision is the way to go for sure
And just as a side note, there is indeed a "one-off" solution as well, where you can tell the physics engine to ignore collisions between two specific colliders: https://docs.unity3d.com/ScriptReference/Physics.IgnoreCollision.html
ah, that's also useful to know, thank you
does anyone know is it good to combine collision meshes into one big mesh
and under 65k triangles
or better to have smaller meshes
does it affect occlusion culling
Hi, I have an issue I need to resolve. I have a car object following a sphere with a rigidbody as the control method. That all works great. The problem comes because I'm using transform.position to move the car to the sphere location, the car can move into a solid object up to the point of the sphere
I've tried messing around with collision layers and adding extra colliders to the sphere, and those don't work. What's the best way to have my car collide with objects properly?
I've tried totally recreating the vehicle and have it move with real physics, and that worked up to a point, then it started clipping through terrain at points, and basically presented a new set of problems
If you're teleporting it how is it supposed to collide?
I think you're going to need to do your second approach with actual physics and figure out those problem
Well, my idea was along the lines of adding a second box collider to the sphere object, then place that in a collision layer that ignores the ground, but interacts with other objects
