How do I get objects in front of the player to be blasted away?
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);
}
}
}
}
try this: hit.GetComponent().AddExplosionForce(force,hit.point, 5); and also you didn't set the force variable
First thing I notice is your explanation of multiple objects, yet you're using Physics.Raycast. Note that Physics.Raycast on cast a thin line forward and will only hit a single object. $$anonymous$$aybe try Physics.SphereCast ins$$anonymous$$d.
Aside from that, could you describe exacly what the script you currently have is causing to happen? Do any of the objects get force added to them at all?
Try GetComponent<Rigidbody>().AddForce(hit.point * force, Force$$anonymous$$ode.Impulse);
. It may not work because i have not tested it.
Answer by FirePlantGames · Oct 30, 2015 at 12:26 AM
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
}
That should work :)
Your answer
Follow this Question
Related Questions
Ball Speed is not increasing as per code 0 Answers
Getting two Objects to the same direction with different speed 0 Answers
How to remove addforce effect 0 Answers
AddForce in Coroutine 1 Answer
Script makes plane point in general direction but doesn't point fully... read description please! 1 Answer