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 aopp · Nov 27, 2012 at 03:50 PM · 2djavascriptmovementrandom

How to create random movement in 2D

My goal is to have human characters run in a randomly chosen direction (up, down, left, right) and keep going in that direction until they run into something (then they would change direction). Here is what I have for that right now:

 //Decides which direction the humans will run
 function Update() {
 
     var randDir = Random.Range(1,4);
 
     //Right
     if (randDir == 4) {
        person.transform.Translate(-Vector2.right*Hspeed*Time.deltaTime);
     }
 
     //Left
     if (randDir == 3) {
        person.transform.Translate(Vector2.right*Hspeed*Time.deltaTime);
     }
 
     //Up
     if (randDir == 2) {
        person.transform.Translate(Vector2.up*Hspeed*Time.deltaTime);
     }
 
     //Down
     if (randDir == 1) {
        person.transform.Translate(-Vector2.up*Hspeed*Time.deltaTime);
     }
 
 }


This makes the humans basically just shake around. I understand why it does this, but does anybody know what I could do to get going in the right direction?

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

2 Replies

· Add your reply
  • Sort: 
avatar image
2
Best Answer

Answer by AlucardJay · Nov 27, 2012 at 03:50 PM

Pick a direction and keep applying it until it hits a wall. Then when that object collides with a wall, pick another new direction then apply that. Currently you are picking a random direction every Update.

The OnCollisionEnter function first checks for the name of the object you hit. For my example I have used a name check, and the arguement is looking for the name Wall. You also in future may run into problems where the object chooses a direction that is the same as the wall it just hit, and so may never leave the wall. Just be aware of this consideration =]

 var randDir : int = 1;
 
 function Update()
 {
     // movement here
     // ....
     switch( randDir )
     {
         case 1 :
             person.transform.Translate(-Vector2.up*Hspeed*Time.deltaTime);
         break;
         case 2 :
             person.transform.Translate(Vector2.up*Hspeed*Time.deltaTime);
         break;
         case 3 :
             person.transform.Translate(Vector2.right*Hspeed*Time.deltaTime);
         break;
         case 4 :
             person.transform.Translate(-Vector2.right*Hspeed*Time.deltaTime);
         break;
     }
 }
 
 
 function OnCollisionEnter( other : Collision )
 {
     // what did the object just hit?
     Debug.Log( "collided with " + other.collider.gameObject.name );
     
     if ( other.collider.gameObject.name == "Wall" ) // for example wall is called Wall
     {
         randDir = Random.Range(1,5);
     }
 }

Thanks to Wolfram for pointing out my not understanding the question!

  • also note that Random.Range for integers, the highest value is exclusive (not included). This means to return 1,2,3 or 4, you need to use

    randDir = Random.Range(1,5); Debug.Log( "randDir = " + randDir );

http://docs.unity3d.com/Documentation/ScriptReference/Random.Range.html

Returns a random integer number between min [inclusive] and max [exclusive]


original answer :

e.g.

 var timer : float = 0.0;
 var timerMax : float = 1.5;
 var randDir : int = 1;

 function Update()
 {
     if ( timer > timerMax )
     {
         // pick a new direction
         randDir = Random.Range(1,5);
         // make a new random Max time
         timerMax = Random.Range( 0.5, 2.5 );
     }

     // movement here
     // ....
     switch( randDir )
     {
         case 1 :
             person.transform.Translate(-Vector2.up*Hspeed*Time.deltaTime);
         break;
         case 2 :
             person.transform.Translate(Vector2.up*Hspeed*Time.deltaTime);
         break;
         case 3 :
             person.transform.Translate(Vector2.right*Hspeed*Time.deltaTime);
         break;
         case 4 :
             person.transform.Translate(-Vector2.right*Hspeed*Time.deltaTime);
         break;
     }
 }
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
1

Answer by Wolfram · Nov 27, 2012 at 04:06 PM

In your script you choose a new random direction every frame. Instead, what you want is to make randDir global, and only change its value if your character actually collides with an object, using one of the OnCollision...()/OnTrigger...() functions.

Also note your bug concerning Random.Range(), which @Jay Kay explained.

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 AlucardJay · Nov 27, 2012 at 04:51 PM 0
Share

Yeah, sorry. I just re-read the question and don't know where I got change direction after random time from?! Thanks for helping me see my misunderstanding, I shall fix the answer .... Answer is fixed, and upvote to you =]

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

12 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

Related Questions

How to create random movement in 2d 2 Answers

how to move an object in 2D sense its position? 0 Answers

Random Movement : 2d 1 Answer

Moving Player Up and Down in 2D 1 Answer

Why does my enemies' movement change whenever my player moves toward and away from the enemies' current position? 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