Reputation: 2134
I am trying to cast a 2D Ray from an instantiated missile prefab as follows:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyMissile : MonoBehaviour {
void Update () {
RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.down,1f);
Debug.DrawRay(transform.position, Vector2.down, Color.green);
if(hit)
{
print("Hit");
}
else
{
print("No hit");
}
}
}
I can clearly see on the scene that the Ray goes through the Player:
The Player has a Rigidbody2D and a BoxCollider2D as trigger:
And the EnemyMissile has its own RigidBody2D and BoxCollider2D as trigger:
However I see nothing printed on the console
The idea to cast a Ray from the missile is to play an AudioClip when the EnemyMissile is going towards Player.
I have seen: Raycast Hit Collider is Always NULL Physics2D.Raycast returning null
Thank you for your help.
EDIT to answer @Monofuse comment: When I select the Player the Transform is: x: 0.4567, y: -1.58, z: 0
When I select the missile the Transform is: x: 0.3699, y: -1.054, z: 0
EDIT to answer @Ada Nub:
I had by default both option checked: Queries Hit Triggers and Queries Start in Colliders.
Now I have unchecked Queries Start in Colliders, however the result is the same, I do not see the print on the console:
I have realized my mistake, I had the Information tab in the console not pressed:
Upvotes: 0
Views: 794
Reputation: 64
Have you turned on 'Queries hit triggers' in Edit > Project Settings > Physics2D? Raycasts by default do not hit triggers, so this may be your issue.
Image of 'Queries hit triggers' option
The option right below it, 'Queries start in colliders', might also be worth looking into; since you're casting the raycast from inside the missile's collider, you'll probably want that option unchecked so that it doesn't count the missile it starts in as a hit.
Upvotes: 5