- Home /
how to add multiple forces on a single object
my player uses rigidbody.velocity to move, and also have an alien that explodes, and also has an explosion effect that pushes objects away, look here what the problem is: https://drive.google.com/open?id=1_-mfqw9JTDO01FMklGxCtup5ZQoGu-4R as you see in the video, all mobs flew away, only the player because i'm moving him using rigidbody, i tried to disable my controller script, and it worked, anyone help pls, here's my movement piece of code:
void FixedUpdate()
{
if (horizontal != 0 && vertical != 0)
{
rb.velocity = new Vector2((horizontal * speed) * speedLimiter, (vertical * speed) * speedLimiter);
}
else
{
rb.velocity = new Vector2(horizontal * speed, vertical * speed);
}
}
and here is the explosion piece of code:
public override void FixedUpdate() {
base.FixedUpdate();
checkDistance();
}
void checkDistance() {
if (player != null) {
if (Vector2.Distance(transform.position, player.position) <= 1.75f)
{
Collider2D[] colliders = Physics2D.OverlapCircleAll(transform.position, radius);
foreach(Collider2D collider in colliders)
{
Rigidbody2D rb = collider.GetComponent<Rigidbody2D>();
if(rb != null)
{
AddExplosionForce(rb, explosionForce, transform.position, radius);
}
}
GameObject instance = SpawnObject.WithRotation(WormSplashEffect, transform);
Destroy(instance, 1f);
Destroy(gameObject);
}
}
}
public void AddExplosionForce(Rigidbody2D body, float explosionForce, Vector3 explosionPosition, float explosionRadius)
{
var dir = (body.transform.position - explosionPosition);
float wearoff = 1 - (dir.magnitude / explosionRadius);
body.AddForce(dir.normalized * explosionForce * wearoff);
}
Answer by DenisGLabrecque · Aug 12, 2019 at 12:06 PM
I think you don't want your player character to move when the explosion force gets applied? Then why not check whether the rigidbody is part of your player, and ignore that one in your foreach loop? Not sure what you mean by "I removed the controller script and it works". What works?
no you did not understand what i mean, as you see in the video, the mobs flew away smoothly, but the player only a bit and unsmoothly, that is because i'm using the player's rigidbody to move him, i want the explosion to affect the player same as it affects the other mobs, is there any way to add forces?
Have you tried offsetting the explosion force away from the character's rigidbody? I have a suspicion the explosion force doesn't have a direction to act, because it is on position 0,0.