- Home /
Raycast2D doesn't seem to work correctly.
Hello,
I'm trying to make a simple top-down game with guns, but the script used to shoot the gun does not seem to be working. The following code block is part of a script that is attached to the player. This method is called every time the player presses the mouse:
void PistolShot()
{
Vector2 origin = transform.position;
Vector2 end = mainCamera.ScreenToWorldPoint(Input.mousePosition);
Vector2 direction = (end - origin).normalized;
int Layer = LayerMask.GetMask("Shootable");
RaycastHit2D hit = Physics2D.Raycast(origin, direction);
if( hit.collider.IsTouchingLayers(Layer))
{
GameObject targetObject = hit.transform.gameObject;
Enemy target = targetObject.GetComponent<Enemy>();
if (target != null)
{
target.TakeDamage(10);
}
}
}
Also, the enemy script looks like this:
public class Enemy : MonoBehaviour {
public int health;
void Start()
{
health = 50;
}
public void TakeDamage(int damage)
{
health -= damage;
if(health <= 0)
{
Destroy(this.gameObject);
}
}
}
The problem is that when I click to use the gun, either the raycast doesn't hit the enemy's collider, or it doesn't seem to be calling the TakeDamage method on the enemy. Either way, when I try to shoot at the enemy, it doesn't make the health any lower. When I use Debug.DrawLine(origin, end), the line drawn seems to go right through the enemy, but I don't think the ray is being cast correctly.
Any help would be greatly appreciated!
I found that when I position the character directly above the "enemy," it will deal the damage, however it only happens when I'm directly above. Why doesn't the ray seem to be going infinitely far until it hits a collider? It's like it only goes a small distance away from the player character.
Answer by Walter_Hulsebos · Jul 16, 2017 at 06:51 AM
Alright, it doesn't work correctly? What does it refuse to do?
Haha! I felt like I forgot something! The problem is that when I click to use the gun, either the raycast doesn't hit the enemy's collider, or it doesn't seem to be calling the TakeDamage method on the enemy. Either way, when I try to shoot at the enemy, it doesn't make the health any lower. When I use Debug.DrawLine(origin, end), the line drawn seems to go right through the enemy, but I don't think the ray is being cast correctly.
Has this question already been asked? I'm stumped. I wish I could show you what it does, but I don't know how.