x


transform.Translate: object NOT moving toward RaycastHit problem

This is a test script i'm using to iron out bugs before i adapt it to use as a 'shoot toward mouse cursor' script.

Basicly, the script is on a cube (NO rigid body), and whenever the mouse cursor touches another object in the scene, the box is supposed to move toward the mouse cursor because the raycast is pointing to the cursor and the box is moving toward the raycast.

HOWEVER, the box moves in a seemingly random direction and NOT toward the mouse cursor (Grrr) Can anyone tell me where i've gone wrong?

function Update() {

var hit : RaycastHit; if(Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), hit)) {

transform.Translate((hit.point) * Time.deltaTime);

}

Thank you, Tom :)

more ▼

asked Jul 19 '12 at 12:21 PM

Tea_Doogun gravatar image

Tea_Doogun
78 4 12 22

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

1 answer: sort voted first

Transform.Translate needs a direction and not a location. So I guess this would do it:

     transform.Translate((hit.point - transform.position) * Time.deltaTime);
more ▼

answered Jul 19 '12 at 12:36 PM

whydoidoit gravatar image

whydoidoit
33.1k 12 23 100

That did it, AND i learned somthing :)

Thanks man, yoo rool!

Tom :)

Jul 19 '12 at 12:40 PM Tea_Doogun
Jul 19 '12 at 01:34 PM Bunny83

Good point. @Tea_Doogun - you should pass Space.World to Translate as if the object were parented it would probably not be moving in the right direction.

Jul 19 '12 at 01:49 PM whydoidoit

@whydoidoit: It doesn't actually need to be parented. Rotated is enough ;) Translate, with the default parameter Space.Self, will translate along the objects local axis. Since the direction you pass is in worldspace it won't be moving the right way, unless the object isn't rotated.

Jul 19 '12 at 10:01 PM Bunny83

Ah yes - serves me right for commenting on a function I don't use :S

Jul 19 '12 at 10:17 PM whydoidoit
(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:

x983
x198
x161
x41

asked: Jul 19 '12 at 12:21 PM

Seen: 670 times

Last Updated: Jul 19 '12 at 10:17 PM