- Home /
Wrote a script to pick up objects detected by raycast, but they are dropping unexpectedly.
The camera in my scene is stationary, and I want to be able to pick up objects that spawn and move them by dragging them with the mouse. It is working for the most part, except that the objects randomly drop while the mouse button is still being held.
{
public Camera gameCamera;
void Update()
{
Ray ray = gameCamera.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo) && Input.GetMouseButton(0) && hitInfo.collider.gameObject.CompareTag("MoveableObject"))
{
hitInfo.collider.gameObject.transform.position = gameCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 8));
}
}
}
Here is what it looks like when playing:
Answer by VioletAbstract · Mar 03 at 11:13 PM
The issue is that you are moving the mouse too fast, so for a frame, the raycast no longer hits the box, and you drop it. An easier way to solve this is to create a script and attach it to the GameObjects you want to move. Using Unity's OnMouseDown and OnMouseUp, we can "select" the object without the need for a raycast.
using UnityEngine;
public class MoveableObject : MonoBehaviour
{
private bool objectSelected;
private void OnMouseDown()
{
objectSelected = true;
}
private void OnMouseUp()
{
objectSelected = false;
}
void Update()
{
if (objectSelected)
{
transform.position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 8));
}
}
}
Your answer
Follow this Question
Related Questions
Help with FOV script 1 Answer
Diagonal Raycasting to detect platform returns true, even when false 1 Answer
camera.ScreenPointToRay always has same origin... 1 Answer
Why doesn't Physics.Raycast(ray, RaycastHit, distance) work? 1 Answer
Help Playing "Sound Clip" on RayCastHit? (RayCast help?) 2 Answers