How to stop game object movement instantly after collision is detected ?
Hi, I have a moving object with some colliders and rigid body attached to it. The colliders used are box and polygon, I use box colliders to identify a part of the moving object as head/leg and polygon for identifying body.All happens in Unity 2018.1.0f2 and working on 2D
I also use box colliders for identifying some elements as destroyer (it destroys any moving object colliding with) and bottom (certain moving objects can step on it and certain can't). All static objects (bottom and destroyer) dont have rigidbodies attached. Moving objects rigidbodies are Type: Kinematic, Simulated: true, Use Full kinematic contacts : true, Collision detection : continuous Sleeping mode: start awake, Interpolate: none
Using OnCollisionEnter2D for checking collisions between the objects. The script for collisions is attached to every moving object and disabled after certain action happens. Another script is using for controlling moving objects movement. and Inside public Vector2 velocity = new Vector2 (0f, -32f); void FixedUpdate () { rb2D.MovePosition (rb2D.position + velocity * Time.fixedDeltaTime); }
void Update () { velocity = Input.GetKey (KeyCode.DownArrow) ? new Vector2 (0f, Mathf.Clamp (velocity.y - 32, -224f, -32f)) : new Vector2 (0f, -32f); }
Local variable Velocity inside Update method is used for controlling speed of movement, and Global Velocity is used as some controllable constant. In script with cellision detections there is a method private void StopRigidBodyMovement () { moveScript.enabled = false; rb2D.bodyType = RigidbodyType2D.Static; }
That is used for stopping rigid body movement, when making it static and prevent further movment disabling the script responsible for moving object. BUT! The problem is that moving object stops after a while and not immediately as expected. And As the question says: How can I immediately stop figure movement after collision happens ?
Answer by kpetkov · May 25, 2018 at 09:08 AM
As the mainual states Physics events like collisions and interactions with other objects works well ONLY FOR DINAMYC TYPE RigidBoby! So to stop RigidBody at the exact moment it has to be dynamic. One possible solution is to use RigidBodyConstraints https://docs.unity3d.com/ScriptReference/RigidbodyConstraints.html, also if rb2D is the RigidBody use rb2D.velocity = Vector2.zero; rb2D.angularVelocity = 0f;