I'm new to Unity and blocked 2nd day with a simple try to raycast. This is the script which I use to raycast:
void Update () {
Debug.DrawLine(transform.position, transform.position - transform.up);
RaycastHit2D[] hits = Physics2D.RaycastAll(transform.position, transform.position - transform.up, Mathf.Infinity);
if(hits.Length > 0)
{
Debug.Log("Hit");
}
}
I have attached this script to a square and put near it another square which acts like a target, also added a 2d box collider to the target. I have disabled the "hit itself" feature like is described here: http://answers.unity3d.com/questions/756380/raycast-ignore-itself.html After performing all this steps the raycast hits nothing, the collider of the hit object is always null (checked this in debug mode, also nothing is written in console) . I drew a debug line, and indeed it points to the target square like in screenshots.
Please help me figure out what I'm doing wrong.
Physics.Raycast
is for 3D Colliders and this includes Box Collider, Sphere Collider and others. No 2D in their names.
Physics2D.Raycast
is for 2D colliders. You need a Box Collider 2D since this is a Sprite Renderer which is a 2D Object.
EDIT :
With your edit, the problem is that the direction of the raycast is too short. You have to multiply it by a number. The value of 100 should be fine.
public float distance = 100f;
void Update()
{
Debug.DrawLine(transform.position, transform.position + transform.right);
RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.position + transform.right * distance, Mathf.Infinity);
if (hit.collider != null)
{
Debug.Log("hit: " + hit.collider.name);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.