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

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

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.

Unity Player passsing through objects

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.

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.

Unity3d - check for collision on non moving objects

I have a sphere build from multiple objects. What I want to do is when I touch/click an object, that object should find all adjunctive objects. But because none off them are moving, no collision detection can be used.
I can't find a way to detect these adjunctive objects even when the colliders do collide with each other, as I can see that in the scene. I tried all the possibilities, but none off them are working, because no objects are moving.
Is there a way to check for manual collision detection, or is there some sort of way to let Unity3d do the collision detection automatically?
You could keep a list of all those objects, then when your event happens you can send messages to all them to do what you want them to do.
Lets assume you want your sphere to break into little pieces. You send a Force message to the sphere. Then you use Newton's Laws of motion and find out how much velocity each piece gets. Remember velocity is a vector thus it has direction.
This is how I would do it and still keep the right amount of control over what happens in my game/simulation. Remember F = ma.
you could use RaycastHit (http://docs.unity3d.com/Documentation/ScriptReference/RaycastHit.html) for your collision, this also works on non-moving objects but it needs more performance
You can add rigidbody to every objects; when you touch one of them, give a force onto it, then it is going to move and trigger event of the adjacent objects.
for the reason you do not want to move the object you touch, you can cancel movement in the OnCollider or OnTrigger event handler function.
I managed to work around this by checking the distance from the selected object and all other objects that are part of the sphere. If the distance is below a certain value, then it is an adjunctive object.
Although this is certaintly not fool proof, it works without problems so far.
I am sorry I was not clear enough. Thanks for all the advice what so ever.

Unity physics about collision and energy

I have been working on a Unity ping pong game using the Leap Motion. I use rigidbody.MovePosition() to move the paddle. However, when I hit the ball (which uses gravity), the paddle launches it too far. Even when I change the masses of both, it doesn't do anything.
What variable should I change to reduce this energy going into the ball?
From the following link.
"MovePosition will put your object at the target location, no matter what. It may push aside other objects in a realistic way, or may blast them out of the way, or may just pass right through them. But it will gladly move you through a solid wall or a mountain.
If you're using MovePosition on a rigidbody to add from where you currently are, it looks like AddForce. With AddForce, the physics step does all the work: applies your velocity, sees the collision and handles the bounce. With MovePosition, the physics step sees you're mysteriously overlapping a solid object. If it isn't too much, it will bounce you apart."
You won't need to use MovePosition. Instead, you can figure out the direction of the shot (based on the position of the ball relative to the paddle). Then you can add an impulse force in that direction to the ball.
Pseudo-code (from the following link):
Vector3 shootDir = ballPosition - paddlePosition; // Calculate direction of the shot
shootDir.Normalize(); // Normalize the shot vector
ball.AddForce(shootDir * speed, ForceMode.Impulse); //Add impulse force in correct direction.
Credit due to Owen Reynolds and Tim Michels.