- Home /
OnMouseDrag, object getting dragged goes through collider instead of stopping
i need some help, when i use OnMouseDrag and move an object, it goes right through objects. i have looked up tutorials to fix this but my code is slighlty diffrent (it uses grid locks and no Y value)
please help ^>^
using System.Collections; using System.Collections.Generic; using UnityEngine;
[RequireComponent(typeof(BoxCollider))] [RequireComponent(typeof(MeshRenderer))]
public class MoveBuilding : MonoBehaviour {
Vector3 screenPoint, offset, scanPos, curPosition, curScreenPoint;
float PosY;
public float gridSize = 1;
// public GameObject Selected; // public GameObject Base; // public GameObject Arrows; void OnMouseDown() { //Arrows.SetActive(true); // GameObject.FindGameObjectWithTag("MainCamera").GetComponent().enabled = false; // GameObject.FindGameObjectWithTag("MainCamera").GetComponent().enabled = true; // Selected.SetActive(true); PosY = this.gameObject.transform.position.y; scanPos = gameObject.transform.position; screenPoint = Camera.main.WorldToScreenPoint(scanPos); offset = scanPos - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z)); } private void OnMouseUp() { // Arrows.SetActive(false); // GameObject.FindGameObjectWithTag("MainCamera").GetComponent().enabled = true; // GameObject.FindGameObjectWithTag("MainCamera").GetComponent().enabled = false;
}
void OnMouseDrag()
{
curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
curPosition.x = (float)(Mathf.Round(curPosition.x) * gridSize);
curPosition.z = (float)(Mathf.Round(curPosition.z) * gridSize);
curPosition.y = PosY;
transform.position = curPosition;
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612124330im_/https://answers.unity.com/themes/thub/images/avi.jpg)