- Home /
using a raycast to apply physics on an object
Ive been figuring out unity tonight and im super stuck. Im trying to make a lil test game and i have a leg attatched to a first person camera that kicks in front when you click. I'm trying to figure out how to use a raycast to apply a force to the objects in front of the player when I do this. I can't seem to figure out how to work the raycast to idenify the object im looking at and apply a force to it at all.
Answer by syclamoth · Jun 16, 2012 at 07:45 AM
This is honestly extremely simple.
void Kick(float kickStrength)
{
RaycastHit hit;
if(Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out hit)
{
if(hit.rigidbody != null)
{
hit.rigidbody.AddForceAtPosition(Camera.main.transform.forward * kickStrength, hit.point, ForceMode.Impulse);
}
}
}
When you want to kick something, do this:
Kick(100);
to kick with a power of 100, like so:
void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
Kick(100);
}
}
thanks man that worked and i think i understand it more or less now. one small question; what is the best way to delay it slightly so as to match up the force with the animation i made
Your answer
Follow this Question
Related Questions
FPS shooting 1 Answer
Drag Rigid Bodies First Person Controller.js 0 Answers
Display issues with GUI only showing details for last object in list. 2 Answers
Raycast Positioning 2 Answers
FPS crosshair ranging 1 Answer