- Home /
Question by
ChichoRD · Sep 12, 2020 at 04:24 PM ·
rigidbody2dphysics2daddforcearray of gameobjects
I'm so lost trying to add a force towards the nearest collder with tag "x"
I want my player to be able to get an impulse towards the nearest gameobject with a specific tag, I'm a bit new to unity so probably parts of my code are no-sense, I know that I have to put all my wanted objects in an array and then calculate the nearest object every frame, please help, I'm lost:
using UnityEngine;
using System.Linq;
public class PlayerAbilities : MonoBehaviour
{
public static PlayerAbilities instance;
private Collider2D[] Gatherables;
private GameObject[] GatherablesObjects = GameObject.FindGameObjectsWithTag("Gatherable");
private float[] distance;
private float nearestCollider;
private Rigidbody2D rb;
public LayerMask whatCanGrab;
public float areaOfEffect;
public float effectForce;
private void Start()
{
foreach (var collider in GatherablesObjects)
{
Gatherables = GetComponents<Collider2D>();
}
rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
for (int i = 0; i < Gatherables.Length; i++)
{
distance[i] = Vector2.Distance(transform.position, Gatherables[i].transform.position);
}
nearestCollider = NearestCollider();
}
public void GrabDash()
{
if (Physics2D.OverlapCircle(transform.position, areaOfEffect, whatCanGrab))
{
rb.AddForce(new Vector2(nearestCollider) * effectForce, ForceMode2D.Impulse);
}
}
private void OnDrawGizmos()
{
//Gizmos.DrawLine(transform.position, Gatherables[].transform.position);
}
private float NearestCollider()
{
return distance.Min();
}
}
Let me know all what you think of my code and how can I improve it please and thanks.
Comment