• 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 /
  • Help Room /
avatar image
0
Question by Allietzuh · Apr 01, 2019 at 03:32 PM · coroutinemovetowards

Movetowards position until new position has been given

Hi all, I am new to unity and hope that I am positing this at the right spot. I have some issues with my player movement. Within the (2D) game, the player is able to move on the x axis. Whenever the player collides with another object, the player will move towards a random position from a list (but is still able to influence the movement with own input from another script). I sort of got it working as the player moves to a random position and has influence. Though, once the given position has been reached, it does not keep moving towards this position til a new collision happened (and with that a new position), which is what I would like to happen. I tried several things such as placing pieces of code elsewhere and a bool to check whether a new position has been given, but I haven't been able to find a solution online so far. I think it has to do with the "while function", but I have no idea what to do differently at this moment. I'm kind of stuck at and would really appreciate any input that could help me to find a solution.

So in short what I need: Collision -> set a target --> move towards target until new collision (even if target has been met in meantime)

Thank you in advance!

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class MoveToTarget: MonoBehaviour
 {
 
     public Vector2 charpos1 = new Vector2(-1.5f, -2.5f);
     public Vector2 charpos2 = new Vector2(-4.5f, -2.5f);
     public Vector2 charpos3 = new Vector2(1.5f, -2.5f);
     public Vector2 charpos4 = new Vector2(4.5f, -2.5f);
 
     public List<Vector2> possiblePositionsVamp;
 
     private Rigidbody2D rb2d;
     public float speed;
     public float newspeed;
     public float newencounterspeed;     
 
     public Transform targetVamp;
 
     public bool craving;
     public bool lastCraving = false;
 
     
     void Start()
     {
         //add to list
         possiblePositionsVamp.Add(charpos1);
         possiblePositionsVamp.Add(charpos2);
         possiblePositionsVamp.Add(charpos3);
         possiblePositionsVamp.Add(charpos4);
     }
 
     // Update is called once per frame
     void Update()
      {
         craving = GameObject.Find("Craving").GetComponent<Craving>().isCraving;
     }
 
 
     void OnTriggerEnter2D(Collider2D other)
     {
         if (other.gameObject.tag.Equals("Blockbar") == true && craving == false)
         {
             //Debug.Log("Collision detected");
           
             StartCoroutine(moveVamp(targetVamp));
         }
    
     }
 
 
     IEnumerator moveVamp(Transform targetVamp)
     {
         //decide on newTarget position for vampire
         
         int randomPosition = Random.Range(0, possiblePositionsVamp.Count);
         Vector2 target = possiblePositionsVamp[randomPosition];
 
 
          while (Vector2.Distance(transform.position, target) > 0.1f)
         {
           
             transform.position = Vector2.MoveTowards(transform.position, target, speed * Time.deltaTime);
           
             yield return null;
 
 
         }
         //print("Reached target");
     }
 
 }
 
 
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 xxmariofer · Apr 01, 2019 at 08:11 PM

not tested but tell me if it works try changing the while to this, and consider using update rather than a corroutine

 while(true)
 {
    transform.position += (target - transform.position).normalized * time.deltaTime * speed;
    yield return null;
 }
Comment
Add comment · Show 4 · 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 Allietzuh · Apr 02, 2019 at 12:32 PM 0
Share

Thank you for your reply @xxmariofer ! If I change the "Vector2 target" to a Vector3 it seems to work at first sight as the player keeps moving towards the target. For some reason however, it does not change the target position anymore in the transform.position. In the debug.log I can see that a new position is generated, but it keeps moving towards the first generated target. In the rare event that it decides to change the target position, it automatically keeps moving towards this position afterwards. Would you happen to have any idea of why this is happening after the change in code?

avatar image xxmariofer Allietzuh · Apr 02, 2019 at 01:44 PM 1
Share

Change all thr while code to the Update event, change the corroutine to a method and create the vector3 target outisde the method and just give it value inside

avatar image Allietzuh xxmariofer · Apr 03, 2019 at 12:28 PM 0
Share

Thank you very much! This made it work exactly as I wanted.

Show more comments

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

176 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

Related Questions

MoveTowards and Lerp not working 1 Answer

Weapon does't meet the target position when using IK 1 Answer

Move object to another position after Mouse Click with MoveTowards function 1 Answer

Changing transform position - from instantaneous to smooth - not sure how. 0 Answers

Using MoveTowards to move GameObject from starting point to mouse cursor 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