- Home /
Question by
Gawron10001 · May 03, 2019 at 07:09 PM ·
c#2d gamedetection
How to get raycast working on 2d objects
So i have 2D game and i wrote this piece of code hoping that it will work on 2d objects and it isn't. Not returning any log, but if i add a 3d cube it returns an log. Can someone could help me transform this script to work in 2d gamescene?
Camera cam;
void Start()
{
cam = Camera.main;
}
void Update()
{
if (Input.GetMouseButtonDown(0)) //checks left mouse button
{
Ray ray = cam.ScreenPointToRay(Input.mousePosition); //cast ray on whatever we click on
RaycastHit hit;
if (Physics.Raycast(ray, out hit))//if ray hits something, this happens
{
//destroy block in range
Debug.Log(" hit" + hit.collider.name);
}
}
}
Comment
Best Answer
Answer by Gawron10001 · May 03, 2019 at 08:55 PM
void Update()
{
if ( Input.GetMouseButtonDown( 0 ) )
{
Vector2 worldPoint = Camera.main.ScreenToWorldPoint( Input.mousePosition );
RaycastHit2D hit = Physics2D.Raycast( worldPoint, Vector2.zero );
if ( hit.collider != null )
{
Debug.Log( hit.collider.name );
}
}
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Detect tag in C# 1 Answer
How would i calculate the size of a 2D area closed off by multiple colliders? 1 Answer