Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 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 Jarlarko · Apr 27, 2015 at 01:26 AM · 2drigidbody2daddforcedirectionforcemode

Using direction and Rigidbody2D.AddForce() to move towards object.

Hello!

I've got an issue using the new Rigidybody2D.Addforce function. Im creating a 2d program, and am working on the enemy AI. I'm trying to add force towards the player when they are far away, and away from the player when they are too close. The direction seems to calculate fine and works with lerp (see commented lines) functions, but I need to use a rigidbody2D to simulate colliding and stop things going through walls. Each enemy has a rigidbody2D and circle collider, each with a mass of 1 (I messed around with this number to no avail).

In this current state, the enemies can be pushed around but refuse to be affected by the force that I presume is affecting them.The function below is called in update, and has been attempted from fixed update, with no changes. Thanks for any assistance!

 Vector2 heading = this.transform.position - player.transform.position;
         double distanceVector = heading.magnitude;
 
         //determine direction towards player
         Vector2 dir = player.transform.position-transform.position;
         dir = dir.normalized;
 
         //overlap circle from enemy searching for player
         inRange = Physics2D.OverlapCircle(this.transform.position, 0.5f, 1 << LayerMask.NameToLayer("Player"));
 
         Vector2 lastKnown = Vector2.zero;
 
         //Raycast to nearby player to determine line of sight.
         if(inRange == true)
         {
             Debug.Log("spotted");
             RaycastHit2D hit = Physics2D.Raycast(this.transform.position, dir);
 
             if(hit.collider != null)
             {
                 if(hit.collider.tag == "Player")
                 {
                     //if enemy is out of weapon range and out of retreat range, move towards player
                     if(distance < reference.getAdvanceRange() && distance > reference.getRetreatRange())
                     {
                         //this.transform.position = Vector2.Lerp(new Vector2(transform.position.x, transform.position.y), dir, 0.2f * Time.deltaTime);
                         this.GetComponent<Rigidbody2D>().AddForce(dir, ForceMode2D.Force);
                         Debug.Log("advancing");
                         lastKnown = new Vector2(player.transform.position.x, player.transform.position.y);
                     }
                 
                     //if too close to player, move back
                     else if(distance < reference.getRetreatRange())
                     {
                         //this.transform.position = Vector2.Lerp(new Vector2(transform.position.x, transform.position.y),-dir, 0.2f * Time.deltaTime);
                         this.GetComponent<Rigidbody2D>().AddForce(-dir, ForceMode2D.Force);
                         Debug.Log("Retreating");
                         lastKnown = new Vector2(player.transform.position.x, player.transform.position.y);
                     }
                     lastKnown = player.transform.position - this.transform.position;
                 }
                 else
                 //moves to last known player location
                 //this.transform.position = Vector2.Lerp(new Vector2(transform.position.x, transform.position.y), lastKnown, 0.2f * Time.deltaTime);
                 this.GetComponent<Rigidbody2D>().AddForce(lastKnown, ForceMode2D.Force);
             }
             //handles rotation of enemy
             lookPosition = player.transform.position;
             this.transform.rotation = Quaternion.LookRotation(Vector3.forward, lookPosition - this.transform.position);
         }
 

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
3

Answer by JoeStrout · Apr 27, 2015 at 02:54 AM

The first parameter to AddForce is supposed to be a force vector -- you're passing in a position instead. That doesn't make sense.

If you want to apply a force in the direction of the player, try something like this:

 Vector2 dir = lastKnown - (Vector2)(player.transform.position);
 dir.Normalize();
 GetComponent<Rigidbody2D>().AddForce(dir * 1000, ForceMode2D.Force);

Play with the strength of the force (1000 in the example above) until it seems right.

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

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

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

Rigidbody2D x velocity not moving unless placed in FixedUpdate 1 Answer

Sphere spawn from border in direction (2D) 0 Answers

Adding force to rigidbody2d to slide 1 Answer

How do add force to the left (x-axis) 2 Answers

Problem with 2 Rigidbodies having respective colliders (2d) 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