- Home /
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);
}
}
Answer by whydoidoit · Jul 13, 2012 at 08:58 PM
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;
That helped, but the object won't follow the mouse on the x axis.
You want it to follow the mouse? Because adding a force will push it away...
Yes, what forces should I add because I don't want to use transforms?
That would be incredibly hard to work out - if you want something to follow the mouse you pretty much have to use transform modification.
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?
Your answer
Follow this Question
Related Questions
Trouble with Ray & Raycasting and AddForce() 1 Answer
Negative raycast direction always returns true 1 Answer
Move toward Mouse Cursor (RaycastHit), without following? 1 Answer
Push an object opposite direction of mouse position 0 Answers
How to incorporate a rotation towards mouse position in this script? I tried 0 Answers