Unity Player passsing through objects - unity3d

player and object both have colliders and rigidbodies, object has position and rotation locked, player has only rotation locked. When the player goes to the blocks, the player goes through the blocks, although they do give a bit of resistance. To move the player im setting the rigidbody's velocity, and doing that in FixedUpdate.
i have no idea why this is happening, any ideas?
main part of the code is:
rigidBody.velocity = new Vector3(direction.x, rigidBody.velocity.y + (-Gravity * Time.deltaTime), direction.z);
(direction is determined by the WASD keys, and i'm using my own gravity)

First of all, you do not need to multiply the velocity by time.DeltaTime, because you are moving your object in the FixedUpdate() method; Which uses fixed time intervals since the physics engine does not run in sync with the regular game engine. Also, both objects do not need rigidbodies in order to collide with one another. I suggest looking at your collision matrix in settings and verifying that everything you need collision for is checked correctly. As others have said as well, check your kinematics on the rigidbody.
A last suggestion for working with your own gravity. Do not change the actual gravity value of the game engine. It is typically recommended that you use a multiplier variable and apply it to the constant gravity already set by the physics engine. If you are completely editing the gravity, than maybe consider using a character controller instead.

I guess it has something to do with what the documentation says "In most cases you should not modify the velocity directly, as this can result in unrealistic behaviour".
Try to use AddForce() or similar functions to alter the properties of the rigid body. Colliders etc will then work as expected.

Related

How do I check for and resolve collisions within FixedUpdate using a kinematic rigidbody?

I have been working on my own kinematic character controller for a while, but only recently learned that one should consider updating its position and rotation using Rigidbody.MovePosition and Rigidbody.MoveRotation instead of directly modifying the Transform component, which is what I am doing now. While my controller works fine, and does not cause any noticeable performance impact in my small games, I want to better understand the benefits of manipulating the Rigidbody component, and especially how this all works within FixedUpdate instead of Update.
To be clear about the supposed impacts on performance, Unity's manual on 2D rigidbodies says:
Any Collider 2D component added to the same GameObject or child GameObject is implicitly attached to that Rigidbody 2D. When a Collider 2D is attached to the Rigidbody 2D, it moves with it. A Collider 2D should never be moved directly using the Transform or any collider offset; the Rigidbody 2D should be moved instead. This offers the best performance and ensures correct collision detection.
Right now, my basic controller loop looks like this in the Update method:
Read the user's input velocity
Modify the controller's velocity based on this input (this velocity is distinct from Rigidbody.velocity)
Using Physics queries, sweep the controller's body against the appropriate collision layers by velocity * Time.deltaTime
Pick a collision resolution position based on a set of rules
Set the controller's Transform.position to this resolution position
I also have a method that moves the controller using Transform.Translate if no collision detection is needed.
As you can see, though my controller GameObject has a kinematic rigidbody attached to it, I never actually use it for anything. Unity's documentation on kinematic rigidbodies is conflicting, stating here:
Note: MovePosition is intended for use with kinematic rigidbodies.
but also here:
If isKinematic is enabled...The rigidbody will be under full control of animation or script control by changing transform.position
I am also unsure about how to manually check for collisions within FixedUpdate, as I have read that FixedUpdate can be called more than once per frame. Frankly, I thought FixedUpdate was only supposed to be used with dynamic rigidbodies to simulate real physics, and thus have only used this method for simple manipulation of those kinds of rigidbodies.
And then Rigidbody.MovePosition states that
2D rigidbodies have a fixed limit on how fast they can move therefore attempting to move large distances over short time-scales can result in the rigidbody not reaching the specified position during the next physics update. It is recommended that you use this for relatively small distance movements only.
What if my character needs to move a very large amount? Do I just set Rigidbody.position directly?
I guess I am trying to figure out how I can reconcile all of this logic to conform to what Unity says is best for performance. Perhaps I need to combine Update and FixedUpdate, but ultimately I am just hoping to receive some clarification and guidance regarding all of this.

How move object with collision (without physics) Unity

I have 3d cube which have 3d box collider.
I want to write jump system for cube with collision, but without physics (without gravity, without rotation, etc) (Like 3d platformer)
You can take advantage of the Physics.OverlapBox API to check for collisions before committing to move your object.
Your code will look something like this:
Vector3 nextPosition = transform.position;
/*
You do your normal movement code, but apply
it to nextPosition instead of transform.position
*/
Collider[] hitColliders = Physics.OverlapBox(nextPosition, transform.localScale/2);
if(hitColliders.Length == 0){
transform.position = nextPosition;
}
Note that the object itself shouldn't have a collider, otherwise it will detect itself. You also shouldn't move in big steps as this method doesn't take colliders on the path into account.
There is a great way of doing this. You will still need physics.
The Steps
Have a rigidbody on your player.
There should be a dropdown menu called spmethiing like "constraints". Find it.
Then Set all rotation constraints in this menu to true.
However, I don't understand why you wouldn't want gravity. Don't all platformers have gravity? (There must be some force to pull your player down when they jump). Anyways, if you don't want gravity, then you must uncheck Use Gravity variable.
**Notes: **
To control your player, you must use AddForce(). If you have any questions about adding force, let me know in the comments.
:) Thanks.

Best way to move a game object in Unity 3D

I'm going through a few different Unity tutorials and the way a game object is moved around in each is a little different.
What are the pros/cons to each of these methods and which is preferred for a first person RPG?
// Here I use MovePosition function on the rigid body of this component
Rigidbody.MovePosition(m_Rigidbody.position + movement);
//Here I apply force to the rigid body and am able to choose force mode
Rigidbody.AddForce(15 * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
// Here I directly change a transforms position value, in this case the cam
Transform.transform.position = playerTransform.position + cameraOffset;
Thanks!!
EDIT;
Something I have noticed is that the applied force seems to memic wheeled vehicles while the position changes memic walking/running.
RigidBodies and Velocities/Physics
The only time, I personally have used the rigidbodys system was when implementing my own boids (flocking behaviour) as you need to calculate a few separate vectors and apply them all to the unit.
Rigidbody.MovePosition(m_Rigidbody.position + movement);
This calculates a movement vector towards a target for you using the physics system, so the object's velocity and movement can still be affected by drag, angular drag and so on.
This particular function is a wrapper around Rigidbody.AddForce I believe.
Pros :
Good if realistic physical reactions is something you are going for
Cons:
A bit unwieldy to use if all you are trying to achieve is moving a object from point A to point B.
Sometimes an errant setting set too high somewhere (for example: Mass > 10000000) can cause really screwy bugs in behaviour that can be quite a pain to pin down and mitigate.
Notes: Rigidbodies when colliding with another Rigidbody would bounce from each other depending on physics settings.
They are also affected by gravity. Basically they try to mimic real life objects but it can be sometimes difficult to tame the objects and make them do exactly what you want.
And Rigidbody.AddForce is basically the same as above except you calculate the vector yourself.
So for example to get a vector towards a target you would do
Vector3 target = target.position - myPosition;
Rigidbody.AddForce(target * 15 * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
If you don't plan on having any major physics mechanics in your game, I would suggest moving by interpolating the objects position.
As it is far easier to get things to behave how you want, unless of course you are going for physical realism!
Interpolating the units position
Pros :
Perhaps a little strange to understand at first but far simpler to make objects move how you want
Cons:
If you wanted realistic reactions to objects impacting you'd have to do a lot of the work yourself. But sometimes this is preferable to using a physics system then trying, as I've said earlier to tame it.
You would use the technique in say a Pokemon game, you don't stop in Pokemon and wait for ash to stop skidding or hit a wall and bounce uncontrollably backwards.
This particular function is setting the objects position like teleporting but you can also use this to move the character smoothly to a position. I suggest looking up 'tweens' for smoothly interpolating between variables.
//change the characters x by + 1 every tick,
Transform.transform.position.x += 1f;
Rigidbody.MovePosition(m_Rigidbody.position + movement);
From the docs:
If Rigidbody interpolation is enabled on the Rigidbody, calling Rigidbody.MovePosition results in a smooth transition between the two positions in any intermediate frames rendered. This should be used if you want to continuously move a rigidbody in each FixedUpdate.
https://docs.unity3d.com/ScriptReference/Rigidbody.MovePosition.html
Rigidbody.AddForce(15 * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
This will make the object accelerate, so it won't travel at a constant velocity (this is because of Newton's second law, Force=mass*acceleration). Also if you have another force going in the opposite direction this force could get cancelled out and the object won't move at all.
Transform.transform.position = playerTransform.position + cameraOffset;
This will teleport the object. No smooth transition, no interaction with any forces already in the game, just an instant change in position.

Unity: Fish with rigid body leaving water

I am making a simulation of some fish in a lake.
I am using rigid body as otherwise they move through the sides. But when they hit into the sides they rotate and then the script I have to set their rotation to 0,0,0 when they leave fails.
Your problem may be occurred by the fact that you are using unity's physics to move the fish but trying to set rotation directly. In this case movement and rotation of the fish are driven by Physics and forces, applied to the object. But you still can affect rotation and position if you reset all forces. Try looking here to learn how to remove forces.
Also when dealing with Physics in Unity, don't mess Update() and FixedUpdate() methods, because it may lead to an incorrect result.
When you say "hit into the sides" do you mean the sides of the simulated lake?
If so, one option might be to set the objects that denote the sides as "kinematic." Then you can detect when a GameObject (such as a fish) collides with it but it won't cause any physics reaction.
(ref: RigidBody)

Unity 2D Bounce Back moving object when colliding with another object

I have an object that, after receiving its respective input, it moves this way:
mov = new Vector3((Input.GetAxis("Horizontal") * vel), 0, 0);
transform.position += mov;
But, I want it to bounce back, once it collides with an object.
I´ve made the procedures already (OnCollisionEnter2D(Collsion2D col){bla bla...}), but I need help with what happens on the collision (bouncing back the object)....
I´ve tried giving the collided object a bouncing material, but it just slows it a bit, my guess is that because of the constant force given by the acceleration.
Greetings.
If you move the object with transform.position what you are doing is basically a "teleport" so it will ignore the bouncing material. If you want it to bounce you have to write the physics code to detect a collision and change the movement or you can do addforce to move the object and it will detect collisions and react automatically.
you are teleporting the object at the current time. instead you should use the Rigidbody.addForce this will add a force in the specified direction thus if you do the opposite direction will "bounce" of the object. Another option would be to create a physics material then not bother with the code.
You are not using materials, right?
See if the content of this post may help you, the OP is using a formula using Raycast and the answer guides him to use the Raycast with Layers Maks:
2D bouncing formula doesn't work properly
There is this one also with fixed angles (like Pong), but it uses material (with values: friction: 0, bounciness: 1):
https://gamedev.stackexchange.com/questions/70294/get-gameobject-to-bounce-of-colliders
But if nothing makes sense and you are going crazy and might want to start from zero, there is this official video tutorial on bouncing and sliding in 2D:
https://unity3d.com/learn/tutorials/modules/beginner/2d/sliding-bouncing-2d