• 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
Question by code-blep · Dec 02, 2012 at 04:26 PM · physicsvector3addforcemoverange

Advice on keeping distance using AddForce

Hi,

I have 2 objects which both move in 3D space. I was using transform position, but I am now converting to Physix for a more realistic movement and collisions.

I have all the Vector3 positions working, and the detection of distance etc to trigger the movements. So for example if not in range, trigger code to move closer to the object until it is. The same goes if an object is too close. If it is move away until the min distance value is met.

What I am investigating before I jump into the conversion, is the best way to implement the Physics based movement.

  1. Is there a way to AddForce in the direction of a Vector3? Most examples that I find are more focused on player control. Would it be best to have the rigidbody transform rotate in the direction of the object I want to move closer to then AddForce until in range?

  2. The other question is how would I go about about moving in the opposite direction to move away. If the rigidbody transform is pointing at the object I want to move away from (as theorised above) can I apply a negative force to move to move in the opposite direction? Or would it just be best to invert the transform while the object is too close?

Everything is written in UnityScript.

I hope this makes sense ;)

Thanks

Paul

Comment

People who like this

0 Show 2
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 DavidDebnar · Dec 02, 2012 at 08:43 PM 0
Share

Hey, this probably won't cover all your questions, but here it is. I'm assuming you want an enemy to chase the player. If this works, just tell me and I'll convert this into an answer.

 var enemyRigidbody : Rigidybody;
 var playerTransform : Transform;
 var distance : float = 3;
 var speed : float = 5;
 
 function FixedUpdate () {
    var pPos : Vector3 = playerTransform.position;
    var ePos : Vector3 = enemyRigidbody.transform.position;
 
    var curDist : float = Vector3.Distance(ePos,pPos);
 
    enemyRigidbody.AddForce(((curDist > 10)?(pPos-ePos):(ePos-pPos)).normalized*speed/*,ForceMode.Force*/);
 }

-- David

avatar image code-blep · Dec 02, 2012 at 10:47 PM 0
Share

That looks interesting David, thanks for that! I will test it over the coming days, as I am in the process of converting everything else and will be doing the movement last.

2 Replies

  • Sort: 
avatar image
Best Answer

Answer by fafase · Dec 03, 2012 at 01:49 PM

So you want to move an object towards a direction.

 Vector3 direction = target.position - transform.position;
 rigidbody.AddForce(direction*speed);

This will get your object in the direction. No need for angle compared to x-axis, teh vector indicates all that.

For the opposite direction simply revert the vector:

 Vector3 direction = target.position - transform.position;
 rigidbody.AddForce(-direction*speed);

See the minus sign?

Now this is goign to add force constantly so they will add up to reach warp speed. You could then cance the previous force to get a smoother effect:

 Vector3 previous = new Vector3(0f,0f,0f);
 void Update(){
    rigidbody.AddForce(-previous*speed);   //Cancel previous
    Vector3 direction = target.position - transform.position;
    rigidbody.AddForce(direction*speed);  //Give new force
    previous = direction;                 //Store for next round
 }

In the end, you are adding F0 then next frame you add -F0 and add F1 and so on.

There might be better solution though...

Comment
code-blep

People who like this

1 Show 6 · 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 code-blep · Dec 03, 2012 at 02:01 PM 0
Share

This looks great fafase. I am at work at the moment, but hope to start work on the physics movement tonight when I get home. I'll post an update, vote etc when done.

avatar image fafase · Dec 03, 2012 at 02:29 PM 0
Share

By the way, I forgot one detail. The destination is not normalized. It means that at large distance, the vector is large and so is the velocity and when getting closer the vector is smaller then you get a smaller velocity. If you want the guy to move always the same velocity add:

  direction.Normalize(); 
avatar image DavidDebnar · Dec 03, 2012 at 04:34 PM 0
Share

fafase, you should use FixedUpdate for Physics operations, but since you cancel the previous out, it shouldn't be a problem ;).

avatar image fafase · Dec 03, 2012 at 07:35 PM 0
Share

indeed I should...

avatar image code-blep · Dec 03, 2012 at 08:45 PM 0
Share

Hi fafase, I just realised that the example you gave is in C# so I am trying to convert it to UnityScript....

Got the first part done:

var direction : Vector3 = attackerStatusScript.targetFollow.position - transform.position; rigidbody.AddForce(direction*currentSpeedSetting);

Show more comments
avatar image

Answer by DavidDebnar · Dec 03, 2012 at 01:39 PM

I made some changes to the code. I doesn't involve physics anymore, but it'd be quite easy to implement.

 #pragma strict
 
 var enemyTransform : Transform;
 var playerTransform : Transform;
 var distance : float = 3;//distance the enemy's going to try keep
 var deadZone : float = 1;//this is some kind of offset, in this dead zone, the enemy won't move. It's used to eliminate weird behaviour. Try to set it to 0 and see what happens.
 var speed : float = 5;
 /*var prev : Vector3;*/
 
 function FixedUpdate () {
    var pPos : Vector3 = playerTransform.position;//position of the player
    var ePos : Vector3 = enemyTransform.position;//position of the enemy
 
    var curDist : float = Vector3.Distance(ePos,pPos);//distance between p and e

    var direction : Vector3 = (curDist > distance+deadZone?pPos-ePos:((curDist < distance-deadZone)?ePos-pPos:Vector3.zero)).normalized;//the direction between p and e. Note the use of ternary operators to determine if the direction should be towards the player, from the player or 0.

    /*enemyTransform.rigidbody.AddForce(-prev*speed, ForceMode.Force);*/
    enemyTransform.rigidbody.AddForce(direction*speed, ForceMode.Force);//you can change the force mode, if you want different behaviour.
 
    /*prev = direction;*/

 }


--David

Comment
code-blep

People who like this

1 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 code-blep · Dec 03, 2012 at 01:57 PM 0
Share

Hi David,

Thanks but as mentioned in the original post, I am changing from transform position movement to physics based movement. This is critical for my desired end result.

avatar image DavidDebnar · Dec 03, 2012 at 05:26 PM 0
Share

I updated the code. It now uses Physics, has comments that'll hopefully give you some insight on the code. Also, if you want to eliminate the previous movement as fafas did, just remove / / form the code.

avatar image code-blep · Dec 03, 2012 at 05:53 PM 0
Share

Sweet! I will try and get on to this part of my code next. I'll update as soon as I have any news etc. Thanks for the input David, always appreciated, I'm giving a thumbs up to you all.

avatar image code-blep · Dec 03, 2012 at 09:12 PM 0
Share

Sorry David but I opted for fafase's solution. The best I can do is give your answer an upvote. Thanks for the time you spent on it. Much appreciated.

Unity Answers is in Read-Only mode

Unity Answers content will be migrated to a new Community platform and we are aiming to launch a public beta by June 9. Please note, Unity Answers is now in read-only so we can prepare for the final data migration.

For more information and updates, please read our full announcement thread in the Unity Forum.

Follow this Question

Answers Answers and Comments

11 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

Related Questions

AddForce makes cube 2 Answers

Why does the train jump? 1 Answer

AddForce made a ball fall with no accelleration 1 Answer

What is the error? 2 Answers

Shoot Raycast to a specified Angle 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