- Home /
 
Unity 2d Freezing Player in Position on Collision
I'm currently making a 2d platformer and I need one of my enemies to freeze the player in it's current position when it collides with the player. I want the player to be unable to move but still able to shoot his gun.
 void OnTriggerEnter2D(Collider2D other){
 if(other.gameObject.tag == "Player"){
 
 transform.position = target.position;
          
 transform.LookAt(new Vector3 (20, 0, 0));
 
 //code to freeze player in place until enemy dies from player gunfire
    }
 }
 
              Answer by palash_bhowmick1 · Oct 16, 2014 at 06:36 PM
if you want to freeze the player, just set its velocity and gravity to 0. Before, you need to add rigidbody2D to the player...
 function OnCollisionEnter2D(coll:Collision2D)
 {
     rigidbody2D.velocity.x=0;
     rigidbody2D.velocity.y=0;
     rigidbody2D.gravityScale=0.0;
         
        //Do other stuffs
 
 }
 
               I guess you want collision, so i used OnCollisionEnter2D()...
I tried: void OnTriggerEnter2D (Collider2D other) { if(other.tag == "RIP") { rigidbody2D.velocity = new Vector2(0,0); rigidbody2D.gravityScale=0.0f; } }
but doesn't work, still moves :(
Answer by lh7746 · Feb 21, 2015 at 05:36 AM
when using OnTriggerEnter2D make sure the gameobject Boxcollider2D property isTrigger is checked?
Answer by christiaancsb · Sep 07, 2017 at 11:52 AM
For the positions:
 rigid.constraints = RigidbodyConstraints2D.FreezePositionX | RigidbodyConstraints2D.FreezePositionY;
 
               For rotation:
 Rigidbody2D.constraints = RigidbodyConstraints2D.FreezeRotationZ;
 
               For both:
 rigid.constraints = RigidbodyConstraints2D.FreezePositionX | RigidbodyConstraints2D.FreezePositionY | RigidbodyConstraints2D.FreezeRotationZ;
 
               PS. code is not tested.
Your answer
 
             Follow this Question
Related Questions
Basic 2d AI follow? 1 Answer
A* pathfinding for 2D top Down 0 Answers
Check lenght from player? 2 Answers
Unity 2D Platformer Enemy follow Player on X-axis only, c# 1 Answer