• 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 Cookiemonster04 · Apr 08, 2020 at 10:06 PM · vector3movetowards

how to move towards a random position above the current position?

Hello, I have a gameobject that when it collides with something for it to move towards a position. but I would like it to move towards a random position (which is in this script "rightpos") higher than the gameobject current position. How would I go about doing this?

 Vector3 rightpos;
 public bool justonce;
 public int numb;
 public float speed;

 void Update()
 {
     (!justonce)
     {
         rightpos = Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, Random.Range(0 + 200f, Screen.height - 200f)));
          justonce = true;
     }

     if(numb == 1)
     {
         transform.position = Vector2.MoveTowards(transform.position, rightpos, speed * Time.deltaTime);
     }
 }

 void OnCollisionEnter2D(Collision2D col)
 {
     if(col.gameobject.tag == "Border")
     {
         justonce = false;
         numb = 1;
     }
 }
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

Answer by Eldoir · Apr 09, 2020 at 08:54 AM

Hi,

I assume you're making a 2D game since i can read OnCollisionEnter2D. Camera.main.ScreenToWorldPoint is probably not the way to go.

Here is what I would do, and you'll find little notes below.

  Vector3? rightpos = null;
  public float speed;
  private string borderTag = "Border";


  void Update()
  {
      if (rightpos != null)
      {
          transform.position = Vector2.MoveTowards(transform.position, rightpos, speed * Time.deltaTime);
      }
  }


  void OnCollisionEnter2D(Collision2D col)
  {
      if (IsBorder(col.gameobject))
      {
         rightpos = GetRandomPositionAbovePlayer(1f);
      }
  }


 void OnCollisionExit2D(Collision2D col)
  {
      if (IsBorder(col.gameobject))
      {
         rightpos = null;
      }
  }


 bool IsBorder(GameObject go)
 {
     return go.tag == borderTag;
 }


 Vector2 GetRandomPositionAbovePlayer(float offsetY)
 {
     return GetRandomPositionAbove(transform, offsetY);
 }


 Vector2 GetRandomPositionAbove(Transform transform, float offsetY)
 {
     Vector2 randomPosition = GetRandomPosition();
     randomPosition.y = Mathf.Abs(randomPosition.y);

     return transform.position + randomPosition + Vector2.up * Mathf.Abs(offsetY);
 }


 Vector2 GetRandomPosition()
 {
     return new Vector2(Random.Range(-1f, 1f), Random.Range(-1f, 1f));
 }

  • I used Vector3? instead of Vector3. This is called a nullable type. You can use it on every variable type you want. It has all of the properties of the type, be it can be assigned the null value. Here, I find it practical because it avoids having 2 variables (one for the position, and one boolean to know if the position has been set).

  • I added an OnCollisionExit2D that sets the position to null so that if the object leaves the collider, it no longer moves. I don't know if that's what you want, but it illustrates my previous point; I can set rightpos to null.

  • I put the border tag at the beginning of the script so if one day it has changed, you don't have to scroll through the script to find the hardcoded value in the middle of something. It also avoids human errors, because having to type "Border" each time you want to check the tag of a GameObject is error-prone.

  • I added an IsBorder method so if one day you change the way you decide what is a border and what is not, you just have to do that in there and not in other random places of the code.

  • The GetRandomPositionAbove uses Mathf.Abs so that even if you input a negative value as the offsetY argument, it still considers it a positive value. The method name contains "Above" so it has to do what it says and can't return a position below.

  • You can see that GetRandomPositionAbovePlayer calls GetRandomPositionAbove, which is directly below, and GetRandomPosition which is again directly below. That way, we you read the script, it reads like a story: you read from top to bottom, and the implementation details appear one by one. Once you've found what you were looking for, you know you don't have to read further to be sure you've not missed something important. This technique is called "The stepdown rule".

  • More generally, I like keeping my methods short so the whole system is easier to read and to debug. Plus, it adds extra functionality that you could need later in the development.

Hope this helps!

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 Cookiemonster04 · Apr 10, 2020 at 07:19 PM 0
Share

Hello, sorry for the late response didn't think anyone answered, but I tried this method & was not quite what I expected, the "rightpos" position is anywhere on the right side of the screen & I needed a gameobject to move towards "rightpos" but above where the gameobject current position is.

avatar image Eldoir Cookiemonster04 · Apr 13, 2020 at 09:57 AM 0
Share

Oh, ok :) Then I guess you just have to keep your original instruction when initialising rightpos, and the rest still makes sense!

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

154 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

Related Questions

conserve momentum of vector3.moveTowards in 2D game 0 Answers

MoveTowards inside Coroutine 2 Answers

Vector3.MoveTowards MaxDistanceDelta value 2 Answers

Vector3.MoveTowards and Quaternion.RotateTowards 1 Answer

How to move character a certain amount? 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