Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
2
Question by pcote · Jul 27, 2011 at 07:44 PM · javascriptraycastcolliderdrag

How to block dragging if collider hits

Hello,

I've been searching for a method to restrict a mouse drag when it collides with another object without using a RigidBody and everything I tried resulted in failure (the block I'm dragging goes straight through the others). I tried with OnCollisionEnter and with a Raycast and both aren't working... my brain is about to explode. (T_T)

Also, what is the lightest method to do this kind of thing on iPhone ?

Thank you very much.

Phil

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
6
Best Answer

Answer by aldonaletto · Jul 28, 2011 at 01:58 AM

If the objects you want to drag can be rigidbodies, move them by setting the velocity, not the position - it allows the object to respect collisions.
The script below picks a rigidbody when the left mouse button is pressed, and drags it while the button is pressed. Instead of setting the object position, the script calculates the difference between mouse and object positions, and apply a proportional velocity to the object. Velocity is limited to maxSpeed to avoid the object to pass through thin objects. speed is a speed factor which controls how fast the rigidbody will follow the mouse pointer.

var speed: float = 5; // speed factor var maxSpeed: float = 15; // speed limit private var dragObj: Transform = null; private var hit: RaycastHit; private var length: float;

function Update(){

 if (Input.GetMouseButton(0)){  // if left mouse button pressed...
     // cast a ray from the mouse pointer
     var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
     if (!dragObj ){  // if nothing picked yet...
         // and the ray hit some rigidbody...
         if (Physics.Raycast(ray, hit) && hit.rigidbody){
             dragObj = hit.transform;  // save picked object's transform
             length = hit.distance;  // get "distance from the mouse pointer"
         }
     } 
     else {  // if some object was picked...
         // calc velocity necessary to follow the mouse pointer
         var vel = (ray.GetPoint(length) - dragObj.position) * speed; 
         // limit max velocity to avoid pass through objects
         if (vel.magnitude > maxSpeed) vel *= maxSpeed / vel.magnitude;
         // set object velocity
         dragObj.rigidbody.velocity = vel;
     }    
 }
 else {  // no mouse button pressed
     dragObj = null;  // dragObj free to drag another object
 }

}

EDITED: This is a CharacterController version. It uses no gravity, and the objects stay at the position you release them.

var speed: float = 10; // speed private var dragObj: Transform = null; private var hit: RaycastHit; private var length: float; private var character: CharacterController;

function Update(){

 if (Input.GetMouseButton(0)){  // if left mouse button pressed...
     // cast a ray from the mouse pointer
     var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
     if (!dragObj ){  // if nothing picked yet...
         // and the ray hit some character...
         if (Physics.Raycast(ray, hit)){
             character = hit.transform.GetComponent(CharacterController);
             if (character){
                 dragObj = hit.transform;  // save picked object's transform
                 length = hit.distance;  // get "distance from the mouse pointer"
             }
         }
     } 
     else {  // if some object was picked...
         // calc mouse pointer displacement
         var mov = ray.GetPoint(length) - dragObj.position; 
         // set object velocity
         character.Move(mov * speed * Time.deltaTime);
     }    
 }
 else {  // no mouse button pressed
     dragObj = null;  // dragObj free to drag another object
 }

}

Comment
Add comment · Show 5 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image pcote · Jul 28, 2011 at 02:07 AM 0
Share

Thank you very much for your answer!! :) Is this kind of behavior possible without using any RigidBodies or it HAS TO go through with it ? I'm using BoxColliders everywhere and there is no use of physics whatsoever. It's a block puzzle game. :) Can I target a collider ins$$anonymous$$d ?

avatar image aldonaletto · Jul 28, 2011 at 04:44 AM 0
Share

You can use the CharacterController ins$$anonymous$$d of a rigidbody. It uses no physics, but recognizes colliders. If your game is 2D, it must run on the XZ plane, since the CharacterController supposes Y is the vertical direction. Just add the CharacterController and it will substitute the collider. I edited my answer to include a CharacterController version.

avatar image pcote · Jul 28, 2011 at 03:43 PM 0
Share

Aww... crap. $$anonymous$$y game is 2D indeed and runs on the XY plane. I'll try to figure a way around that... I'll tell you if I succeed. Thanks.

avatar image pcote · Jul 28, 2011 at 05:46 PM 0
Share

Well, I tried the second solution on a brand new scene to test on the XZ plane and when I click/drag the block, it doesn't move at all. Wouldn't ray casting and measuring distance be a good way to do it ? EDIT: Isn't it what you are doing ? :)

$$anonymous$$y initial logic was to do something like this: On$$anonymous$$ouseDown $$anonymous$$esure the Length of Starting point and Collision Point (on both left and right since my game slides blocks only horizontally) then clamp the $$anonymous$$in / $$anonymous$$ax values. I succeeded on clamping with my play field so far but don't have any clue on how to accurately measure the distance of the Raycast until it collides (an do it maybe just once at the beginning to make sure the clamp is precise ?).

Do you think this would be a good way to do it ?

EDIT: I'll try with the RigidBody and lock all position / rotation then destroy the RigidBody once the object is in place.

SECOND EDIT: Your first script works great with 3D cubes but doesn't work well with 2D sprites. $$anonymous$$y sprites are all having BoxColliders. Also, like I said previously, I succeeded into restricting the blocks' movement by clamping an X value (X values of the playfield). I think my problem is different than my question... Thanks for helping me! :)

avatar image Robby-rEINEWALD · May 28, 2015 at 02:30 AM 0
Share

How can I make it to multi touch script ? so different fingers will drag different object.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

3 People are following this question.

avatar image avatar image avatar image

Related Questions

Bomberman like explosion 0 Answers

Accessing colliders, in if statement 2 Answers

How do I register damage from the actual sword? not Raycast 1 Answer

Click&Drag Misterious Disappearing! 1 Answer

Trouble with RayCast, rigid body and the colliders tag 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges