- Home /
Placing object with ray cast
I am trying to give a cube the position of a raycast hit(with the mouse pos). But when I connect the cube's position with the ray cast hit point, the cube goes back and forth along the ray's line.
Here is the code of the script that is connected to the cube:
function Update(){
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit)) {
Debug.DrawLine (ray.origin, hit.point);
transform.position=hit.point;
}
}
Answer by Joshua · Apr 24, 2011 at 04:04 AM
Do you have any other forces working on your cube? Because the code looks correct.
Wait, you're line is hitting against something (so it's something with a collider) and you're placing an object there. That won't work because you're placing part of the object inside the collider your ray just hit.. try placing it half the size of the cube in front of it.
Also, you're doing this every frame, try doing it just once when you press a key
Answer by Tom 20 · Apr 24, 2011 at 09:09 AM
When I Erase the: transform.position=hit.point; The debug line works fine, but when I add that row the cube starts going back and forth along the ray, and the debug line is affected as well.
Answer by Tom 20 · Apr 24, 2011 at 09:15 AM
I tryed something like that:
function Update(){
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit)) {
Debug.DrawLine (ray.origin, hit.point);
Debug.Log(hit.point);
var xx=hit.point.x;
var yy=hit.point.y+0.55;
var zz=hit.point.z;
transform.position=Vector3(xx,yy,zz);
}}
And it works, but when i change the 0.55 val, to a lower num, it causes the same problem.
Your answer
Follow this Question
Related Questions
place a object not in a object 0 Answers
Game Object Chains 1 Answer
Having Physics.Raycast rotate with the gameObject 2 Answers