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 /
  • Help Room /
avatar image
1
Question by Temseii · Aug 31, 2016 at 05:23 PM · collider2daddforcetransform.positionvector3.lerp

Moving an object to a random position between two objects

Hello,

I have a set of enemies currently moving to a set object. This object is on the far left of my game, and another object is at the far left. How could I make the enemies individually move to a random spot between these objects? This is my current code for their movement;

  void Update() {
           transform.position = Vector3.Lerp(startingPos, endingPos,
           Mathf.SmoothStep(0f,1f, Time.time/secondsForOneLength));
  }

Also, for some reason while using the above code my collider isn't applying the AddForce I've set to it. If I remove the code for their movement, it'll work just fine.

Here's the code for my collider;

 void OnTriggerEnter2D(Collider2D other) {
     if (other.gameObject.tag == "Enemy") {
         other.GetComponent<Rigidbody2D>().AddForce(new Vector2(speed, speed));            
         }           
 }

Been struggling with this for some hours now. Any help much appreciated!

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

Answer by mj321 · Aug 31, 2016 at 05:48 PM

Suppose your two points are p0 and p1, use this:

 Vector3 v = p1 - p0;
 Vector3 target_position = p0 + Random.value * v;

v is the vector that goes from p0 to p1. By multiplying that vector with a value between 0 and 1 you choose a random point between p0 and p1.

Comment
Add comment · Show 13 · 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 Temseii · Aug 31, 2016 at 05:56 PM 0
Share

Hmm, didn't seem to make a difference. The objects are still moving to the first target point. Here's what I have:

 public Transform farEnd;
 public Transform farEnd2;

 void Start() {
          endingPos = farEnd.position;
          endingPos1 = farEnd2.position;
 
      }

 void Update() {        
         transform.position = Vector3.$$anonymous$$oveTowards(transform.position, endingPos, movementSpeed * Time.deltaTime);
 
         Vector3 v = endingPos1 - endingPos;
         Vector3 randomPoint = endingPos + Random.value * v;
 }



avatar image mj321 Temseii · Aug 31, 2016 at 06:01 PM 1
Share

You need to set the position to the new calculated vector, randomPoint.

avatar image Temseii mj321 · Aug 31, 2016 at 06:54 PM 0
Share
  Vector3 v = endingPos1 - endingPos;
 
 transform.position = Vector3.$$anonymous$$oveTowards(transform.position, endingPos + Random.value * v, movementSpeed * Time.deltaTime);

Should that be fine? It's getting closer to the goal but not quite working as intended yet. The objects are going to the same area (a real small one in the middle of the x axis) and just end up shaking there next to eachother.

Show more comments
avatar image Temseii · Aug 31, 2016 at 09:32 PM 0
Share

Your script works wonderfully! Thank you so much. Some of it goes a bit over my understanding though, would love to get some insight on the technical side if you don't $$anonymous$$d!

The GameObject we're instantiating is to create temporary "clones" out of the object we drag into the source slot, right? W

What exactly is the StartCoroutines purpose in the script and when would you want to use it in general?

Thanks again!

EDIT: Also, where should I modify their movement speed? Running into issues when I try to implement it

avatar image mj321 Temseii · Aug 31, 2016 at 09:43 PM 1
Share

The GameObject we're instantiating is to create temporary "clones" out of the object we drag into the source slot, right?

Yes.

What exactly is the StartCoroutines purpose in the script and when would you want to use it in general?

When you use a Coroutine, the calling function (StartCoroutine()) returns immediately, but the Coroutine itself continues to work in the background until it's done. It makes it easier to write code that needs to do some work over a longer period of time. In this example, it slowly moves the object from one position to another, then waits 3 seconds, and then destroys the object. If you wanted to do this inside Update() you'd need several variables and flags to keep track of everything.

However, a Coroutine does not run in another thread, so it needs your cooperation to do its work. You need to call "yield return null;" inside the loop. This will wait one frame and then continue where it left off.


(FFS i hate this text editor. Why can't i have line breaks where i want them??)

avatar image Temseii mj321 · Aug 31, 2016 at 09:55 PM 0
Share

Thanks! Really appreciate your help man.

Just a few more things..

Where should I modify their movement speed? Running into issues when I try to implement it in the script.

It seems that their movement is locked until they get to their target position. I want to be able to interrupt their movement with a collider. How could this be accomplished?

avatar image mj321 Temseii · Aug 31, 2016 at 09:56 PM 1
Share

Also, where should I modify their movement speed? Running into issues when I try to implement it

 StartCoroutine( $$anonymous$$oveObjectToPosition(newobject.transform, target_position, 1.0f) );

The last parameter (1.0f) is the duration in seconds. If you want the transition to be faster, just set 0.3 seconds for example.

avatar image Temseii mj321 · Aug 31, 2016 at 10:41 PM 0
Share

Seems I can make it faster but not slower by modifying that number. What I noticed though, is that while their movement speed to the target doesn't change if I set it to 3f for example, but if I trigger a collider on them it'll take 3 seconds for it to activate.

Show more comments
Show more comments
avatar image mj321 Temseii · Aug 31, 2016 at 11:52 PM 1
Share

The Coroutine doesn't know anything about colliders or anything else happening "outside". It just updates the object's position until it's done. If you want to abort it, you have two options:

a) Add an "abort" flag to the script that you set when a collision or anything else occurs. And inside the coroutine you check the flag and exit when it's set.

b) Just call StopAllCoroutines() which will stop the Coroutine immediately

avatar image Temseii mj321 · Sep 01, 2016 at 12:58 AM 0
Share

Got it working as I hoped for :) thanks again for your help, would've been stuck with this for a long time if it wasn't for you! Learned many new things too.

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

3 People are following this question.

avatar image avatar image avatar image

Related Questions

Colliders not working 2 Answers

Convert transform.position to Force 0 Answers

My transform.localScale = Vector3.Lerp isnt working. 0 Answers

how to fire my player out of a Cannon? 0 Answers

Stop transform.position by collider 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