Unity 2018.4 (I have an old computer)
Short version:
Collider.Raycast() does a raycast check that ignores all colliders but this collider. Collider2D.Raycast() does something different. I’m making a 2D game, but I want the functionality that comes from the 3D collider’s raycast.
Do I need to use Collider objects in my 2D game, or is there some way to use Collider2D to do this?
Long version:
I have many Character objects. These objects have polygon colliders with irregular shapes. Part of the game mechanics require them to navigate by finding the closest point between their collider and a target position.
I want to use raycasts (or better: circlecasts) to find this point.
My problem is that if these character objects use the Physics2D, or Collider2D, version of Raycast(), they might hit another character’s collider and mistake it for their own.
I’ve attached some example code and screenshots of my setup that (I hope) demonstrate the problem.
Is there a better way of achieving this? Should I just use Collider objects instead of Collider2D?
Thanks.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Example1 : MonoBehaviour
{
public GameObject target;
private Collider2D myCollider;
private Vector2 mousePosition, direction;
private RaycastHit2D hitInfo;
// Start is called before the first frame update
void Start()
{
myCollider = GetComponent<Collider2D>();
}
// Update is called once per frame
void Update()
{
mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
hitInfo = Physics2D.Raycast(mousePosition, (Vector2)gameObject.transform.position);
if (hitInfo.collider != null) target.transform.position = hitInfo.point;
}
}
Fig 1. System before code execution
(Each “Character” object has it’s own target and copy of Example1 script to execute.)
Fig 2. System after code execution.
(Notice how some of the targets have jumped over to other characters.)