- Home /
I don't get Raycasts
I have been fiddling around with raycasts for over an hour reading various documentation and watching several videos. All I want is to cast a raycast down so that when it hits an object with on a specific layer it will tell me the distance between the origin of the raycast and the impact of the object so that I can use that distance for some other functions. This is what I've got:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class pacman : MonoBehaviour
{
Vector2 direction = -Vector2.up;
float offset = 2f;
float range = 1000000;
void GetDistance()
{
RaycastHit2D hit;
Vector2 position = new Vector2(transform.position.x, gameObject.transform.position.y - offset);
int layer_mask = LayerMask.GetMask("PlayerBounds");
if (Physics2D.Raycast(position, direction, out hit, range, layer_mask))
{
Debug.Log(hit.distance);
}
}
}
This by all means should work, yet my visual studios keeps telling me something is wrong. It highlights "hit" and "range" in red telling me that the "hit" argument may not be passed without "out", which it already has in that same line and that "range" can not be converted from float to integer. Why should that matter? Range is supposed to be the range of the raycast and I've seen several other people using floats for their range. The reason range is set to 1 million is because I want it to be infinite range. I know that when it's left unspecified the range automatically become infinite, but then it highlights that the layer_mask is wrong. I am at a loss of words and energy and I would love for someone to explain to me why it won't out hit so I can put the raycast information into RaycastHit2D. I've tried other ways, such as putting it into the update function (even though that's not what I want because if the raycast is in the update function it will most likely continue to cast the ray each frame and I would like to be cost efficient on the engine whenever I can). I've tried decalring the ray with the same line used in the unity documentation on RaycastHit2D like this RaycastHit2D hit = Physics2D.Raycast(this.gameObject.transform.position, direction);
but still end up not getting the result I want. I'm desperate here as I now have been coding on and off again for a year and fuck me why are Raycasts so difficult to work with?
Your answer
Follow this Question
Related Questions
Unity Physics2D.Raycast always returns “the invoker” as hit 2 Answers
How can I raycast in 2d 0 Answers
What's wrong with my RaycastHit2D? 1 Answer