#⚛️┃physics
1 messages · Page 78 of 1
In the editor's game view, it runs perfect
It seems reasonable
Oh then you have some framerate dependent code for sure
Show your code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerController : MonoBehaviour
{
public float speed = 4;
Vector2 relativeMovement;
public float gravity;
public float smoothTime = 10.0F;
public Vector2 accelerationVector;
private Vector2 velocity = Vector2.zero;
private Rigidbody rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
private void Update()
{
Vector3 movement = new Vector3(InputController.movementX, 0.0f, InputController.movementY);
Vector3 cameraMovement = Camera.main.transform.TransformDirection(movement);
relativeMovement = new Vector2(cameraMovement.x, cameraMovement.z);
relativeMovement.Normalize();
accelerationVector = Vector2.SmoothDamp(accelerationVector, relativeMovement, ref velocity, smoothTime * Time.deltaTime);
}
void FixedUpdate()
{
rb.AddForce(accelerationVector.x * speed, 0, accelerationVector.y * speed);
rb.AddForce(Vector3.down * gravity * rb.mass);
}
}
It's every object though, even the ones that just have a rigidbody and a collider
What happens if you get rid of the smoothing code there for a sec
Just set accelerationVector = relativeMovement;
Does that fix the weird difference in behavior?
Just checking. In editor is fine, building real quick
you literally factor in deltatime to your addforce there
accelerationVector = Vector2.SmoothDamp(accelerationVector, relativeMovement, ref velocity, smoothTime * Time.deltaTime);
rb.AddForce(accelerationVector.x * speed, 0, accelerationVector.y * speed);
That's just for how fast the speed vector ramps up
It's still slower in build, but not by as much.
but why is that a thing in the first place?
Either way, this code wouldn't effect the gravity of the other physics objects
Because applying a sudden force to the marble makes it look like it's being pushed. There's a slight ramp up so it looks like it begins to roll on it's own.
What's your framerate
In the build
If you're hitting the max timestep it'll actually slow down the physics simulation
Though it doesn't seem likely here...
I’ll have to check in a bit, got to do something for now.
Is it ok to make things real world scale, when I'm working with miniature scale stuff?
Like, the main marble being 18mm
it can cause issues but I'd try first because drawing too many conclusions
physx kinda struggles with tiny objects, especially if you have like angled surfaces and joints etc
It's ideal to make things real world scale if you want them to look and behave like they're that scale
especially if you're using physics
but also for lighting
I learned that when doing some pinball game for game jam once...things broke in really weird ways 😄
well yes if things are very small you may need to play with some of the defaults in the physics settings
like contact offsets
and yeah there's a limit
18mm is not crazy small though
this is basically why we make prototypes and test things
see yourself if it works in real to life scale and only worry about it if you see it's causing issues
if you have to spoof the scale, it comes with extra baggage and side effect
This is my main reason for wanting to. It's the reason my marble has seemed "floaty" so far
scaling everything by say 10x isn't issue physics wise, you just up the gravity and forces to counter it
but it's still simpler to keep things in right scale if possible
Would gravity scale evenly? Like, 98.1m/s2 instead at 10x?
I feel dumb for saying "When are we gonna use this" to math/physics teachers XD
you can also do the math yourself if you want 🙂
a lot of the basic physics equations apply as is to game physics
you use newtons laws a ton here
So far I have been. My marble should be 0.024 mass if it's in kilograms, based on steel density
The AO/shadows definitely seems sketchier at this scale
Is there a way to work out a realistic restitution value?
they list some estimates there
Ooh yeah. Is that a 1-1 with unity?
considering they have values over 1.0 there, I doubt it
any figure higher than 1 would start generating extra energy instead of damping the motion
that being said, their do say COR = relative velocity after collision / relative velocity before collision
so... wonder what's up with those figures then
ah
"The COR for plastics and rubbers are greater than their actual values because they do not behave as ideally elastic as metals, glasses, and ceramics due to heating during compression"
It does say at the top "Values over 1 indicate an error in the estimate"
Steel is 0.9, which in unity would mean almost fully bouncy
True
I'm already having physics issues in unity
The marble is just falling through the floor
you know newton's cradle?
if you get rid of extra frictions, it will keep going for a quite long time
heh
not a problem most would have
there could have been some scale setting for those
Maybe scaling stuff would be better
?
how is it any kind of issue
shadow resolution is relative to your shadow distance
Really? I couldn't find any settings for it beyond that
I've scaled everything up and that seems fine, apart from gravity.
With realistic gravity, it's suuuper hard to climb ramps unless you're moving really fast.
@young rapids the first value on urp asset under "shadows" is "max distance"
your perceived shadow resolution is basically just combination of the overall shadow map size in the map (distance from camera) and it's resolution
if we neglect the different shadow filtering algo's effect for a second here that is
but those wouldn't actually change the shadow resolution, just how it looks
Ahh, thank you. Shadow's are appearing in game view but not editer though
how to make hands (or other parts) of model to collide with other objects properly?
Right now, during attack animations, hands just go inside of mesh.
The issue with realistic gravity 😅
You should generally use Inverse Kinematics to properly position hands during animation
I've just realised, for some reason my objects now have 0 bounciness
Even when I set them to max
No pun intended
I mean, yeah XD
I've gone back to the old scale, everything x 100, and it's working much better.
Just used normal gravity x 4, which is technically less than half what it should be, but it's working pretty well.
How do you use a non-convex collider?
If it's a static object, there's nothing special to do
if it's a moving object, it's better to build up the collider out of multiple primitives if possible
Ah ok
I've found a non-convex collider on the asset store too that I'm trying
Though, it seems to be voxel based...
It seems a little funky, though may just be my mesh
If the mesh geometry is abnormal it may certainly cause issues
seems ok to me? 🤔
Yeah, it works, just not as smooth as I hoped
Actaully I think I know why
There's a bug with the voxel collider I bought, it wouldn't go away even when the component was removed
@young rapidsfor that type of collision, I'd use contact modifications (only available since Unity 2021.2) but it's bit more advanced concept
Baring in mind I really starting learning unity 2 days ago XD
yeah, hence mentioning it not being something I'd recommend for newcomers, it's not that well documented and you have to figure out the math yourself if you use it
(it basically lets you spoof collision pair data before physics engine solves the collisions based on the data)
I think the collision's fairly satisfying at the moment. The only issue is my marble crushing something light like the small die against a wall is very bouncy
also btw, there's a package from Unity that lets you do VHACD but it's not exactly easy to find
(basically similar thing that paid nonconvex thing from asset store does)
right now this is only available via github so you can't use package manager to fetch that one
also worth noting that I haven't ever tried this specific package but I have used other VHACD wrappers for Unity in past
Yeah this is the first asset I'm considering refunding
Cause, anything other thing the small props in the examples, voxel's are not gonna work
refunding is tricky, especially if you've already downloaded the asset
unless the asset publisher is willing to give refund and the asset does what it's advertised, Unity doesn't typically give a refund
only exception is if you just bought the asset and haven't downloaded it yet
no primitive type for it on physx no
you need convex collider for it
(or capsule with those contact modifications)
bruuuuuh, watched long video on IK and when time came for actual code part it said "buy full course here" and skipped it
feels like IK is some kind of black magic rn
WASD - move
Space - jump
Shift - dodge/airdodge
I - shorthop
thoughts? i made this in two days
I have been playing with physics. I attached camera to cube and trying to move it around
When I move this cube to one side of another cube, it phases through.
But when I move it to another side of cube, it collides properly
why does it happen?
A static object is like "pushing it out"
I want to make some kind of swing for my marble platformer, using physics
Is it realistic for me to just make it so when the swing hits the middle point, it adds some force to keep it going, so it doesn't slow down?
I'm having a problem with physics being really unstable in a pooling situation.
Background: I'm building a large VR game for the Quest, with lots of interactable, simulated items. Think houses full of objects you can grab, push, open, pick up, including furniture elements. Now since most of the houses share stuff, I decided to pre-spawn all of their contents, and just move them between houses as the player changes position. The pooling works, but most of the simulated bodies exhibit really unstable behaviour.
Process: When the player gets in proximity of a building I populate it as follows:
- Get all item positions from special markers present in the scene, and get the correct object instances from object pools.
- Set all object rigidbodies to kinematic, move then to their designated positions (I use both transform.position and rigidbody.position), and set their GameObjects active.
- Gradually remove the kinematic flag on all rigidbodies, 2 per frame, to avoid CPU spiking. Large objects (i.e. furniture elements) are handled first, small objects second.
Problem: Things explode during the last step. It's mostly items positioned inside furniture drawers that get haywire to the point of blowing the drawer open and flying out (or through). All of them are carefully positioned by simulating gravity inside edit mode, so there's no collider intersection. Nearly everything in the scene uses box colliders. My simulation steps are set to 12, and I don't really have the budget to set them higher, due to sheer amount of items in each house.
Is there any way to make this behave less volatile?
I think I need to move here from beginners
My marble's kind of...gliding?
I'm just gonna post my entire playerController and hope someone can see an issue https://gdl.space/lulifosedu.cs
What is better for perfomance:
9 simple cube colliders or 1 mesh collider in form of box (that has empty space inside)?
cube colliders
that mesh collider would have to be concave, and those are the worst kind for performance
also that would prohibit your object from being a dynamic rigidbody
oh yeah, those are nice points
so best practice is creating buildings/environment out of multiple simple meshes instead of creating complex meshes?
that kinda depends on how exactly the meshes work
but for complex geometry, we usually separate colliders from the meshes
i.e. scene geometry that's immobile
and either make it all box colliders
yeah, I know about that feature
I guess my question is a bit out of perfomance question here
or prepare separate mesh colliders that are simpler than the item itself
but more of level design practice
you could make a low poly version of the mesh, add a mesh collider, and set it to convex
it's uses less performance, and it's still dynamic
technique I want to try but haven't got the time to recreate the physic meshes
i am looking for some explanation or code for how boxcollider2d and rigidbody2d work by default, i mean that the box that has force pushes another box if it is not stationary
i want to implement such behaviour outside unity
unity uses Box2D for 2D physics
All the code is open source https://github.com/erincatto/box2d
You can just use Box2D in your non-unity application if you want
No need to reinvent the wheel
i found it more difficult to import and make box2d working than to make my own physics, but your tip is useful that unity uses box2d
I have attached the following script to my cube:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShipController : MonoBehaviour
{
// forward movement speed
public float forwardSpeed = 25f;
// side to side movement speed
public float strafeSpeed = 7.5f;
// how fast we move up and down
public float hoverSpeed = 5.0f;
private float activeForwardSpeed;
private float activeStrafeSpeed;
private float activeHoverSpeed;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
activeForwardSpeed = Input.GetAxisRaw("Vertical") * forwardSpeed;
activeStrafeSpeed = Input.GetAxisRaw("Horizontal") * strafeSpeed;
activeHoverSpeed = Input.GetAxisRaw("Hover") * hoverSpeed;
Vector3 forward = transform.forward * activeForwardSpeed * Time.fixedDeltaTime;
Vector3 strafe = transform.right * activeStrafeSpeed * Time.fixedDeltaTime;
Vector3 hover = transform.up * activeHoverSpeed * Time.fixedDeltaTime;
Vector3 movement = forward + strafe + hover;
this.GetComponent<Rigidbody>().MovePosition(this.transform.position + movement);
}
}
Cube moves, but... it does not collide with other cubes on scene
Here is a hierarchy
I have these settings on a moving cube:
These are settings on another object
How do I get collisions here?
you are getting collisions, but they are not resolved by physics simulation
kinematic rigidbodies can only be moved by script, physics simulation will not affect them, nor any other forces
i assume you want a rigidbody that is controlled by you, but also behaves correctly after hitting something
there are two ways to do that - either leave the RB kinematic and simulate your own collision response, or turn off kinematic and use forces to move it (rb.AddForce, rb.AddTorque)
which one is better depends on how your game is built
So, I assume that I should change line
this.GetComponent<Rigidbody>().MovePosition(this.transform.position + movement);
What is Kinematic for?
Thank you so much!
I disabled IsKinematic on my object
and used
this.GetComponent<Rigidbody>().AddForce(movement);
Now collisions are processed properly.
And it added up a bit of innertia, which looks cute
as a side note, caching components you perform frequent operations on is considered good practice, since fetching the component is rather expensive - this quickly adds up in larger projects
glad to hear a simulated rigibody worked out for your use case
Speaking about rigidbodies, I have add relative force to a rigid body with a 100 units of mass. when they colide the bounce off of each other like expected but, it's too much. The space ships spin out of control and move away for far to long.
What variables should I look into to solve this? Drag maybe?
angular drag?
Yes, it was angular drag. I guess I had to think that one up out loud
does omitting an object from collision for another specific object require a script?
all goods, sorted it out with the layer matrix
Why does a normal rigidbody not have a gravity scale unlike a 2D rigidbody?
I am trying to edit how fast a certain object falls
Probably because its unrealistic to have different gravity scales and they didnt find it too useful to have that because its super simple to code the gravity yourself if youre not happy with the build-in gravity
But it would be realistic if the objects had different weights
2d and 3d physics also uses different physics engines and unity have different teams working on them so not all the features are same
No its not, in real life falling acceleration is same for every object no matter the weight
Okay I dont really know much about physics. I guess I just have to make my own system
You can just disable the gravity and use addforce (use ForceMode.Acceleration) to add gravity
rb.AddForce(Physics.gravity * gravityScale, ForceMode.Acceleration) should work
Thanks
I got a ragdolled ( through wizard ) character, I need it to swing around a pole. The hands are connected to the pole with a Fixed Joint component.
I can't make it swing around the pole
https://gyazo.com/6164c634b6022adf2b3db5ed66a2c197
This is the code
if (Input.GetMouseButton(1))
{
bone_spine.GetComponent<Rigidbody>().velocity = new Vector3(bone_spine.GetComponent<Rigidbody>().velocity.x + 0.1f, bone_spine.GetComponent<Rigidbody>().velocity.y + 0.1f, 0);
}
if (Input.GetMouseButton(0))
{
bone_spine.GetComponent<Rigidbody>().velocity = new Vector3(bone_spine.GetComponent<Rigidbody>().velocity.x - 0.1f, bone_spine.GetComponent<Rigidbody>().velocity.y - 0.1f, 0);
} ```
I'm completely lost, do y'all have any resources about this kind of ragdoll physics?
and is what i'm trying to achieve even possible?
Unity is weird at times. I'll never understand that when you a rigidbody. when the built in character controller. than attempt to move the character is unaffected by gravity until you stop moving
i just started out with unity, so this is a basic problem im guessing.
im trying to have a capsule being controlled by the player be able to move around and whatnot. The problem im having is that when the player tries to move into another rigidbody object, it looks like the capsule shudders back and forth until i stop moving toward the cube.
code for player:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerScript : MonoBehaviour
{
public string testString = "this working?";
public float lookSpeed = 3;
public float moveSpeed = 3;
private Vector2 rotation = Vector2.zero;
private Rigidbody rb;
void Start()
{
Debug.Log("player active, " + testString);
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
rb = GetComponent<Rigidbody>();
}
void OnCollisionEnter(Collision collision)
{
moveSpeed = 0;
}
void Update()
{
float horizontalInput = Input.GetAxis("Horizontal");
float forwardInput = Input.GetAxis("Vertical");
rotation.y += Input.GetAxis("Mouse X");
rotation.x += -Input.GetAxis("Mouse Y");
rotation.x = Mathf.Clamp(rotation.x, -15f, 15f);
transform.eulerAngles = new Vector2(0,rotation.y) * lookSpeed;
Camera.main.transform.localRotation = Quaternion.Euler(rotation.x * lookSpeed, 0, 0);
//Move the object to XYZ coordinates defined as horizontalInput, 0, and verticalInput respectively.
transform.Translate(new Vector3(horizontalInput, 0, forwardInput) * moveSpeed * Time.deltaTime);
moveSpeed = 3;
if (Input.GetKeyDown("escape"))
{
Cursor.lockState = CursorLockMode.None;
}
}
}
all im doing here is moving sideways against the cube, and it stutters and tilts the player
is the rigidbody on the player kinematic?
also, irrespective of that
you should be using a player controller component for stuff like that, it has built-in deflection on collisions, so you won't be forcing the player into the object you're collinding with
Rigidbody and CharacterController are two completely different approaches to character movement and should not be used together, as they will conflict.
moving your object with Transform.Translate does not play nice with physics. You want to use Rigidbody.MovePosition or Rigidbody.AddForce or use a CharacterController. And do it in FixedUpdate, not Update.
or setting the Rigidbody's velocity directly works too
yes
yeah, that's better than translating a simulated rigibody at least
you might want to a) move your code to FixedUpdate, since that syncs what you're doing with the physics simulation b) use rigidbody.MovePosition
but that still won't give you nice collision deflection
for a beginner i'd suggest using the character controller and removing the rigidbody
you'll get far nicer results
If the body is kinematic I don't think it's going to respect any collisions at all
even with MovePosition
kinematic objects are unstoppable forces
so i fixed it, but now whenever i try and move while looking around with the mouse, it gets kinda buggy. should i change anything about the way it looks around?
yeah
ok so when i try doing both, it only lets me do one
do rotation in Update
like i cant look and move at the same time
you should rotate the player controller on the y (up) axis, but rotate the camera parented to it on the x axis
yeah i am
in what way exactly is it buggy, and how's the code look now
void FixedUpdate()
{
Vector3 m_Input = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
rb.MovePosition(transform.position + m_Input * Time.deltaTime * speed);
}
void Update()
{
rotation.y += Input.GetAxis("Mouse X");
rotation.x += -Input.GetAxis("Mouse Y");
rotation.x = Mathf.Clamp(rotation.x, -15f, 15f);
transform.eulerAngles = new Vector2(0,rotation.y) * lookSpeed;
Camera.main.transform.localRotation = Quaternion.Euler(rotation.x * lookSpeed, 0, 0);
if (Input.GetKeyDown("escape"))
{
Cursor.lockState = CursorLockMode.None;
}
}
when i move around and look around at the same time it stops the player movement until i stop looking around
like it wont process mouse and keyboard inputs at the same time
ok and also i just played around with it more, and let me figure out how to word how this is broken
moving forward/back/left/right is broken, like it doesnt register me turning to be a change for moving. so when i turn and look to the right, pressing w doesnt make me move forward, instead it moves me to the left. or if i press play, then look behind me, pressing s would move me forward, and w would move me back
that's because you're moving the character by an absolute direction, not his local "forward" direction
Vector3 m_Input = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")).normalize;
first off, normalize your input
now let's try rotating this vector so it matches the direction your controller is facing
rb.MovePosition(transform.position + (rb.rotation * m_Input) * Time.deltaTime * speed);
might work, might not, but it'll get us somewhere 
i put .normalize in that line and it gave me an error
Vector3' does not contain a definition for 'normalize' and no accessible extension method 'normalize' accepting a first argument of type 'Vector3' could be found (are you missing a using directive or an assembly reference?
normalized
yeah, normalized
hang on, let me try to do it on my end
well, it works on my end
rb.MovePosition(transform.position + (rb.rotation * m_Input) * Time.deltaTime * speed);```
I am just trying to make a simple pong game using unity physics to control the bouncing of the ball, but after several bounces the ball always ends up going either straight up and down or side to side. does anyone know the issue?
I already set bounce to 1 for the physics material and changed the bounce threshold to 0 in the project settings
figured it out. all the objects materials need to have bounce set to 1
maybe its the code i use for mouse. heres my full script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerScript : MonoBehaviour
{
public float lookSpeed = 3;
private Vector2 rotation = Vector2.zero;
public float speed = 5f;
Rigidbody rb;
void Start()
{
Debug.Log("Start() works on player");
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
rb = GetComponent<Rigidbody>();
}
void OnCollisionEnter(Collision collision)
{
//moveSpeed = 0;
}
void FixedUpdate()
{
Vector3 m_Input = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")).normalized;
rb.MovePosition(transform.position + (rb.rotation * m_Input) * Time.deltaTime * speed);
}
void Update()
{
rotation.y += Input.GetAxis("Mouse X");
rotation.x += -Input.GetAxis("Mouse Y");
rotation.x = Mathf.Clamp(rotation.x, -15f, 15f);
transform.eulerAngles = new Vector2(0,rotation.y) * lookSpeed;
Camera.main.transform.localRotation = Quaternion.Euler(rotation.x * lookSpeed, 0, 0);
if (Input.GetKeyDown("escape"))
{
Cursor.lockState = CursorLockMode.None;
}
}
}
hey how would i be able to move this green brick against the wall?
this is how the joint moves
The table has box colider only
The green box has Box colider, rigidbody(freez position on z, freeze rotation on x,y,z, and has continus detection) everything else is default
The end joint has Capsulie colisder, rigidbody(free rotation, position on all axis, no gravity)and evetythin is defualt
@pure quarry ok, i see the issue
here's the working controller with explaination
public class PlayerController : MonoBehaviour
{
public float speed = 5.0f;
public float lookSpeed = 400.0f;
public Rigidbody rb;
private Vector3 rotation;
private Vector3 mouseInput;
private Vector3 kbInput;
void Awake()
{
rotation = rb.rotation.eulerAngles;
Cursor.lockState = CursorLockMode.Locked;
}
// Turn on interpolation in the rigidbody component for smoother movement.
void FixedUpdate()
{
var oldRot = rb.rotation;
var newRot = Quaternion.Euler(0, oldRot.eulerAngles.y + (mouseInput.x * lookSpeed * Time.fixedDeltaTime), 0);
rb.MoveRotation(newRot);
rb.MovePosition(transform.position + (rb.rotation * kbInput) * Time.fixedDeltaTime * speed);
}
void Update()
{
mouseInput = new Vector3(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
kbInput = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")).normalized;
rotation.x = Mathf.Clamp(rotation.x - (mouseInput.y * lookSpeed * Time.deltaTime), -35f, 35f);
// transform.eulerAngles = new Vector2(0,rotation.y) * lookSpeed;
// !!!
// You can't manipulate the transform *and* move the rigidbody.
// Doing this will cause objects to be forcibly re-synced, thus i.e. blocking movement when rotating.
// If a rigidbody is present on a gameobject, you only move the rigidbody and leave the transform alone.
// Rigidbodies exist independently in a "physics-world", and then sync transforms to their positions in game scene after a simulation step.
// Instead we only rotate the camera (since it's not a rigidbody), and store the remaining inputs to be processed in FixedUpdate.
Camera.main.transform.localRotation = Quaternion.Euler(rotation.x,0 ,0);
if (Input.GetKeyDown("escape"))
{
Cursor.lockState = CursorLockMode.None;
}
}
}
does anyone know how linear drag is calculated in unity? I can choose the values I need, but I would like to be able to control them precisely.
The result is completely different values.
is this 3D physics or 2D physics?
2d
then it's not physx
it's box2d
found this, not sure if it's current
you can verify that here
This feels a lot slower than it should be...
How would I set up a series of joints to work similarly to the Dynamic Bone plugin? Specifically, imagine you cut down a sapling and stripped it down, how springy it would be as you waved it around. It would flex on both axes, but not stretch, and return to its original shape when you stop moving it. I thought about using a hinge joint, but that only rotates around one axis. I then tried using a character joint, setting the twist limits to 0, and setting the swing limits to 0 but giving them some bounciness, on the theory that if the swing were higher than 0 they would swing but not return to their original position, and the bounciness would be what allowed them to flex beyond the limits, but this doesn't seem to work at all.
I don't want to use Dynamic Bones because they require their own colliders and don't collide with the world, and I can't adjust the mass of things to get proper physical reactions.
Its either gravity or drag (or your script) thats making it slow
There's no drag, and gravity is 4 times stronger already.
I made it 10 times stronger and it was still slow like that
Are you simulating rolling resistant yourself in code?
No, it's mostly just the rigidbody. My movement code is just adding force./torque.
Well, adding force and torque can very easily cause that 😄 . Have you tried disabling the movement script and testing if its still as slow even with high gravity?
so for some reason the mesh collider doesn't work for me. I'm trying if one piece will fit into another, for 3d printing, in unity but it doesn't have a collider
thanks, but ah, how do i use the controller with the player? right now its saying that "the referenced script on this behavior (game object 'player') is missing"
paste it into a fresh script called PlayerController
should i change public class PlayerController : MonoBehaviour?
or rename to your class
ah ok thats what i was thinking
filename and class name have to match
how do i move gameobject along x-axis with unity articulation body?
Is there something like Dynamic Bones which works with regular colliders? For one, I'd like them to collide with the world, and it's a real pain having to recreate all the colliders in the hands for dynamic bone colliders every time I update the Hurricane VR SDK. It's already got capsule colliders. I've tried using character joints to create a similar effect to Dynamic Bones but with no luck.
I want to add a fan mechanic for my marble game.
I'm just wondering what the best way to do that is? Should I make a cylinder/capsole trigger in front of the fan, and make that add force to the player?
https://gyazo.com/e400590eca43f26b37a8c91cabd6f9f0
I'm trying to move around the ragdoll through one of its hands, however when I do this happens. How can i fix it?
Is there a way to kind of snap RigidBody to certain point (in my case it's where cursor is), while retaining all physics and collisions (so if that point goes behind wall, object will just get stuck behind it)?
How would you make a see-saw in unity?
Like, an object that can move with a rigidbody, but is fixed in 1 point?
Hello. I am trying to apply a Torque to a rigidbody, but nothing happens.
this.GetComponent<Rigidbody>().AddTorque(torque);
torque vector is (0;25.0f; 0)
Am I missing something?
AddForce works fine
Oh
I had this enabled:
😂 🆗
@young rapids joints
Does the other side need to be a rigidbody?
Or can it connect to something static?
if you don't specify a connected rigidbody on a joint instance, it's affixed to a point in space
Thanks 🙂
It works, but is there a way to add..resistance to the joint?
Would that just be drag?
do you need a rigidbody for collisions to work?
I have made a knife script that damages an opponent when its close enough to the knife and the player presses "shoot" at the same time. Its just a raycast that damages the player if the raycast htis it. How would i make it so that the raycast is in a wider range? So it would go from a dot raycast to a line raycast if somebody understands.
No, just a collider
I have been sitting for a long time and I can’t come up with a solution
Let's say we have such values
F = 11
S = 10
DT = 0.02
V = 0.2 (initial value)
D =?
And there is such a formula.
V = V * (1 / (1 + DT * D))
It is necessary that through F repetitions V be as close as possible to S (9.8-10.2).
couldnt you shorten V = V * (1 / (1 + DT * D)) to V *= (1 / (1 + DT * D))?
V *= (1 / (1 + DT * D)) repeated F times is the same as V *= Mathf.Pow((1 / 1 + DT * D)), F). Set that equal to S and solve for D.
I am curious, what is this equation for?
I am very confused, is NVidia FleX still a thing in Unity or is it not anymore ?
You could cast a flat box instead of a ray for example
Refer to the tables at the end of this page from the manual https://docs.unity3d.com/Manual/CollidersOverview.html
@lofty coral I believe Physics.BoxCast is what you're looking for
three raycasts (two for edges, one for knife's point) might be just as viable, though
also cheaper
Hey, I'm trying to make a chain that swings back and forth and never slows down. I'm using hinge joints. Is there a way to do this?
youtube
Nothing
i have been trying to figure this out for the past few days so don't judge me - my projectile (the white cube inside is for reference cause its hard to see without it) goes on a weird rotation if i spawn it while the camera is moving
void Update(){
if(Input.GetButtonDown("Fire1")){
Shoot();
}
}
// Update is called once per frame
public void Shoot()
{
if(canShoot){
GameObject spell = Instantiate(spellObj, transform.position, cam.rotation);
spell.GetComponent<Rigidbody>().AddForce(spell.transform.forward * shootForce * 100f);
canShoot = false;
Invoke(nameof(ResetShooting), shootCooldown);
}
}
public void ResetShooting(){
canShoot = true;
}
it shoots fine when the camera is still
Hello, I'm currently making a smooth movement implementation for a platformer and would like to ask for help with a problem and advice from those who understand. I made vertical movement, like jumping, using addForce. I noticed that if there is an equivalent difference between mass and drag (1, 1 or 0.1, 10), then the acceleration will occur exactly to the specified value and I think I understand how it works, but now it doesn't matter to me. Thanks to this method, I can control acceleration, top speed and deceleration. While doing the jumps, I decided to use ForceMode2d.Impuls. Basically everything works the way I want it to except that my dragging slows down my jumping a lot. I tried to calculate and change the speed changes but it doesn't work. I would like to know your opinion on how this problem can be solved and whether it is worth using such an implementation at all.
Hi, I'm making a 2D platformer, and I have an irregular shape roof, and I'm wondering if it's possible to make that roof (Which I use a polygon collider 2d) a one way collision? Meaning I can jump on it from below?
This is the roof shape
I know with a normal flat platform you can do a y check
It's possible. There are tutorials for that out there. I forgot what the term is though
generally you can do that easily with a kinematic character controller that just ignores collider hits with a down-facing normal while moving up, but also with a physics driven one you can use a raycast to detect an upcoming collision with its normal and disable the edge when moving "up".
I just found an extremely easy way to do that for anyone wanting to make one way platforms even at angles
There's a component called Platform Effector 2D
you can set how much of a platform is detected by collisions
Does anyone know how to edit the collisionMask attribute in script? I'm trying to change a platforms collision with the Player layer when I press a key
That doesnt show the syntax of how to change the values
With the = operator, same way you change any variable/value
it's an int. You change it just like any other int
Yesnt. You could change it as any other int but its bitmask, not regular integer representing the layer. You can make LayerMask variable with [SerializeField] attribute so you can change it on inspector. Then you can just set the mask to be that LayerMask variable. LayerMask is basically an int but it allows you to edit the mask without touching any bitwise operators and stuff
does anyone know why my game object is bouncing when my player goes fast, btw im using velocity to change the the movement and my player is using rigidbody
Are you using collision detection mode continuos?
And what about the physics material?
oh about that i use no friction for my material
And bpunciness?
one sec
sorry i gtg for a few mins ill be back
Np
alr im back and bounciness is at 0
lol
Most probably is your movement
want my script???
i can send in #archived-code-general
i have an issue, sometimes ennemies and players fall though platform while walking on the ground when it looks like this
not code related since disabling the platform script still creates the issue
ok widening the surface arc seems to fix it
Hello,
this happens to me when I use rb.MoveRotation
is there any chance of keeping the player on that moving wing?
https://ctrlv.tv/0D5S
Hello guys, I've got a physics/velocity problem. So my Character Controller should jump once after having a connection to a collider to the environment (here ground) and sometimes the Character just jump 10x -100x as high as he should and I don't understand why. Here is the extract of my code which controls it:
public float jumpHeight; (assigned in Editor)
private bool readyToJump;
public Transform ground;
public LayerMask groundLayer;
public float groundDistance = 0.5f;
... update ()
... Jump ()...
void Jump()
{
readyToJump = Physics.OverlapSphere(ground.position, groundDistance, groundLayer).Length > 0;
if (Input.GetButtonDown("Jump") && readyToJump)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * Physics.gravity.y) * Time.deltaTime;
}
myController.Move(velocity);
}
The gravity is constantly pushing the player down and resets the velocity if he is grounded, so I dont think there should be a problem with the speed
(In another method) - Please feel free to @ me if you can help me with this
You should not be incorporating deltaTime into a velocity variable
deltaTime Is reasonable for calculating a new position given a velocity vector, or the amount of velocity to add for an acceleration. But velocity itself should not be different because of a different framerate.
I'm trying to simulate an object at the end of a rope, as shown by the following video. However, I'm encountering an issue where the bounce doesn't damped, shown at the end of the video, and I'm not sure sure how to fix that. I'm not spectacular at physics, so I could already have the base calculations wrong. I'm also pretty new to Unity so that also doesn't help all that much
I calculate the amount to accelerate the cube by:
Vector2 distance = endPos - (Vector2)boxCollider2D.bounds.center;
float ropeLength = ropeSegmentLength * totalSegments; // Length of rope
if (distance.magnitude > ropeLength) {
float mass = rigidBody.mass;
float tension = 65f * (distance.magnitude - ropeLength) + 49f;
rigidBody.velocity += tension / mass * distance.normalized * Time.fixedDeltaTime;
}
This is called from fixedUpdate()
added cloth component to this object and getting z flickering... anyone know how to solve this?
I'm working on a kinematic rigidbody character controller for a 3d game and I have this code which I call on every fixed update
private Vector3 ResolveCollisions() {
Vector3 resolveCollisionsOffset = Vector3.zero;
Collider[] cols = new Collider[16];
LayerMask myLayerMask = GameUtils.MaskForLayer(gameObject.layer);
int cFound = Physics.OverlapBoxNonAlloc(m_Col.bounds.center, m_Col.bounds.extents, cols, Quaternion.identity, myLayerMask);
for (int i = 0; i < cFound; i++) {
var c = cols[i];
if (Physics.GetIgnoreCollision(m_Col, c) || m_Col.Equals(c)) {
continue;
}
if (Physics.ComputePenetration(m_Col, transform.position, transform.rotation, c,
c.transform.position, c.transform.rotation, out Vector3 dir, out float dist)) {
resolveCollisionsOffset += dir * dist;
}
}
return resolveCollisionsOffset;
}```
This gives me the offset to get my character out of any walls or floors it may find itself in (so far). Anyone know how I can expand this to find collision points/normals without relying on OnCollision___() callbacks to provide collision data?
I think the data might already be in there. I'm just not really sure how the contact point is calculated, or how what I have could be used to find it.
so short cut my player slides when it's grounded and its collider collides with the ground obj so tried to use the trace hit distance and added to the origin up the amount I go sink into the ground it works but when my player on hight speed it doesn't work for seconds untill he's on low speed again I do set the velocity to 0 when he's grounded kinematic rb
not sure if this is the correct channel, but I have a few bugs with my code that will cause major glitches.
The first bug is when holding A + S + W + shift(sprint) the player sprints at higher than normal speeds.
First bug fixed
The second bug is when sprinting + jumping towards an object that is lower than the head camera, the player jumps at a higher distance than normal.
Looking for some help on how to solve these bugs.
What is the reason for the flickering? Why is there overlapping geometry?
It’s a store asset. I think I’ll need to edit the geometry
I need some help. I've got this continuous physics simulation where a ball spawns and follows a track. The issue is the path the ball takes is deviating between each ball (which shouldn't be the case as they're spawning in the same place each time). I can't quite seem to work out why it's not working properly.
I don't think PhysX makes any promises about determinism or consistency. It's optimized for performance
Yeah this is what I’ve been reading when googling this issue
So how can I get around it?
there is "enhanced determinism" flag in physics setting but I don't think it would help on your use case
basically you can make that scene deterministic in way it always simulates the same way when you run it (meaning you get same behavior each time you start the scene again, but not for individual ball runs)
Hmmm
I’m tempted to forget about the continuous simulation and get the scene to reset when the ball hits a trigger tbh
why is the determinism important here?
I just read about something called DOTS
just curious why you care about it
Basically, I wanted the ball to run it’s course then a new ball would spawn and would run the course again. Like a repeating animation loop
well.. if you reload the scene, it should simulate exactly same way on next run
unless you actually alter the scene at the beginning yourself
if you have like checkpoints and stuff, you lose determinism there already since you can't restore mid simulation states 100% on physx
that DOTS "unity physics" package is stateless, so you that would help you there
on physx, bullet, havok etc you are dealing with cached states etc in addition
For this particular situation I think a hard reset would work fine. Not an ideal solution but saves a lot of unnecessary headache
Kind of a shame in terms of the aesthetics though
I haven't actually tested Unity's physx determinism, they could still mess it up somewhere... I did fix bunch of things a long time ago on Unreal to make physx fully deterministic there on each scene reload and it never deviated there
determinism is funny in a way that even single floating point digit change, no matter how small, can make physics objects bounce in totally different directions
I was wanting to have the ball go off screen, destroy then drop in from the top
Yeah I was reading a little bit about floating point accuracy
Deviation by a tiny margin (like .0000001) can knock the whole simulation off
the reasons why checkpoints are pain for determinism:
- most physics engines have cached states which you can't manually restore
- physx rigidbody setters and getters do extra math operations which basically guarantee that due to floating point math accuracy, you can never tell if it's set the value exactly same as it was internally
on top of that, Unity could also do some operations in addition but we wouldn't know since we don't have source code access to this
for the dots physics, this is different, there we have access to everything
I guess the only way to guarantee the ball takes the same path each time would be to do it with animation
if it's not player driven thing, could just simulate it once yourself and record it's run into animation clip
there's https://docs.unity3d.com/Packages/com.unity.recorder@2.0/manual/index.html but I've never used it so can't tell much about it
Interesting 🤔 thanks I’ll check it out
Anyone able to help me with this?
When coming to a stop from walking backwards there's this slight push back before coming to a complete stop, and when you hold shift(Sprint) + S and let go of shift the push back is far noticeable
Thats most likely the axis of GetAxis having too low gravity value
Gravity means the deacceleration towards 0 when releasing
You can change that from input manager
Thank you! That was the issue. Messed around with the gravity values and found the perfect values and now the issue is fixed.
How do I make it so Object3 swings with Object2 when it moves with Object1? It seems very hard to describe this.
Object3 will have a rigidbody. It is.. somehow "tied" to object2 so when object2 moves (Without a rigidbody force, (transform)), Object3 moves with it. But.. swings?
Maybe with joints
I thought so. What joints would I use?
Object2 does not have a rigidbody.
Why don’t give it one
Well, it is attached to an object that has a rigidbody as a child. I could add one though.
I want to be able to move it around without using force. (Since I would be moving it around with the Object1
So like
The object 3 has a rope connected to object 2
And then object 2 is child to 1
Yes!
can anyone help me? im trying to make a bmx game but the front wheel is on the ground and the wheel collider is up in the air but if i move the wheel collider it moves the whee
Hmm I tried a spring but it was.. bouncy. I want it to be more of a hinge There is a hinge joint but I can't figure it out.
Object3 just doesn't move when Object1 is moved
I gtg to sleep pretty late for me
I wish you the best of luck
Thank you! You have helped a lot.
hello :)
I am using a rigidbody character controller/mover I put together but it moves the character by setting velocity,
this does not fit with my intentions because it overwrites any external forces being applied to whatever character is using it.
I have tried using AddForce but each character has a different weight and just increasing the force applied by the character causes them to travel at different speeds when performing different movements, with some movements are entirely counteracted by friction...
Any suggestion on ways of keeping external forces and close to constant speed are appreciated.
Yes, use one of the ForceModes that ignores mass.
You will need to use Acceleration or VelocityChange modes
hi. What's causing my player to jump higher than normal when sprinting + jumping towards objects like these?
is your gravity being applied while the jump happens meaning that it might deactivate when you touched the boxes
or it could be that your velocity vector has some value on the y
cause it bounces
Likely your code is not properly handling the relevant vector math
Hello!
I have two vectors, first of which is velocity of a rigidbody and second is transform.forward of an object (just a point defining that forward direction).
How can I make so velocity becomes 0 in all directions except for that transform.forward direction?
If I just do Vector3.Scale(rb.velocity, point.forward.normalized); it will work fine with those points which direction isn't angled to a world axis, but if it's angled, velocity won't be properly stopped in other directions than that forward.
Example of how it looks in a game is in this video, where at the second clip player's velocity isn't stopped how it's needed and it leads to falling.
This is happened because point.transform.forward is something like (0.7, 0, 0.7) and when scaling it with velocity it's probably really problematic.
What I want to do is to make player stop on the moment it begins the rail grind, but I want to keep it's momentum in direction of this rail, so it doesn't stop and accelerate from 0 every time it begins grinding.
finally came up with a good working solution, where I just used the overall magnitude of velocity
Vector projection is what you're looking for. Vector3.Project
oh yeah you're absolutely right! should've looked up vector3 functions, didn't know there's one for this...
Damn this game looks so sick 🔥🔥
I was testing out which way works better and well.. it's complicated a bit
Using my way, when hitting an angled rail, almost perpendicularly it bounces off? While it can look damn awesome as a game feature, it's still uncontrollable and only happens on angled rails
And trying this exact thing but with Vector3.Project, it just slips off the rail.
Note that it only happens if player is angled in a range of 70-120 degrees from the rail that is also angled relatively to world axis
But why?
Are there any tools / scripts out there for automatically adding joints and colliders to a chain of bones like an ear or a tail which will make it behave like the dynamic bones plugin, with springiness? If I use the Dynamic Bones plugin I have to create specific colliders for the bones on my VR hands, I have to assign those colliders to every avatar with dynamic bones, and those dynamic bones wouldn't be able to collide with the environment. It seems absurd to do this when Unity already has all the physics stuff built in. And if I don't have to create the scripts myself to set all this up, well, that'd be nice. Plus I'm not exactly sure what settings to use for those joints, so it would save me a lot of trial and error.
https://ctrlv.tv/mNo5
Does anyone know how to do that when standing on the propeller so that the player does not turn so unnaturally? The parent's throw didn't help .
My colliders are phasing through each other (both in 2D and 3D), even when there are rigidbodies attached
Are they just moving via gravity and forces?
in 3d, the movement is through script
well, in general it's through script
though I think it's 2 different issues. In 3D the collision is detected but it still phases, while in 2D the collision isn't even detected
If you're moving them via their Transform instead of via the Rigidbody's force/velocity/MovePosition you're bypassing the physics simulation
ah, so that's why
IDK how I could make it work though (this is for the controllable character)
@hollow echo though wait, I'm using "Physics.SyncTransforms();"
That doesn't help, that will just teleport the physics system to where the transforms are
oh, in that case what should I do
Use forces/velocity/MovePosition
The functions on the Rigidbody that are not just .position
oh, so I move the object through the rigidbody instead of its own transform
The physics system can only react to collisions if it understands how the object moved. If it's being forced to a position then it can only resolve penetrations, and if it's being forced there every frame it might resolve and then be overridden by that movement.
ah, wait in that case what's the character controller for?
wait, wait, wait. @hollow echo I just noticed something, I wasn't using transform.position to move, I was using the character controller's .Simplemove
I'm not very familiar with character controllers, but I thought that was physics-based
The other reason physics objects would not collide (that isn't code moving them improperly) is if their layer based collision is set up to not collide.
https://docs.unity3d.com/Manual/LayerBasedCollision.html
thing is, they are colliding (like, oncollisionenter works)
but they're passing through each other
Are they travelling at high speeds?
they're somewhat real-world scaled objects? In the realm of meters not milimeters or kilometers
If they are, that should work. Recording a video of what happens would be helpful
If the player is using a character controller it shouldn't have a rigidbody on it afaik
I only added the rigidbody today though, before that it was already passing through things
though I think the other object didn't have one before that?
ok here it is
(I already took out the rigidbody from the player)
If things don't move, they don't need rigidbodies.
And character controller uses this callback when it hits things https://docs.unity3d.com/ScriptReference/CharacterController.OnControllerColliderHit.html as it doesn't use Rigidbody
taking out the rigidbodies changes nothing
the floor is a plane using a meshcollider, so that may change things? IDK
it doesn't have a rigidbody btw
yeah but how is that box just stuck there and not falling through it or being pushed around? It shouldn't be able to be half in the floor
Is its rigidbody position constrained there or something?
Or is it marked as static?
oh I thought you meant the moving one. It's not static but yeah its position was constrained. Though without the rigidbody nothing changes
yes
oooooooh
ok
🤦♂️
though now I still have my issue with the 2D collision just straight up not working
It's gotta be one of the issues I've mentioned previously. Screenshotting what's involved / posting videos will definitely help if you cannot track it down
this one is through transform.position, but wouldn't the oncollisionenter function still be called?
If it worked, it would work inconsistently at best
here's a video either way
sorry, I didn't read all the context, but its a big red flag that both Rigidbody2Ds you showed in that video have static body types. You should read about the different body types: https://docs.unity3d.com/Manual/class-Rigidbody2D.html
A Static Rigidbody 2D is designed to not move under simulation at all; if anything collides with it, a Static Rigidbody 2D behaves like an immovable object (as though it has infinite mass). It is also the least resource-intensive body type to use. A Static body only collides with Dynamic Rigidbody 2Ds. Having two Static Rigidbody 2Ds collide is not supported, since they are not designed to move.
Hi, I have a rigidbody (player) I push around a terrain. Problem is that most of the times the rigidbody will clip trough the terrain (shown in video). I have tried all the different Collosion detection on the rigidbody with no luck. Does the roughness of the terrain play any role in this? Also after the application has run for a while I see a huge increase in the physics processing in the profiler
how are you moving the body? If you're not moving it in a physics-friendly way, collisions will generally not be respected
Using rigidbody.MovePosition
hmm - do you need it to be a Rigidbody really? You might have better luck with a CharacterController
Is it going to be pushing other objects around?
I am using a rigidbody because i am mobning it around based on GPS coordinates, but guess I can still do that with CharacterController?
yeah CC works pretty much the same way as a RB with MovePosition
main difference is it won't push around other rigidbodies
Also the limitation of only being capsule shaped
i have been trying to figure out this for ages so don't make fun of me if it is something really simple -
my instantiated objects is normal when my player is still (and the place where the position parameter is referenced from is a child of the player) but when the player moves it acts really weirdly
Looks like they're children of some object which is not scaled uniformly
That will cause skew especially as they're offset from the parent
i just restarted unity and it now works...!?
Hi. There's a pushback when crouch and crawling sideways and backwards when the value is set to low. I had this issue before when my height was set to normal and all I had to do was adjust the gravity of the axis but that doesn't work for this.
I have a question for the Photon Quantum / TrueSync developer's
With TrueSync, your Rollback solution will only restore a world that has the corresponding body's already existing. If a Body was removed on frame x and a rollback was required on frame x + 1, the rollback would fail.
Is this because it would be to difficult to instantiate the game object for the physics body you are rollback?
Just curious 😛
Photon/Exit Games has their own discord and the devs are pretty active there. You probably won't get an answer here but will probably get one there
Thank you!
did you solve it?
Hi ihave a problem with this paper bin. i don't know how i can make the collider.
have you tried mesh collider?
Yes but it don't creates the hole
you have to uncheck the convex toggle
also that seems quite high high poly mesh so id definitely make a low poly version of that and use that for the mesh collider so it renders the high quality mesh but physics uses the low poly one
thanks i'll try it.
anyone?
I'm trying to make a windsock. I already modelled one, but now I want it to do something. I made a wind volume that adds fluctuating forces to rigisbodies within it. Now I would like to make a windsock to show the direction and strength of the wind in knots.
I tried using cloth, but it doesn't respond to forces unless I specifically set them (not a huge deal, just not ideal). On top of that I can't get the cloth to behave the way a windsock does. Also it collides with itself because of the shape.... Altogether it just seems like a difficult component to use for this.
Any tips? Tricks? Suggestions? How would you make a windsock that responds to forces?
I've also considered using an armiture and simply animating it manually, but that's really a last resort type of thing for me.
m_RigidBody.velocity = new Vector3(m_RigidBody.velocity.x / drag?, m_RigidBody.velocity.y, m_RigidBody.velocity.z / drag?);
What would be the appropriate way to calculate drag on this vector?
That's up to you
There are many ways to compute drag
some more realistic than others
basically I want to set m_RigidBody.drag = 5f; but only for x and z
@timid dove so if I could use the internal method for drag on those directions that would be ideal.
Right
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
YOu can adapt this to only apply on the axes you want
m_RigidBody.velocity = new Vector3(m_RigidBody.velocity.x * (1f - Time.deltaTime * 5f), m_RigidBody.velocity.y, m_RigidBody.velocity.z * (1f - Time.deltaTime * 5f));
This appears to work! (for now)
@timid dove thanks for the help!
I've just tried using multiple sphere colliders inside of the sock but that also doesn't work since the rotation causes the sock to slide off and move through the colliders making a mess.
On a sidenote, is this the right channel to ask this question?
hello
What is the right way to move a rigidbody in tandem with a moving platform ? i could go just use the parenting method but is there any other way to do this ? preferably something that follow the physic of real world ?
i been looking into using dynamic friction but i don't know how to use it
@hallow egretWhat's wrong with parenting though? How does it not follow physics?
generally parenting is the way to get stuff to move with platforms
I've never done moving platforms with rigidbodies though so maybe I'm missing something
I got some weird issues when parenting, like scaling issues and weird jitter. But honestly im fine with just parenting, i could find a workaround it. I'm just looking if there's a better way of doing this
@hallow egretMaybe experiment with physics materials
or turn your guy into a character controller instead of a rigidbody when he's on a moving platform
I think if your moving platform isn't a rigidbody, you shouldn't really have many issues parenting a rigidbody player to it
im using a kinematic rb for the platform so the player could still collide with it. Is this wrong ?
rb can collide with any collider
by default
kinematic means it doesnt talk to the physics engine (for the most part)
people use kinematic to return collision events
So basically I have issues with player. It is not correctly colliding with other obstacles. What might be the problem?
both player and obstacle needs colliders
Yes, both of them have colliders. But when I move a player to the obstacle, there is always a ~0.015 gap between them. Their colliders are squares with side length of 1
Is that really an issue?
You can probably play around with the collision detection settings on your rigidbodies
@prime trail You can also try playing around with this. Depenetration velocity sounds interesting
other than that, physx is pretty much a blackbox
mind screenshotting the gap between colliders?
This is zoomed game. The white thing is a player, the brown thing is an obstacle. There is a gap between them. Also, player's position is -2.481784, 0.4850001 while I think it should be -2.5, 0.5
You'll need to show the actual colliders too
The colliders are perfectly aligned in the scene editor, the thing happens only when I launch the game.
no clue
that's using 2d physics ig?
physics are not very accurate anyways and it's very common to have little gaps here and there.
hey all
I need some help
Beginner to unity here
I've trying to make a project
It's a snowboarding type game
Thing is, my main/board object is not falling correctly
It's like it will reach a certain height then fall straight
Any pointers on this ?
well we need your code, tho probably a time.deltatime wasn't applied
I don't think code will help here much
Because I've not written any code when Object is not in touch with ground
I think it has to with --rigidBody on Surface effector
but whatever you need,
We can probably join a VC , there I can everything required
Check the air drag on the object
A higher value will result in a trajectory like you have shown
thanks man you're epic
I tried some tweaks here and there with drag
And it worked !!

Does anybody know how to make the FPS controller a cylinder, not a capsule?
Sadly cylinder collider doesn't exist in PhysX. you could probably try convex mesh collider with cylinder mesh on it.
if you want to make "perfect" cylinder shape with decent performance, you probably have to do contact modification. I'm not familiar with contact modification tho, maybe someone other can help with it if you want to give it a try
oh
hey, I think this is the place to ask - I just updated from unity 2019 to 2020 (LTS), and walls aren't working for me anymore. They just slowly push me out
(there's an invisible cube with a box collider over the particles)
previously collision worked perfectly, except for an occasional bug where an object slipped through, but yeah now it's like the walls are made of jello or something
ok, I've figured out a jank fix, which is setting velocity instead of using MovePosition
is DOTS physics really stateless
Hence I can serialize and deserialize just with bodies positions velocities masses etc?
So I made a ramp in blender.. converted it to a mesh.. exported as FBX I think it is.. and added a rigid body to a sphere.. but the sphere is falling through the imported mesh and landing on the plane(which was created in unity) below it
Ah nice found it. It was lacking the mesh collider
yo guys is there an alternative for rb.gravityScale for RigidBody 3D?
Guys is it possible to collide kinematic rigidbodies with other colliders like a normal physics with non kinamatics ?
I wrote a rewind system for time but when some other walls in map generated by code and also they are not rewindable so when i was rewinding the last (position,rotation,vel,angularVel) of rigidbody that doesnt collide with anything i cant figure out how can i do that with rigidbody ?
should i use extra physic scene or something like that ?
You can only completely enable or disable gravity for a particular body. If you want something in between you have to implement it yourself
void FixedUpdate () {
rb.AddForce(customGravity, ForceMode.Acceleration);
}```
Is there some kind of article or table on that stuff?
I wonder what it means for velocities of objects then
Think about it.
x-y gives you z such that
y + z = x
if you substract one velocity from another
It's the acceleration(change in velocity) needed to get from one velocity to the other
delta velocity
I see
any tip how to google all that stuff?
I remember I learnt it like 5 years ago xD
I really need to refresh my head
Subtraction always gives you the change you need to get back to the first from the second
No matter what the quantity represents
it's not just substraction I interested in
multiplication, division (if that's a thing)
adding
There's at least 4 different ways to "multiply" with vectors and none of them are directly analogous to normal linear multiplication
not interested in actual math, but usage of it instead
Addition and subtraction are pretty straightforward
Look up dot product, cross product
what about angular velocity of some object? Let's say cylinder.
What is the beginning point of that velocity vector?
I'm guessing it defines how object will change it's rotation only
Yes it's the rate of rotation on each axis in degrees per second
Yes
Evening guys,
I'm Working on an ALT+F4 type of game (platformer with traps) and I cannot find how to manage physics.
I got a really big rotating hammer above a platform, the idea would be to eject the player (rigid body with collider, mass 1, no drag, collision set to continuous) at the speed of the tip of the hammer (a box collider with kinematic rigidbody, collision set to continuous dynamic)...
But somehow the player is not yeeted properly, but squeeze is way through the hammer and is barely pushed...
The hammer is not even very fast: 1 second to fully rotate.
What do I miss.
This is the setup.
human fall flat???
But way shittier.
Alright understood, thanks for ur suggestion!
Hey im new here and to unity, im trying to add some interactions and Id love some help cause google doesnt have the guide ;-;
There's no such thing as the guide. Specify what you're trying to do.
If you wonder why ⬇️
Hello, I have 2 meshes, each with a mesh collider (Convex turned off), next to each other.
They match perfectly (see screenshot). There is no gap/overlap.
When I roll a sphere over the "seam"/the cut where the meshes meet the ball jumps into the air as if it would roll over a bump. Does anyone know why?
How is center of mass defined in object?
Is it simply offsetting point from pivot?
It's calculated from all the colliders on the Rigidbody. It's assumed the object is of uniform density. You can forgo the calculated COM and set your own on the Rigidbody however you wish if desired
I actually trying to understand difference between angular damping and inertia tensor
it seems pretty similiar to me
So you know how objects with larger mass require stronger forces to get them going and have more inertia once they're moving?
Inertia tensor is the same thing but for rotation instead of linear motion.
And it is a Vector3 because an object can have "rotational inertia" that is different per axis
For example a sphere has the same inertia on all axes, but a long rod will spin much easier if used as an axle vs if it's tumbling lengthwise
Im not sure if im able to explain why that happens but thats very usual on collider edges. Im not sure if theres any ways to prevent that. Decreasing physics timestep could help bit but thats not going to be perfectly smooth either.
You could also try different collision detection modes but iirc thats not helping either
I just learned today that slowing Time.timeScale causes also slows Time.fixedTimeStep. Is there a clean work around for this? (Edit: mistyped fixedTimeStep as fixedDeltaTime)
I want to create a slowdown effect, but because the Physics updates less times per second than the frame rate does it makes the game look like it's lagging. I'm just wondering if there's a easy way to avoid this
Turn on interpolation for your rigidbodies
man, 3D physics are extremely fun
so:
this is supposed to be float3 impulse
dashpot.strength * (posB - posA) + dashpot.damping * (lvB - lvA)
I get the part in posB and posA substraction, but what exactly is happeneing in lvB and lvA substraction?
lv - linear velocity
and why is it added to delta position?
I'm tired but looks like it's your acceleration
accel is a delta in velocity
velocity is a delta of position
- some damping for friction probably
and .strenght is the force of your impulse then
this snippet of code suffers some clarity. Could use some intermediate variable names to be understood at a glance
@tender flower that tutorialset had numerous logic flaws, no idea if you get anything functional by following it
Basic raycast suspension in the nutshell: trace rays from preset suspension points in you main rigidbody and trace them downwards from the main rigidbody transform. Then use spring-damper physics equation to compute the forces for each wheel: https://gafferongames.com/post/spring_physics/
There is way more to making proper vehicle suspension but that should get you going
that snippet is official Unity Physics sample xD
But I get the idea now, thanks
Haha I guess they were going too fast and didnt clean up the code 🙂
anything related to physics in their samples is really hard to read
Yeah I agree, so much boilerplate to dig through, you don't remember what you were looking for in the first place
My player has a CapsuleCollider and it walks over BoxColliders. However, OnCollisionEnter, the ContactPoint normal is not Vector.up. Instead, it prints vectors such as (-0.8, 0.6, 0)
this feature / bugfix in Unity
2021.2.8 may be of interest to someone
Physics: Added a new contact modification event to differentiate CCD and discrete callbacks. (1372526)
https://unity3d.com/unity/whats-new/2021.2.8
I have this trouble where if I set the player's position to zero, the line renderer aligns exactly with the mouse cursor, but when I move the player's position like at the top of the screen it creates a weird distance between them like the image I attached (the mouse is the circle below the line). Any idea what's causing it?
Never mind, I figured it out.
anyone knows if meshCollider convex-hull meshes need normals ?
I got a convex hull generator that is not generating normals but it seems to be working fine so far... wonder if that's a problem
"Optimization tip: If a Mesh Collider only uses a Mesh, you can disable Normals in Import Settings, because the physics system doesn’t need them."
In fact the only thing the convex hull needs is the vertices
I need some help. Does anyone know what is causing this?
Trying to mess with some stuff. I thought I could roll a ball down a ramp easier than this.. but no matter how far it drops from it stops here..
what values did you put for friction and bounce?
I ended up using .2 for both and 0 bounce but the friction combine really help me get alot more roll
High friction + low drag/angular drag would probably make the ball keep its velocity better
Hello, does anyone have experience working with DOTS and havok. My balls seem to be ignoring collision with the walls and just pass through 😦
Hmmm I don't see anything wrong in the code after a very quick glance, but something I wouldn't do like you is having multiple collider types on the same gameobject (trigger AND collider)
Drag is 0 and Angular drag is 0.05 I can try raising the friction a bit, but I think it slowed more when friction was higher than these values.
if the ball rotates, friction shouldn't slower the ball.
it would just make it feel more natural because it makes it roll faster
the ball does not make it down the path with 0.3 friction but at .2 it will make it
Static friction is what it takes to move it from a stopped state? and Dynamic is from the state when it's already moving right?
yes
then you probably have to decrease angular drag
if the ball doesn't move relative to the path (only rolls), friction shouldn't really matter
it rolls but when friction is at .3 the sphere gets stuck
weird
🤷♂️ still trying to figure it out.. I wish I knew what made it weird or not.. lol
have you tried decreasing angular drag? because it's sphere, angular drag should actually be 0 and drag should have some small value. (there should also be rolling resistance which PhysX doesn't simulate automatically)
Looking at it now.
angular drag is at 0
Does seems to react to slopes better with angular drag at 0 and drag at .1
has anyone tried setting the rigidbody.inertiaTensor manually in script in 2022?
editing it is apparently freezing the rotation of rigidbodies
correction: editing the inertiaTensor while rotational constraints are active means that when you deactivate the constraints it will still be frozen rotationally.
actually im not sure anymore
it seems like if you set the inertia tensor on the same tick that it is constrained on, then it will bork
Yeah that was the problem. I was using a collider for grounded detection instead of the default mesh collider
Ty though for responding!
I wouldn't be surprised if setting inertia tensor kills the current angularVelocity
Hey! I kinda need help with some very basic physics problems applied to unity, could someone help me?
There are 3 scenes I have to make. The first one is a spherical projectile that is launched by a force (set in design time), the second one is a sphere that has to go through 4 checkpoints and accelerate and decelerate when getting away/ near a checkpoint, at the end it should return to its starting pos. The last one is some kind of 2D game.
I would like to create Realistic physics like the first video.
What I managed to achieve so far is in the second video
How can I improve the whole?
Hi! Im trying to create procedural meshes that require complex mesh colliders. Unfortunately, each time I change something in the mesh and reassign it to a mesh collider, it appears to trigger a very lengthy baking process that recalculates everything having to do with the mesh
Is there any way to bake smaller meshes independently, combine them, and assign them to a mesh collider?
My goal is to limit the number of gameobjects while avoiding very lengthy bake processes triggered by small modifications to large meshes. If anyone has any idea of how to do this please reply.
how many gameobjects are we talking about here?
I would like to keep the count under 512, but my current method that produces an acceptable physics bake time requires tens of thousands. Gameobjects are too heavy for that unfortunately.
Generating a ton of procedural stuff. Thats why I wonder if I can bake small physics meshes independently and combine them as needed to minimize gameobjects
@waxen phoenix I don't quite understand what you mean by 'bake' small physics meshes...
if your objects are dynamic then I don't think you can do that, because unity requires dynamic objects to have convex shapes
and joining a bunch of meshes together would break that requirement and also the physics of your game
So the resulting gameobjects will never move. They need to be concave though. Im just trying to generate the same collision mesh that is generated when you assign a mesh to a meshcollider
I know you can do this with a call to physics.bake
However, I need to make this process take less time. Which is why I'm wondering if you can combine these baked meshes before assigning them to a mesh collider
yes you can do that
take a look at unity's Job system
it's a really fast way of handling fat and long amounts of data
I use it for meshes all over my game
I recently ported Oskar's quickHull implementation to Job + Burst and it's like 100x faster no jk
Does that system support concave meshes? I mean would you mind sharing some snippets of pointers on how to do this?
I think you can but there are websites for snippets, give me a second
I mean try https://wtools.io/paste-code but really any sharing website will do
it's not going to compile as I haven't tested it
but that's around what you would want to do
also, you actually need to install the proper packages (Job system + Burst + Collections)
Thanks, I'll take a look. Pointers are enough I'll clean it and get it running.
If it works for what I intended I'll let you know.
ok
So, it doesn't work. If I combine the meshes and assign them to a mesh collider, the physics mesh gets rebuilt @north linden
It was worth a shot though
Problem is I don't have Unity's source code to see what it is doing and how I can get around it
There doesn't seem to be any way of doing what I want in Unity, only Unity dots but at that point you might as well be on a different game engine
im 99% sure it's a legitimate bug; when the inertiaTensor is set with rotational constraints active, and then constraints are turned off, rotation is still locked
submit it
yea i ended up submitting a report
it's one of those ultra-niche issues, but it might be useful to understand what is causing it
my guess is that there is some internal inertia caches that are scaled to infinity when constraints are used, and since i am setting the inertiaTensor once by script, the usual logic that handles inertiaTensor resets don't trigger like they normally would
I'm having a problem with TimeScale again 😅 It has to do with TimeScale changing Fixed Timestep. When I pause my game I set TimeScale to 0, my vr hand tracking breaks because its updated in FixedUpdate which gets called 0 times while time scale is 0. Is there anyway to change timescale without effecting how often FixedUpdates get called?
a different solution would be to update your trackers outside of fixed update
is there a way to find that red dot with vector properties?
no
What information are you starting with
I have v, k and w
they are vectors
starting from the origin
and I know the red dot is on the perpendicular line projected from the top of v
me neither haha
I just bring all I thought could help
I know there's a solution using trigonometry, but I want to do it without it
idk about using vector properties
but certainly with some trigonometry
you have a triangle with all three angles known, and you have the length of one of the sides
I think you can probably find the length of the other two sides from there
especially since it's a right triangle
soh-cah-toa applies
gimme a sec...
yes I have the v length
yeah, and you have thje angle between V and K which is just Vector3.Angle(v, k)
float vLength = v.magnitude;
float angle = Vector3.Angle(k, v);
// cosine of angle = adjacent/hypotenuse. vLength is adjecent
float cosOfAngle = Mathf.Cos(angle * Mathf.deg2Rad);
// hypo = adj/cosangle
float hypotenuseLength = vLength / cosOfAngle;
Vector3 result = k.normalized * hypotenuseLength;```
I think this is what you need?
if my trig is correct @karmic thorn
Thought about it and came up with this based on cosecant of angle A in a unit circle is 1 / sin(A), looks equivalent to praetor's on first glance. (was bored during breakfast, 😉 )
float CosecantProjection(Vector3 v, Vector3 k) => (1f / Mathf.Sin(Vector3.Angle(v, k) * Mathf.Deg2Rad)) * v.magnitude;
Vector3 CosecantPoint(Vector3 v, Vector3 k) => (1f / Mathf.Sin(Vector3.Angle(v, k) * Mathf.Deg2Rad)) * v.normalized;
bool IsGrounded()
{
// genericCollider is a Collider base class component
Vector3 boxSize = new Vector3(genericCollider.bounds.size.x, genericCollider.bounds.size.y, genericCollider.bounds.size.z);
float maxDistance = genericCollider.bounds.size.y / 2 + .01f;
bool isGrounded = Physics.BoxCast(transform.position, boxSize, Vector3.down, out RaycastHit hit, transform.rotation, maxDistance, groundMask);
// DEBUG
Vector3 drawBox = new Vector3(boxSize.x, maxDistance*2, boxSize.z) / 2;
ExtDebug.DrawBox(transform.position, drawBox, Quaternion.identity, Color.green);
return isGrounded;
}```
First time using BoxCast. I'm having trouble understanding why it doesn't return true, when the box is intersecting the ground collider
(NOTE: it returns true if the player is less on the edge of the ground collider, but not if it's almost falling, like in the picture)
Is this supposed to be using 3D physics? Is the ground a 3d collider?
Yes, core mechanic needs the game to be in 3D.
maybe your debug drawing is incorrect?
maybe the BoxCast maxDistance is incorrect vs the drawBox, but still, traveling too much would still return a groundMask hit, no?
you are also not debug-drawing the orientation of the boxcast
bool IsGrounded()
{
// CAPSULE COLLIDER
Collider collider = genericCollider;
Vector3 halfExtents = new Vector3(collider.bounds.extents.x, collider.bounds.extents.y, collider.bounds.extents.z);
float maxDistance = .1f;
// groundMask is layer number 7. groundMask = 1 << 7
bool isGrounded = Physics.BoxCast(transform.position, halfExtents, -transform.up, out RaycastHit hit, transform.rotation, maxDistance, groundMask);
return isGrounded;
}
private void OnDrawGizmos()
{
Gizmos.color = Color.blue;
Gizmos.DrawWireCube(transform.position + (-transform.up * .1f), genericCollider.bounds.size);
}
I think this is right. I'm getting isGrounded = false 100% of the time. It never returns true.
sorry, i don't have any additional ideas but to check that you haven't missed any of the obvious things (enabled, values correct, assumptions all true). but i suppose you have done that multiple times already.
I removed layermask and changed the distance to 2f (capsule halfExtent height is around 1f). Now it does return true, but only when I jump (mid jump). If I'm on the platform it's always false. This function is on FixedUpdate running without being in IFs statements. I don't really understand how BoxCast works
one more: is the box you are casting actually aligned the same way as the capsule you are deriving it from... you are adding the transform.rotation but that isn't necessarily the capsule's orientation (might be 90° off)
Capsule Collider is on the same obj as the script that casts the Boxcast. Sometimes the obj's rotation can vary, but transform.up is always (0, 1, 0)
so passing a Quaternion.identity into the boxcast doesn't change anything?
bool isGrounded = Physics.BoxCast(transform.position, halfExtents, -transform.up, out RaycastHit hit, Quaternion.identity); this returns a hit only when jumping, altho the Boxcast is running on fixed update.
Raycasts will not detect Colliders for which the Raycast origin is inside the Collider.
i'm guessing your boxcast origin needs a small offset which the jump provides
Ah I think this was the issue. The BoxCast was spawning already penetrating the ground colliders.
can someone tell me why the leg goes through the skirt, even though I set colliders for the legs in the dynamic bones?
Hey all! What arcade style physics libs do you recommend? There’s of course wheel colliders vs a sphere and libs Edys Vehicle Physics. I’m going for a feel similar to Smashy Road Wanted.
hey everyone, I have a small problem. I have an Box Collider trigger above my Teleportation Area, the problem is if I want to teleport into it the teleport control thinks its an object and wants to teleport me on top of it. How do I keep the box as a trigger but ignore it when teleporting? E: Got it! Change Trace Layer Mask on Teleport Function and exclue Box Collider Trigger
any reason why tilemapcollider2d doesnt work but boxcollider2d does work on seperate tiles?
driving me nuts
how can i use a set jump height with an impulse rigidbody addforce?
wdym by "it doesn't work"?
My character just walks trough it. I fixed it now tho. No clue how
hi
I need the blue vector to displace like the magenta but reaching the yellow
intersection
they are the reflection of the black long vector
the magenta is being displaced like
magenta = blue + longBlack.dotProduct(shortBlack)
so the real question I think is how long is that green segment
So I have this box cast to check if iam grounded but sometimes it bugges and keep me ungrounded and grounded very simple box cast at 1,1.1,1 size on hit iam grounded else not so idk what the prob
How would I go about adding a limit to much speed you can add via continuous AddForce?
Most solutions I find just ClampMagnitude rigidbody.velocity but that's not what I want, since that always sets a max speed you cant pass, even if you were to say, go on a jump pad or fall really fast
I need to figure out a way to clamp the amount of force you add from moving so it wont go above max speed
Any ideas?
It's a bit more complex but what I do is project my continuous force into the current velocity vector and check if it will put me above the speed limit, and if so I remove the component of the force vector that is in line with the current velocity before applying it
It requires you to be quite comfortable with vector arithmetic and projection etc
I just wanted to make a roll-a-ball 
By project do you mean Dot?
No I mean vector projection
Hello, how do I calculate angular drag?
eg, If I have a ball of 3kg weight rolling on a flat surface how can I
calculate the float number of angularDrag of my game object
um... perfect ball doesn't have angular drag. you're most likely looking for rolling resistance. using angular drag may not be the correct way to simulate rolling resistance (i'm not aware of the correct rolling resistance formula tho)
Not sure if this would belong here or not... if someone was doing a game with body sliders (make the arms bigger/smaller, add muscle/remove, increase/decrease chub all around) kind of stuff how exactly is that handled? Especially if you want to keep it consistent and prevent clipping from like, armor, grapples, etc?
how to get shortest distance between point X (cube on picture) to some Axis (vector on picture) in space?
So it's shortest distance not between 2 points, but 1 point and axis.
Hello!
I have the following problem.
I have a game object with a box collider and an animator component.
This game object is basically a door.
When I push a button, it goes down when it opens or back up when it closes.
Problem is:
If I put a box with a rigid body component on top of the door when it's opened and then push the button in order to close the door, it goes right through the box.
Why does your door need a rigidbody?
The box I put on top of the door has a rigid body component.
The door itself only has a box collider and the animator component.
Why do you mean by "on top" of the door?
When I open the door, it lowers itself and I can place the box on top of it.
So you want the box to prevent the door from closing again?
No. When the door closes, it raises back up. If a box is on top of the door when it raises, it should push the box aswell.
Instead, it just goes through the box.
Here is a video if you want to see what I'm talking about.
@wide nebula?
@oak depot You should use mp4 format so video would embed.
It's less likely someone would see it if they need to download it
As above, but I downloaded it anyway lol.
The thing is, you need to be moving your door with physics if you want it to physically interact with objects.
True. I haven't uploaded a video on Discord for so long that I forgot I should use the .mp4 format.
So if I move an object by animating it, collisions will still be ignored.
Noted! 🙂
Thank you!
Right, because animations move by transforming the position (ie, teleporting it each frame).
So you kind of have to decide what to do here. If causing a block to jump out when it's hit by a door is not really important (in that, you were basically just trying to handle an edge case), you could also handle it by not allowing the door to be closed if it detects an object on it. Otherwise, you'll need to add physics to your door.
this may not be the fastest but this is what came to my mind. if you have any point A on that axis, you could use vector projection like this: Vector3.Distance(A-X, Vector3.Project(A-X, Axis)). I have no idea if this even works but I hope so.
Actually I figured you just need to calculate delta vector on 2D xD
multiplier of that vector would be distance
I didn't check tho
hi, I have a very big problem, I want to make a 2D ragdoll, and I had following this tutorial https://www.youtube.com/watch?v=bCkvh0lZFVk... but my character just explodes
Check out my Udemy course!! Link below (all 12.99 USD):
(Create a Rail Shooter Game with Unity - Newest)
http://www.milkishgames.com/udemy/rail-shooter.php
(Create a 90's Point & Click Adventure Game)
http://www.milkishgames.com/udemy/point-click.php
(Create a Shoot-Em-Up Game)
http://www.milkishgames.com/udemy/shmup.php
And Skillshare course f...
🥲
i'm using the unity 2020.3.23f1 version
maybe will help
nah, it's different question
my question was actually super simple
I think you would get a point on the axis that's on the same height as the point X and just get the distance
Yep
By continuous force, do you mean rb.velocity + force2add?
or just force2add
I am so close to figuring out the math D:
@timid dove I did this and I'm not sure if I did it right to cap the speed you can add
It does cap the speed when going in one direction, but making sharp turns is now very sluggish and makes a U-turn, and doing so also lets you break past the speed limit
I think I accidentally recreated Source-engine air-strafing
Nevermind I fixed it!
Now there'll be no weird turning nonsense but speed is properly clamped without directly touching rigidbody velocity!
One question though, if we break past the speed limit, will inputting movement in the direction break your force?
Might test that myself
@wide nebula, thanks for explaining to me how the animations actually work. I added a rigid body component to the door and made a script to control its movement. This is how it looks now.
Oh nice, that's pretty cool
I'm currently working on this motorcycle game and I'm not sure if I'm coding my road right. Currently I have a prefab that I'm just scrolling the length of plane while the motorcycle is at the center. Is this the correct way to make an endless road? Or should I have a long plane that extends the scene and have a material be animated on the background for all the lines in the road? Right now when I put cars on there sometimes they fly off and I'm thinking the reason might be because I'm moving all these road objects under them and they're getting caught in the cracks and getting projected into the sky
currently working on a 2d platformer and i have an issue where, whenever the player lands on the ground, the sprite very briefly goes through the floor, which looks really weird
dont know it anyone else has had this issue, please help!
im just using gravity to simulate jumping and falling
does it happen when the script is not running?
im running the scene
so it should be??
its when i jump and fall down, it briefly glitches through
put the player 5 meters above the ground and deactivate the player script or scripts
just wanna make sure that is a script
or not
i dont think it is clipping anymore?
its a bit laggy to tell but it doesnt seem to
if its not scripts, what should i do
so its the script affecting it?
or is the physics of the object/ground?
or could check your pc
it might be
if it is, what can i do
i dont think theres anything that could affect it
Hello! I'm want to display the velocity magnitude of a rigid body inside the console when I apply a force to it but it returns 0.
I looked on forums but haven't found anything to help me figure out why this happens.
Anybody got an idea why this issue occurs?
is there away to reduce the cost of rigid2d physics? i don't want my zombies on top of each other but with it on i can only have about 300 with it off i got upto 1000 before it started to get below 60fps
hey guys
so i did this
and i want the coins to fall on the grass
so i did this for the coins:
right
i did the grass like the tilemaps kinda thing
and did this to the tile maps:
but it ain't working
whats the problem
why
coins fell to the void of vikings
like
why
PLEASE HELP
Does the coins also have colliders?
They should
ok
Unity handles collisions only between colliders (and rigidbodies, static objects doesnt need rb tho)
If object doesnt have collider, it cant collide with anything and other objects cant collide with it
NO ONE helping
Does anyone have an idea why I get randomly stuck sometimes? I know when it happens which is right before I cross over from 1 box collider to another, but I am using a grid to place the blocks so it is 100% the same size and everything. I am trying to keep my boxcollider over a capsule collider if possible but if that is the only way to fix it then I will go for it. or just make it float above the ground but I wanted to avoid it because placement became semi inconsistent
This is just how physics behave in Unity. Perfectly aligned colliders still stop or apply weird forces when you cross over. If you roll a sphere collider over two boxes that are perfectly aligned and static, the sphere will usually make a small jump as a result
"rounded" colliders dont usually stop though, they just excibit that small jump, usually not even noticable (unless you go fast, then you make insane jumps for unknown reasons)
ah okay, in that case I will just make him float above the ground again
let me ask another question then because I had it before, when shooting a raycast from above the ground towards the ground I am trying to use Rayhit.Point to get the exact height that the block is at to jump on it, so I can reset the height and keep the robot at that level. Now I do not always get the same height. Do you have any idea why that is then? https://cdn.discordapp.com/attachments/497874004401586176/933993127587512361/unknown.png
RaycastHit2D[] colliders = Physics2D.BoxCastAll(m_GroundCheck.position, m_GroundCheckBoxBounds, 0, -Vector2.up, m_GroundCheckBoxBounds.y, m_WhatIsGround);
for (int i = 0; i < colliders.Length; i++)
{
if (colliders[i].collider.gameObject != gameObject && m_Rigidbody2D.velocity.y <= 0)
{
m_Grounded = true;
m_HasGrappled = false;
m_CoyoteTimer = m_CoyoteTime;
m_JumpDustParticleSystem.position = new Vector3(gameObject.transform.position.x, colliders[i].point.y, m_JumpDustParticleSystem.position.z);
if (!wasGrounded)
{
m_OnLandEvent.Invoke();
m_Rigidbody2D.gravityScale = 0;
m_Rigidbody2D.velocity = new Vector2(m_Rigidbody2D.velocity.x, 0);
RaycastHit2D rayHit = Physics2D.Raycast(new Vector2(colliders[i].point.x, m_GroundCheck.transform.position.y), -Vector2.up, float.MaxValue, m_WhatIsGround);
print(rayHit.point.y);
transform.position = new Vector3(transform.position.x, rayHit.point.y + (m_BaseCollider.size.y / 2) + m_GroundCheckBoxBounds.y, transform.position.z);
m_Rigidbody2D.velocity = new Vector2(m_Rigidbody2D.velocity.x, 0);
}```
(also I know it is a bit double to do a raycast from the x position of a boxcast but it gave me an a lot better positioning with less variation so until I have figured out a better way, that is it)
or does this not count as a physics problem? 🤔
hello, heres a video on my problem with sprite clipping
and idk how to fix it
im using unitys gravity for movement
the car drifts too much can anyone help me
Maybe this is the right place to post this, i have the movement created for my character (although its extremely clunky and bad) and sometimes the sprite for the player just falls on its sides, on really bad ocasions it can even just do a full 180 flip (ignore the typical assets from kenney, just wanted something to look at while prototyping that wasnt a white square)
How do I stop this? Is it code related or just physics settings?
You probably have to freeze rotation from your player’s rigidbody
oooh ofc, wow im dumb lol
thanks
np!