Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 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
0
Question by Funlamb · Mar 15, 2015 at 02:30 AM · c#addforcemousedrag

Moving GameObject with Add force and mouse drag

Imgur

The picture above is what I am trying to accomplish. I want the player to be able to drag their finger and move the object around. Once the finger is removed I would like the object to keep moving. How would I do something like this? I don't know what is involved so I don't really know where to start. Even just a list of things to do with out code would be helpful because I don't know where to start.

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

2 Replies

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

Answer by Funlamb · Mar 16, 2015 at 02:22 AM

So I feel like I noted it pretty well. It was just as easy as just setting the gameObjest.rigidBody.velocity to the force that is found through the two points of the mouse.

     public Vector3 gameObjectSreenPoint;
     public Vector3 mousePreviousLocation;
     public Vector3 mouseCurLocation;
     void OnMouseDown()
     {
         //This grabs the position of the object in the world and turns it into the position on the screen
         gameObjectSreenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
         //Sets the mouse pointers vector3
         mousePreviousLocation = new Vector3(Input.mousePosition.x, Input.mousePosition.y, gameObjectSreenPoint.z);
     }
 
     public Vector3 force;
     public Vector3 objectCurrentPosition;
     public Vector3 objectTargetPosition;
     public float topSpeed = 10;
     void OnMouseDrag()
     {
         mouseCurLocation = new Vector3(Input.mousePosition.x, Input.mousePosition.y, gameObjectSreenPoint.z);
         force = mouseCurLocation - mousePreviousLocation;//Changes the force to be applied
         mousePreviousLocation = mouseCurLocation;
     }
 
     public void OnMouseUp()
     {
         //Makes sure there isn't a ludicrous speed
         if (rigidbody.velocity.magnitude > topSpeed)
             force = rigidbody.velocity.normalized * topSpeed;
     }
 
     public void FixedUpdate()
     {
         rigidbody.velocity = force;
     }
Comment
Add comment · Show 2 · 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 Thernos · May 14, 2018 at 03:50 AM 0
Share

Thank you for the script! A couple of things, though:

1) When throwing an object upwards, there are no physics that cause it to lose rigidbody.velocity.y, so it ascends to infinity. This is easily solved by including this:

 void Update () {
     if (force.y > 0.0f) {
         force.y -= 0.1f;
     }

2) Recently rigidbody.velocity has been phased out and must be replaced with GetComponent<Rigidbody>().velocity.

3) I don't know why, but this script causes gameobjects to descend incredibly slowly.

Have an updated script with anti-ascension protection:

     // Use this for initialization
     void Start () {
         
     }
 
     // Update is called once per frame
     void Update () {
     //This prevents your thrown object from ascending to infinity and beyond. Disable if you're trying to throw Buzz Lightyear.
     if (force.y > 0.0f) {
         force.y -= 0.1f;
     }
     }
 public Vector3 gameObjectSreenPoint;
 public Vector3 mousePreviousLocation;
 public Vector3 mouseCurLocation;
 void On$$anonymous$$ouseDown() {
     //This grabs the position of the object in the world and turns it into the position on the screen
     gameObjectSreenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
     //Sets the mouse pointers vector3
     mousePreviousLocation = new Vector3(Input.mousePosition.x, Input.mousePosition.y, gameObjectSreenPoint.z);
 }
 
 public Vector3 force;
 public Vector3 objectCurrentPosition;
 public Vector3 objectTargetPosition;
 public float topSpeed = 10;
 void On$$anonymous$$ouseDrag() {
     mouseCurLocation = new Vector3(Input.mousePosition.x, Input.mousePosition.y, gameObjectSreenPoint.z);
     force = mouseCurLocation - mousePreviousLocation;//Changes the force to be applied
     mousePreviousLocation = mouseCurLocation;
 }
 
 public void On$$anonymous$$ouseUp() {
     //$$anonymous$$akes sure there isn't a ludicrous speed
     if (GetComponent<Rigidbody>().velocity.magnitude > topSpeed)
         force = GetComponent<Rigidbody>().velocity.normalized * topSpeed;
 }
 
 public void FixedUpdate() {
     GetComponent<Rigidbody>().velocity = force;
 }


avatar image Jslonim · Oct 19, 2020 at 09:25 PM 0
Share

The object falls super slow, I made this version that let's go of the object after release

private Rigidbody2D rigidbody; public Vector3 gameObjectSreenPoint; public Vector3 mousePreviousLocation; public Vector3 mouseCurLocation; private Vector3 offset; private bool isDragging = false;

 public Vector3 force;
 public float topSpeed = 50;

 private void Start()
 {
     rigidbody = GetComponent<Rigidbody2D>();
 }

 void On$$anonymous$$ouseDown()
 {
     //This grabs the position of the object in the world and turns it into the position on the screen
     gameObjectSreenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
     //Sets the mouse pointers vector3
     mousePreviousLocation = new Vector3(Input.mousePosition.x, Input.mousePosition.y, gameObjectSreenPoint.z);
     offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, gameObjectSreenPoint.z));
 }

 void On$$anonymous$$ouseDrag()
 {
     mouseCurLocation = new Vector3(Input.mousePosition.x, Input.mousePosition.y, gameObjectSreenPoint.z);
     force = mouseCurLocation - mousePreviousLocation;//Changes the force to be applied
     mousePreviousLocation = mouseCurLocation;
     Vector3 curPosition = Camera.main.ScreenToWorldPoint(mouseCurLocation) - offset;
     transform.position = curPosition;
     isDragging = true;
 }

 public void On$$anonymous$$ouseUp()
 {
     //$$anonymous$$akes sure there isn't a ludicrous speed
     if (rigidbody.velocity.magnitude > topSpeed)
         force = rigidbody.velocity.normalized * topSpeed;

     isDragging = false;
 }

 public void FixedUpdate()
 {
     if (isDragging)
     {
         rigidbody.velocity = force;
     }
 }
avatar image
1

Answer by Denvery · Mar 15, 2015 at 09:32 PM

I think you need to do 2 main things: 1. Checking the drag and moving objects with the finger 2. Check if finger is up and adding the Force to the GameObject.

May be your simplest solution's Update() can look like this:

         bool _touchBegan = false;
         private void Update()
         {
             if (Input.touchCount <= 0)
             {
                 return;
             }
 
             Touch currentTouch = Input.GetTouch(0);
             Vector2 currentTouchPosition = currentTouch.position;
             Vector3 touchPointInWorld = Camera.main.ScreenToWorldPoint(new Vector3(currentTouchPosition.x, currentTouchPosition.y));
             
             if (currentTouch.phase == TouchPhase.Began && _spriteRenderer.bounds.Contains(touchPointInWorld) && !_touchBegan)
             {
                 _touchBegan = true;
                 return;
             }
            
             if (currentTouch.phase == TouchPhase.Moved && _touchBegan)
             {
                 transform.localPosition = Camera.main.ScreenToWorldPoint(new Vector3(currentTouchPosition.x, currentTouchPosition.y));
                 return;
             }
             
             if (currentTouch.phase == TouchPhase.Ended || currentTouch.phase == TouchPhase.Canceled && _touchBegan)
             {
                 //AddForce
                 _touchBegan = false;
                 return;
             }
         }


So you should to attach this script to the object which you want to drag.

_spriteRenderer.bounds.Contains(touchPointInWorld) - checking if the touch's point in inside the bounds of you gameObject (in my case it is gameObject with SpriteRenderer, i.e. Unity 2d sprite).

//AddForce - this means that in this moment finger is Up and you may to add force by rigidbody.AddForce(...) or in the other way.

So it is the simplest solution, I hope this lines are readable and I hope they will help you:)

Comment
Add comment · Show 3 · 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 Funlamb · Mar 15, 2015 at 10:50 PM 0
Share

This is a great start. I need to change this to get used by the mouse for now. Should I mark this as the correct answer now or get it to work first then mark it as correct?

avatar image Funlamb · Mar 16, 2015 at 02:22 AM 0
Share

Thanks you got me in the right direction. I'll be referring to this when I need to get this on a phone and need to base the inputs on touch.

avatar image Denvery · Mar 16, 2015 at 12:31 PM 0
Share

I'm glad that you've find nice solution for mouse. (I understood that you need this on a phone because you've wrote about fingers:)

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

24 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

Move Physics2D Object With Mouse Using AddForce? 0 Answers

How to aim a ball with cross hair? 2 Answers

How to use addforce after animation? 1 Answer


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