- Home /
Game Object flies out of screen when dragged
Why is my object flying into the screen when I drag it? It will start off in the correct mouse to world pos correctly, but fly through the screen repeatedly while I hold it to drag. How do I stop making it do that? thanks
function OnMouseDrag(){
var hit: RaycastHit;
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, hit)){
gameObject.transform.position = hit.point;
}
}
Answer by kolban · Apr 28, 2012 at 03:53 AM
It sounds to me like you want to use a code fragment as follows:
var distance:float = Vector3.Distance(Camera.main.transform.position, gameObject.transform.position);
gameObject.transform.position = Camera.main.ScreenToWorldPoint(Vector3(Input.mousePosition.x, Input.mousePosition.y, -distance));
It is not clear to me that you want to use Raycasting. Rather, what you want to do is convert a screen coordinate to a world coordinate.
I don't even know how to describe what happened when I tried that code- but it didn't work properly. I tried to restrict only the objects x & z axis by replacing transform.position = hit.point; with (transform.position.x= hit.point.x; && transform.position.z= hit.point.z;) and it stopped flying towards the screen, but now its movements are erractic and choppy.
Your answer
![](https://koobas.hobune.stream/wayback/20220613070840im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Fire weapon from turret to mouse position (3D Isometric shooter) 1 Answer
Drag Object Via Axis Handles 0 Answers
Checking if mouse dragged from one point to another 2 Answers
GameObject Moving Slow when drag with hand 0 Answers
Raycast To Collect Items 0 Answers