- Home /
Affecting the game object that my raycast hit
I'm trying to apply a forward force to whatever game object is hit by my raycast, which gets called every time I click the left mouse button. I think I have the raycast down, but I can't apply the force.
Here's my code: void Update () { if (Input.GetKey (KeyCode.Mouse0)) { if(Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), Mathf.Infinity)) { GetComponent<Rigidbody>().AddExplosionForce(500,cameraTransform.forward, 5); } } }
Answer by MacDx · Oct 31, 2017 at 08:05 PM
The problem is that you want to affect the game object hit by the raycast but nowhere in your code you are getting a reference to the object hit. When you call the GetComponent method by itself it will only look for components that are attached to the same game object this script is attached to, so that is your mistake.
To get a reference to the object hit you will need to change your raycast method a little bit.
void Update()
{
if (Input.GetKey(KeyCode.Mouse0))
{
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity))
{
Rigidbody body = hit.collider.GetComponent<Rigidbody>();
if(body != null)
body.AddExplosionForce(500, Camera.main.transform.forward, 5);
}
}
}
The changes here are the following:
Physics Raycast is now using a version of the method that includes a RaycastHit variable. After the method gets called the raycast hit variable will contain the results of the raycast, including the gameobject that was hit
Instead of calling GetComponent by itself, GetComponent is now being called from the object that was hit, which will get said object's rigidbody.
Finally, there is also a null check to avoid a runtime error. Your raycast may hit something that does not contains a rigidbody which will return a null component and if you try to call a function on that component you will get an error, so the null check is to avoid that.
Hope this helps!
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
Want to move object slowly to where the mouse clicks? 1 Answer
check if can place object 1 Answer