Help Creating Explosion Knockback
So I've tried a few different approaches to getting this working and none seemed to have worked, so I'm going to ask here.
What I'm trying to accomplish is have a barrel explode when it collides with the player, knocking back all Rigidbody2D with a certain radius of the object.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BarrelCollision : MonoBehaviour {
private Collider[] colliders;
private Rigidbody2D rb2d;
//private Rigidbody2D[] all_rigidbodies;
public float radius = 10f;
public float BlastForce;
// Use this for initialization
void Start () {
rb2d = GetComponent<Rigidbody2D> ();
Vector2 SpawnHop = new Vector2 (0f, 6f);
rb2d.AddForce (SpawnHop, ForceMode2D.Impulse);
}
// Update is called once per frame
void Update () {
}
public void Explode (){
Rigidbody2D all_rigidbodies = (Rigidbody2D)FindObjectOfType(typeof(Rigidbody2D));
foreach (Rigidbody2D r in all_rigidbodies)
{
if (Vector2.Distance(r.transform.position, transform.position) < 6)
{
float px = r.transform.position.x - transform.position.x;
float py = r.transform.position.y - transform.position.y;
r.AddForce ((Vector2 (px, py) * BlastForce), ForceMode2D.Impulse);
}
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag ("Player"))
{
Explode ();
/*colliders = Physics.OverlapSphere (transform.position, radius);
foreach (Collider col in colliders)
{
if (col.GetComponent<Rigidbody2D> () != null)
{
Rigidbody2D rb2dother;
rb2dother = col.GetComponent<Rigidbody2D> ();
Vector2 dir = (rb2d.transform.position - rb2dother.transform.position);
rb2dother.AddForce ((dir * BlastForce), ForceMode2D.Impulse);
}
}*/
}
}
}
The code that's not commented out threw me this error: Assets/BarrelCollision.cs(32,29): error CS1579: foreach statement cannot operate on variables of type UnityEngine.Rigidbody2D because it does not contain a definition for GetEnumerator or is inaccessible
The code that IS commented out didn't work at all. The Player object hit the barrel and just knocked it over (I have two colliders on it, one set to trigger and one not)
If any can help me out it would be greatly appreciated.
Your answer
Follow this Question
Related Questions
plz I need a script of diagonal moving for rigidbody 2d 0 Answers
Predicting max jump height of a force impulse 1 Answer
2D Top-Down Character: How to make my character move using physics? 1 Answer
How to make arrows fly to user mouse position? 0 Answers
RigidBody2D.AddForce() horizontally is not working! 2 Answers