- Home /
Placing object where ray collides
I have this code so far for a script that I want to have move an object to where the mouse is looking. It works on objects, but when the ray collides with any terrain or trees from the terrain, the object move to the origin of the terrain, not where the mouse is looking. Any suggestions?
#pragma strict
var hit: RaycastHit;
var origin: GameObject;//origin of ray
var hitObject: GameObject;
var hitTest: Vector3;
function Start () {
}
function Update () {
/////////////RAYCASTING
var forward: Vector3= transform.TransformDirection(Vector3.forward*10);
var fwd= transform.TransformDirection(Vector3.forward);
Debug.DrawRay(origin.transform.position,forward*200,Color.green);
if(Physics.Raycast(transform.position,fwd,hit)){
hitTest=hit.transform.position;
print("Collision with: "+hit.collider.tag);
hitObject.SetActive(true);
hitObject.transform.position= hitTest;
} else {
hitObject.SetActive(false);
}
/////////////// RAYCASTING
}
Answer by Mouton · Jul 03, 2015 at 08:16 AM
You are looking for the position of the hit point: http://docs.unity3d.com/ScriptReference/RaycastHit-point.html
hitTest = hit.point;
Thanks, this worked great! Note for other readers, however, that if the object that moves to the hitpoint has a collider, the object keeps moving towards the camera.
Your answer
Follow this Question
Related Questions
Raycast object as far as possible? 1 Answer
Raycast script help? 1 Answer
(Raycasting) Changing Position 0 Answers
Question about FPS and Raycasting Javascript 2 Answers
Raycast help..... 2 Answers