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
0
Question by EmeraldMadness · Mar 11, 2017 at 10:05 AM · javascriptjava

Left Click Once, Does An Action, Left Click Again, Does Another Action.,

Hi. I'm trying to make a code that makes it when you left mouse click an object you pick it up, but when you press the left mouse button again you drop the item.

Heres my code:

  var onhand : Transform;
 
  function Update () {
 
  }
 
  function OnMouseDown () {
      GetComponent.<Rigidbody>().useGravity = false;
      GetComponent.<Rigidbody>().constraints = RigidbodyConstraints.FreezePositionX | RigidbodyConstraints.FreezePositionZ | RigidbodyConstraints.FreezePositionY | RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationZ | RigidbodyConstraints.FreezeRotationY;
      this.transform.position = onhand.position;
       this.transform.rotation = onhand.rotation;
      this.transform.parent = GameObject.Find("FPSController").transform;
      this.transform.parent = GameObject.Find("FirstPersonCharacter").transform;
      }
 }


Any help is appreciated!

Comment
Add comment · Show 2
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 Masterio · Mar 11, 2017 at 09:14 PM 0
Share

Add state enum like:

enum State { None = 0, Pick = 1, Drop = 2 }

then on first click change state to Pick and handle it in update, if you click again then change state to Drop and handle it again. After drop handle add change state to None.

avatar image EmeraldMadness Masterio · Mar 11, 2017 at 11:30 PM 0
Share

Thanks! But I'm like really bad when it comes to coding.. Can you show me how you would code it?

  var onhand : Transform;
 
  function Update () {
 
 
  }
 
  enum State { None = 0, Pick = 1, Drop = 2 }
 
  function On$$anonymous$$ouseDown () {
      GetComponent.<Rigidbody>().useGravity = false;
      GetComponent.<Rigidbody>().constraints = RigidbodyConstraints.FreezePositionX | RigidbodyConstraints.FreezePositionZ | RigidbodyConstraints.FreezePositionY | RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationZ | RigidbodyConstraints.FreezeRotationY;
      this.transform.position = onhand.position;
       this.transform.rotation = onhand.rotation;
      this.transform.parent = GameObject.Find("FPSController").transform;
      this.transform.parent = GameObject.Find("FirstPersonCharacter").transform;
      }
 
 
  function On$$anonymous$$ouseUp () {
      this.transform.parent = null;
      GetComponent.<Rigidbody>().useGravity = true;
       GetComponent.<Rigidbody>().constraints = RigidbodyConstraints.None;
  }
   
 

I Added the "enum State { None = 0, Pick = 1, Drop = 2 }" but I don't know what you mean by "change state to Pick and handle it in update". Again, I'm Sorry.

2 Replies

· Add your reply
  • Sort: 
avatar image
1

Answer by Masterio · Mar 12, 2017 at 11:32 AM

Sorry for using c#. I am attaching code and example project :)

 using UnityEngine;
 using System.Collections;
 
 /// <summary>
 /// Mouse picker.
 /// Author: Matthew Mazan [Masterio]
 /// </summary>
 public class MousePicker : MonoBehaviour 
 {
     enum State
     {
         None = 0,
         Pick = 1,
         Drop = 2
     }
 
     private State _state = State.None;
     private GameObject _pickedObject;
     private Vector3 _spawn;                                    // keeps position before object pick
 
     public const float PICK_DISTANCE = 2f;                    // high of the pick
     public const float PICK_SPEED = 10f;                    // pick speed
     public const float DROP_SPEED = 10f;                    // drop speed
     public const string GROUND_LEAYER_NAME = "ground";        // ground layer name
 
 
     void Update()
     {
         // mouse listener
         if(Input.GetMouseButtonDown(0))
         {
             OnMouseClick();
         }
 
         // when object is picked up
         if(_state == State.Pick)
         {
             OnObjectPickUpdate();
         }
         else if(_state == State.Drop)
         {
             OnObjectDropUpdate();
         }
 
     }
 
     public void OnMouseClick()
     {
         // pickup
         if(_state == State.None)
         {
             if(CastOnObject())
             {
                 OnObjectPickEnter();
             }
         }
         // drop
         else if(_state == State.Pick)
         {
             _state = State.Drop;
         }
     }
 
     // f.e. turn off physics, change color, etc.
     private void OnObjectPickEnter()
     {
         _state = State.Pick;
 
         // use to get the y position
         _spawn = _pickedObject.transform.position;
 
         // change color
         MeshRenderer mr = _pickedObject.GetComponent<MeshRenderer>();
         mr.material.color = Color.red;
 
     }
 
     // f.e. turn on physics, change color, etc.
     private void OnObjectDropExit()
     {
         _state = State.None;
 
         // set equal position
         _pickedObject.transform.position = new Vector3(_pickedObject.transform.position.x, _spawn.y, _pickedObject.transform.position.z);
 
         // change color back
         MeshRenderer mr = _pickedObject.GetComponent<MeshRenderer>();
         mr.material.color = Color.white;
 
         // release object handler
         _pickedObject = null;
     }
 
     // f.e. assing the object position to the mouse cursor position.
     private void OnObjectPickUpdate()
     {
         // move object up
         _pickedObject.transform.position = Vector3.Lerp(_pickedObject.transform.position, new Vector3(_pickedObject.transform.position.x, _spawn.y + PICK_DISTANCE, _pickedObject.transform.position.z), Time.deltaTime * PICK_SPEED);
     
         // assing object to the mouse position [x, z only]
         RaycastHit hit;
         
         if(Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 100f, 1 << LayerMask.NameToLayer(GROUND_LEAYER_NAME)))        // you MUST cast on separated layer [iam using ground layer]
         {
             // slowly follow by cursor
             //_pickedObject.transform.position = Vector3.MoveToward(_pickedObject.transform.position, new Vector3(hit.point.x, _pickedObject.transform.position.y, hit.point.z), Time.deltaTime * 10f);
             // or
             // set cursor position
             _pickedObject.transform.position = new Vector3(hit.point.x, _pickedObject.transform.position.y, hit.point.z);
         }
     }
 
     // f.e. place object on map again.
     private void OnObjectDropUpdate()
     {
         // move object down
         _pickedObject.transform.position = Vector3.Lerp(_pickedObject.transform.position, new Vector3(_pickedObject.transform.position.x, _spawn.y, _pickedObject.transform.position.z), Time.deltaTime * DROP_SPEED);
 
         // exit if position y same as spawn y
         if(_pickedObject.transform.position.y <= _spawn.y + 0.1f)
            OnObjectDropExit();
     }
 
     private bool CastOnObject()
     {
         RaycastHit hit;
 
         if(Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit))        // should be casted on separated layer
         {
             // picks only pickable objects [you can add layer or tag checks, if layer is used then remove this "if" condition]
             if(hit.transform.gameObject.name.StartsWith("pickable_"))
             {
                 // temporary keep the object handler
                 _pickedObject = hit.transform.gameObject;
                 return true;
             }
         }
 
         return false;
     }
 
     public GameObject pickedObject 
     {
         get {
             return _pickedObject;
         }
     }
 
 }
 


Project: https://mega.nz/#!b4pBTbYY!ad4daavEQP1oHDXxFU02I7eA5LDMdFtEnZuEah4GSgk

alt text


schowek01.jpg (37.6 kB)
Comment
Add comment · 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
0

Answer by toddisarockstar · Mar 12, 2017 at 12:23 AM

 var onhand : Transform;
  
   function Update () {
  
  
   function OnMouseDown () {
 
 if(transform.parent==null){
 
      rigidbody.useGravity = false;
      rigidbody.constraints = RigidbodyConstraints.FreezePositionX | RigidbodyConstraints.FreezePositionZ | RigidbodyConstraints.FreezePositionY | RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationZ | RigidbodyConstraints.FreezeRotationY;
       transform.position = onhand.position;
        transform.rotation = onhand.rotation;
       transform.parent = GameObject.Find("FPSController").transform;
       transform.parent = GameObject.Find("FirstPersonCharacter").transform;
      
 
  }else{
  
       transform.parent = null;
       rigidbody.useGravity = true;
       rigidbody.constraints = RigidbodyConstraints.None;
 
 }}}
    
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 EmeraldMadness · Mar 12, 2017 at 12:56 AM 0
Share

For some reason, it says "expecting (, found 'On$$anonymous$$ouseDown' " and " ';' expected. Insert a semicolon at the end.".

Thanks Anyways.

avatar image SnStarr EmeraldMadness · Mar 14, 2017 at 07:01 AM 0
Share

Thats because you need a; when setting the enum

ins$$anonymous$$d of

 enum Directions{ North, South, East, West }

you need

 enum Directions{ North, South, East, West };

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

8 People are following this question.

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

Related Questions

Launching a Projectile to a Raycast 1 Answer

Can someone help me fix my Javascript for Flickering Light? 6 Answers

level up script please help 1 Answer

How to move the object at the center of the grid cell? 0 Answers

Need help with enum and stuff (right, left click) in JavaScript 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