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 martocapo · Dec 07, 2020 at 02:13 AM · movementmovement scriptmovetowards

Script click to move not working, MoveTowards always move forward

Hello guys, good day! I am trying to create a script that move my player with rigidbody 2d to a specific location selected with the mouse. So far its not working, the ony movement i can see is when i click anywhere the player moves to the right always. can you help me ? See my code: thanks you in advance

 public class ClickToMove2 : MonoBehaviour
 {
     //private float speed = 1100;
     private Vector3 targetPosition;
     private Camera mainCamera;
     [SerializeField] private float movementSpeed;
     Animator Anim;
 
     // Update is called once per frame
     private void Start()
     {
         mainCamera = Camera.main;
         Anim = GetComponent<Animator>();
     }
     void Update()
     {
         if (Input.GetMouseButton(0))
         {
             CalculateTargetPosition();
             MoveToTarget();
         }
         
     }
     void CalculateTargetPosition()
     {
         Vector3 mousePosition = Input.mousePosition;
         mousePosition.z = 10;
         //Debug.Log("Mouse: " + mousePosition);
         Vector3 transformedPosition = mainCamera.ScreenToWorldPoint(mousePosition);
         //Debug.Log("Mouse trans: " + transformedPosition);
         targetPosition = new Vector3(transformedPosition.x, transformedPosition.y, transformedPosition.z);
         //Debug.Log("Mouse target: " + targetPosition);
     }
 
     private void MoveToTarget()
     {
         transform.position = Vector3.MoveTowards(transform.position, targetPosition, Time.deltaTime * movementSpeed);
     }
 }

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

3 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by bayonetBlaster · Dec 07, 2020 at 04:38 AM

Hi, I think using Vector3.Lerp would probably be a better option. You would end up with something like that:

 public IEnumerator LerpController(Vector2 targetPos, float duration)
 {
     float time = 0;
     Vector3 startPos = transform.position;
     while (time < duration)
     {
         transform.position = Vector3.Lerp(startPos, targetPos, time / duration);
         time += Time.deltaTime;
         yield return null;
     }

     transform.position = targetPos;
 }

startPos would be the current position of your object and targetPos would be your mouse position.

You can call it like:

 Vector2 mousePos = Input.mousePosition;
 
 void OnMouseDown()
 {
 StartCoroutine(LerpController(mousePos, .3f));
 }

Here is some more information: https://docs.unity3d.com/ScriptReference/Vector3.Lerp.html

Hope that helps:)

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 martocapo · Dec 07, 2020 at 06:18 PM 0
Share

Its still no working, i just tried. The news is that the character was moving to the right because i added a line (Rb.addforce) yesterday trying to troubleshot the issue, so i removed and now its not doing anything, even with your script suggested. Could it be because i am using Addforce to the Rb for the movement? Here is my code for the movement:

 Vector2 movement = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
         Rb.AddForce(movement * Time.deltaTime * speed2);
         if (Input.GetAxis("Horizontal") > 0)
         {
             Anim.SetTrigger("Right");
         }
         if (Input.GetAxis("Horizontal") < 0)
         {
             Anim.SetTrigger("Left");
         }
         if (Input.GetAxis("Vertical") > 0)
         {
             Anim.SetTrigger("Up");
         }
         if (Input.GetAxis("Vertical") < 0)
         {
             Anim.SetTrigger("Down");
         }

thanks you very much in advance, any suggestion and hint it will be really appreciate it. Best Regards

avatar image
0

Answer by martocapo · Dec 07, 2020 at 05:55 PM

Thanks a lot for you reply, i will definitely give it a try. Best regards

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 fuego_see_money · Dec 07, 2020 at 08:20 PM

Why are you setting the mouseposition to always be 10? This will cause the resulting position to have its z value affected to be 10 every time. Even if this is intended behavior for a 2D game, you should make that a global variable of some kind so its not randomly scattered throughout scripts.

As far as getting intended behavior, why not use Physics.Raycast? This will allow you to specify further down the road of development which objects you want the player to be able to move to and which you don't.

I made a few changes to your script - I added a moveupdate flag that allows a single-click to perpetually update the movement instead of having to hold the mouse button down. I also set targetPosition to equal the object's initial position on Awake().

 public class ClickToMove2 : MonoBehaviour
 {
     // -- serialized attributes
     [SerializeField]
     private bool moveupdate = true;
     [SerializeField] 
     private float movementSpeed;
     [SerializeField]
     private LayerMask hitmask;
     [SerializeField]
     private float maxdist = 100;
 
     // -- private attributes
     private new Camera camera;
     private Vector3 targetPosition;
 
     void Awake()
     {
         targetPosition = transform.position;
     }
 
     void Start()
     {
         camera = Camera.main;
     }
 
     void Update()
     {
         bool holdingmouse = Input.GetMouseButton(0);
         if (holdingmouse)
         {
             CalculateTargetPosition();
             if (!moveupdate)
                 MoveToTarget();
         }
 
         if(moveupdate)
             MoveToTarget();
     }
 
     void CalculateTargetPosition()
     {
         Ray ray = camera.ScreenPointToRay(Input.mousePosition);
         if (Physics.Raycast(ray, out RaycastHit hit, maxdist, hitmask, QueryTriggerInteraction.Ignore))
         {
             targetPosition = hit.point;
         }
     }
 
     private void MoveToTarget()
     {
         transform.position = Vector3.MoveTowards(transform.position, targetPosition, Time.deltaTime * movementSpeed);
     }
 }

[Edit]: Here is a gif link to see the results of my script:

https://media.giphy.com/media/Wtik6Jc8VcYi8jEyk8/giphy.gif

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 martocapo · Dec 07, 2020 at 09:34 PM 0
Share

Thanks you very much for taking the time to rewrite the script. I just checked and for some reason is not working too. I saw you GIF showing that is working but my player use rb and i believe this is the reason why its not working. The game is a 2d multi scene aventure like monkey island and configured a lot of colliders to limit the player to move around. i use for movement the following script:

 void Update()
     {
         Vector2 movement = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
         Rb.AddForce(movement * Time.deltaTime * speed2);
         if (Input.GetAxis("Horizontal") > 0)
         {
             Anim.SetTrigger("Right");
         }
         if (Input.GetAxis("Horizontal") < 0)
         {
             Anim.SetTrigger("Left");
         }
         if (Input.GetAxis("Vertical") > 0)
         {
             Anim.SetTrigger("Up");
         }
         if (Input.GetAxis("Vertical") < 0)
         {
             Anim.SetTrigger("Down");
         }
     }

I configured the camera z in 10 because I saw someone doing it and fix his issue, i am almost new in unity but not as developer, thanks you again and i hope you can show me the way for the solution because this issue is drive me nuts BEst Regards

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

211 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 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

Moving only if straight path dijkstra 1 Answer

Convert WASD to local rotation 1 Answer

Move Character to touched Position 2D (Without RigidBody and Animated Movement) 1 Answer

MoveTowards is moveing my object to random position when i click it is already on a way 1 Answer

Interrupt a MoveTowards when triggering 2 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