- Home /
2D Rigidbody Drag with Mouse
Hi, I'm trying to drag a rigidbody in 2D space, which works perfectly with this script I found and tweaked on the forums. What I'm trying to accomplish however, is that the rigidbody being dragged, 'stops' at collision. Let's say for example, if the rigidbody is dragged into a wall, it will pass right through... I want it to just stay at that location until the mouse is once again in a reachable area.
I already made a variable that checks if the object is touching or not, I access it through a different script.
This is the script I'm currently using. Anyone has any suggestions?
#pragma strict
// Attach this script to an orthographic camera.
var touching = false;
private var object : Transform; // The object we will move.
private var offSet : Vector3; // The object's position relative to the mouse position.
function Update () {
print(touching);
var ray = camera.ScreenPointToRay(Input.mousePosition); // Gets the mouse position in the form of a ray.
if (Input.GetButtonDown("Fire1")) { // If we click the mouse...
if (!object) { // And we are not currently moving an object...
var hit : RaycastHit;
if (Physics.Raycast(ray, hit, Mathf.Infinity)) { // Then see if an object is beneath us using raycasting.
object = hit.transform; // If we hit an object then hold on to the object.
offSet = object.position-ray.origin; // This is so when you click on an object its center does not align with mouse position.
}
}
}
else if (Input.GetButtonUp("Fire1")) {
object = null; // Let go of the object.
}
if (object) {
object.position = Vector3(ray.origin.x+offSet.x, ray.origin.y+offSet.y, object.position.z); // Only move the object on a 2D plane.
}
}