- Home /
Click and drag - Object go through other objects when dragging
Hello,
I created a script with which you can drag objects, but when I drag an object it doesn't collide with other objects and go through them... Here's the code:
var speed:float;
var target : Vector3;
var start : Vector3;
private var pos;
var self : GameObject;
var distanceToObject : float = 7.5;
var dragging : boolean = false;
function Start()
{
start = transform.position;
pos = transform.position;
}
function Update ()
{
if(Input.GetMouseButtonDown(0))
{
var ray = Camera.main.ScreenPointToRay(Vector3(Screen.width * 0.5, Screen.height * 0.5, 0.0));
var hit : RaycastHit;
if(Physics.Raycast(ray, hit, distanceToObject))
{
if(hit.collider.gameObject == self)
{
Destroy(self.GetComponent(Rigidbody));
dragging = true;
}
}
}
if(Input.GetMouseButtonUp(0)) {
if(dragging) {
self.AddComponent(Rigidbody);
dragging = false;
}
}
if(dragging) {
pos = Input.mousePosition;
pos.z = 3.5;
pos = Camera.main.ScreenToWorldPoint(pos);
transform.position = Vector3.Lerp(transform.position, pos, speed*Time.deltaTime);
}
}
What should I do?
Also you need to add this if you want it to work right:
function Start() {
Screen.lockCursor = true;
}
Exa$$anonymous$$e the standard DragRigidbody.js script. If you don't have it you can get it by:
Assets > Import Package > Scripts
After you do the Import Package, type DragRigidbody in the search field at the top of the Project window...or you can just create a game object and then click on the Add Component button and add the DragRigidbody script to a game object. You will want to copy the code to a new file before you start modifying so that you have the original file with the original name available.
Answer by Anxo · Apr 11, 2014 at 06:49 PM
When ever you set transform.position, you are telling it it should be there in absolute terms, you are not telling it to move in a direction or anything like that, you are telling it where its position should be so it will not care about collisions.
If you have a rigidbody and collider on the object, you can use rigidbody.velocity to move it to your mouse but it will not go through object.
Thank you very much, but i am just going to put the Drag Rigidbody script =)
Your answer
Follow this Question
Related Questions
Scene and hierarchy suddenly empty 0 Answers
Unity 2D Character controller bug problem 0 Answers
Unity Backdating itself 0 Answers
Normal map color change problem. BUG? 1 Answer
A node in a childnode? 1 Answer