- Home /
(C#) 2D Raycast wrong direction
Hi all, So I've been trying to dig into 2D for the first time, and I've immediately gotten stuck with raycasting.
What I'm trying to do is have a ray be cast from the barrel of a gun to the position of the mouse in 2D space. This is the code I have now:
if(Input.GetButton("Fire1"))
{
if(canShoot)
{
timer = rateOfFire;
bulletsLeft -= 1;
canShoot = false;
RaycastHit2D hit = Physics2D.Raycast(gunBarrel.position, (Camera.main.ScreenToWorldPoint(Input.mousePosition) - gunBarrel.position), range);
if(hit.collider != null)
{
if(hit.collider.tag == "EnemyBody" || hit.collider.tag == "EnemyHead" || hit.collider.tag == "Enemy")
{
enemy_health = hit.collider.gameObject.GetComponentInParent<EnemyHealth>();
}
if(hit.collider.tag == "EnemyBody")
{
enemy_health.ReceiveDamage(damage, 2);
}
else
if(hit.collider.tag == "EnemyHead")
{
enemy_health.ReceiveDamage(damage, 1);
}
else
if(hit.collider.tag == "Enemy")
{
enemy_health.ReceiveDamage(damage, 3);
}
}
}
}
What's happening now is that the ray is cast into a completely wrong direction, and nowhere near where the mouse is. None of the objects here are children of another object.
I know this issue has been adressed a few times here already, but I haven't found my answer here yet. Thanks in advance.
EDIT I noticed that Unity is able to get my mouse's position in pixel coordinates, but when it turns those coordinates into world space coordinates, it just gives them the same value as my main camera's coordinates. Does anyone know why this would be happening?
Use Debug.Log
to see the numbers that you're actually giving to the raycast, and use Debug.DrawRay
or Debug.DrawLine
to see the ray in the scene view. That should help you narrow down your problem.
I've already tried that, but it doesn't really help with the problem. Updated the question.
RaycastHit2D hit = Physics2D.Raycast(gunBarrel.position, (Camera.main.ScreenToWorldPoint(Input.mousePosition) + gunBarrel.position), range);
re_edit this line like this or check the rotation of gunBarrel :)
There's nothing wrong with the rotation of the gunBarrel object, and that didn't seem to work. I may have to look into some other way of doing the raycasting here.