Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
2 captures
12 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
4
Question by csgeorge · Nov 19, 2015 at 06:47 PM · c#physicsrigidbody

Push Object in Opposite Direction of Collision

I want my player character gameObject to be pushed a short distance away from an enemy it comes in contact with. So I want to use OnCollisionEnter, if colliding object has the tag enemy, for the gameObject to move a short distance in the opposite direction of the enemy object it collided with. How would I go about doing this?

Comment
Add comment · Show 1
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 highpockets · Nov 19, 2015 at 08:08 PM 0
Share

I think you should give it a shot and show the code that you use if it doesn't work out, but this sounds like you just want someone to supply you with the code.

Anyways, in the OnCollisionEnter function you need to find out where the enemy is in relation to the player object. So, if it is an object which is tagged as enemy, subtract the player position by the enemy position to find the direction to move in and then use that direction vector to move your player in that direction by whatever means you are using for movement.

3 Replies

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

Answer by MythralFTW · Nov 19, 2015 at 09:12 PM

This should accomplish your needs, let me know if you have questions.

 void OnCollisionEnter(Collision c)
 {
     // force is how forcefully we will push the player away from the enemy.
     float force = 3;
 
     // If the object we hit is the enemy
     if (c.gameObject.tag == "enemy")
     {
         // Calculate Angle Between the collision point and the player
         Vector3 dir = c.contacts[0].point - transform.position;
         // We then get the opposite (-Vector3) and normalize it
         dir = -dir.normalized;
         // And finally we add force in the direction of dir and multiply it by force. 
         // This will push back the player
         GetComponent<Rigidbody>().AddForce(dir*force);
     }
 }
Comment
Add comment · Show 8 · 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 csgeorge · Nov 22, 2015 at 07:23 PM 0
Share

Thank you, this worked, but (and I say just in case someone else looks to this page for the same information) I had to make the force value much greater than 3 to see any noticeable effect.

avatar image LethianGames · May 23, 2016 at 09:27 AM 0
Share

I have a quick question. Assu$$anonymous$$g I want to use this code in a 2D environment - i changed it to "OnCollisionEnter2D" and changed the vector3 in line 10 to vector2 - but I'm still getting the error that "contacts" (line 10 as well) is not defined...any idea what i have to change in order to make it work? Thx for any help :)

avatar image highpockets LethianGames · May 23, 2016 at 07:41 PM 0
Share

did you put, OnCollisionEnter2D( Collision2D c )?

avatar image LethianGames highpockets · May 25, 2016 at 08:38 AM 2
Share

Couldn't get it to work - i'm now using:

 void OnTriggerEnter2D (Collider2D other)
     {
         wallTrigger = false;
     }
 
     void OnTriggerExit2D (Collider2D other)
     {
         wallTrigger = true;
 
         var magnitude = 2500;
 
         var force = transform.position - other.transform.position;
 
         force.Normalize ();
         GetComponent<Rigidbody2D> ().AddForce (-force * magnitude);
 
 
     }

Seems a little rough, but works fine for now ;) Thx for the help though!

Show more comments
avatar image Rexor4321 · Sep 11, 2017 at 09:41 AM 0
Share

Thank you! Never would've figured this one out on my own

avatar image Arithebee · Jun 16, 2019 at 11:15 PM 0
Share

perfect thanks

avatar image
5

Answer by kingcoyote · Nov 19, 2015 at 08:11 PM

Assuming you are using rigidbodies with correctly set mass and physics interaction layers...

Inside the OnCollisionEnter function, add this code:

 public void OnCollisionEnter(Collision other) {
     // how much the character should be knocked back
     var magnitude = 5000;
     // calculate force vector
     var force = transform.position - other.transform.position;
     // normalize force vector to get direction only and trim magnitude
     force.Normalize();

     gameObject.GetComponent<RigidBody>().AddForce(force * magnitude);
 }
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 artiumxweb · Dec 23, 2019 at 03:21 AM 0
Share

you have to add a physics material 2d with bouncing in 1, if used in 2d

avatar image zarthera · Mar 31 at 04:22 AM 0
Share

This worked a lot better than the most liked answer for me. With the other answer's solution my collisions weren't always detecting for me for some reason. Thanks ;)

avatar image
0

Answer by normoustgstaff · Feb 06, 2019 at 01:33 AM

Hi, I want to make the same think but with kimenatic object, and its not working I have tried to make it with velocity but the object starts to move constantly.

Any suggestions ?,Hi , I want to do the same but with kinematic object, and its not working , i have tried with velocity but the object start to move constantly.

Any suggestions ?

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 blockchan · Feb 08, 2019 at 01:31 PM 0
Share

You will have to use $$anonymous$$athf.Lerp to start with very low velocity and increase it every frame until you reach desired velocity. This will simulate acceleration.

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

52 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

Related Questions

Rigidbody character controller can't walk on stairs 0 Answers

Rigidbody.SweepTest Hit Trigger Colliders 0 Answers

What is the best way to prevent a physics object from going through thin colliders? 2 Answers

Issue with adding force and lerping position? Possible unity bug? 0 Answers

Moving a player with Rigidbody 2 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