- Home /
I can't change a value to Regidbody2D.centerOfMass
First, I'm not native english user. so I apologize for having an incorrect expression.
I'm developing 2D puzzle action game. There is an object to rotate by Rigidbody2D.MoveRotation in the game. I changed that object's Rigidbody2D.centerOfMass for changing center of rotation. However, when I check the log, the centerOfMass has not changed. I want to know how to solve this problem.
void Update(){
// Change centerOfMass
rd2D.centerOfMass = new Vector2(100.0f, 100.0f);
Debug.Log ("Center =" + rd2D.centerOfMass); //The result is "Center=(0.0,0.0)"
}
Answer by Kciwsolb · Jun 05, 2018 at 01:57 PM
While I don't think you need to be updating centerOfMass every Update, this should work assuming "rd2D" is a valid Rigidbody2D.
I ran the following code in Unity and it behaves as expected:
private Rigidbody2D rigidbody2D;
private void Start ()
{
rigidbody2D = GetComponent<Rigidbody2D>();
rigidbody2D.centerOfMass = new Vector2(100.0f, 100.0f);
Debug.Log(rigidbody2D.centerOfMass); //Outputs: "(100.0, 100.0)"
}
I am guessing there is something wrong with your "rd2D" variable. Try copying the above code, and see it it works properly. Maybe you could post the rest of your code so we can see if there is a problem elsewhere.
By the way, your English is better than many native English speakers. There's no need at all to apologize.
Thank you for answering. I tried copying your code,but it wasn't work. Tentatively, I will post the full code of the rotate object.
public class test : $$anonymous$$onoBehaviour {
Rigidbody2D rigidbody2D = new Rigidbody2D ();
float rotfloat=0;
// Use this for initialization
void Start() {
rigidbody2D= GetComponent<Rigidbody2D>();
rigidbody2D.centerOf$$anonymous$$ass = new Vector2(100.0f, 100.0f);
Debug.Log ("Center =" + rigidbody2D.centerOf$$anonymous$$ass); //Somehow (0.0,0.0) outputs.
}
void Update(){
rotfloat += 0.5f;
if (rotfloat > 180) {
rotfloat = 0;}
rigidbody2D.$$anonymous$$oveRotation(rotfloat);
}
}
Answer by sokigb0128 · Jun 06, 2018 at 02:40 AM
solved!!!
Since "Rigidbody2D.centerOfMass" is a local coordinate with "transform.position" as the origin.
So I create new sprite in the object's script, and specify new sprite's pivot coordinate.
I still don't know the reason why the value does not change centerOfMass, but I could the processing I was looking for.
Thank you for your help!!
private void Start() {
Sprite nowSprite = GetComponent<SpriteRenderer>().sprite;
Sprite newSprite =Sprite.Create (nowSprite.texture, nowSprite.rect, new Vector2 (3,3)); //texture,rect,Pivot
GetComponent<SpriteRenderer> ().sprite = newSprite;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612164121im_/https://answers.unity.com/themes/thub/images/avi.jpg)