x


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.

more ▼

asked Jun 16 '12 at 07:34 AM

kuato gravatar image

kuato
2 1 1

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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);
    }
}
more ▼

answered Jun 16 '12 at 07:45 AM

syclamoth gravatar image

syclamoth
14.8k 7 15 80

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

Jun 16 '12 at 09:50 AM kuato

scratch that i got it

Jun 16 '12 at 10:50 AM kuato

thanks dude i think i kind of have a handle on this now

Jun 16 '12 at 03:16 PM kuato
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x1531
x1175
x292
x6

asked: Jun 16 '12 at 07:34 AM

Seen: 400 times

Last Updated: Jun 16 '12 at 03:17 PM