I have a scene where there is a first person controller and a bunch of blocks stacked in a wall with a rigidbody. I want to make it so that when the player left clicks, a blast of force is exerted from the front of the player. I know you need to use rigidbody.AddExplosionForce to get this reaction, but whatever I am doing isn’t working.
I am using C#
using UnityEngine;
using System.Collections;
public class Speak : MonoBehaviour
{
public float force;
void Update ()
{
if(Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray, out hit, 100))
{
GetComponent<Rigidbody>().AddExplosionForce(force,hit.point, 5);
}
}
}
}
As far as I can see, your code is correct in terms of theory.
However, it seems like you are applying the force to your own gameobject (I’m assuming this code is on the player, and your player is probably a character controller, so it doesn’t do anything)
if(Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray, out hit, 100))
{
print("Hit: " + hit.transform.name;
hit.GetComponent<Rigidbody>().AddExplosionForce(force,hit.point, 5);
}
}
If it prints something, and still nothing happens, than increase the force variable (You need a crazy amount, like 9000 to actually do something) to simplify this in the inspector, you can simply use
void Start()
{
force *= 5000; //Or something just to give make the inspector look a little simpler
}