Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Rigidbody2D -changing bodyType to Static in runtime

Discussion in 'Project Tiny' started by Sladzio, Mar 27, 2019.

  1. Sladzio

    Sladzio

    Joined:
    Apr 15, 2014
    Posts:
    14
    Hey! Is it possible to change the Rigidbody2D body type from dynamic to static in runtime in order to prevent affecting the object by gravity?
     
  2. Zoelovezle

    Zoelovezle

    Joined:
    Aug 7, 2015
    Posts:
    54
    I tried the same :(. Unfortunately, it's not working so I ended up creating my own physics using HitBox I would suggest the same for you.
     
  3. Sladzio

    Sladzio

    Joined:
    Apr 15, 2014
    Posts:
    14
    Thanks!
     
  4. Eulenmensch

    Eulenmensch

    Joined:
    Mar 10, 2018
    Posts:
    19
    I know this might be a little late at this point but it might be useful for others still that search the forums. I personally just save the component data of the rb, remove it and then re-add it with the same values except I get the body type from a reference entity that only has a rigidbody2d component with the desired body type value. Here's the code that I use. I have a component "ChangeBodyType" that only has an entityReference field.

    Code (JavaScript):
    1. this.world.forEach([ut.Entity, ut.Physics2D.RigidBody2D, ChangeBodyType],(entity, rigidBody, changeBodyType) => {
    2.                 let friction = rigidBody.friction;
    3.                 let restitution = rigidBody.restitution;
    4.                 let density = rigidBody.density;
    5.                 let freezeRotation = rigidBody.freezeRotation;
    6.  
    7.                 let bodyType = this.world.getComponentData(changeBodyType.ReferenceRigidBody, ut.Physics2D.RigidBody2D).bodyType;
    8.  
    9.                 this.world.removeComponent(entity, ut.Physics2D.RigidBody2D);
    10.                 this.world.addComponent(entity, ut.Physics2D.RigidBody2D);
    11.                 let newRigidBody = this.world.getComponentData(entity, ut.Physics2D.RigidBody2D);
    12.                 newRigidBody.bodyType = bodyType;
    13.                 newRigidBody.friction = friction;
    14.                 newRigidBody.restitution = restitution;
    15.                 newRigidBody.density = density;
    16.                 newRigidBody.freezeRotation = freezeRotation;
    17.                 this.world.setComponentData(entity, newRigidBody);
    18.             })
    I hope this can still help someone
     
    mondayoff likes this.