Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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 RgClube · Nov 28, 2020 at 08:49 PM · raycastraycasthit2dinput.mouseposition

Unexpected problems with moving objects with a mouse click.

Hello everyone, I have a script that moves an object to a specific position by clicking on it, but on the first and second mouse clicks, the objects move to the same position but must be in different positions. Here is the code, first part where I determine where the object should go:

 void Update () {
        Debug.Log(NumPos);
          if (Input.GetMouseButtonDown(0))
          {
              Vector2 origin = new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x,
                                           Camera.main.ScreenToWorldPoint(Input.mousePosition).y);
              RaycastHit2D hit = Physics2D.Raycast(origin, Vector2.zero, 0f);
              if (hit.transform.gameObject.tag == "Ball") {
                  if(goFirstPos == false)
                  {
                      NumPos = 0;
                      goFirstPos = true;
                    
                  }
                  else
                  {
                      if(goSecondPos == false )
                      {
                          NumPos =1;
                          goSecondPos = true;
                      }
                      else
                      {
                          if(goThirdPos == false)
                          {
                              NumPos = 2;
                              goThirdPos = true;
                          }
                           else
                          {
                              if(goForthPos == false)
                              {
                                  NumPos = 3;
                                  goForthPos = true;
                              } else
                              {
                                  if(goFivePos == false)
                                  {
                                      NumPos = 4;
                                      goFivePos = true;
                                  } else
                                  {
                                      if(goSixPos == false)
                                      {
                                          NumPos = 5;
                                          goSixPos = true;
                                      }
                                  }
                              }
                          }
                      }
                  }
                
              }
          }
      }

and the second where the movement is applied:

 private bool ballHitted = false;
     BallHit ballHit;
     int i = 7;
  
     // Start is called before the first frame update
     void Start()
     {
         ballHit = FindObjectOfType<BallHit>();
        
     }
  
     // Update is called once per frame
     void Update()
     {
             if(ballHitted)
             transform.position = Vector2.MoveTowards(transform.position, tentacle[i].transform.position, speed * Time.deltaTime);
        
         /* RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
         if(hit.transform.name== "ball")
         {
             Debug.Log("sdds");
         } */
        
     }
     private void OnMouseDown() {
         i = ballHit.NumPos;
         ballHitted = true;
        
     }

By the way, these are two different scripts, the second one is attached to an object

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
0
Best Answer

Answer by highpockets · Nov 29, 2020 at 12:20 AM

Ok there seems to be a lot going on here that could be simplified, but I think your main issue is that you are depending on a OnMouseDown() in the second script and Input.GetMouseButtonDown() on the first. I’m unsure when OnMouseDown() is called, but if it is before Update(), you will not get the changes in your second script, so my thought is that it is an execution order issue. I think your first script should fire an event that the second one listens to and your first script doesn’t seem to need all those Booleans. Consider the following:

 using UnityEngine.Events; // make sure to include events

 [System.Serializable]
 public class MyIntEvent : UnityEvent<int>   {}

 public class BallHit : MonoBehaviour
 {
 
 public MyIntEvent posChangeEvent;
 private int NumPos = 0;
 
 void Start()
 {
     if(posChangeEvent == null)
         posChangeEvent = new  MyIntEvent();
 }
 
 void Update () {
         Debug.Log(NumPos);
           if (Input.GetMouseButtonDown(0))
           {
               Vector2 origin = new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x,
                                            Camera.main.ScreenToWorldPoint(Input.mousePosition).y);
               RaycastHit2D hit = Physics2D.Raycast(origin, Vector2.zero, 0f);
               if (hit.transform.gameObject.tag == "Ball") {
                  NumPos++;
                  posChangeEvent.Invoke(NumPos);
               }
           }
       }
 }

This just adds 1 to NumPos and fires an event with the NumPos. Now just listen for this in your second script. private bool ballHitted = false; BallHit ballHit; int i = 7;

      // Start is called before the first frame update
      void Start()
      {
          ballHit = FindObjectOfType<BallHit>();
          ballHit.posChangeEvent.AddListener(PosChange);
      }
   
      // Update is called once per frame
      void Update()
      {
              if(ballHitted)
              transform.position = Vector2.MoveTowards(transform.position, tentacle[i].transform.position, speed * Time.deltaTime);
      }
      private void PosChange(int num) {
          i = num;
          ballHitted = true;
      }
     void OnDestroy()
     {
         ballHit.posChangeEvent.RemoveListener(PosChange); //avoid memory leaks by removing the event listener.
     }
Comment
Add comment · Show 1 · 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 RgClube · Nov 29, 2020 at 05:38 AM 0
Share

Thank you very much, events are what I needed :) But I still think that I need boolean values, because I planned that the player can destroy 2 identical objects, and the new objects should know where the free position without the object is and move there.

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

195 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 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 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 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 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 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 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 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 avatar image avatar image avatar image

Related Questions

Raycasting in 2D to prevent a player from moving through walls? 1 Answer

RayCast2d Not colliding with objects in other layers 1 Answer

Raycast2D/Line Renderer offset on colliders based on mouse position 0 Answers

My Raycasts seem to sometimes miss 0 Answers

Error with 2D Raycast 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