x


Raycast Hit Question

I can't seem to get this to work, what I'm trying to do is get the gameObject to add force in the direction of the hit point of the raycast which is being casted from the mosue position, however nothing I have tried so far works. Here's my code:

        if (Input.GetButton ("Fire1")) {

        var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
        var hit : RaycastHit;

        if (Physics.Raycast (ray, hit, Mathf.Infinity)) {

         var newVector3 = hit.point;

            var moveDir = transform.position - newVector3;

            rigidbody.AddForce (moveDir * speed);
        }
    }
more ▼

asked Jul 13 '12 at 08:54 PM

Chimera3D gravatar image

Chimera3D
479 17 35 49

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

1 answer: sort voted first

Well the direction of the hit is the direction of the ray - which you can get from ray.direction. Or are you thinking you want to take the direction from something else? in which case your moveDir logic is backwards right now and you probably want to do a .normalized on it.

   var moveDir = (hit.point - transform.position).normalized;
more ▼

answered Jul 13 '12 at 08:58 PM

whydoidoit gravatar image

whydoidoit
33.1k 12 23 101

That helped, but the object won't follow the mouse on the x axis.

Jul 13 '12 at 09:12 PM Chimera3D

You want it to follow the mouse? Because adding a force will push it away...

Jul 13 '12 at 09:25 PM whydoidoit

Yes, what forces should I add because I don't want to use transforms?

Jul 13 '12 at 09:28 PM Chimera3D

That would be incredibly hard to work out - if you want something to follow the mouse you pretty much have to use transform modification.

Jul 13 '12 at 09:32 PM whydoidoit

Ok then, I already knew how to do it with transforms. Well how can I get the object to rotate towards the hit point one one axis?

Jul 13 '12 at 09:43 PM Chimera3D
(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:

x1535
x286
x245
x194
x75

asked: Jul 13 '12 at 08:54 PM

Seen: 330 times

Last Updated: Jul 13 '12 at 10:00 PM