- Home /
Decrease rigidbody2D velocity per object attached to parent
I want to make the velocity of my Player to decrease based on how many object(Child) attached to it. here's my code so far, but this one just sets the velocity to a certain amount, I want it to decrease 1f per oject(Child) attached:
if (!dead)
{
if(transform.Find("Enemy2")){
Vector2 newVelocity = rigidbody2D.velocity;
newVelocity.x = 1.5f;
rigidbody2D.velocity = newVelocity;
}else{
Vector2 newVelocity = rigidbody2D.velocity;
newVelocity.x = forwardMovementSpeed;
rigidbody2D.velocity = newVelocity;
}
Answer by Mangas · Mar 10, 2015 at 08:57 AM
Do something like this then:
newVelocity.x -= 1f * transform.childCount;
this boosts the player backwards at lightspeed. lol. I think it keeps on finding the "Enemy2" child, so the velocity kept on subtracting even though it only has 1 child. how can I stop that from happening?
You have to make it so the above script is not modifying the current speed so it should be something like
Vector2 newVelocity = rigidbody2D.velocity;
//this
newVelocity.x = 1.5f/transform.childCount;
//or this and it will never be negative
newVelocity.x =$$anonymous$$athf.$$anonymous$$ax (1.5f-(transform.childCount*0.1f),0);
$$anonymous$$aybe what you need is to Clamp the velocity as well:
$$anonymous$$athf.Clamp(newVelocity, [$$anonymous$$ value], [max value]);
That way the velocity will never go over the maximum value, obviously I'm not posting the entire solution here, but with transform.childCount and $$anonymous$$athf.Clamp() you should be good to go.
Pendantic's suggestion worked great! though the children are getting detached after the player stops moving, but I'll try to figure that one on my own:) and also, thanks for the tips $$anonymous$$angas, I've never tried Clamp before but now I will.