- Home /
Unity2d Set Different Physics Properties on Gameobjects (potentially at Runtime)
I currently have two gameobjects of the same prefab interacting with physics but cannot get the right settings to make it do what I want.
What I have is:
When I make the red controllable gameobject move into the blue character it nudges the blue gameobject.
What I want is:
if blue object is selected, red gameobject acts as an impassable wall to the blue gameobject.
if red object is selected, blue gameobject acts as an impassable wall to the red gameobject.
Here is the snippet of code I am using to make the selected gameobject move with keyboard input
SelectedGameObject.rigidbody2D.velocity = new Vector2(xCom, yCom).normalized * 5;
Current settings for my two gameobjects are shown in the inspector
Answer by Oliver1135 · Dec 26, 2014 at 10:52 PM
Slight update, In Unity it looks like if you have a collider without a rigidbody for all intents and purposes that object is considered static so the way I have hacked this is by adding and removing the rigidbody attached to all of the gameobjects based on whether I have it selected/am in control of moving it. Going to leave this question up for a day or two to see if anyone knows a 'better' way to do this else I'll just mark it as solved afterwards
void Update ()
{
if (this.gameObject == GameManager.SelectedGameObject)
{
if (this.gameObject.rigidbody2D == null)
{
this.gameObject.AddComponent<Rigidbody2D>();
}
}
else
{
if (this.rigidbody2D != null)
{
Destroy (this.rigidbody2D);
}
}
}
I've been using this method for my little project for some time with no problems arisen or strange behavior co$$anonymous$$g out of it.
The better method is to just set is$$anonymous$$inematic. Adding and removing physics components will probably hurt your performance significantly.
Answer by AurimasBlazulionis · Dec 26, 2014 at 10:52 PM
I could suggest you use rigidbody constraints. But as it is 2D you can not because unity didin't implement it in 2d. So you can set the non selected objects rigidbody to kinematic by doing this:
Rigidbody2D.isKinematic = true
If that doesn't work then always set the not selected object's velocity to 0
Also don't forget to set fixedAngle value to true on the not selected object by doing this:
Rigidbody2D.fixedAngle = true
I hope it helps. It would be the way easier with constraints but I don't know why it's not implemented in 2D rigidbody
Your answer
Follow this Question
Related Questions
rigidbody2D.MovePosition() Can't Found 2 Answers
How to create an Asteroids style moving in 2D mode? 2 Answers
Improve ray detection? 0 Answers
Velocity doesnt change properly 1 Answer
player jumps too high when clicking with two fingers. 2 Answers