- Home /
How to destroy specific gameobject with a mouse click once player is looking at them using a Ray
Hi,
So I have a scene set up where the end goal is to get within range of the villain, look at them, and click to destroy them with the mouse (not necessarily with the mouse cursor pointed on them, just with the player character looking at them with the raycast). I have been able to set it up to where the enemy is destroyed on click no matter where the player is, however I want this to only occur once the ray is looking at them. Could anyone help me figure out how to create this code? (I am also very new to coding so I am not familiar with all of the functions yet)
Hero code to cast the ray:
Ray r = new Ray();
r.origin = gameObject.transform.position;
r.direction = gameObject.transform.forward;
Debug.DrawLine(r.origin, r.origin + r.direction * 10.0f, Color.magenta);
RaycastHit rhit;
if (Physics.Raycast(r, out rhit, 10.0f))
{
if (rhit.collider.gameObject.tag == "Enemy")
{
gameObject.GetComponent<MeshRenderer>().material.color = Color.green;
/* if(Input.GetMouseButtonDown(0))
{
Destroy(gameObject);
}*/
}
else
{
gameObject.GetComponent<MeshRenderer>().material.color = Color.blue;
}
}
Villain code to be destroyed on click:
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Destroy(gameObject);
}
}
Answer by tormentoarmagedoom · Mar 22, 2020 at 06:44 PM
Hello.
You are very close!
Lets see the RAYCAST manual :https://docs.unity3d.com/ScriptReference/Physics.Raycast.html
IF you look all the page, will see there are different ways to "send" a ray. But If you think a little, will realize you always need the same, an origin for the ray, and a direction+distance or a destination. If not is impossible for Unity to do any ray..
In your code you are using this:
if (Physics.Raycast(r, out rhit, 10.0f))
So, you are saying: if Generating the ray "r" with max distance of "10", if hits something, return me true and "rhit" will be the point where the ray hits.
BUUT What is ray "r" ? You diddnt defined it in your code! For Unity, ray "r" is nothing, so Unity is casting a null ray, so is casting nothing!!
You need to define the ray first! OR you can use the Raycast function directly with the origin and the direction, like this:
if (Physics.Raycast(Vector3 origin, Vector3 direction, float maxDistance))
I recommend you to learn to use raycasts before continue. Do a simple object with a script only for test raycast things until you domine it.
Good luck!
Your answer
Follow this Question
Related Questions
Click Point From Raycasting Not Yielding Expected Coordinates 1 Answer
Use raycast to click on object 3 Answers
I am stuck and don't know what to do, After upgrading to 2019 mouse and raycast don't work well 1 Answer
question about instantiating 2 Answers
How to create gameobjects by clicking in the scene view in the editor? 1 Answer