- Home /
Question by
Caldas · Jul 19, 2017 at 07:53 PM ·
shootraytop down shooter
Top down shooter. How can i shoot a ray from my gun and know if that ray passed by some enemy.
Im making a 3d Shooter and i want to shoot a ray from my gun and know if that ray passe by some enemy. Here is an image.
Here is my the code that makes the gun look at the mouse click. Hope somebody can help. Thanks.
public class lookat : MonoBehaviour { Vector3 lookPos;
public int damage = 10;
void Update()
{
if(Input.GetMouseButton(0))
{
MouseAim();
}
}
void MouseAim()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100))
{
lookPos = hit.point;
Target target = hit.transform.GetComponent<Target>();
if(target != null)
{
target.TakeDamage(damage);
}
}
Vector3 lookDir = lookPos - transform.position;
lookDir.y = 0;
transform.LookAt(transform.position + lookDir, Vector3.up);
}
}
sem-titulo.png
(44.4 kB)
Comment
Best Answer
Answer by Beks_Omega · Jul 19, 2017 at 08:30 PM
Have you checked out Physics.Raycast? I think this may be what you're looking for.
https://docs.unity3d.com/ScriptReference/Physics.Raycast.html
It basically sends a ray out into space and sees if it hits anything, then you can get information about what it hit.